-
Yes another redesign...
- Yeah I designed to redesign my website again to it's old style.
- I wanted more controll on images so I can start using Jpeg XL
- before it's supported in website builder software.
-
-
example:
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+ Owen Quinlan (BuyMyMojo) ☕
+
+
+
+
+
+
+ Summary
+
+
+ Dedicated Game Development Student. Strong background in Rust, Python, C#, with a focus on interactive
+ mediums that make an impact on users. Passionate about roles involving game development,
+ software development, and leveraging Rust for high-performance, thread-safe applications.
+ Actively seeking opportunities that align with career goals of contributing to impactful, engaging
+ media in game devlopment fields.
+
-
-
- The image above is most likely displaying in .webp format but if the browser
- doesnt support that(like old browsers) it will show a .png image and if your
- browser supports jpegXL then it will show a .jxl image.
-
-
- Pretty simple reason but it's the sort of control I want.
-
-
+
+
+
+ Work Experience
+ Jr Software Developer & Server Administrator Mammoth Esports Australaia | 2018 - 2022
Designed and created a Discord bot for user managment used in over 400 Discord servers managing thousands of users and requests daily. Handled the backend of our game server renting system The company is now defunct but it was a good introduction to an industry I want to work in. Phone Repair Technician Cohuna Phone Repairs | Jan 2024 - Present
Experince in data recovery, repair of phones and computers and general electronics repairs.
+
+
+
+ Projects
+ 📍pinned project Soul Abscence I worked together with a small group to make my first proper game jam game! This was for Godot Wild Jam #80 Soul Abscence is a resource managment simulation game inpired by 911 operator. Adding 113 commits totalling around 12K lines of formatted code(unformatted number is most likely smaller!) I worked on things like level loading, A⭐ path finding, Menus and Options. It was made over the course of about 9 days and I'm super happy with the work we've all put in! There is of coure a lot of things I'd do differently if we made the game again but that's just how it is when you make effectively a "prototype" game. Game jam entry + rating page Godot Wild Jam #80 Check out 911 Operator on steam! pinned project Open FBTOpen sourced version of a large scale discord bot for user managment. Built in Rust and uses the Redis database to store user data. In over 400 servers at time of writing(september 2024) Origionally written in Python then converted to Rust to improve ease of deployment and improve performance significantly. View OpenFBT on GitHub. Made in tandum with discord chat partser written in python and then Go for user moderation. Mojo Kitchen Chaos - An overcooked-like game made in Unity following an online course Made over the course of a week following a course by Code Monkey . GitHub Repo Itch.io page RedisFS - A pointless file storage solution written in Rust Sores files up to 500mb in a Redis database. GitHub Repo Video FPS overlay Origionally made to take FPS data from a csv file generated with Nvidia FrameView and display it in a Digital Foundry like graph. Never reached a fully functioning state but it was a fun old project. Written in Python GitHub Repo
+
+
+
\ No newline at end of file
diff --git a/node_modules/.bin/mpd-to-m3u8-json b/node_modules/.bin/mpd-to-m3u8-json
deleted file mode 100644
index 2dbcfcc..0000000
--- a/node_modules/.bin/mpd-to-m3u8-json
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/sh
-basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
-
-case `uname` in
- *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
-esac
-
-if [ -x "$basedir/node" ]; then
- "$basedir/node" "$basedir/../mpd-parser/bin/parse.js" "$@"
- ret=$?
-else
- node "$basedir/../mpd-parser/bin/parse.js" "$@"
- ret=$?
-fi
-exit $ret
diff --git a/node_modules/.bin/mpd-to-m3u8-json.cmd b/node_modules/.bin/mpd-to-m3u8-json.cmd
deleted file mode 100644
index 0a61d64..0000000
--- a/node_modules/.bin/mpd-to-m3u8-json.cmd
+++ /dev/null
@@ -1,17 +0,0 @@
-@ECHO off
-SETLOCAL
-CALL :find_dp0
-
-IF EXIST "%dp0%\node.exe" (
- SET "_prog=%dp0%\node.exe"
-) ELSE (
- SET "_prog=node"
- SET PATHEXT=%PATHEXT:;.JS;=;%
-)
-
-"%_prog%" "%dp0%\..\mpd-parser\bin\parse.js" %*
-ENDLOCAL
-EXIT /b %errorlevel%
-:find_dp0
-SET dp0=%~dp0
-EXIT /b
diff --git a/node_modules/.bin/mpd-to-m3u8-json.ps1 b/node_modules/.bin/mpd-to-m3u8-json.ps1
deleted file mode 100644
index d3522c5..0000000
--- a/node_modules/.bin/mpd-to-m3u8-json.ps1
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/usr/bin/env pwsh
-$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
-
-$exe=""
-if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
- # Fix case when both the Windows and Linux builds of Node
- # are installed in the same directory
- $exe=".exe"
-}
-$ret=0
-if (Test-Path "$basedir/node$exe") {
- & "$basedir/node$exe" "$basedir/../mpd-parser/bin/parse.js" $args
- $ret=$LASTEXITCODE
-} else {
- & "node$exe" "$basedir/../mpd-parser/bin/parse.js" $args
- $ret=$LASTEXITCODE
-}
-exit $ret
diff --git a/node_modules/.bin/muxjs-transmux b/node_modules/.bin/muxjs-transmux
deleted file mode 100644
index 521c12a..0000000
--- a/node_modules/.bin/muxjs-transmux
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/sh
-basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
-
-case `uname` in
- *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
-esac
-
-if [ -x "$basedir/node" ]; then
- "$basedir/node" "$basedir/../mux.js/bin/transmux.js" "$@"
- ret=$?
-else
- node "$basedir/../mux.js/bin/transmux.js" "$@"
- ret=$?
-fi
-exit $ret
diff --git a/node_modules/.bin/muxjs-transmux.cmd b/node_modules/.bin/muxjs-transmux.cmd
deleted file mode 100644
index e473a86..0000000
--- a/node_modules/.bin/muxjs-transmux.cmd
+++ /dev/null
@@ -1,17 +0,0 @@
-@ECHO off
-SETLOCAL
-CALL :find_dp0
-
-IF EXIST "%dp0%\node.exe" (
- SET "_prog=%dp0%\node.exe"
-) ELSE (
- SET "_prog=node"
- SET PATHEXT=%PATHEXT:;.JS;=;%
-)
-
-"%_prog%" "%dp0%\..\mux.js\bin\transmux.js" %*
-ENDLOCAL
-EXIT /b %errorlevel%
-:find_dp0
-SET dp0=%~dp0
-EXIT /b
diff --git a/node_modules/.bin/muxjs-transmux.ps1 b/node_modules/.bin/muxjs-transmux.ps1
deleted file mode 100644
index fd19b84..0000000
--- a/node_modules/.bin/muxjs-transmux.ps1
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/usr/bin/env pwsh
-$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
-
-$exe=""
-if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
- # Fix case when both the Windows and Linux builds of Node
- # are installed in the same directory
- $exe=".exe"
-}
-$ret=0
-if (Test-Path "$basedir/node$exe") {
- & "$basedir/node$exe" "$basedir/../mux.js/bin/transmux.js" $args
- $ret=$LASTEXITCODE
-} else {
- & "node$exe" "$basedir/../mux.js/bin/transmux.js" $args
- $ret=$LASTEXITCODE
-}
-exit $ret
diff --git a/node_modules/.bin/pkcs7 b/node_modules/.bin/pkcs7
deleted file mode 100644
index 3db3ebe..0000000
--- a/node_modules/.bin/pkcs7
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/sh
-basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
-
-case `uname` in
- *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
-esac
-
-if [ -x "$basedir/node" ]; then
- "$basedir/node" "$basedir/../pkcs7/bin/cli.js" "$@"
- ret=$?
-else
- node "$basedir/../pkcs7/bin/cli.js" "$@"
- ret=$?
-fi
-exit $ret
diff --git a/node_modules/.bin/pkcs7.cmd b/node_modules/.bin/pkcs7.cmd
deleted file mode 100644
index f81b501..0000000
--- a/node_modules/.bin/pkcs7.cmd
+++ /dev/null
@@ -1,17 +0,0 @@
-@ECHO off
-SETLOCAL
-CALL :find_dp0
-
-IF EXIST "%dp0%\node.exe" (
- SET "_prog=%dp0%\node.exe"
-) ELSE (
- SET "_prog=node"
- SET PATHEXT=%PATHEXT:;.JS;=;%
-)
-
-"%_prog%" "%dp0%\..\pkcs7\bin\cli.js" %*
-ENDLOCAL
-EXIT /b %errorlevel%
-:find_dp0
-SET dp0=%~dp0
-EXIT /b
diff --git a/node_modules/.bin/pkcs7.ps1 b/node_modules/.bin/pkcs7.ps1
deleted file mode 100644
index 4fb8a14..0000000
--- a/node_modules/.bin/pkcs7.ps1
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/usr/bin/env pwsh
-$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
-
-$exe=""
-if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
- # Fix case when both the Windows and Linux builds of Node
- # are installed in the same directory
- $exe=".exe"
-}
-$ret=0
-if (Test-Path "$basedir/node$exe") {
- & "$basedir/node$exe" "$basedir/../pkcs7/bin/cli.js" $args
- $ret=$LASTEXITCODE
-} else {
- & "node$exe" "$basedir/../pkcs7/bin/cli.js" $args
- $ret=$LASTEXITCODE
-}
-exit $ret
diff --git a/node_modules/@babel/runtime/LICENSE b/node_modules/@babel/runtime/LICENSE
deleted file mode 100644
index f31575e..0000000
--- a/node_modules/@babel/runtime/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-MIT License
-
-Copyright (c) 2014-present Sebastian McKenzie and other 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.
diff --git a/node_modules/@babel/runtime/README.md b/node_modules/@babel/runtime/README.md
deleted file mode 100644
index 119c99d..0000000
--- a/node_modules/@babel/runtime/README.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# @babel/runtime
-
-> babel's modular runtime helpers
-
-See our website [@babel/runtime](https://babeljs.io/docs/en/babel-runtime) for more information.
-
-## Install
-
-Using npm:
-
-```sh
-npm install --save @babel/runtime
-```
-
-or using yarn:
-
-```sh
-yarn add @babel/runtime
-```
diff --git a/node_modules/@babel/runtime/helpers/AsyncGenerator.js b/node_modules/@babel/runtime/helpers/AsyncGenerator.js
deleted file mode 100644
index cdca7f5..0000000
--- a/node_modules/@babel/runtime/helpers/AsyncGenerator.js
+++ /dev/null
@@ -1,99 +0,0 @@
-var AwaitValue = require("./AwaitValue.js");
-
-function AsyncGenerator(gen) {
- var front, back;
-
- function send(key, arg) {
- return new Promise(function (resolve, reject) {
- var request = {
- key: key,
- arg: arg,
- resolve: resolve,
- reject: reject,
- next: null
- };
-
- if (back) {
- back = back.next = request;
- } else {
- front = back = request;
- resume(key, arg);
- }
- });
- }
-
- function resume(key, arg) {
- try {
- var result = gen[key](arg);
- var value = result.value;
- var wrappedAwait = value instanceof AwaitValue;
- Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) {
- if (wrappedAwait) {
- resume(key === "return" ? "return" : "next", arg);
- return;
- }
-
- settle(result.done ? "return" : "normal", arg);
- }, function (err) {
- resume("throw", err);
- });
- } catch (err) {
- settle("throw", err);
- }
- }
-
- function settle(type, value) {
- switch (type) {
- case "return":
- front.resolve({
- value: value,
- done: true
- });
- break;
-
- case "throw":
- front.reject(value);
- break;
-
- default:
- front.resolve({
- value: value,
- done: false
- });
- break;
- }
-
- front = front.next;
-
- if (front) {
- resume(front.key, front.arg);
- } else {
- back = null;
- }
- }
-
- this._invoke = send;
-
- if (typeof gen["return"] !== "function") {
- this["return"] = undefined;
- }
-}
-
-AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () {
- return this;
-};
-
-AsyncGenerator.prototype.next = function (arg) {
- return this._invoke("next", arg);
-};
-
-AsyncGenerator.prototype["throw"] = function (arg) {
- return this._invoke("throw", arg);
-};
-
-AsyncGenerator.prototype["return"] = function (arg) {
- return this._invoke("return", arg);
-};
-
-module.exports = AsyncGenerator;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/AwaitValue.js b/node_modules/@babel/runtime/helpers/AwaitValue.js
deleted file mode 100644
index d36df6e..0000000
--- a/node_modules/@babel/runtime/helpers/AwaitValue.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _AwaitValue(value) {
- this.wrapped = value;
-}
-
-module.exports = _AwaitValue;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js b/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js
deleted file mode 100644
index feaeab8..0000000
--- a/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js
+++ /dev/null
@@ -1,31 +0,0 @@
-function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
- var desc = {};
- Object.keys(descriptor).forEach(function (key) {
- desc[key] = descriptor[key];
- });
- desc.enumerable = !!desc.enumerable;
- desc.configurable = !!desc.configurable;
-
- if ('value' in desc || desc.initializer) {
- desc.writable = true;
- }
-
- desc = decorators.slice().reverse().reduce(function (desc, decorator) {
- return decorator(target, property, desc) || desc;
- }, desc);
-
- if (context && desc.initializer !== void 0) {
- desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
- desc.initializer = undefined;
- }
-
- if (desc.initializer === void 0) {
- Object.defineProperty(target, property, desc);
- desc = null;
- }
-
- return desc;
-}
-
-module.exports = _applyDecoratedDescriptor;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/arrayLikeToArray.js b/node_modules/@babel/runtime/helpers/arrayLikeToArray.js
deleted file mode 100644
index a459c8e..0000000
--- a/node_modules/@babel/runtime/helpers/arrayLikeToArray.js
+++ /dev/null
@@ -1,12 +0,0 @@
-function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
-
- for (var i = 0, arr2 = new Array(len); i < len; i++) {
- arr2[i] = arr[i];
- }
-
- return arr2;
-}
-
-module.exports = _arrayLikeToArray;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/arrayWithHoles.js b/node_modules/@babel/runtime/helpers/arrayWithHoles.js
deleted file mode 100644
index 9a36e2a..0000000
--- a/node_modules/@babel/runtime/helpers/arrayWithHoles.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _arrayWithHoles(arr) {
- if (Array.isArray(arr)) return arr;
-}
-
-module.exports = _arrayWithHoles;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js b/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js
deleted file mode 100644
index aac913f..0000000
--- a/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js
+++ /dev/null
@@ -1,8 +0,0 @@
-var arrayLikeToArray = require("./arrayLikeToArray.js");
-
-function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) return arrayLikeToArray(arr);
-}
-
-module.exports = _arrayWithoutHoles;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/assertThisInitialized.js b/node_modules/@babel/runtime/helpers/assertThisInitialized.js
deleted file mode 100644
index 352e1e6..0000000
--- a/node_modules/@babel/runtime/helpers/assertThisInitialized.js
+++ /dev/null
@@ -1,10 +0,0 @@
-function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
-
- return self;
-}
-
-module.exports = _assertThisInitialized;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js b/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js
deleted file mode 100644
index 91f6d61..0000000
--- a/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js
+++ /dev/null
@@ -1,57 +0,0 @@
-function _asyncGeneratorDelegate(inner, awaitWrap) {
- var iter = {},
- waiting = false;
-
- function pump(key, value) {
- waiting = true;
- value = new Promise(function (resolve) {
- resolve(inner[key](value));
- });
- return {
- done: false,
- value: awaitWrap(value)
- };
- }
-
- ;
-
- iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function () {
- return this;
- };
-
- iter.next = function (value) {
- if (waiting) {
- waiting = false;
- return value;
- }
-
- return pump("next", value);
- };
-
- if (typeof inner["throw"] === "function") {
- iter["throw"] = function (value) {
- if (waiting) {
- waiting = false;
- throw value;
- }
-
- return pump("throw", value);
- };
- }
-
- if (typeof inner["return"] === "function") {
- iter["return"] = function (value) {
- if (waiting) {
- waiting = false;
- return value;
- }
-
- return pump("return", value);
- };
- }
-
- return iter;
-}
-
-module.exports = _asyncGeneratorDelegate;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/asyncIterator.js b/node_modules/@babel/runtime/helpers/asyncIterator.js
deleted file mode 100644
index d59aa99..0000000
--- a/node_modules/@babel/runtime/helpers/asyncIterator.js
+++ /dev/null
@@ -1,16 +0,0 @@
-function _asyncIterator(iterable) {
- var method;
-
- if (typeof Symbol !== "undefined") {
- if (Symbol.asyncIterator) method = iterable[Symbol.asyncIterator];
- if (method == null && Symbol.iterator) method = iterable[Symbol.iterator];
- }
-
- if (method == null) method = iterable["@@asyncIterator"];
- if (method == null) method = iterable["@@iterator"];
- if (method == null) throw new TypeError("Object is not async iterable");
- return method.call(iterable);
-}
-
-module.exports = _asyncIterator;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/asyncToGenerator.js b/node_modules/@babel/runtime/helpers/asyncToGenerator.js
deleted file mode 100644
index ec5daa8..0000000
--- a/node_modules/@babel/runtime/helpers/asyncToGenerator.js
+++ /dev/null
@@ -1,38 +0,0 @@
-function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
- try {
- var info = gen[key](arg);
- var value = info.value;
- } catch (error) {
- reject(error);
- return;
- }
-
- if (info.done) {
- resolve(value);
- } else {
- Promise.resolve(value).then(_next, _throw);
- }
-}
-
-function _asyncToGenerator(fn) {
- return function () {
- var self = this,
- args = arguments;
- return new Promise(function (resolve, reject) {
- var gen = fn.apply(self, args);
-
- function _next(value) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
- }
-
- function _throw(err) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
- }
-
- _next(undefined);
- });
- };
-}
-
-module.exports = _asyncToGenerator;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js b/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js
deleted file mode 100644
index c338fee..0000000
--- a/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js
+++ /dev/null
@@ -1,8 +0,0 @@
-var AwaitValue = require("./AwaitValue.js");
-
-function _awaitAsyncGenerator(value) {
- return new AwaitValue(value);
-}
-
-module.exports = _awaitAsyncGenerator;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js
deleted file mode 100644
index 521c1e0..0000000
--- a/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js
+++ /dev/null
@@ -1,23 +0,0 @@
-function _classApplyDescriptorDestructureSet(receiver, descriptor) {
- if (descriptor.set) {
- if (!("__destrObj" in descriptor)) {
- descriptor.__destrObj = {
- set value(v) {
- descriptor.set.call(receiver, v);
- }
-
- };
- }
-
- return descriptor.__destrObj;
- } else {
- if (!descriptor.writable) {
- throw new TypeError("attempted to set read only private field");
- }
-
- return descriptor;
- }
-}
-
-module.exports = _classApplyDescriptorDestructureSet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js
deleted file mode 100644
index f750596..0000000
--- a/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js
+++ /dev/null
@@ -1,10 +0,0 @@
-function _classApplyDescriptorGet(receiver, descriptor) {
- if (descriptor.get) {
- return descriptor.get.call(receiver);
- }
-
- return descriptor.value;
-}
-
-module.exports = _classApplyDescriptorGet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js
deleted file mode 100644
index 997b264..0000000
--- a/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js
+++ /dev/null
@@ -1,14 +0,0 @@
-function _classApplyDescriptorSet(receiver, descriptor, value) {
- if (descriptor.set) {
- descriptor.set.call(receiver, value);
- } else {
- if (!descriptor.writable) {
- throw new TypeError("attempted to set read only private field");
- }
-
- descriptor.value = value;
- }
-}
-
-module.exports = _classApplyDescriptorSet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classCallCheck.js b/node_modules/@babel/runtime/helpers/classCallCheck.js
deleted file mode 100644
index 026da41..0000000
--- a/node_modules/@babel/runtime/helpers/classCallCheck.js
+++ /dev/null
@@ -1,8 +0,0 @@
-function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
-}
-
-module.exports = _classCallCheck;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js
deleted file mode 100644
index 67373aa..0000000
--- a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js
+++ /dev/null
@@ -1,8 +0,0 @@
-function _classCheckPrivateStaticAccess(receiver, classConstructor) {
- if (receiver !== classConstructor) {
- throw new TypeError("Private static access of wrong provenance");
- }
-}
-
-module.exports = _classCheckPrivateStaticAccess;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js
deleted file mode 100644
index 3b93472..0000000
--- a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js
+++ /dev/null
@@ -1,8 +0,0 @@
-function _classCheckPrivateStaticFieldDescriptor(descriptor, action) {
- if (descriptor === undefined) {
- throw new TypeError("attempted to " + action + " private static field before its declaration");
- }
-}
-
-module.exports = _classCheckPrivateStaticFieldDescriptor;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js b/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js
deleted file mode 100644
index aaaac8c..0000000
--- a/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js
+++ /dev/null
@@ -1,10 +0,0 @@
-function _classExtractFieldDescriptor(receiver, privateMap, action) {
- if (!privateMap.has(receiver)) {
- throw new TypeError("attempted to " + action + " private field on non-instance");
- }
-
- return privateMap.get(receiver);
-}
-
-module.exports = _classExtractFieldDescriptor;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classNameTDZError.js b/node_modules/@babel/runtime/helpers/classNameTDZError.js
deleted file mode 100644
index bf740fa..0000000
--- a/node_modules/@babel/runtime/helpers/classNameTDZError.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _classNameTDZError(name) {
- throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys.");
-}
-
-module.exports = _classNameTDZError;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js
deleted file mode 100644
index 50b9fb0..0000000
--- a/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js
+++ /dev/null
@@ -1,11 +0,0 @@
-var classApplyDescriptorDestructureSet = require("./classApplyDescriptorDestructureSet.js");
-
-var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js");
-
-function _classPrivateFieldDestructureSet(receiver, privateMap) {
- var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set");
- return classApplyDescriptorDestructureSet(receiver, descriptor);
-}
-
-module.exports = _classPrivateFieldDestructureSet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js
deleted file mode 100644
index df55969..0000000
--- a/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js
+++ /dev/null
@@ -1,11 +0,0 @@
-var classApplyDescriptorGet = require("./classApplyDescriptorGet.js");
-
-var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js");
-
-function _classPrivateFieldGet(receiver, privateMap) {
- var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get");
- return classApplyDescriptorGet(receiver, descriptor);
-}
-
-module.exports = _classPrivateFieldGet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js
deleted file mode 100644
index 3acdb7b..0000000
--- a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js
+++ /dev/null
@@ -1,10 +0,0 @@
-function _classPrivateFieldBase(receiver, privateKey) {
- if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
- throw new TypeError("attempted to use private field on non-instance");
- }
-
- return receiver;
-}
-
-module.exports = _classPrivateFieldBase;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js
deleted file mode 100644
index 3c0c552..0000000
--- a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js
+++ /dev/null
@@ -1,8 +0,0 @@
-var id = 0;
-
-function _classPrivateFieldKey(name) {
- return "__private_" + id++ + "_" + name;
-}
-
-module.exports = _classPrivateFieldKey;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js
deleted file mode 100644
index d4a59b0..0000000
--- a/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js
+++ /dev/null
@@ -1,12 +0,0 @@
-var classApplyDescriptorSet = require("./classApplyDescriptorSet.js");
-
-var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js");
-
-function _classPrivateFieldSet(receiver, privateMap, value) {
- var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set");
- classApplyDescriptorSet(receiver, descriptor, value);
- return value;
-}
-
-module.exports = _classPrivateFieldSet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js
deleted file mode 100644
index d2f8ab1..0000000
--- a/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js
+++ /dev/null
@@ -1,10 +0,0 @@
-function _classPrivateMethodGet(receiver, privateSet, fn) {
- if (!privateSet.has(receiver)) {
- throw new TypeError("attempted to get private field on non-instance");
- }
-
- return fn;
-}
-
-module.exports = _classPrivateMethodGet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js
deleted file mode 100644
index f500d16..0000000
--- a/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _classPrivateMethodSet() {
- throw new TypeError("attempted to reassign private method");
-}
-
-module.exports = _classPrivateMethodSet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js
deleted file mode 100644
index 57e2c7f..0000000
--- a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var classApplyDescriptorDestructureSet = require("./classApplyDescriptorDestructureSet.js");
-
-var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js");
-
-var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js");
-
-function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) {
- classCheckPrivateStaticAccess(receiver, classConstructor);
- classCheckPrivateStaticFieldDescriptor(descriptor, "set");
- return classApplyDescriptorDestructureSet(receiver, descriptor);
-}
-
-module.exports = _classStaticPrivateFieldDestructureSet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js
deleted file mode 100644
index 136c1f6..0000000
--- a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var classApplyDescriptorGet = require("./classApplyDescriptorGet.js");
-
-var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js");
-
-var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js");
-
-function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) {
- classCheckPrivateStaticAccess(receiver, classConstructor);
- classCheckPrivateStaticFieldDescriptor(descriptor, "get");
- return classApplyDescriptorGet(receiver, descriptor);
-}
-
-module.exports = _classStaticPrivateFieldSpecGet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js
deleted file mode 100644
index e6ecfa4..0000000
--- a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js
+++ /dev/null
@@ -1,15 +0,0 @@
-var classApplyDescriptorSet = require("./classApplyDescriptorSet.js");
-
-var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js");
-
-var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js");
-
-function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) {
- classCheckPrivateStaticAccess(receiver, classConstructor);
- classCheckPrivateStaticFieldDescriptor(descriptor, "set");
- classApplyDescriptorSet(receiver, descriptor, value);
- return value;
-}
-
-module.exports = _classStaticPrivateFieldSpecSet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js
deleted file mode 100644
index 5bc41fc..0000000
--- a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js
+++ /dev/null
@@ -1,9 +0,0 @@
-var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js");
-
-function _classStaticPrivateMethodGet(receiver, classConstructor, method) {
- classCheckPrivateStaticAccess(receiver, classConstructor);
- return method;
-}
-
-module.exports = _classStaticPrivateMethodGet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js
deleted file mode 100644
index 06cfcc1..0000000
--- a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _classStaticPrivateMethodSet() {
- throw new TypeError("attempted to set read only static private field");
-}
-
-module.exports = _classStaticPrivateMethodSet;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/construct.js b/node_modules/@babel/runtime/helpers/construct.js
deleted file mode 100644
index 108b39a..0000000
--- a/node_modules/@babel/runtime/helpers/construct.js
+++ /dev/null
@@ -1,26 +0,0 @@
-var setPrototypeOf = require("./setPrototypeOf.js");
-
-var isNativeReflectConstruct = require("./isNativeReflectConstruct.js");
-
-function _construct(Parent, args, Class) {
- if (isNativeReflectConstruct()) {
- module.exports = _construct = Reflect.construct;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- } else {
- module.exports = _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) setPrototypeOf(instance, Class.prototype);
- return instance;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- }
-
- return _construct.apply(null, arguments);
-}
-
-module.exports = _construct;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/createClass.js b/node_modules/@babel/runtime/helpers/createClass.js
deleted file mode 100644
index 293bd61..0000000
--- a/node_modules/@babel/runtime/helpers/createClass.js
+++ /dev/null
@@ -1,18 +0,0 @@
-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);
- }
-}
-
-function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
-}
-
-module.exports = _createClass;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js b/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js
deleted file mode 100644
index 9098865..0000000
--- a/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js
+++ /dev/null
@@ -1,61 +0,0 @@
-var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
-
-function _createForOfIteratorHelper(o, allowArrayLike) {
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
-
- if (!it) {
- if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
- if (it) o = it;
- var i = 0;
-
- var F = function F() {};
-
- return {
- s: F,
- n: function n() {
- if (i >= o.length) return {
- done: true
- };
- return {
- done: false,
- value: o[i++]
- };
- },
- e: function e(_e) {
- throw _e;
- },
- f: F
- };
- }
-
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
-
- var normalCompletion = true,
- didErr = false,
- err;
- return {
- s: function s() {
- it = it.call(o);
- },
- n: function n() {
- var step = it.next();
- normalCompletion = step.done;
- return step;
- },
- e: function e(_e2) {
- didErr = true;
- err = _e2;
- },
- f: function f() {
- try {
- if (!normalCompletion && it["return"] != null) it["return"]();
- } finally {
- if (didErr) throw err;
- }
- }
- };
-}
-
-module.exports = _createForOfIteratorHelper;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js b/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js
deleted file mode 100644
index 2dedbc9..0000000
--- a/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js
+++ /dev/null
@@ -1,25 +0,0 @@
-var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
-
-function _createForOfIteratorHelperLoose(o, allowArrayLike) {
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
- if (it) return (it = it.call(o)).next.bind(it);
-
- if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
- if (it) o = it;
- var i = 0;
- return function () {
- if (i >= o.length) return {
- done: true
- };
- return {
- done: false,
- value: o[i++]
- };
- };
- }
-
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
-}
-
-module.exports = _createForOfIteratorHelperLoose;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/createSuper.js b/node_modules/@babel/runtime/helpers/createSuper.js
deleted file mode 100644
index 0acdd51..0000000
--- a/node_modules/@babel/runtime/helpers/createSuper.js
+++ /dev/null
@@ -1,25 +0,0 @@
-var getPrototypeOf = require("./getPrototypeOf.js");
-
-var isNativeReflectConstruct = require("./isNativeReflectConstruct.js");
-
-var possibleConstructorReturn = require("./possibleConstructorReturn.js");
-
-function _createSuper(Derived) {
- var hasNativeReflectConstruct = isNativeReflectConstruct();
- return function _createSuperInternal() {
- var Super = getPrototypeOf(Derived),
- result;
-
- if (hasNativeReflectConstruct) {
- var NewTarget = getPrototypeOf(this).constructor;
- result = Reflect.construct(Super, arguments, NewTarget);
- } else {
- result = Super.apply(this, arguments);
- }
-
- return possibleConstructorReturn(this, result);
- };
-}
-
-module.exports = _createSuper;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/decorate.js b/node_modules/@babel/runtime/helpers/decorate.js
deleted file mode 100644
index 80d1751..0000000
--- a/node_modules/@babel/runtime/helpers/decorate.js
+++ /dev/null
@@ -1,401 +0,0 @@
-var toArray = require("./toArray.js");
-
-var toPropertyKey = require("./toPropertyKey.js");
-
-function _decorate(decorators, factory, superClass, mixins) {
- var api = _getDecoratorsApi();
-
- if (mixins) {
- for (var i = 0; i < mixins.length; i++) {
- api = mixins[i](api);
- }
- }
-
- var r = factory(function initialize(O) {
- api.initializeInstanceElements(O, decorated.elements);
- }, superClass);
- var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators);
- api.initializeClassElements(r.F, decorated.elements);
- return api.runClassFinishers(r.F, decorated.finishers);
-}
-
-function _getDecoratorsApi() {
- _getDecoratorsApi = function _getDecoratorsApi() {
- return api;
- };
-
- var api = {
- elementsDefinitionOrder: [["method"], ["field"]],
- initializeInstanceElements: function initializeInstanceElements(O, elements) {
- ["method", "field"].forEach(function (kind) {
- elements.forEach(function (element) {
- if (element.kind === kind && element.placement === "own") {
- this.defineClassElement(O, element);
- }
- }, this);
- }, this);
- },
- initializeClassElements: function initializeClassElements(F, elements) {
- var proto = F.prototype;
- ["method", "field"].forEach(function (kind) {
- elements.forEach(function (element) {
- var placement = element.placement;
-
- if (element.kind === kind && (placement === "static" || placement === "prototype")) {
- var receiver = placement === "static" ? F : proto;
- this.defineClassElement(receiver, element);
- }
- }, this);
- }, this);
- },
- defineClassElement: function defineClassElement(receiver, element) {
- var descriptor = element.descriptor;
-
- if (element.kind === "field") {
- var initializer = element.initializer;
- descriptor = {
- enumerable: descriptor.enumerable,
- writable: descriptor.writable,
- configurable: descriptor.configurable,
- value: initializer === void 0 ? void 0 : initializer.call(receiver)
- };
- }
-
- Object.defineProperty(receiver, element.key, descriptor);
- },
- decorateClass: function decorateClass(elements, decorators) {
- var newElements = [];
- var finishers = [];
- var placements = {
- "static": [],
- prototype: [],
- own: []
- };
- elements.forEach(function (element) {
- this.addElementPlacement(element, placements);
- }, this);
- elements.forEach(function (element) {
- if (!_hasDecorators(element)) return newElements.push(element);
- var elementFinishersExtras = this.decorateElement(element, placements);
- newElements.push(elementFinishersExtras.element);
- newElements.push.apply(newElements, elementFinishersExtras.extras);
- finishers.push.apply(finishers, elementFinishersExtras.finishers);
- }, this);
-
- if (!decorators) {
- return {
- elements: newElements,
- finishers: finishers
- };
- }
-
- var result = this.decorateConstructor(newElements, decorators);
- finishers.push.apply(finishers, result.finishers);
- result.finishers = finishers;
- return result;
- },
- addElementPlacement: function addElementPlacement(element, placements, silent) {
- var keys = placements[element.placement];
-
- if (!silent && keys.indexOf(element.key) !== -1) {
- throw new TypeError("Duplicated element (" + element.key + ")");
- }
-
- keys.push(element.key);
- },
- decorateElement: function decorateElement(element, placements) {
- var extras = [];
- var finishers = [];
-
- for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) {
- var keys = placements[element.placement];
- keys.splice(keys.indexOf(element.key), 1);
- var elementObject = this.fromElementDescriptor(element);
- var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject);
- element = elementFinisherExtras.element;
- this.addElementPlacement(element, placements);
-
- if (elementFinisherExtras.finisher) {
- finishers.push(elementFinisherExtras.finisher);
- }
-
- var newExtras = elementFinisherExtras.extras;
-
- if (newExtras) {
- for (var j = 0; j < newExtras.length; j++) {
- this.addElementPlacement(newExtras[j], placements);
- }
-
- extras.push.apply(extras, newExtras);
- }
- }
-
- return {
- element: element,
- finishers: finishers,
- extras: extras
- };
- },
- decorateConstructor: function decorateConstructor(elements, decorators) {
- var finishers = [];
-
- for (var i = decorators.length - 1; i >= 0; i--) {
- var obj = this.fromClassDescriptor(elements);
- var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj);
-
- if (elementsAndFinisher.finisher !== undefined) {
- finishers.push(elementsAndFinisher.finisher);
- }
-
- if (elementsAndFinisher.elements !== undefined) {
- elements = elementsAndFinisher.elements;
-
- for (var j = 0; j < elements.length - 1; j++) {
- for (var k = j + 1; k < elements.length; k++) {
- if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) {
- throw new TypeError("Duplicated element (" + elements[j].key + ")");
- }
- }
- }
- }
- }
-
- return {
- elements: elements,
- finishers: finishers
- };
- },
- fromElementDescriptor: function fromElementDescriptor(element) {
- var obj = {
- kind: element.kind,
- key: element.key,
- placement: element.placement,
- descriptor: element.descriptor
- };
- var desc = {
- value: "Descriptor",
- configurable: true
- };
- Object.defineProperty(obj, Symbol.toStringTag, desc);
- if (element.kind === "field") obj.initializer = element.initializer;
- return obj;
- },
- toElementDescriptors: function toElementDescriptors(elementObjects) {
- if (elementObjects === undefined) return;
- return toArray(elementObjects).map(function (elementObject) {
- var element = this.toElementDescriptor(elementObject);
- this.disallowProperty(elementObject, "finisher", "An element descriptor");
- this.disallowProperty(elementObject, "extras", "An element descriptor");
- return element;
- }, this);
- },
- toElementDescriptor: function toElementDescriptor(elementObject) {
- var kind = String(elementObject.kind);
-
- if (kind !== "method" && kind !== "field") {
- throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"');
- }
-
- var key = toPropertyKey(elementObject.key);
- var placement = String(elementObject.placement);
-
- if (placement !== "static" && placement !== "prototype" && placement !== "own") {
- throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"');
- }
-
- var descriptor = elementObject.descriptor;
- this.disallowProperty(elementObject, "elements", "An element descriptor");
- var element = {
- kind: kind,
- key: key,
- placement: placement,
- descriptor: Object.assign({}, descriptor)
- };
-
- if (kind !== "field") {
- this.disallowProperty(elementObject, "initializer", "A method descriptor");
- } else {
- this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor");
- this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor");
- this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor");
- element.initializer = elementObject.initializer;
- }
-
- return element;
- },
- toElementFinisherExtras: function toElementFinisherExtras(elementObject) {
- var element = this.toElementDescriptor(elementObject);
-
- var finisher = _optionalCallableProperty(elementObject, "finisher");
-
- var extras = this.toElementDescriptors(elementObject.extras);
- return {
- element: element,
- finisher: finisher,
- extras: extras
- };
- },
- fromClassDescriptor: function fromClassDescriptor(elements) {
- var obj = {
- kind: "class",
- elements: elements.map(this.fromElementDescriptor, this)
- };
- var desc = {
- value: "Descriptor",
- configurable: true
- };
- Object.defineProperty(obj, Symbol.toStringTag, desc);
- return obj;
- },
- toClassDescriptor: function toClassDescriptor(obj) {
- var kind = String(obj.kind);
-
- if (kind !== "class") {
- throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"');
- }
-
- this.disallowProperty(obj, "key", "A class descriptor");
- this.disallowProperty(obj, "placement", "A class descriptor");
- this.disallowProperty(obj, "descriptor", "A class descriptor");
- this.disallowProperty(obj, "initializer", "A class descriptor");
- this.disallowProperty(obj, "extras", "A class descriptor");
-
- var finisher = _optionalCallableProperty(obj, "finisher");
-
- var elements = this.toElementDescriptors(obj.elements);
- return {
- elements: elements,
- finisher: finisher
- };
- },
- runClassFinishers: function runClassFinishers(constructor, finishers) {
- for (var i = 0; i < finishers.length; i++) {
- var newConstructor = (0, finishers[i])(constructor);
-
- if (newConstructor !== undefined) {
- if (typeof newConstructor !== "function") {
- throw new TypeError("Finishers must return a constructor.");
- }
-
- constructor = newConstructor;
- }
- }
-
- return constructor;
- },
- disallowProperty: function disallowProperty(obj, name, objectType) {
- if (obj[name] !== undefined) {
- throw new TypeError(objectType + " can't have a ." + name + " property.");
- }
- }
- };
- return api;
-}
-
-function _createElementDescriptor(def) {
- var key = toPropertyKey(def.key);
- var descriptor;
-
- if (def.kind === "method") {
- descriptor = {
- value: def.value,
- writable: true,
- configurable: true,
- enumerable: false
- };
- } else if (def.kind === "get") {
- descriptor = {
- get: def.value,
- configurable: true,
- enumerable: false
- };
- } else if (def.kind === "set") {
- descriptor = {
- set: def.value,
- configurable: true,
- enumerable: false
- };
- } else if (def.kind === "field") {
- descriptor = {
- configurable: true,
- writable: true,
- enumerable: true
- };
- }
-
- var element = {
- kind: def.kind === "field" ? "field" : "method",
- key: key,
- placement: def["static"] ? "static" : def.kind === "field" ? "own" : "prototype",
- descriptor: descriptor
- };
- if (def.decorators) element.decorators = def.decorators;
- if (def.kind === "field") element.initializer = def.value;
- return element;
-}
-
-function _coalesceGetterSetter(element, other) {
- if (element.descriptor.get !== undefined) {
- other.descriptor.get = element.descriptor.get;
- } else {
- other.descriptor.set = element.descriptor.set;
- }
-}
-
-function _coalesceClassElements(elements) {
- var newElements = [];
-
- var isSameElement = function isSameElement(other) {
- return other.kind === "method" && other.key === element.key && other.placement === element.placement;
- };
-
- for (var i = 0; i < elements.length; i++) {
- var element = elements[i];
- var other;
-
- if (element.kind === "method" && (other = newElements.find(isSameElement))) {
- if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) {
- if (_hasDecorators(element) || _hasDecorators(other)) {
- throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated.");
- }
-
- other.descriptor = element.descriptor;
- } else {
- if (_hasDecorators(element)) {
- if (_hasDecorators(other)) {
- throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ").");
- }
-
- other.decorators = element.decorators;
- }
-
- _coalesceGetterSetter(element, other);
- }
- } else {
- newElements.push(element);
- }
- }
-
- return newElements;
-}
-
-function _hasDecorators(element) {
- return element.decorators && element.decorators.length;
-}
-
-function _isDataDescriptor(desc) {
- return desc !== undefined && !(desc.value === undefined && desc.writable === undefined);
-}
-
-function _optionalCallableProperty(obj, name) {
- var value = obj[name];
-
- if (value !== undefined && typeof value !== "function") {
- throw new TypeError("Expected '" + name + "' to be a function");
- }
-
- return value;
-}
-
-module.exports = _decorate;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/defaults.js b/node_modules/@babel/runtime/helpers/defaults.js
deleted file mode 100644
index 576c5a4..0000000
--- a/node_modules/@babel/runtime/helpers/defaults.js
+++ /dev/null
@@ -1,17 +0,0 @@
-function _defaults(obj, defaults) {
- var keys = Object.getOwnPropertyNames(defaults);
-
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- var value = Object.getOwnPropertyDescriptor(defaults, key);
-
- if (value && value.configurable && obj[key] === undefined) {
- Object.defineProperty(obj, key, value);
- }
- }
-
- return obj;
-}
-
-module.exports = _defaults;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js b/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js
deleted file mode 100644
index 4fe90c3..0000000
--- a/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js
+++ /dev/null
@@ -1,25 +0,0 @@
-function _defineEnumerableProperties(obj, descs) {
- for (var key in descs) {
- var desc = descs[key];
- desc.configurable = desc.enumerable = true;
- if ("value" in desc) desc.writable = true;
- Object.defineProperty(obj, key, desc);
- }
-
- if (Object.getOwnPropertySymbols) {
- var objectSymbols = Object.getOwnPropertySymbols(descs);
-
- for (var i = 0; i < objectSymbols.length; i++) {
- var sym = objectSymbols[i];
- var desc = descs[sym];
- desc.configurable = desc.enumerable = true;
- if ("value" in desc) desc.writable = true;
- Object.defineProperty(obj, sym, desc);
- }
- }
-
- return obj;
-}
-
-module.exports = _defineEnumerableProperties;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/defineProperty.js b/node_modules/@babel/runtime/helpers/defineProperty.js
deleted file mode 100644
index 1cd65ac..0000000
--- a/node_modules/@babel/runtime/helpers/defineProperty.js
+++ /dev/null
@@ -1,17 +0,0 @@
-function _defineProperty(obj, key, value) {
- if (key in obj) {
- Object.defineProperty(obj, key, {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
- } else {
- obj[key] = value;
- }
-
- return obj;
-}
-
-module.exports = _defineProperty;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js
deleted file mode 100644
index 919aab8..0000000
--- a/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js
+++ /dev/null
@@ -1,95 +0,0 @@
-import AwaitValue from "./AwaitValue.js";
-export default function AsyncGenerator(gen) {
- var front, back;
-
- function send(key, arg) {
- return new Promise(function (resolve, reject) {
- var request = {
- key: key,
- arg: arg,
- resolve: resolve,
- reject: reject,
- next: null
- };
-
- if (back) {
- back = back.next = request;
- } else {
- front = back = request;
- resume(key, arg);
- }
- });
- }
-
- function resume(key, arg) {
- try {
- var result = gen[key](arg);
- var value = result.value;
- var wrappedAwait = value instanceof AwaitValue;
- Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) {
- if (wrappedAwait) {
- resume(key === "return" ? "return" : "next", arg);
- return;
- }
-
- settle(result.done ? "return" : "normal", arg);
- }, function (err) {
- resume("throw", err);
- });
- } catch (err) {
- settle("throw", err);
- }
- }
-
- function settle(type, value) {
- switch (type) {
- case "return":
- front.resolve({
- value: value,
- done: true
- });
- break;
-
- case "throw":
- front.reject(value);
- break;
-
- default:
- front.resolve({
- value: value,
- done: false
- });
- break;
- }
-
- front = front.next;
-
- if (front) {
- resume(front.key, front.arg);
- } else {
- back = null;
- }
- }
-
- this._invoke = send;
-
- if (typeof gen["return"] !== "function") {
- this["return"] = undefined;
- }
-}
-
-AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () {
- return this;
-};
-
-AsyncGenerator.prototype.next = function (arg) {
- return this._invoke("next", arg);
-};
-
-AsyncGenerator.prototype["throw"] = function (arg) {
- return this._invoke("throw", arg);
-};
-
-AsyncGenerator.prototype["return"] = function (arg) {
- return this._invoke("return", arg);
-};
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/AwaitValue.js b/node_modules/@babel/runtime/helpers/esm/AwaitValue.js
deleted file mode 100644
index 5237e18..0000000
--- a/node_modules/@babel/runtime/helpers/esm/AwaitValue.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _AwaitValue(value) {
- this.wrapped = value;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js b/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js
deleted file mode 100644
index 84b5961..0000000
--- a/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js
+++ /dev/null
@@ -1,28 +0,0 @@
-export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
- var desc = {};
- Object.keys(descriptor).forEach(function (key) {
- desc[key] = descriptor[key];
- });
- desc.enumerable = !!desc.enumerable;
- desc.configurable = !!desc.configurable;
-
- if ('value' in desc || desc.initializer) {
- desc.writable = true;
- }
-
- desc = decorators.slice().reverse().reduce(function (desc, decorator) {
- return decorator(target, property, desc) || desc;
- }, desc);
-
- if (context && desc.initializer !== void 0) {
- desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
- desc.initializer = undefined;
- }
-
- if (desc.initializer === void 0) {
- Object.defineProperty(target, property, desc);
- desc = null;
- }
-
- return desc;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js b/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js
deleted file mode 100644
index edbeb8e..0000000
--- a/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js
+++ /dev/null
@@ -1,9 +0,0 @@
-export default function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
-
- for (var i = 0, arr2 = new Array(len); i < len; i++) {
- arr2[i] = arr[i];
- }
-
- return arr2;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js b/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js
deleted file mode 100644
index be734fc..0000000
--- a/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _arrayWithHoles(arr) {
- if (Array.isArray(arr)) return arr;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js b/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js
deleted file mode 100644
index f7d8dc7..0000000
--- a/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import arrayLikeToArray from "./arrayLikeToArray.js";
-export default function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) return arrayLikeToArray(arr);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js b/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
deleted file mode 100644
index bbf849c..0000000
--- a/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
+++ /dev/null
@@ -1,7 +0,0 @@
-export default function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
-
- return self;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js b/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js
deleted file mode 100644
index a7ccd67..0000000
--- a/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js
+++ /dev/null
@@ -1,54 +0,0 @@
-export default function _asyncGeneratorDelegate(inner, awaitWrap) {
- var iter = {},
- waiting = false;
-
- function pump(key, value) {
- waiting = true;
- value = new Promise(function (resolve) {
- resolve(inner[key](value));
- });
- return {
- done: false,
- value: awaitWrap(value)
- };
- }
-
- ;
-
- iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function () {
- return this;
- };
-
- iter.next = function (value) {
- if (waiting) {
- waiting = false;
- return value;
- }
-
- return pump("next", value);
- };
-
- if (typeof inner["throw"] === "function") {
- iter["throw"] = function (value) {
- if (waiting) {
- waiting = false;
- throw value;
- }
-
- return pump("throw", value);
- };
- }
-
- if (typeof inner["return"] === "function") {
- iter["return"] = function (value) {
- if (waiting) {
- waiting = false;
- return value;
- }
-
- return pump("return", value);
- };
- }
-
- return iter;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/asyncIterator.js b/node_modules/@babel/runtime/helpers/esm/asyncIterator.js
deleted file mode 100644
index 91ddb42..0000000
--- a/node_modules/@babel/runtime/helpers/esm/asyncIterator.js
+++ /dev/null
@@ -1,13 +0,0 @@
-export default function _asyncIterator(iterable) {
- var method;
-
- if (typeof Symbol !== "undefined") {
- if (Symbol.asyncIterator) method = iterable[Symbol.asyncIterator];
- if (method == null && Symbol.iterator) method = iterable[Symbol.iterator];
- }
-
- if (method == null) method = iterable["@@asyncIterator"];
- if (method == null) method = iterable["@@iterator"];
- if (method == null) throw new TypeError("Object is not async iterable");
- return method.call(iterable);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js b/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
deleted file mode 100644
index 2a25f54..0000000
--- a/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
+++ /dev/null
@@ -1,35 +0,0 @@
-function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
- try {
- var info = gen[key](arg);
- var value = info.value;
- } catch (error) {
- reject(error);
- return;
- }
-
- if (info.done) {
- resolve(value);
- } else {
- Promise.resolve(value).then(_next, _throw);
- }
-}
-
-export default function _asyncToGenerator(fn) {
- return function () {
- var self = this,
- args = arguments;
- return new Promise(function (resolve, reject) {
- var gen = fn.apply(self, args);
-
- function _next(value) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
- }
-
- function _throw(err) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
- }
-
- _next(undefined);
- });
- };
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js
deleted file mode 100644
index ccca65e..0000000
--- a/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import AwaitValue from "./AwaitValue.js";
-export default function _awaitAsyncGenerator(value) {
- return new AwaitValue(value);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js
deleted file mode 100644
index 4472adc..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js
+++ /dev/null
@@ -1,20 +0,0 @@
-export default function _classApplyDescriptorDestructureSet(receiver, descriptor) {
- if (descriptor.set) {
- if (!("__destrObj" in descriptor)) {
- descriptor.__destrObj = {
- set value(v) {
- descriptor.set.call(receiver, v);
- }
-
- };
- }
-
- return descriptor.__destrObj;
- } else {
- if (!descriptor.writable) {
- throw new TypeError("attempted to set read only private field");
- }
-
- return descriptor;
- }
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js
deleted file mode 100644
index 0fad169..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js
+++ /dev/null
@@ -1,7 +0,0 @@
-export default function _classApplyDescriptorGet(receiver, descriptor) {
- if (descriptor.get) {
- return descriptor.get.call(receiver);
- }
-
- return descriptor.value;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js
deleted file mode 100644
index f295f3e..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js
+++ /dev/null
@@ -1,11 +0,0 @@
-export default function _classApplyDescriptorSet(receiver, descriptor, value) {
- if (descriptor.set) {
- descriptor.set.call(receiver, value);
- } else {
- if (!descriptor.writable) {
- throw new TypeError("attempted to set read only private field");
- }
-
- descriptor.value = value;
- }
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classCallCheck.js b/node_modules/@babel/runtime/helpers/esm/classCallCheck.js
deleted file mode 100644
index 2f1738a..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classCallCheck.js
+++ /dev/null
@@ -1,5 +0,0 @@
-export default function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js
deleted file mode 100644
index 098ed30..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js
+++ /dev/null
@@ -1,5 +0,0 @@
-export default function _classCheckPrivateStaticAccess(receiver, classConstructor) {
- if (receiver !== classConstructor) {
- throw new TypeError("Private static access of wrong provenance");
- }
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js
deleted file mode 100644
index 0ef34b8..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js
+++ /dev/null
@@ -1,5 +0,0 @@
-export default function _classCheckPrivateStaticFieldDescriptor(descriptor, action) {
- if (descriptor === undefined) {
- throw new TypeError("attempted to " + action + " private static field before its declaration");
- }
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js b/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js
deleted file mode 100644
index 8dabe9a..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js
+++ /dev/null
@@ -1,7 +0,0 @@
-export default function _classExtractFieldDescriptor(receiver, privateMap, action) {
- if (!privateMap.has(receiver)) {
- throw new TypeError("attempted to " + action + " private field on non-instance");
- }
-
- return privateMap.get(receiver);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js b/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js
deleted file mode 100644
index f7b6dd5..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _classNameTDZError(name) {
- throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys.");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js
deleted file mode 100644
index fb58833..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js
+++ /dev/null
@@ -1,6 +0,0 @@
-import classApplyDescriptorDestructureSet from "./classApplyDescriptorDestructureSet.js";
-import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js";
-export default function _classPrivateFieldDestructureSet(receiver, privateMap) {
- var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set");
- return classApplyDescriptorDestructureSet(receiver, descriptor);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js
deleted file mode 100644
index 53cd137..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js
+++ /dev/null
@@ -1,6 +0,0 @@
-import classApplyDescriptorGet from "./classApplyDescriptorGet.js";
-import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js";
-export default function _classPrivateFieldGet(receiver, privateMap) {
- var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get");
- return classApplyDescriptorGet(receiver, descriptor);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js
deleted file mode 100644
index 5b10916..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js
+++ /dev/null
@@ -1,7 +0,0 @@
-export default function _classPrivateFieldBase(receiver, privateKey) {
- if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
- throw new TypeError("attempted to use private field on non-instance");
- }
-
- return receiver;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js
deleted file mode 100644
index 5b7e5ac..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js
+++ /dev/null
@@ -1,4 +0,0 @@
-var id = 0;
-export default function _classPrivateFieldKey(name) {
- return "__private_" + id++ + "_" + name;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js
deleted file mode 100644
index ad91be4..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import classApplyDescriptorSet from "./classApplyDescriptorSet.js";
-import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js";
-export default function _classPrivateFieldSet(receiver, privateMap, value) {
- var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set");
- classApplyDescriptorSet(receiver, descriptor, value);
- return value;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js
deleted file mode 100644
index 38b9d58..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js
+++ /dev/null
@@ -1,7 +0,0 @@
-export default function _classPrivateMethodGet(receiver, privateSet, fn) {
- if (!privateSet.has(receiver)) {
- throw new TypeError("attempted to get private field on non-instance");
- }
-
- return fn;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js
deleted file mode 100644
index 2bbaf3a..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _classPrivateMethodSet() {
- throw new TypeError("attempted to reassign private method");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js
deleted file mode 100644
index 77afcfb..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import classApplyDescriptorDestructureSet from "./classApplyDescriptorDestructureSet.js";
-import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js";
-import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js";
-export default function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) {
- classCheckPrivateStaticAccess(receiver, classConstructor);
- classCheckPrivateStaticFieldDescriptor(descriptor, "set");
- return classApplyDescriptorDestructureSet(receiver, descriptor);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js
deleted file mode 100644
index d253d31..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import classApplyDescriptorGet from "./classApplyDescriptorGet.js";
-import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js";
-import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js";
-export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) {
- classCheckPrivateStaticAccess(receiver, classConstructor);
- classCheckPrivateStaticFieldDescriptor(descriptor, "get");
- return classApplyDescriptorGet(receiver, descriptor);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js
deleted file mode 100644
index b0b0cc6..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js
+++ /dev/null
@@ -1,9 +0,0 @@
-import classApplyDescriptorSet from "./classApplyDescriptorSet.js";
-import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js";
-import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js";
-export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) {
- classCheckPrivateStaticAccess(receiver, classConstructor);
- classCheckPrivateStaticFieldDescriptor(descriptor, "set");
- classApplyDescriptorSet(receiver, descriptor, value);
- return value;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js
deleted file mode 100644
index fddc7b2..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js
+++ /dev/null
@@ -1,5 +0,0 @@
-import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js";
-export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) {
- classCheckPrivateStaticAccess(receiver, classConstructor);
- return method;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js
deleted file mode 100644
index d5ab60a..0000000
--- a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _classStaticPrivateMethodSet() {
- throw new TypeError("attempted to set read only static private field");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/construct.js b/node_modules/@babel/runtime/helpers/esm/construct.js
deleted file mode 100644
index 0c39835..0000000
--- a/node_modules/@babel/runtime/helpers/esm/construct.js
+++ /dev/null
@@ -1,18 +0,0 @@
-import setPrototypeOf from "./setPrototypeOf.js";
-import isNativeReflectConstruct from "./isNativeReflectConstruct.js";
-export default function _construct(Parent, args, Class) {
- if (isNativeReflectConstruct()) {
- _construct = Reflect.construct;
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
-
- return _construct.apply(null, arguments);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/createClass.js b/node_modules/@babel/runtime/helpers/esm/createClass.js
deleted file mode 100644
index d6cf412..0000000
--- a/node_modules/@babel/runtime/helpers/esm/createClass.js
+++ /dev/null
@@ -1,15 +0,0 @@
-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);
- }
-}
-
-export default function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js
deleted file mode 100644
index a7a2a50..0000000
--- a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js
+++ /dev/null
@@ -1,57 +0,0 @@
-import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
-export default function _createForOfIteratorHelper(o, allowArrayLike) {
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
-
- if (!it) {
- if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
- if (it) o = it;
- var i = 0;
-
- var F = function F() {};
-
- return {
- s: F,
- n: function n() {
- if (i >= o.length) return {
- done: true
- };
- return {
- done: false,
- value: o[i++]
- };
- },
- e: function e(_e) {
- throw _e;
- },
- f: F
- };
- }
-
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
-
- var normalCompletion = true,
- didErr = false,
- err;
- return {
- s: function s() {
- it = it.call(o);
- },
- n: function n() {
- var step = it.next();
- normalCompletion = step.done;
- return step;
- },
- e: function e(_e2) {
- didErr = true;
- err = _e2;
- },
- f: function f() {
- try {
- if (!normalCompletion && it["return"] != null) it["return"]();
- } finally {
- if (didErr) throw err;
- }
- }
- };
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js
deleted file mode 100644
index 640ec68..0000000
--- a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js
+++ /dev/null
@@ -1,21 +0,0 @@
-import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
-export default function _createForOfIteratorHelperLoose(o, allowArrayLike) {
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
- if (it) return (it = it.call(o)).next.bind(it);
-
- if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
- if (it) o = it;
- var i = 0;
- return function () {
- if (i >= o.length) return {
- done: true
- };
- return {
- done: false,
- value: o[i++]
- };
- };
- }
-
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/createSuper.js b/node_modules/@babel/runtime/helpers/esm/createSuper.js
deleted file mode 100644
index ea5ea99..0000000
--- a/node_modules/@babel/runtime/helpers/esm/createSuper.js
+++ /dev/null
@@ -1,19 +0,0 @@
-import getPrototypeOf from "./getPrototypeOf.js";
-import isNativeReflectConstruct from "./isNativeReflectConstruct.js";
-import possibleConstructorReturn from "./possibleConstructorReturn.js";
-export default function _createSuper(Derived) {
- var hasNativeReflectConstruct = isNativeReflectConstruct();
- return function _createSuperInternal() {
- var Super = getPrototypeOf(Derived),
- result;
-
- if (hasNativeReflectConstruct) {
- var NewTarget = getPrototypeOf(this).constructor;
- result = Reflect.construct(Super, arguments, NewTarget);
- } else {
- result = Super.apply(this, arguments);
- }
-
- return possibleConstructorReturn(this, result);
- };
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/decorate.js b/node_modules/@babel/runtime/helpers/esm/decorate.js
deleted file mode 100644
index daf56da..0000000
--- a/node_modules/@babel/runtime/helpers/esm/decorate.js
+++ /dev/null
@@ -1,396 +0,0 @@
-import toArray from "./toArray.js";
-import toPropertyKey from "./toPropertyKey.js";
-export default function _decorate(decorators, factory, superClass, mixins) {
- var api = _getDecoratorsApi();
-
- if (mixins) {
- for (var i = 0; i < mixins.length; i++) {
- api = mixins[i](api);
- }
- }
-
- var r = factory(function initialize(O) {
- api.initializeInstanceElements(O, decorated.elements);
- }, superClass);
- var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators);
- api.initializeClassElements(r.F, decorated.elements);
- return api.runClassFinishers(r.F, decorated.finishers);
-}
-
-function _getDecoratorsApi() {
- _getDecoratorsApi = function _getDecoratorsApi() {
- return api;
- };
-
- var api = {
- elementsDefinitionOrder: [["method"], ["field"]],
- initializeInstanceElements: function initializeInstanceElements(O, elements) {
- ["method", "field"].forEach(function (kind) {
- elements.forEach(function (element) {
- if (element.kind === kind && element.placement === "own") {
- this.defineClassElement(O, element);
- }
- }, this);
- }, this);
- },
- initializeClassElements: function initializeClassElements(F, elements) {
- var proto = F.prototype;
- ["method", "field"].forEach(function (kind) {
- elements.forEach(function (element) {
- var placement = element.placement;
-
- if (element.kind === kind && (placement === "static" || placement === "prototype")) {
- var receiver = placement === "static" ? F : proto;
- this.defineClassElement(receiver, element);
- }
- }, this);
- }, this);
- },
- defineClassElement: function defineClassElement(receiver, element) {
- var descriptor = element.descriptor;
-
- if (element.kind === "field") {
- var initializer = element.initializer;
- descriptor = {
- enumerable: descriptor.enumerable,
- writable: descriptor.writable,
- configurable: descriptor.configurable,
- value: initializer === void 0 ? void 0 : initializer.call(receiver)
- };
- }
-
- Object.defineProperty(receiver, element.key, descriptor);
- },
- decorateClass: function decorateClass(elements, decorators) {
- var newElements = [];
- var finishers = [];
- var placements = {
- "static": [],
- prototype: [],
- own: []
- };
- elements.forEach(function (element) {
- this.addElementPlacement(element, placements);
- }, this);
- elements.forEach(function (element) {
- if (!_hasDecorators(element)) return newElements.push(element);
- var elementFinishersExtras = this.decorateElement(element, placements);
- newElements.push(elementFinishersExtras.element);
- newElements.push.apply(newElements, elementFinishersExtras.extras);
- finishers.push.apply(finishers, elementFinishersExtras.finishers);
- }, this);
-
- if (!decorators) {
- return {
- elements: newElements,
- finishers: finishers
- };
- }
-
- var result = this.decorateConstructor(newElements, decorators);
- finishers.push.apply(finishers, result.finishers);
- result.finishers = finishers;
- return result;
- },
- addElementPlacement: function addElementPlacement(element, placements, silent) {
- var keys = placements[element.placement];
-
- if (!silent && keys.indexOf(element.key) !== -1) {
- throw new TypeError("Duplicated element (" + element.key + ")");
- }
-
- keys.push(element.key);
- },
- decorateElement: function decorateElement(element, placements) {
- var extras = [];
- var finishers = [];
-
- for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) {
- var keys = placements[element.placement];
- keys.splice(keys.indexOf(element.key), 1);
- var elementObject = this.fromElementDescriptor(element);
- var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject);
- element = elementFinisherExtras.element;
- this.addElementPlacement(element, placements);
-
- if (elementFinisherExtras.finisher) {
- finishers.push(elementFinisherExtras.finisher);
- }
-
- var newExtras = elementFinisherExtras.extras;
-
- if (newExtras) {
- for (var j = 0; j < newExtras.length; j++) {
- this.addElementPlacement(newExtras[j], placements);
- }
-
- extras.push.apply(extras, newExtras);
- }
- }
-
- return {
- element: element,
- finishers: finishers,
- extras: extras
- };
- },
- decorateConstructor: function decorateConstructor(elements, decorators) {
- var finishers = [];
-
- for (var i = decorators.length - 1; i >= 0; i--) {
- var obj = this.fromClassDescriptor(elements);
- var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj);
-
- if (elementsAndFinisher.finisher !== undefined) {
- finishers.push(elementsAndFinisher.finisher);
- }
-
- if (elementsAndFinisher.elements !== undefined) {
- elements = elementsAndFinisher.elements;
-
- for (var j = 0; j < elements.length - 1; j++) {
- for (var k = j + 1; k < elements.length; k++) {
- if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) {
- throw new TypeError("Duplicated element (" + elements[j].key + ")");
- }
- }
- }
- }
- }
-
- return {
- elements: elements,
- finishers: finishers
- };
- },
- fromElementDescriptor: function fromElementDescriptor(element) {
- var obj = {
- kind: element.kind,
- key: element.key,
- placement: element.placement,
- descriptor: element.descriptor
- };
- var desc = {
- value: "Descriptor",
- configurable: true
- };
- Object.defineProperty(obj, Symbol.toStringTag, desc);
- if (element.kind === "field") obj.initializer = element.initializer;
- return obj;
- },
- toElementDescriptors: function toElementDescriptors(elementObjects) {
- if (elementObjects === undefined) return;
- return toArray(elementObjects).map(function (elementObject) {
- var element = this.toElementDescriptor(elementObject);
- this.disallowProperty(elementObject, "finisher", "An element descriptor");
- this.disallowProperty(elementObject, "extras", "An element descriptor");
- return element;
- }, this);
- },
- toElementDescriptor: function toElementDescriptor(elementObject) {
- var kind = String(elementObject.kind);
-
- if (kind !== "method" && kind !== "field") {
- throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"');
- }
-
- var key = toPropertyKey(elementObject.key);
- var placement = String(elementObject.placement);
-
- if (placement !== "static" && placement !== "prototype" && placement !== "own") {
- throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"');
- }
-
- var descriptor = elementObject.descriptor;
- this.disallowProperty(elementObject, "elements", "An element descriptor");
- var element = {
- kind: kind,
- key: key,
- placement: placement,
- descriptor: Object.assign({}, descriptor)
- };
-
- if (kind !== "field") {
- this.disallowProperty(elementObject, "initializer", "A method descriptor");
- } else {
- this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor");
- this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor");
- this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor");
- element.initializer = elementObject.initializer;
- }
-
- return element;
- },
- toElementFinisherExtras: function toElementFinisherExtras(elementObject) {
- var element = this.toElementDescriptor(elementObject);
-
- var finisher = _optionalCallableProperty(elementObject, "finisher");
-
- var extras = this.toElementDescriptors(elementObject.extras);
- return {
- element: element,
- finisher: finisher,
- extras: extras
- };
- },
- fromClassDescriptor: function fromClassDescriptor(elements) {
- var obj = {
- kind: "class",
- elements: elements.map(this.fromElementDescriptor, this)
- };
- var desc = {
- value: "Descriptor",
- configurable: true
- };
- Object.defineProperty(obj, Symbol.toStringTag, desc);
- return obj;
- },
- toClassDescriptor: function toClassDescriptor(obj) {
- var kind = String(obj.kind);
-
- if (kind !== "class") {
- throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"');
- }
-
- this.disallowProperty(obj, "key", "A class descriptor");
- this.disallowProperty(obj, "placement", "A class descriptor");
- this.disallowProperty(obj, "descriptor", "A class descriptor");
- this.disallowProperty(obj, "initializer", "A class descriptor");
- this.disallowProperty(obj, "extras", "A class descriptor");
-
- var finisher = _optionalCallableProperty(obj, "finisher");
-
- var elements = this.toElementDescriptors(obj.elements);
- return {
- elements: elements,
- finisher: finisher
- };
- },
- runClassFinishers: function runClassFinishers(constructor, finishers) {
- for (var i = 0; i < finishers.length; i++) {
- var newConstructor = (0, finishers[i])(constructor);
-
- if (newConstructor !== undefined) {
- if (typeof newConstructor !== "function") {
- throw new TypeError("Finishers must return a constructor.");
- }
-
- constructor = newConstructor;
- }
- }
-
- return constructor;
- },
- disallowProperty: function disallowProperty(obj, name, objectType) {
- if (obj[name] !== undefined) {
- throw new TypeError(objectType + " can't have a ." + name + " property.");
- }
- }
- };
- return api;
-}
-
-function _createElementDescriptor(def) {
- var key = toPropertyKey(def.key);
- var descriptor;
-
- if (def.kind === "method") {
- descriptor = {
- value: def.value,
- writable: true,
- configurable: true,
- enumerable: false
- };
- } else if (def.kind === "get") {
- descriptor = {
- get: def.value,
- configurable: true,
- enumerable: false
- };
- } else if (def.kind === "set") {
- descriptor = {
- set: def.value,
- configurable: true,
- enumerable: false
- };
- } else if (def.kind === "field") {
- descriptor = {
- configurable: true,
- writable: true,
- enumerable: true
- };
- }
-
- var element = {
- kind: def.kind === "field" ? "field" : "method",
- key: key,
- placement: def["static"] ? "static" : def.kind === "field" ? "own" : "prototype",
- descriptor: descriptor
- };
- if (def.decorators) element.decorators = def.decorators;
- if (def.kind === "field") element.initializer = def.value;
- return element;
-}
-
-function _coalesceGetterSetter(element, other) {
- if (element.descriptor.get !== undefined) {
- other.descriptor.get = element.descriptor.get;
- } else {
- other.descriptor.set = element.descriptor.set;
- }
-}
-
-function _coalesceClassElements(elements) {
- var newElements = [];
-
- var isSameElement = function isSameElement(other) {
- return other.kind === "method" && other.key === element.key && other.placement === element.placement;
- };
-
- for (var i = 0; i < elements.length; i++) {
- var element = elements[i];
- var other;
-
- if (element.kind === "method" && (other = newElements.find(isSameElement))) {
- if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) {
- if (_hasDecorators(element) || _hasDecorators(other)) {
- throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated.");
- }
-
- other.descriptor = element.descriptor;
- } else {
- if (_hasDecorators(element)) {
- if (_hasDecorators(other)) {
- throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ").");
- }
-
- other.decorators = element.decorators;
- }
-
- _coalesceGetterSetter(element, other);
- }
- } else {
- newElements.push(element);
- }
- }
-
- return newElements;
-}
-
-function _hasDecorators(element) {
- return element.decorators && element.decorators.length;
-}
-
-function _isDataDescriptor(desc) {
- return desc !== undefined && !(desc.value === undefined && desc.writable === undefined);
-}
-
-function _optionalCallableProperty(obj, name) {
- var value = obj[name];
-
- if (value !== undefined && typeof value !== "function") {
- throw new TypeError("Expected '" + name + "' to be a function");
- }
-
- return value;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/defaults.js b/node_modules/@babel/runtime/helpers/esm/defaults.js
deleted file mode 100644
index 3de1d8e..0000000
--- a/node_modules/@babel/runtime/helpers/esm/defaults.js
+++ /dev/null
@@ -1,14 +0,0 @@
-export default function _defaults(obj, defaults) {
- var keys = Object.getOwnPropertyNames(defaults);
-
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- var value = Object.getOwnPropertyDescriptor(defaults, key);
-
- if (value && value.configurable && obj[key] === undefined) {
- Object.defineProperty(obj, key, value);
- }
- }
-
- return obj;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js b/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js
deleted file mode 100644
index 7981acd..0000000
--- a/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js
+++ /dev/null
@@ -1,22 +0,0 @@
-export default function _defineEnumerableProperties(obj, descs) {
- for (var key in descs) {
- var desc = descs[key];
- desc.configurable = desc.enumerable = true;
- if ("value" in desc) desc.writable = true;
- Object.defineProperty(obj, key, desc);
- }
-
- if (Object.getOwnPropertySymbols) {
- var objectSymbols = Object.getOwnPropertySymbols(descs);
-
- for (var i = 0; i < objectSymbols.length; i++) {
- var sym = objectSymbols[i];
- var desc = descs[sym];
- desc.configurable = desc.enumerable = true;
- if ("value" in desc) desc.writable = true;
- Object.defineProperty(obj, sym, desc);
- }
- }
-
- return obj;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/defineProperty.js b/node_modules/@babel/runtime/helpers/esm/defineProperty.js
deleted file mode 100644
index 7cf6e59..0000000
--- a/node_modules/@babel/runtime/helpers/esm/defineProperty.js
+++ /dev/null
@@ -1,14 +0,0 @@
-export default function _defineProperty(obj, key, value) {
- if (key in obj) {
- Object.defineProperty(obj, key, {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
- } else {
- obj[key] = value;
- }
-
- return obj;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/extends.js b/node_modules/@babel/runtime/helpers/esm/extends.js
deleted file mode 100644
index b9b138d..0000000
--- a/node_modules/@babel/runtime/helpers/esm/extends.js
+++ /dev/null
@@ -1,17 +0,0 @@
-export default function _extends() {
- _extends = Object.assign || function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
-
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
-
- return target;
- };
-
- return _extends.apply(this, arguments);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/get.js b/node_modules/@babel/runtime/helpers/esm/get.js
deleted file mode 100644
index 1bce020..0000000
--- a/node_modules/@babel/runtime/helpers/esm/get.js
+++ /dev/null
@@ -1,20 +0,0 @@
-import superPropBase from "./superPropBase.js";
-export default function _get(target, property, receiver) {
- if (typeof Reflect !== "undefined" && Reflect.get) {
- _get = Reflect.get;
- } else {
- _get = function _get(target, property, receiver) {
- var base = superPropBase(target, property);
- if (!base) return;
- var desc = Object.getOwnPropertyDescriptor(base, property);
-
- if (desc.get) {
- return desc.get.call(receiver);
- }
-
- return desc.value;
- };
- }
-
- return _get(target, property, receiver || target);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js b/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js
deleted file mode 100644
index 5abafe3..0000000
--- a/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js
+++ /dev/null
@@ -1,6 +0,0 @@
-export default function _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/inherits.js b/node_modules/@babel/runtime/helpers/esm/inherits.js
deleted file mode 100644
index aee0f10..0000000
--- a/node_modules/@babel/runtime/helpers/esm/inherits.js
+++ /dev/null
@@ -1,15 +0,0 @@
-import setPrototypeOf from "./setPrototypeOf.js";
-export default function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
-
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
- });
- if (superClass) setPrototypeOf(subClass, superClass);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js b/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
deleted file mode 100644
index 90bb796..0000000
--- a/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
+++ /dev/null
@@ -1,6 +0,0 @@
-import setPrototypeOf from "./setPrototypeOf.js";
-export default function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- setPrototypeOf(subClass, superClass);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js b/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js
deleted file mode 100644
index 26fdea0..0000000
--- a/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js
+++ /dev/null
@@ -1,9 +0,0 @@
-export default function _initializerDefineProperty(target, property, descriptor, context) {
- if (!descriptor) return;
- Object.defineProperty(target, property, {
- enumerable: descriptor.enumerable,
- configurable: descriptor.configurable,
- writable: descriptor.writable,
- value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
- });
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js b/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js
deleted file mode 100644
index 30d518c..0000000
--- a/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _initializerWarningHelper(descriptor, context) {
- throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.');
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/instanceof.js b/node_modules/@babel/runtime/helpers/esm/instanceof.js
deleted file mode 100644
index 8c43b71..0000000
--- a/node_modules/@babel/runtime/helpers/esm/instanceof.js
+++ /dev/null
@@ -1,7 +0,0 @@
-export default function _instanceof(left, right) {
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
- return !!right[Symbol.hasInstance](left);
- } else {
- return left instanceof right;
- }
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js b/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js
deleted file mode 100644
index c2df7b6..0000000
--- a/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js
+++ /dev/null
@@ -1,5 +0,0 @@
-export default function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- "default": obj
- };
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js b/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js
deleted file mode 100644
index 662ff7e..0000000
--- a/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import _typeof from "@babel/runtime/helpers/typeof";
-
-function _getRequireWildcardCache(nodeInterop) {
- if (typeof WeakMap !== "function") return null;
- var cacheBabelInterop = new WeakMap();
- var cacheNodeInterop = new WeakMap();
- return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) {
- return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
- })(nodeInterop);
-}
-
-export default function _interopRequireWildcard(obj, nodeInterop) {
- if (!nodeInterop && obj && obj.__esModule) {
- return obj;
- }
-
- if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
- return {
- "default": obj
- };
- }
-
- var cache = _getRequireWildcardCache(nodeInterop);
-
- if (cache && cache.has(obj)) {
- return cache.get(obj);
- }
-
- var newObj = {};
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
-
- for (var key in obj) {
- if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
-
- if (desc && (desc.get || desc.set)) {
- Object.defineProperty(newObj, key, desc);
- } else {
- newObj[key] = obj[key];
- }
- }
- }
-
- newObj["default"] = obj;
-
- if (cache) {
- cache.set(obj, newObj);
- }
-
- return newObj;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js b/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js
deleted file mode 100644
index 7b1bc82..0000000
--- a/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _isNativeFunction(fn) {
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js b/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js
deleted file mode 100644
index 0da1624..0000000
--- a/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js
+++ /dev/null
@@ -1,12 +0,0 @@
-export default function _isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
-
- try {
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArray.js b/node_modules/@babel/runtime/helpers/esm/iterableToArray.js
deleted file mode 100644
index cfe9fbd..0000000
--- a/node_modules/@babel/runtime/helpers/esm/iterableToArray.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _iterableToArray(iter) {
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js
deleted file mode 100644
index c72ca94..0000000
--- a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js
+++ /dev/null
@@ -1,29 +0,0 @@
-export default function _iterableToArrayLimit(arr, i) {
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
-
- if (_i == null) return;
- var _arr = [];
- var _n = true;
- var _d = false;
-
- var _s, _e;
-
- try {
- for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
- _arr.push(_s.value);
-
- if (i && _arr.length === i) break;
- }
- } catch (err) {
- _d = true;
- _e = err;
- } finally {
- try {
- if (!_n && _i["return"] != null) _i["return"]();
- } finally {
- if (_d) throw _e;
- }
- }
-
- return _arr;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js
deleted file mode 100644
index 27c15e0..0000000
--- a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js
+++ /dev/null
@@ -1,14 +0,0 @@
-export default function _iterableToArrayLimitLoose(arr, i) {
- var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
-
- if (_i == null) return;
- var _arr = [];
-
- for (_i = _i.call(arr), _step; !(_step = _i.next()).done;) {
- _arr.push(_step.value);
-
- if (i && _arr.length === i) break;
- }
-
- return _arr;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/jsx.js b/node_modules/@babel/runtime/helpers/esm/jsx.js
deleted file mode 100644
index 328fadf..0000000
--- a/node_modules/@babel/runtime/helpers/esm/jsx.js
+++ /dev/null
@@ -1,46 +0,0 @@
-var REACT_ELEMENT_TYPE;
-export default function _createRawReactElement(type, props, key, children) {
- if (!REACT_ELEMENT_TYPE) {
- REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7;
- }
-
- var defaultProps = type && type.defaultProps;
- var childrenLength = arguments.length - 3;
-
- if (!props && childrenLength !== 0) {
- props = {
- children: void 0
- };
- }
-
- if (childrenLength === 1) {
- props.children = children;
- } else if (childrenLength > 1) {
- var childArray = new Array(childrenLength);
-
- for (var i = 0; i < childrenLength; i++) {
- childArray[i] = arguments[i + 3];
- }
-
- props.children = childArray;
- }
-
- if (props && defaultProps) {
- for (var propName in defaultProps) {
- if (props[propName] === void 0) {
- props[propName] = defaultProps[propName];
- }
- }
- } else if (!props) {
- props = defaultProps || {};
- }
-
- return {
- $$typeof: REACT_ELEMENT_TYPE,
- type: type,
- key: key === undefined ? null : "" + key,
- ref: null,
- props: props,
- _owner: null
- };
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js b/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js
deleted file mode 100644
index f687959..0000000
--- a/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js
+++ /dev/null
@@ -1,9 +0,0 @@
-import arrayLikeToArray from "./arrayLikeToArray.js";
-export default function _maybeArrayLike(next, arr, i) {
- if (arr && !Array.isArray(arr) && typeof arr.length === "number") {
- var len = arr.length;
- return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len);
- }
-
- return next(arr, i);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js b/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js
deleted file mode 100644
index d6cd864..0000000
--- a/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js
+++ /dev/null
@@ -1,5 +0,0 @@
-export default function _newArrowCheck(innerThis, boundThis) {
- if (innerThis !== boundThis) {
- throw new TypeError("Cannot instantiate an arrow function");
- }
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js b/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js
deleted file mode 100644
index b349d00..0000000
--- a/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _nonIterableRest() {
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js b/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js
deleted file mode 100644
index 82d8296..0000000
--- a/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js b/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js
deleted file mode 100644
index 82b67d2..0000000
--- a/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _objectDestructuringEmpty(obj) {
- if (obj == null) throw new TypeError("Cannot destructure undefined");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/objectSpread.js b/node_modules/@babel/runtime/helpers/esm/objectSpread.js
deleted file mode 100644
index 8c38ca7..0000000
--- a/node_modules/@babel/runtime/helpers/esm/objectSpread.js
+++ /dev/null
@@ -1,19 +0,0 @@
-import defineProperty from "./defineProperty.js";
-export default function _objectSpread(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i] != null ? Object(arguments[i]) : {};
- var ownKeys = Object.keys(source);
-
- if (typeof Object.getOwnPropertySymbols === 'function') {
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
- }));
- }
-
- ownKeys.forEach(function (key) {
- defineProperty(target, key, source[key]);
- });
- }
-
- return target;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/objectSpread2.js b/node_modules/@babel/runtime/helpers/esm/objectSpread2.js
deleted file mode 100644
index be42b4d..0000000
--- a/node_modules/@babel/runtime/helpers/esm/objectSpread2.js
+++ /dev/null
@@ -1,39 +0,0 @@
-import defineProperty from "./defineProperty.js";
-
-function ownKeys(object, enumerableOnly) {
- var keys = Object.keys(object);
-
- if (Object.getOwnPropertySymbols) {
- var symbols = Object.getOwnPropertySymbols(object);
-
- if (enumerableOnly) {
- symbols = symbols.filter(function (sym) {
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
- });
- }
-
- keys.push.apply(keys, symbols);
- }
-
- return keys;
-}
-
-export default function _objectSpread2(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i] != null ? arguments[i] : {};
-
- if (i % 2) {
- ownKeys(Object(source), true).forEach(function (key) {
- defineProperty(target, key, source[key]);
- });
- } else if (Object.getOwnPropertyDescriptors) {
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
- } else {
- ownKeys(Object(source)).forEach(function (key) {
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
- });
- }
- }
-
- return target;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js b/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
deleted file mode 100644
index 0fef321..0000000
--- a/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
+++ /dev/null
@@ -1,19 +0,0 @@
-import objectWithoutPropertiesLoose from "./objectWithoutPropertiesLoose.js";
-export default function _objectWithoutProperties(source, excluded) {
- if (source == null) return {};
- var target = objectWithoutPropertiesLoose(source, excluded);
- var key, i;
-
- if (Object.getOwnPropertySymbols) {
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
-
- for (i = 0; i < sourceSymbolKeys.length; i++) {
- key = sourceSymbolKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
- target[key] = source[key];
- }
- }
-
- return target;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js b/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
deleted file mode 100644
index c36815c..0000000
--- a/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
+++ /dev/null
@@ -1,14 +0,0 @@
-export default function _objectWithoutPropertiesLoose(source, excluded) {
- if (source == null) return {};
- var target = {};
- var sourceKeys = Object.keys(source);
- var key, i;
-
- for (i = 0; i < sourceKeys.length; i++) {
- key = sourceKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- target[key] = source[key];
- }
-
- return target;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/package.json b/node_modules/@babel/runtime/helpers/esm/package.json
deleted file mode 100644
index aead43d..0000000
--- a/node_modules/@babel/runtime/helpers/esm/package.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "type": "module"
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js b/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js
deleted file mode 100644
index 0ae22f4..0000000
--- a/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js
+++ /dev/null
@@ -1,9 +0,0 @@
-import _typeof from "@babel/runtime/helpers/typeof";
-import assertThisInitialized from "./assertThisInitialized.js";
-export default function _possibleConstructorReturn(self, call) {
- if (call && (_typeof(call) === "object" || typeof call === "function")) {
- return call;
- }
-
- return assertThisInitialized(self);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/readOnlyError.js b/node_modules/@babel/runtime/helpers/esm/readOnlyError.js
deleted file mode 100644
index 166e40e..0000000
--- a/node_modules/@babel/runtime/helpers/esm/readOnlyError.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _readOnlyError(name) {
- throw new TypeError("\"" + name + "\" is read-only");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/set.js b/node_modules/@babel/runtime/helpers/esm/set.js
deleted file mode 100644
index 9c54773..0000000
--- a/node_modules/@babel/runtime/helpers/esm/set.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import superPropBase from "./superPropBase.js";
-import defineProperty from "./defineProperty.js";
-
-function set(target, property, value, receiver) {
- if (typeof Reflect !== "undefined" && Reflect.set) {
- set = Reflect.set;
- } else {
- set = function set(target, property, value, receiver) {
- var base = superPropBase(target, property);
- var desc;
-
- if (base) {
- desc = Object.getOwnPropertyDescriptor(base, property);
-
- if (desc.set) {
- desc.set.call(receiver, value);
- return true;
- } else if (!desc.writable) {
- return false;
- }
- }
-
- desc = Object.getOwnPropertyDescriptor(receiver, property);
-
- if (desc) {
- if (!desc.writable) {
- return false;
- }
-
- desc.value = value;
- Object.defineProperty(receiver, property, desc);
- } else {
- defineProperty(receiver, property, value);
- }
-
- return true;
- };
- }
-
- return set(target, property, value, receiver);
-}
-
-export default function _set(target, property, value, receiver, isStrict) {
- var s = set(target, property, value, receiver || target);
-
- if (!s && isStrict) {
- throw new Error('failed to set property');
- }
-
- return value;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js b/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
deleted file mode 100644
index e6ef03e..0000000
--- a/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
+++ /dev/null
@@ -1,8 +0,0 @@
-export default function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
-
- return _setPrototypeOf(o, p);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js b/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js
deleted file mode 100644
index cadd9bb..0000000
--- a/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js
+++ /dev/null
@@ -1,7 +0,0 @@
-export default function _skipFirstGeneratorNext(fn) {
- return function () {
- var it = fn.apply(this, arguments);
- it.next();
- return it;
- };
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/slicedToArray.js b/node_modules/@babel/runtime/helpers/esm/slicedToArray.js
deleted file mode 100644
index 618200b..0000000
--- a/node_modules/@babel/runtime/helpers/esm/slicedToArray.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import arrayWithHoles from "./arrayWithHoles.js";
-import iterableToArrayLimit from "./iterableToArrayLimit.js";
-import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
-import nonIterableRest from "./nonIterableRest.js";
-export default function _slicedToArray(arr, i) {
- return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js b/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js
deleted file mode 100644
index efc7429..0000000
--- a/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import arrayWithHoles from "./arrayWithHoles.js";
-import iterableToArrayLimitLoose from "./iterableToArrayLimitLoose.js";
-import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
-import nonIterableRest from "./nonIterableRest.js";
-export default function _slicedToArrayLoose(arr, i) {
- return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/superPropBase.js b/node_modules/@babel/runtime/helpers/esm/superPropBase.js
deleted file mode 100644
index feffe6f..0000000
--- a/node_modules/@babel/runtime/helpers/esm/superPropBase.js
+++ /dev/null
@@ -1,9 +0,0 @@
-import getPrototypeOf from "./getPrototypeOf.js";
-export default function _superPropBase(object, property) {
- while (!Object.prototype.hasOwnProperty.call(object, property)) {
- object = getPrototypeOf(object);
- if (object === null) break;
- }
-
- return object;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js
deleted file mode 100644
index 421f18a..0000000
--- a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js
+++ /dev/null
@@ -1,11 +0,0 @@
-export default function _taggedTemplateLiteral(strings, raw) {
- if (!raw) {
- raw = strings.slice(0);
- }
-
- return Object.freeze(Object.defineProperties(strings, {
- raw: {
- value: Object.freeze(raw)
- }
- }));
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js
deleted file mode 100644
index c8f081e..0000000
--- a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js
+++ /dev/null
@@ -1,8 +0,0 @@
-export default function _taggedTemplateLiteralLoose(strings, raw) {
- if (!raw) {
- raw = strings.slice(0);
- }
-
- strings.raw = raw;
- return strings;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/tdz.js b/node_modules/@babel/runtime/helpers/esm/tdz.js
deleted file mode 100644
index d5d0adc..0000000
--- a/node_modules/@babel/runtime/helpers/esm/tdz.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _tdzError(name) {
- throw new ReferenceError(name + " is not defined - temporal dead zone");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/temporalRef.js b/node_modules/@babel/runtime/helpers/esm/temporalRef.js
deleted file mode 100644
index b25f7c4..0000000
--- a/node_modules/@babel/runtime/helpers/esm/temporalRef.js
+++ /dev/null
@@ -1,5 +0,0 @@
-import undef from "./temporalUndefined.js";
-import err from "./tdz.js";
-export default function _temporalRef(val, name) {
- return val === undef ? err(name) : val;
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js b/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js
deleted file mode 100644
index 1a35717..0000000
--- a/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js
+++ /dev/null
@@ -1 +0,0 @@
-export default function _temporalUndefined() {}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/toArray.js b/node_modules/@babel/runtime/helpers/esm/toArray.js
deleted file mode 100644
index ad7c871..0000000
--- a/node_modules/@babel/runtime/helpers/esm/toArray.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import arrayWithHoles from "./arrayWithHoles.js";
-import iterableToArray from "./iterableToArray.js";
-import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
-import nonIterableRest from "./nonIterableRest.js";
-export default function _toArray(arr) {
- return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js b/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js
deleted file mode 100644
index bd91285..0000000
--- a/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import arrayWithoutHoles from "./arrayWithoutHoles.js";
-import iterableToArray from "./iterableToArray.js";
-import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
-import nonIterableSpread from "./nonIterableSpread.js";
-export default function _toConsumableArray(arr) {
- return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/toPrimitive.js b/node_modules/@babel/runtime/helpers/esm/toPrimitive.js
deleted file mode 100644
index 4cb70a5..0000000
--- a/node_modules/@babel/runtime/helpers/esm/toPrimitive.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import _typeof from "@babel/runtime/helpers/typeof";
-export default function _toPrimitive(input, hint) {
- if (_typeof(input) !== "object" || input === null) return input;
- var prim = input[Symbol.toPrimitive];
-
- if (prim !== undefined) {
- var res = prim.call(input, hint || "default");
- if (_typeof(res) !== "object") return res;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
-
- return (hint === "string" ? String : Number)(input);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js b/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js
deleted file mode 100644
index f1ba8a2..0000000
--- a/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js
+++ /dev/null
@@ -1,6 +0,0 @@
-import _typeof from "@babel/runtime/helpers/typeof";
-import toPrimitive from "./toPrimitive.js";
-export default function _toPropertyKey(arg) {
- var key = toPrimitive(arg, "string");
- return _typeof(key) === "symbol" ? key : String(key);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/typeof.js b/node_modules/@babel/runtime/helpers/esm/typeof.js
deleted file mode 100644
index eb444f7..0000000
--- a/node_modules/@babel/runtime/helpers/esm/typeof.js
+++ /dev/null
@@ -1,15 +0,0 @@
-export default function _typeof(obj) {
- "@babel/helpers - typeof";
-
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- _typeof = function _typeof(obj) {
- return typeof obj;
- };
- } else {
- _typeof = function _typeof(obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- };
- }
-
- return _typeof(obj);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js b/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js
deleted file mode 100644
index c0f63bd..0000000
--- a/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js
+++ /dev/null
@@ -1,9 +0,0 @@
-import arrayLikeToArray from "./arrayLikeToArray.js";
-export default function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js
deleted file mode 100644
index 723b2dd..0000000
--- a/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js
+++ /dev/null
@@ -1,6 +0,0 @@
-import AsyncGenerator from "./AsyncGenerator.js";
-export default function _wrapAsyncGenerator(fn) {
- return function () {
- return new AsyncGenerator(fn.apply(this, arguments));
- };
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js b/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js
deleted file mode 100644
index 512630d..0000000
--- a/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js
+++ /dev/null
@@ -1,37 +0,0 @@
-import getPrototypeOf from "./getPrototypeOf.js";
-import setPrototypeOf from "./setPrototypeOf.js";
-import isNativeFunction from "./isNativeFunction.js";
-import construct from "./construct.js";
-export default function _wrapNativeSuper(Class) {
- var _cache = typeof Map === "function" ? new Map() : undefined;
-
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
- if (Class === null || !isNativeFunction(Class)) return Class;
-
- if (typeof Class !== "function") {
- throw new TypeError("Super expression must either be null or a function");
- }
-
- if (typeof _cache !== "undefined") {
- if (_cache.has(Class)) return _cache.get(Class);
-
- _cache.set(Class, Wrapper);
- }
-
- function Wrapper() {
- return construct(Class, arguments, getPrototypeOf(this).constructor);
- }
-
- Wrapper.prototype = Object.create(Class.prototype, {
- constructor: {
- value: Wrapper,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- return setPrototypeOf(Wrapper, Class);
- };
-
- return _wrapNativeSuper(Class);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js b/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js
deleted file mode 100644
index 4d65336..0000000
--- a/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js
+++ /dev/null
@@ -1,65 +0,0 @@
-import _typeof from "@babel/runtime/helpers/typeof";
-import setPrototypeOf from "./setPrototypeOf.js";
-import inherits from "./inherits.js";
-export default function _wrapRegExp() {
- _wrapRegExp = function _wrapRegExp(re, groups) {
- return new BabelRegExp(re, undefined, groups);
- };
-
- var _super = RegExp.prototype;
-
- var _groups = new WeakMap();
-
- function BabelRegExp(re, flags, groups) {
- var _this = new RegExp(re, flags);
-
- _groups.set(_this, groups || _groups.get(re));
-
- return setPrototypeOf(_this, BabelRegExp.prototype);
- }
-
- inherits(BabelRegExp, RegExp);
-
- BabelRegExp.prototype.exec = function (str) {
- var result = _super.exec.call(this, str);
-
- if (result) result.groups = buildGroups(result, this);
- return result;
- };
-
- BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {
- if (typeof substitution === "string") {
- var groups = _groups.get(this);
-
- return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
- return "$" + groups[name];
- }));
- } else if (typeof substitution === "function") {
- var _this = this;
-
- return _super[Symbol.replace].call(this, str, function () {
- var args = arguments;
-
- if (_typeof(args[args.length - 1]) !== "object") {
- args = [].slice.call(args);
- args.push(buildGroups(args, _this));
- }
-
- return substitution.apply(this, args);
- });
- } else {
- return _super[Symbol.replace].call(this, str, substitution);
- }
- };
-
- function buildGroups(result, re) {
- var g = _groups.get(re);
-
- return Object.keys(g).reduce(function (groups, name) {
- groups[name] = result[g[name]];
- return groups;
- }, Object.create(null));
- }
-
- return _wrapRegExp.apply(this, arguments);
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js b/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js
deleted file mode 100644
index 9170bd4..0000000
--- a/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function _writeOnlyError(name) {
- throw new TypeError("\"" + name + "\" is write-only");
-}
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/extends.js b/node_modules/@babel/runtime/helpers/extends.js
deleted file mode 100644
index eaf9547..0000000
--- a/node_modules/@babel/runtime/helpers/extends.js
+++ /dev/null
@@ -1,21 +0,0 @@
-function _extends() {
- module.exports = _extends = Object.assign || function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
-
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
-
- return target;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _extends.apply(this, arguments);
-}
-
-module.exports = _extends;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/get.js b/node_modules/@babel/runtime/helpers/get.js
deleted file mode 100644
index 3ed600f..0000000
--- a/node_modules/@babel/runtime/helpers/get.js
+++ /dev/null
@@ -1,27 +0,0 @@
-var superPropBase = require("./superPropBase.js");
-
-function _get(target, property, receiver) {
- if (typeof Reflect !== "undefined" && Reflect.get) {
- module.exports = _get = Reflect.get;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- } else {
- module.exports = _get = function _get(target, property, receiver) {
- var base = superPropBase(target, property);
- if (!base) return;
- var desc = Object.getOwnPropertyDescriptor(base, property);
-
- if (desc.get) {
- return desc.get.call(receiver);
- }
-
- return desc.value;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- }
-
- return _get(target, property, receiver || target);
-}
-
-module.exports = _get;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/getPrototypeOf.js b/node_modules/@babel/runtime/helpers/getPrototypeOf.js
deleted file mode 100644
index a6916eb..0000000
--- a/node_modules/@babel/runtime/helpers/getPrototypeOf.js
+++ /dev/null
@@ -1,10 +0,0 @@
-function _getPrototypeOf(o) {
- module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _getPrototypeOf(o);
-}
-
-module.exports = _getPrototypeOf;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/inherits.js b/node_modules/@babel/runtime/helpers/inherits.js
deleted file mode 100644
index 3003e01..0000000
--- a/node_modules/@babel/runtime/helpers/inherits.js
+++ /dev/null
@@ -1,19 +0,0 @@
-var setPrototypeOf = require("./setPrototypeOf.js");
-
-function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
-
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
- });
- if (superClass) setPrototypeOf(subClass, superClass);
-}
-
-module.exports = _inherits;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/inheritsLoose.js b/node_modules/@babel/runtime/helpers/inheritsLoose.js
deleted file mode 100644
index 93e4305..0000000
--- a/node_modules/@babel/runtime/helpers/inheritsLoose.js
+++ /dev/null
@@ -1,10 +0,0 @@
-var setPrototypeOf = require("./setPrototypeOf.js");
-
-function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- setPrototypeOf(subClass, superClass);
-}
-
-module.exports = _inheritsLoose;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/initializerDefineProperty.js b/node_modules/@babel/runtime/helpers/initializerDefineProperty.js
deleted file mode 100644
index 6b1069e..0000000
--- a/node_modules/@babel/runtime/helpers/initializerDefineProperty.js
+++ /dev/null
@@ -1,12 +0,0 @@
-function _initializerDefineProperty(target, property, descriptor, context) {
- if (!descriptor) return;
- Object.defineProperty(target, property, {
- enumerable: descriptor.enumerable,
- configurable: descriptor.configurable,
- writable: descriptor.writable,
- value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
- });
-}
-
-module.exports = _initializerDefineProperty;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/initializerWarningHelper.js b/node_modules/@babel/runtime/helpers/initializerWarningHelper.js
deleted file mode 100644
index 9d02886..0000000
--- a/node_modules/@babel/runtime/helpers/initializerWarningHelper.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _initializerWarningHelper(descriptor, context) {
- throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.');
-}
-
-module.exports = _initializerWarningHelper;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/instanceof.js b/node_modules/@babel/runtime/helpers/instanceof.js
deleted file mode 100644
index 654ebc8..0000000
--- a/node_modules/@babel/runtime/helpers/instanceof.js
+++ /dev/null
@@ -1,10 +0,0 @@
-function _instanceof(left, right) {
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
- return !!right[Symbol.hasInstance](left);
- } else {
- return left instanceof right;
- }
-}
-
-module.exports = _instanceof;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/interopRequireDefault.js b/node_modules/@babel/runtime/helpers/interopRequireDefault.js
deleted file mode 100644
index 6a21368..0000000
--- a/node_modules/@babel/runtime/helpers/interopRequireDefault.js
+++ /dev/null
@@ -1,8 +0,0 @@
-function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- "default": obj
- };
-}
-
-module.exports = _interopRequireDefault;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/interopRequireWildcard.js b/node_modules/@babel/runtime/helpers/interopRequireWildcard.js
deleted file mode 100644
index 635f8bb..0000000
--- a/node_modules/@babel/runtime/helpers/interopRequireWildcard.js
+++ /dev/null
@@ -1,54 +0,0 @@
-var _typeof = require("@babel/runtime/helpers/typeof")["default"];
-
-function _getRequireWildcardCache(nodeInterop) {
- if (typeof WeakMap !== "function") return null;
- var cacheBabelInterop = new WeakMap();
- var cacheNodeInterop = new WeakMap();
- return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) {
- return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
- })(nodeInterop);
-}
-
-function _interopRequireWildcard(obj, nodeInterop) {
- if (!nodeInterop && obj && obj.__esModule) {
- return obj;
- }
-
- if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
- return {
- "default": obj
- };
- }
-
- var cache = _getRequireWildcardCache(nodeInterop);
-
- if (cache && cache.has(obj)) {
- return cache.get(obj);
- }
-
- var newObj = {};
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
-
- for (var key in obj) {
- if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
-
- if (desc && (desc.get || desc.set)) {
- Object.defineProperty(newObj, key, desc);
- } else {
- newObj[key] = obj[key];
- }
- }
- }
-
- newObj["default"] = obj;
-
- if (cache) {
- cache.set(obj, newObj);
- }
-
- return newObj;
-}
-
-module.exports = _interopRequireWildcard;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/isNativeFunction.js b/node_modules/@babel/runtime/helpers/isNativeFunction.js
deleted file mode 100644
index 50eb8f5..0000000
--- a/node_modules/@babel/runtime/helpers/isNativeFunction.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _isNativeFunction(fn) {
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
-}
-
-module.exports = _isNativeFunction;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js b/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js
deleted file mode 100644
index 3a201a6..0000000
--- a/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js
+++ /dev/null
@@ -1,15 +0,0 @@
-function _isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
-
- try {
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
-}
-
-module.exports = _isNativeReflectConstruct;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/iterableToArray.js b/node_modules/@babel/runtime/helpers/iterableToArray.js
deleted file mode 100644
index 03f955d..0000000
--- a/node_modules/@babel/runtime/helpers/iterableToArray.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _iterableToArray(iter) {
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
-}
-
-module.exports = _iterableToArray;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js b/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js
deleted file mode 100644
index da9cee0..0000000
--- a/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js
+++ /dev/null
@@ -1,32 +0,0 @@
-function _iterableToArrayLimit(arr, i) {
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
-
- if (_i == null) return;
- var _arr = [];
- var _n = true;
- var _d = false;
-
- var _s, _e;
-
- try {
- for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
- _arr.push(_s.value);
-
- if (i && _arr.length === i) break;
- }
- } catch (err) {
- _d = true;
- _e = err;
- } finally {
- try {
- if (!_n && _i["return"] != null) _i["return"]();
- } finally {
- if (_d) throw _e;
- }
- }
-
- return _arr;
-}
-
-module.exports = _iterableToArrayLimit;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js b/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js
deleted file mode 100644
index fb05b12..0000000
--- a/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js
+++ /dev/null
@@ -1,17 +0,0 @@
-function _iterableToArrayLimitLoose(arr, i) {
- var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
-
- if (_i == null) return;
- var _arr = [];
-
- for (_i = _i.call(arr), _step; !(_step = _i.next()).done;) {
- _arr.push(_step.value);
-
- if (i && _arr.length === i) break;
- }
-
- return _arr;
-}
-
-module.exports = _iterableToArrayLimitLoose;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/jsx.js b/node_modules/@babel/runtime/helpers/jsx.js
deleted file mode 100644
index 21ac847..0000000
--- a/node_modules/@babel/runtime/helpers/jsx.js
+++ /dev/null
@@ -1,50 +0,0 @@
-var REACT_ELEMENT_TYPE;
-
-function _createRawReactElement(type, props, key, children) {
- if (!REACT_ELEMENT_TYPE) {
- REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7;
- }
-
- var defaultProps = type && type.defaultProps;
- var childrenLength = arguments.length - 3;
-
- if (!props && childrenLength !== 0) {
- props = {
- children: void 0
- };
- }
-
- if (childrenLength === 1) {
- props.children = children;
- } else if (childrenLength > 1) {
- var childArray = new Array(childrenLength);
-
- for (var i = 0; i < childrenLength; i++) {
- childArray[i] = arguments[i + 3];
- }
-
- props.children = childArray;
- }
-
- if (props && defaultProps) {
- for (var propName in defaultProps) {
- if (props[propName] === void 0) {
- props[propName] = defaultProps[propName];
- }
- }
- } else if (!props) {
- props = defaultProps || {};
- }
-
- return {
- $$typeof: REACT_ELEMENT_TYPE,
- type: type,
- key: key === undefined ? null : "" + key,
- ref: null,
- props: props,
- _owner: null
- };
-}
-
-module.exports = _createRawReactElement;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/maybeArrayLike.js b/node_modules/@babel/runtime/helpers/maybeArrayLike.js
deleted file mode 100644
index 3ab618b..0000000
--- a/node_modules/@babel/runtime/helpers/maybeArrayLike.js
+++ /dev/null
@@ -1,13 +0,0 @@
-var arrayLikeToArray = require("./arrayLikeToArray.js");
-
-function _maybeArrayLike(next, arr, i) {
- if (arr && !Array.isArray(arr) && typeof arr.length === "number") {
- var len = arr.length;
- return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len);
- }
-
- return next(arr, i);
-}
-
-module.exports = _maybeArrayLike;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/newArrowCheck.js b/node_modules/@babel/runtime/helpers/newArrowCheck.js
deleted file mode 100644
index 8d7570b..0000000
--- a/node_modules/@babel/runtime/helpers/newArrowCheck.js
+++ /dev/null
@@ -1,8 +0,0 @@
-function _newArrowCheck(innerThis, boundThis) {
- if (innerThis !== boundThis) {
- throw new TypeError("Cannot instantiate an arrow function");
- }
-}
-
-module.exports = _newArrowCheck;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/nonIterableRest.js b/node_modules/@babel/runtime/helpers/nonIterableRest.js
deleted file mode 100644
index 22be4f5..0000000
--- a/node_modules/@babel/runtime/helpers/nonIterableRest.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _nonIterableRest() {
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
-}
-
-module.exports = _nonIterableRest;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/nonIterableSpread.js b/node_modules/@babel/runtime/helpers/nonIterableSpread.js
deleted file mode 100644
index 4ba722d..0000000
--- a/node_modules/@babel/runtime/helpers/nonIterableSpread.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
-}
-
-module.exports = _nonIterableSpread;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js b/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js
deleted file mode 100644
index 1bb88ac..0000000
--- a/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _objectDestructuringEmpty(obj) {
- if (obj == null) throw new TypeError("Cannot destructure undefined");
-}
-
-module.exports = _objectDestructuringEmpty;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/objectSpread.js b/node_modules/@babel/runtime/helpers/objectSpread.js
deleted file mode 100644
index 00af209..0000000
--- a/node_modules/@babel/runtime/helpers/objectSpread.js
+++ /dev/null
@@ -1,23 +0,0 @@
-var defineProperty = require("./defineProperty.js");
-
-function _objectSpread(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i] != null ? Object(arguments[i]) : {};
- var ownKeys = Object.keys(source);
-
- if (typeof Object.getOwnPropertySymbols === 'function') {
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
- }));
- }
-
- ownKeys.forEach(function (key) {
- defineProperty(target, key, source[key]);
- });
- }
-
- return target;
-}
-
-module.exports = _objectSpread;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/objectSpread2.js b/node_modules/@babel/runtime/helpers/objectSpread2.js
deleted file mode 100644
index 337d30e..0000000
--- a/node_modules/@babel/runtime/helpers/objectSpread2.js
+++ /dev/null
@@ -1,42 +0,0 @@
-var defineProperty = require("./defineProperty.js");
-
-function ownKeys(object, enumerableOnly) {
- var keys = Object.keys(object);
-
- if (Object.getOwnPropertySymbols) {
- var symbols = Object.getOwnPropertySymbols(object);
-
- if (enumerableOnly) {
- symbols = symbols.filter(function (sym) {
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
- });
- }
-
- keys.push.apply(keys, symbols);
- }
-
- return keys;
-}
-
-function _objectSpread2(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i] != null ? arguments[i] : {};
-
- if (i % 2) {
- ownKeys(Object(source), true).forEach(function (key) {
- defineProperty(target, key, source[key]);
- });
- } else if (Object.getOwnPropertyDescriptors) {
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
- } else {
- ownKeys(Object(source)).forEach(function (key) {
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
- });
- }
- }
-
- return target;
-}
-
-module.exports = _objectSpread2;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/objectWithoutProperties.js b/node_modules/@babel/runtime/helpers/objectWithoutProperties.js
deleted file mode 100644
index c000db7..0000000
--- a/node_modules/@babel/runtime/helpers/objectWithoutProperties.js
+++ /dev/null
@@ -1,23 +0,0 @@
-var objectWithoutPropertiesLoose = require("./objectWithoutPropertiesLoose.js");
-
-function _objectWithoutProperties(source, excluded) {
- if (source == null) return {};
- var target = objectWithoutPropertiesLoose(source, excluded);
- var key, i;
-
- if (Object.getOwnPropertySymbols) {
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
-
- for (i = 0; i < sourceSymbolKeys.length; i++) {
- key = sourceSymbolKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
- target[key] = source[key];
- }
- }
-
- return target;
-}
-
-module.exports = _objectWithoutProperties;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js b/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js
deleted file mode 100644
index d9a73de..0000000
--- a/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js
+++ /dev/null
@@ -1,17 +0,0 @@
-function _objectWithoutPropertiesLoose(source, excluded) {
- if (source == null) return {};
- var target = {};
- var sourceKeys = Object.keys(source);
- var key, i;
-
- for (i = 0; i < sourceKeys.length; i++) {
- key = sourceKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- target[key] = source[key];
- }
-
- return target;
-}
-
-module.exports = _objectWithoutPropertiesLoose;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js b/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js
deleted file mode 100644
index 259ea2b..0000000
--- a/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var _typeof = require("@babel/runtime/helpers/typeof")["default"];
-
-var assertThisInitialized = require("./assertThisInitialized.js");
-
-function _possibleConstructorReturn(self, call) {
- if (call && (_typeof(call) === "object" || typeof call === "function")) {
- return call;
- }
-
- return assertThisInitialized(self);
-}
-
-module.exports = _possibleConstructorReturn;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/readOnlyError.js b/node_modules/@babel/runtime/helpers/readOnlyError.js
deleted file mode 100644
index e805f89..0000000
--- a/node_modules/@babel/runtime/helpers/readOnlyError.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _readOnlyError(name) {
- throw new TypeError("\"" + name + "\" is read-only");
-}
-
-module.exports = _readOnlyError;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/set.js b/node_modules/@babel/runtime/helpers/set.js
deleted file mode 100644
index b7d184d..0000000
--- a/node_modules/@babel/runtime/helpers/set.js
+++ /dev/null
@@ -1,55 +0,0 @@
-var superPropBase = require("./superPropBase.js");
-
-var defineProperty = require("./defineProperty.js");
-
-function set(target, property, value, receiver) {
- if (typeof Reflect !== "undefined" && Reflect.set) {
- set = Reflect.set;
- } else {
- set = function set(target, property, value, receiver) {
- var base = superPropBase(target, property);
- var desc;
-
- if (base) {
- desc = Object.getOwnPropertyDescriptor(base, property);
-
- if (desc.set) {
- desc.set.call(receiver, value);
- return true;
- } else if (!desc.writable) {
- return false;
- }
- }
-
- desc = Object.getOwnPropertyDescriptor(receiver, property);
-
- if (desc) {
- if (!desc.writable) {
- return false;
- }
-
- desc.value = value;
- Object.defineProperty(receiver, property, desc);
- } else {
- defineProperty(receiver, property, value);
- }
-
- return true;
- };
- }
-
- return set(target, property, value, receiver);
-}
-
-function _set(target, property, value, receiver, isStrict) {
- var s = set(target, property, value, receiver || target);
-
- if (!s && isStrict) {
- throw new Error('failed to set property');
- }
-
- return value;
-}
-
-module.exports = _set;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/setPrototypeOf.js b/node_modules/@babel/runtime/helpers/setPrototypeOf.js
deleted file mode 100644
index 415797b..0000000
--- a/node_modules/@babel/runtime/helpers/setPrototypeOf.js
+++ /dev/null
@@ -1,12 +0,0 @@
-function _setPrototypeOf(o, p) {
- module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _setPrototypeOf(o, p);
-}
-
-module.exports = _setPrototypeOf;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js b/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js
deleted file mode 100644
index ed60585..0000000
--- a/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js
+++ /dev/null
@@ -1,10 +0,0 @@
-function _skipFirstGeneratorNext(fn) {
- return function () {
- var it = fn.apply(this, arguments);
- it.next();
- return it;
- };
-}
-
-module.exports = _skipFirstGeneratorNext;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/slicedToArray.js b/node_modules/@babel/runtime/helpers/slicedToArray.js
deleted file mode 100644
index 101f404..0000000
--- a/node_modules/@babel/runtime/helpers/slicedToArray.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var arrayWithHoles = require("./arrayWithHoles.js");
-
-var iterableToArrayLimit = require("./iterableToArrayLimit.js");
-
-var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
-
-var nonIterableRest = require("./nonIterableRest.js");
-
-function _slicedToArray(arr, i) {
- return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
-}
-
-module.exports = _slicedToArray;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js b/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js
deleted file mode 100644
index 188db63..0000000
--- a/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var arrayWithHoles = require("./arrayWithHoles.js");
-
-var iterableToArrayLimitLoose = require("./iterableToArrayLimitLoose.js");
-
-var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
-
-var nonIterableRest = require("./nonIterableRest.js");
-
-function _slicedToArrayLoose(arr, i) {
- return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
-}
-
-module.exports = _slicedToArrayLoose;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/superPropBase.js b/node_modules/@babel/runtime/helpers/superPropBase.js
deleted file mode 100644
index ce12a88..0000000
--- a/node_modules/@babel/runtime/helpers/superPropBase.js
+++ /dev/null
@@ -1,13 +0,0 @@
-var getPrototypeOf = require("./getPrototypeOf.js");
-
-function _superPropBase(object, property) {
- while (!Object.prototype.hasOwnProperty.call(object, property)) {
- object = getPrototypeOf(object);
- if (object === null) break;
- }
-
- return object;
-}
-
-module.exports = _superPropBase;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js b/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js
deleted file mode 100644
index 1a524b3..0000000
--- a/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js
+++ /dev/null
@@ -1,14 +0,0 @@
-function _taggedTemplateLiteral(strings, raw) {
- if (!raw) {
- raw = strings.slice(0);
- }
-
- return Object.freeze(Object.defineProperties(strings, {
- raw: {
- value: Object.freeze(raw)
- }
- }));
-}
-
-module.exports = _taggedTemplateLiteral;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js b/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js
deleted file mode 100644
index ab78e62..0000000
--- a/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js
+++ /dev/null
@@ -1,11 +0,0 @@
-function _taggedTemplateLiteralLoose(strings, raw) {
- if (!raw) {
- raw = strings.slice(0);
- }
-
- strings.raw = raw;
- return strings;
-}
-
-module.exports = _taggedTemplateLiteralLoose;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/tdz.js b/node_modules/@babel/runtime/helpers/tdz.js
deleted file mode 100644
index a5b35a6..0000000
--- a/node_modules/@babel/runtime/helpers/tdz.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _tdzError(name) {
- throw new ReferenceError(name + " is not defined - temporal dead zone");
-}
-
-module.exports = _tdzError;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/temporalRef.js b/node_modules/@babel/runtime/helpers/temporalRef.js
deleted file mode 100644
index d4e9460..0000000
--- a/node_modules/@babel/runtime/helpers/temporalRef.js
+++ /dev/null
@@ -1,10 +0,0 @@
-var temporalUndefined = require("./temporalUndefined.js");
-
-var tdz = require("./tdz.js");
-
-function _temporalRef(val, name) {
- return val === temporalUndefined ? tdz(name) : val;
-}
-
-module.exports = _temporalRef;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/temporalUndefined.js b/node_modules/@babel/runtime/helpers/temporalUndefined.js
deleted file mode 100644
index aeae645..0000000
--- a/node_modules/@babel/runtime/helpers/temporalUndefined.js
+++ /dev/null
@@ -1,4 +0,0 @@
-function _temporalUndefined() {}
-
-module.exports = _temporalUndefined;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/toArray.js b/node_modules/@babel/runtime/helpers/toArray.js
deleted file mode 100644
index 3b911bd..0000000
--- a/node_modules/@babel/runtime/helpers/toArray.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var arrayWithHoles = require("./arrayWithHoles.js");
-
-var iterableToArray = require("./iterableToArray.js");
-
-var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
-
-var nonIterableRest = require("./nonIterableRest.js");
-
-function _toArray(arr) {
- return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
-}
-
-module.exports = _toArray;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/toConsumableArray.js b/node_modules/@babel/runtime/helpers/toConsumableArray.js
deleted file mode 100644
index f084cd1..0000000
--- a/node_modules/@babel/runtime/helpers/toConsumableArray.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var arrayWithoutHoles = require("./arrayWithoutHoles.js");
-
-var iterableToArray = require("./iterableToArray.js");
-
-var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
-
-var nonIterableSpread = require("./nonIterableSpread.js");
-
-function _toConsumableArray(arr) {
- return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
-}
-
-module.exports = _toConsumableArray;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/toPrimitive.js b/node_modules/@babel/runtime/helpers/toPrimitive.js
deleted file mode 100644
index ac40338..0000000
--- a/node_modules/@babel/runtime/helpers/toPrimitive.js
+++ /dev/null
@@ -1,17 +0,0 @@
-var _typeof = require("@babel/runtime/helpers/typeof")["default"];
-
-function _toPrimitive(input, hint) {
- if (_typeof(input) !== "object" || input === null) return input;
- var prim = input[Symbol.toPrimitive];
-
- if (prim !== undefined) {
- var res = prim.call(input, hint || "default");
- if (_typeof(res) !== "object") return res;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
-
- return (hint === "string" ? String : Number)(input);
-}
-
-module.exports = _toPrimitive;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/toPropertyKey.js b/node_modules/@babel/runtime/helpers/toPropertyKey.js
deleted file mode 100644
index 066b3f2..0000000
--- a/node_modules/@babel/runtime/helpers/toPropertyKey.js
+++ /dev/null
@@ -1,11 +0,0 @@
-var _typeof = require("@babel/runtime/helpers/typeof")["default"];
-
-var toPrimitive = require("./toPrimitive.js");
-
-function _toPropertyKey(arg) {
- var key = toPrimitive(arg, "string");
- return _typeof(key) === "symbol" ? key : String(key);
-}
-
-module.exports = _toPropertyKey;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/typeof.js b/node_modules/@babel/runtime/helpers/typeof.js
deleted file mode 100644
index 02a5d8a..0000000
--- a/node_modules/@babel/runtime/helpers/typeof.js
+++ /dev/null
@@ -1,22 +0,0 @@
-function _typeof(obj) {
- "@babel/helpers - typeof";
-
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- module.exports = _typeof = function _typeof(obj) {
- return typeof obj;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- } else {
- module.exports = _typeof = function _typeof(obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- }
-
- return _typeof(obj);
-}
-
-module.exports = _typeof;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js b/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js
deleted file mode 100644
index 11bca7b..0000000
--- a/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js
+++ /dev/null
@@ -1,13 +0,0 @@
-var arrayLikeToArray = require("./arrayLikeToArray.js");
-
-function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
-}
-
-module.exports = _unsupportedIterableToArray;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js b/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js
deleted file mode 100644
index 057cd19..0000000
--- a/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js
+++ /dev/null
@@ -1,10 +0,0 @@
-var AsyncGenerator = require("./AsyncGenerator.js");
-
-function _wrapAsyncGenerator(fn) {
- return function () {
- return new AsyncGenerator(fn.apply(this, arguments));
- };
-}
-
-module.exports = _wrapAsyncGenerator;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/wrapNativeSuper.js b/node_modules/@babel/runtime/helpers/wrapNativeSuper.js
deleted file mode 100644
index 981c8dd..0000000
--- a/node_modules/@babel/runtime/helpers/wrapNativeSuper.js
+++ /dev/null
@@ -1,45 +0,0 @@
-var getPrototypeOf = require("./getPrototypeOf.js");
-
-var setPrototypeOf = require("./setPrototypeOf.js");
-
-var isNativeFunction = require("./isNativeFunction.js");
-
-var construct = require("./construct.js");
-
-function _wrapNativeSuper(Class) {
- var _cache = typeof Map === "function" ? new Map() : undefined;
-
- module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {
- if (Class === null || !isNativeFunction(Class)) return Class;
-
- if (typeof Class !== "function") {
- throw new TypeError("Super expression must either be null or a function");
- }
-
- if (typeof _cache !== "undefined") {
- if (_cache.has(Class)) return _cache.get(Class);
-
- _cache.set(Class, Wrapper);
- }
-
- function Wrapper() {
- return construct(Class, arguments, getPrototypeOf(this).constructor);
- }
-
- Wrapper.prototype = Object.create(Class.prototype, {
- constructor: {
- value: Wrapper,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- return setPrototypeOf(Wrapper, Class);
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _wrapNativeSuper(Class);
-}
-
-module.exports = _wrapNativeSuper;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/wrapRegExp.js b/node_modules/@babel/runtime/helpers/wrapRegExp.js
deleted file mode 100644
index e80a8b6..0000000
--- a/node_modules/@babel/runtime/helpers/wrapRegExp.js
+++ /dev/null
@@ -1,72 +0,0 @@
-var _typeof = require("@babel/runtime/helpers/typeof")["default"];
-
-var setPrototypeOf = require("./setPrototypeOf.js");
-
-var inherits = require("./inherits.js");
-
-function _wrapRegExp() {
- module.exports = _wrapRegExp = function _wrapRegExp(re, groups) {
- return new BabelRegExp(re, undefined, groups);
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- var _super = RegExp.prototype;
-
- var _groups = new WeakMap();
-
- function BabelRegExp(re, flags, groups) {
- var _this = new RegExp(re, flags);
-
- _groups.set(_this, groups || _groups.get(re));
-
- return setPrototypeOf(_this, BabelRegExp.prototype);
- }
-
- inherits(BabelRegExp, RegExp);
-
- BabelRegExp.prototype.exec = function (str) {
- var result = _super.exec.call(this, str);
-
- if (result) result.groups = buildGroups(result, this);
- return result;
- };
-
- BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {
- if (typeof substitution === "string") {
- var groups = _groups.get(this);
-
- return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) {
- return "$" + groups[name];
- }));
- } else if (typeof substitution === "function") {
- var _this = this;
-
- return _super[Symbol.replace].call(this, str, function () {
- var args = arguments;
-
- if (_typeof(args[args.length - 1]) !== "object") {
- args = [].slice.call(args);
- args.push(buildGroups(args, _this));
- }
-
- return substitution.apply(this, args);
- });
- } else {
- return _super[Symbol.replace].call(this, str, substitution);
- }
- };
-
- function buildGroups(result, re) {
- var g = _groups.get(re);
-
- return Object.keys(g).reduce(function (groups, name) {
- groups[name] = result[g[name]];
- return groups;
- }, Object.create(null));
- }
-
- return _wrapRegExp.apply(this, arguments);
-}
-
-module.exports = _wrapRegExp;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/helpers/writeOnlyError.js b/node_modules/@babel/runtime/helpers/writeOnlyError.js
deleted file mode 100644
index 6751a74..0000000
--- a/node_modules/@babel/runtime/helpers/writeOnlyError.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function _writeOnlyError(name) {
- throw new TypeError("\"" + name + "\" is write-only");
-}
-
-module.exports = _writeOnlyError;
-module.exports["default"] = module.exports, module.exports.__esModule = true;
\ No newline at end of file
diff --git a/node_modules/@babel/runtime/package.json b/node_modules/@babel/runtime/package.json
deleted file mode 100644
index 8433f5a..0000000
--- a/node_modules/@babel/runtime/package.json
+++ /dev/null
@@ -1,861 +0,0 @@
-{
- "_from": "@babel/runtime@^7.12.5",
- "_id": "@babel/runtime@7.14.6",
- "_inBundle": false,
- "_integrity": "sha512-/PCB2uJ7oM44tz8YhC4Z/6PeOKXp4K588f+5M3clr1M4zbqztlo0XEfJ2LEzj/FgwfgGcIdl8n7YYjTCI0BYwg==",
- "_location": "/@babel/runtime",
- "_phantomChildren": {},
- "_requested": {
- "type": "range",
- "registry": true,
- "raw": "@babel/runtime@^7.12.5",
- "name": "@babel/runtime",
- "escapedName": "@babel%2fruntime",
- "scope": "@babel",
- "rawSpec": "^7.12.5",
- "saveSpec": null,
- "fetchSpec": "^7.12.5"
- },
- "_requiredBy": [
- "/@videojs/http-streaming",
- "/@videojs/vhs-utils",
- "/@videojs/xhr",
- "/aes-decrypter",
- "/m3u8-parser",
- "/mpd-parser",
- "/mux.js",
- "/pkcs7",
- "/video.js"
- ],
- "_resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.14.6.tgz",
- "_shasum": "535203bc0892efc7dec60bdc27b2ecf6e409062d",
- "_spec": "@babel/runtime@^7.12.5",
- "_where": "F:\\Documents\\websites\\BMM\\node_modules\\video.js",
- "author": {
- "name": "The Babel Team",
- "url": "https://babel.dev/team"
- },
- "bugs": {
- "url": "https://github.com/babel/babel/issues"
- },
- "bundleDependencies": false,
- "dependencies": {
- "regenerator-runtime": "^0.13.4"
- },
- "deprecated": false,
- "description": "babel's modular runtime helpers",
- "engines": {
- "node": ">=6.9.0"
- },
- "exports": {
- "./helpers/jsx": [
- {
- "node": "./helpers/jsx.js",
- "import": "./helpers/esm/jsx.js",
- "default": "./helpers/jsx.js"
- },
- "./helpers/jsx.js"
- ],
- "./helpers/esm/jsx": "./helpers/esm/jsx.js",
- "./helpers/objectSpread2": [
- {
- "node": "./helpers/objectSpread2.js",
- "import": "./helpers/esm/objectSpread2.js",
- "default": "./helpers/objectSpread2.js"
- },
- "./helpers/objectSpread2.js"
- ],
- "./helpers/esm/objectSpread2": "./helpers/esm/objectSpread2.js",
- "./helpers/typeof": [
- {
- "node": "./helpers/typeof.js",
- "import": "./helpers/esm/typeof.js",
- "default": "./helpers/typeof.js"
- },
- "./helpers/typeof.js"
- ],
- "./helpers/esm/typeof": "./helpers/esm/typeof.js",
- "./helpers/wrapRegExp": [
- {
- "node": "./helpers/wrapRegExp.js",
- "import": "./helpers/esm/wrapRegExp.js",
- "default": "./helpers/wrapRegExp.js"
- },
- "./helpers/wrapRegExp.js"
- ],
- "./helpers/esm/wrapRegExp": "./helpers/esm/wrapRegExp.js",
- "./helpers/asyncIterator": [
- {
- "node": "./helpers/asyncIterator.js",
- "import": "./helpers/esm/asyncIterator.js",
- "default": "./helpers/asyncIterator.js"
- },
- "./helpers/asyncIterator.js"
- ],
- "./helpers/esm/asyncIterator": "./helpers/esm/asyncIterator.js",
- "./helpers/AwaitValue": [
- {
- "node": "./helpers/AwaitValue.js",
- "import": "./helpers/esm/AwaitValue.js",
- "default": "./helpers/AwaitValue.js"
- },
- "./helpers/AwaitValue.js"
- ],
- "./helpers/esm/AwaitValue": "./helpers/esm/AwaitValue.js",
- "./helpers/AsyncGenerator": [
- {
- "node": "./helpers/AsyncGenerator.js",
- "import": "./helpers/esm/AsyncGenerator.js",
- "default": "./helpers/AsyncGenerator.js"
- },
- "./helpers/AsyncGenerator.js"
- ],
- "./helpers/esm/AsyncGenerator": "./helpers/esm/AsyncGenerator.js",
- "./helpers/wrapAsyncGenerator": [
- {
- "node": "./helpers/wrapAsyncGenerator.js",
- "import": "./helpers/esm/wrapAsyncGenerator.js",
- "default": "./helpers/wrapAsyncGenerator.js"
- },
- "./helpers/wrapAsyncGenerator.js"
- ],
- "./helpers/esm/wrapAsyncGenerator": "./helpers/esm/wrapAsyncGenerator.js",
- "./helpers/awaitAsyncGenerator": [
- {
- "node": "./helpers/awaitAsyncGenerator.js",
- "import": "./helpers/esm/awaitAsyncGenerator.js",
- "default": "./helpers/awaitAsyncGenerator.js"
- },
- "./helpers/awaitAsyncGenerator.js"
- ],
- "./helpers/esm/awaitAsyncGenerator": "./helpers/esm/awaitAsyncGenerator.js",
- "./helpers/asyncGeneratorDelegate": [
- {
- "node": "./helpers/asyncGeneratorDelegate.js",
- "import": "./helpers/esm/asyncGeneratorDelegate.js",
- "default": "./helpers/asyncGeneratorDelegate.js"
- },
- "./helpers/asyncGeneratorDelegate.js"
- ],
- "./helpers/esm/asyncGeneratorDelegate": "./helpers/esm/asyncGeneratorDelegate.js",
- "./helpers/asyncToGenerator": [
- {
- "node": "./helpers/asyncToGenerator.js",
- "import": "./helpers/esm/asyncToGenerator.js",
- "default": "./helpers/asyncToGenerator.js"
- },
- "./helpers/asyncToGenerator.js"
- ],
- "./helpers/esm/asyncToGenerator": "./helpers/esm/asyncToGenerator.js",
- "./helpers/classCallCheck": [
- {
- "node": "./helpers/classCallCheck.js",
- "import": "./helpers/esm/classCallCheck.js",
- "default": "./helpers/classCallCheck.js"
- },
- "./helpers/classCallCheck.js"
- ],
- "./helpers/esm/classCallCheck": "./helpers/esm/classCallCheck.js",
- "./helpers/createClass": [
- {
- "node": "./helpers/createClass.js",
- "import": "./helpers/esm/createClass.js",
- "default": "./helpers/createClass.js"
- },
- "./helpers/createClass.js"
- ],
- "./helpers/esm/createClass": "./helpers/esm/createClass.js",
- "./helpers/defineEnumerableProperties": [
- {
- "node": "./helpers/defineEnumerableProperties.js",
- "import": "./helpers/esm/defineEnumerableProperties.js",
- "default": "./helpers/defineEnumerableProperties.js"
- },
- "./helpers/defineEnumerableProperties.js"
- ],
- "./helpers/esm/defineEnumerableProperties": "./helpers/esm/defineEnumerableProperties.js",
- "./helpers/defaults": [
- {
- "node": "./helpers/defaults.js",
- "import": "./helpers/esm/defaults.js",
- "default": "./helpers/defaults.js"
- },
- "./helpers/defaults.js"
- ],
- "./helpers/esm/defaults": "./helpers/esm/defaults.js",
- "./helpers/defineProperty": [
- {
- "node": "./helpers/defineProperty.js",
- "import": "./helpers/esm/defineProperty.js",
- "default": "./helpers/defineProperty.js"
- },
- "./helpers/defineProperty.js"
- ],
- "./helpers/esm/defineProperty": "./helpers/esm/defineProperty.js",
- "./helpers/extends": [
- {
- "node": "./helpers/extends.js",
- "import": "./helpers/esm/extends.js",
- "default": "./helpers/extends.js"
- },
- "./helpers/extends.js"
- ],
- "./helpers/esm/extends": "./helpers/esm/extends.js",
- "./helpers/objectSpread": [
- {
- "node": "./helpers/objectSpread.js",
- "import": "./helpers/esm/objectSpread.js",
- "default": "./helpers/objectSpread.js"
- },
- "./helpers/objectSpread.js"
- ],
- "./helpers/esm/objectSpread": "./helpers/esm/objectSpread.js",
- "./helpers/inherits": [
- {
- "node": "./helpers/inherits.js",
- "import": "./helpers/esm/inherits.js",
- "default": "./helpers/inherits.js"
- },
- "./helpers/inherits.js"
- ],
- "./helpers/esm/inherits": "./helpers/esm/inherits.js",
- "./helpers/inheritsLoose": [
- {
- "node": "./helpers/inheritsLoose.js",
- "import": "./helpers/esm/inheritsLoose.js",
- "default": "./helpers/inheritsLoose.js"
- },
- "./helpers/inheritsLoose.js"
- ],
- "./helpers/esm/inheritsLoose": "./helpers/esm/inheritsLoose.js",
- "./helpers/getPrototypeOf": [
- {
- "node": "./helpers/getPrototypeOf.js",
- "import": "./helpers/esm/getPrototypeOf.js",
- "default": "./helpers/getPrototypeOf.js"
- },
- "./helpers/getPrototypeOf.js"
- ],
- "./helpers/esm/getPrototypeOf": "./helpers/esm/getPrototypeOf.js",
- "./helpers/setPrototypeOf": [
- {
- "node": "./helpers/setPrototypeOf.js",
- "import": "./helpers/esm/setPrototypeOf.js",
- "default": "./helpers/setPrototypeOf.js"
- },
- "./helpers/setPrototypeOf.js"
- ],
- "./helpers/esm/setPrototypeOf": "./helpers/esm/setPrototypeOf.js",
- "./helpers/isNativeReflectConstruct": [
- {
- "node": "./helpers/isNativeReflectConstruct.js",
- "import": "./helpers/esm/isNativeReflectConstruct.js",
- "default": "./helpers/isNativeReflectConstruct.js"
- },
- "./helpers/isNativeReflectConstruct.js"
- ],
- "./helpers/esm/isNativeReflectConstruct": "./helpers/esm/isNativeReflectConstruct.js",
- "./helpers/construct": [
- {
- "node": "./helpers/construct.js",
- "import": "./helpers/esm/construct.js",
- "default": "./helpers/construct.js"
- },
- "./helpers/construct.js"
- ],
- "./helpers/esm/construct": "./helpers/esm/construct.js",
- "./helpers/isNativeFunction": [
- {
- "node": "./helpers/isNativeFunction.js",
- "import": "./helpers/esm/isNativeFunction.js",
- "default": "./helpers/isNativeFunction.js"
- },
- "./helpers/isNativeFunction.js"
- ],
- "./helpers/esm/isNativeFunction": "./helpers/esm/isNativeFunction.js",
- "./helpers/wrapNativeSuper": [
- {
- "node": "./helpers/wrapNativeSuper.js",
- "import": "./helpers/esm/wrapNativeSuper.js",
- "default": "./helpers/wrapNativeSuper.js"
- },
- "./helpers/wrapNativeSuper.js"
- ],
- "./helpers/esm/wrapNativeSuper": "./helpers/esm/wrapNativeSuper.js",
- "./helpers/instanceof": [
- {
- "node": "./helpers/instanceof.js",
- "import": "./helpers/esm/instanceof.js",
- "default": "./helpers/instanceof.js"
- },
- "./helpers/instanceof.js"
- ],
- "./helpers/esm/instanceof": "./helpers/esm/instanceof.js",
- "./helpers/interopRequireDefault": [
- {
- "node": "./helpers/interopRequireDefault.js",
- "import": "./helpers/esm/interopRequireDefault.js",
- "default": "./helpers/interopRequireDefault.js"
- },
- "./helpers/interopRequireDefault.js"
- ],
- "./helpers/esm/interopRequireDefault": "./helpers/esm/interopRequireDefault.js",
- "./helpers/interopRequireWildcard": [
- {
- "node": "./helpers/interopRequireWildcard.js",
- "import": "./helpers/esm/interopRequireWildcard.js",
- "default": "./helpers/interopRequireWildcard.js"
- },
- "./helpers/interopRequireWildcard.js"
- ],
- "./helpers/esm/interopRequireWildcard": "./helpers/esm/interopRequireWildcard.js",
- "./helpers/newArrowCheck": [
- {
- "node": "./helpers/newArrowCheck.js",
- "import": "./helpers/esm/newArrowCheck.js",
- "default": "./helpers/newArrowCheck.js"
- },
- "./helpers/newArrowCheck.js"
- ],
- "./helpers/esm/newArrowCheck": "./helpers/esm/newArrowCheck.js",
- "./helpers/objectDestructuringEmpty": [
- {
- "node": "./helpers/objectDestructuringEmpty.js",
- "import": "./helpers/esm/objectDestructuringEmpty.js",
- "default": "./helpers/objectDestructuringEmpty.js"
- },
- "./helpers/objectDestructuringEmpty.js"
- ],
- "./helpers/esm/objectDestructuringEmpty": "./helpers/esm/objectDestructuringEmpty.js",
- "./helpers/objectWithoutPropertiesLoose": [
- {
- "node": "./helpers/objectWithoutPropertiesLoose.js",
- "import": "./helpers/esm/objectWithoutPropertiesLoose.js",
- "default": "./helpers/objectWithoutPropertiesLoose.js"
- },
- "./helpers/objectWithoutPropertiesLoose.js"
- ],
- "./helpers/esm/objectWithoutPropertiesLoose": "./helpers/esm/objectWithoutPropertiesLoose.js",
- "./helpers/objectWithoutProperties": [
- {
- "node": "./helpers/objectWithoutProperties.js",
- "import": "./helpers/esm/objectWithoutProperties.js",
- "default": "./helpers/objectWithoutProperties.js"
- },
- "./helpers/objectWithoutProperties.js"
- ],
- "./helpers/esm/objectWithoutProperties": "./helpers/esm/objectWithoutProperties.js",
- "./helpers/assertThisInitialized": [
- {
- "node": "./helpers/assertThisInitialized.js",
- "import": "./helpers/esm/assertThisInitialized.js",
- "default": "./helpers/assertThisInitialized.js"
- },
- "./helpers/assertThisInitialized.js"
- ],
- "./helpers/esm/assertThisInitialized": "./helpers/esm/assertThisInitialized.js",
- "./helpers/possibleConstructorReturn": [
- {
- "node": "./helpers/possibleConstructorReturn.js",
- "import": "./helpers/esm/possibleConstructorReturn.js",
- "default": "./helpers/possibleConstructorReturn.js"
- },
- "./helpers/possibleConstructorReturn.js"
- ],
- "./helpers/esm/possibleConstructorReturn": "./helpers/esm/possibleConstructorReturn.js",
- "./helpers/createSuper": [
- {
- "node": "./helpers/createSuper.js",
- "import": "./helpers/esm/createSuper.js",
- "default": "./helpers/createSuper.js"
- },
- "./helpers/createSuper.js"
- ],
- "./helpers/esm/createSuper": "./helpers/esm/createSuper.js",
- "./helpers/superPropBase": [
- {
- "node": "./helpers/superPropBase.js",
- "import": "./helpers/esm/superPropBase.js",
- "default": "./helpers/superPropBase.js"
- },
- "./helpers/superPropBase.js"
- ],
- "./helpers/esm/superPropBase": "./helpers/esm/superPropBase.js",
- "./helpers/get": [
- {
- "node": "./helpers/get.js",
- "import": "./helpers/esm/get.js",
- "default": "./helpers/get.js"
- },
- "./helpers/get.js"
- ],
- "./helpers/esm/get": "./helpers/esm/get.js",
- "./helpers/set": [
- {
- "node": "./helpers/set.js",
- "import": "./helpers/esm/set.js",
- "default": "./helpers/set.js"
- },
- "./helpers/set.js"
- ],
- "./helpers/esm/set": "./helpers/esm/set.js",
- "./helpers/taggedTemplateLiteral": [
- {
- "node": "./helpers/taggedTemplateLiteral.js",
- "import": "./helpers/esm/taggedTemplateLiteral.js",
- "default": "./helpers/taggedTemplateLiteral.js"
- },
- "./helpers/taggedTemplateLiteral.js"
- ],
- "./helpers/esm/taggedTemplateLiteral": "./helpers/esm/taggedTemplateLiteral.js",
- "./helpers/taggedTemplateLiteralLoose": [
- {
- "node": "./helpers/taggedTemplateLiteralLoose.js",
- "import": "./helpers/esm/taggedTemplateLiteralLoose.js",
- "default": "./helpers/taggedTemplateLiteralLoose.js"
- },
- "./helpers/taggedTemplateLiteralLoose.js"
- ],
- "./helpers/esm/taggedTemplateLiteralLoose": "./helpers/esm/taggedTemplateLiteralLoose.js",
- "./helpers/readOnlyError": [
- {
- "node": "./helpers/readOnlyError.js",
- "import": "./helpers/esm/readOnlyError.js",
- "default": "./helpers/readOnlyError.js"
- },
- "./helpers/readOnlyError.js"
- ],
- "./helpers/esm/readOnlyError": "./helpers/esm/readOnlyError.js",
- "./helpers/writeOnlyError": [
- {
- "node": "./helpers/writeOnlyError.js",
- "import": "./helpers/esm/writeOnlyError.js",
- "default": "./helpers/writeOnlyError.js"
- },
- "./helpers/writeOnlyError.js"
- ],
- "./helpers/esm/writeOnlyError": "./helpers/esm/writeOnlyError.js",
- "./helpers/classNameTDZError": [
- {
- "node": "./helpers/classNameTDZError.js",
- "import": "./helpers/esm/classNameTDZError.js",
- "default": "./helpers/classNameTDZError.js"
- },
- "./helpers/classNameTDZError.js"
- ],
- "./helpers/esm/classNameTDZError": "./helpers/esm/classNameTDZError.js",
- "./helpers/temporalUndefined": [
- {
- "node": "./helpers/temporalUndefined.js",
- "import": "./helpers/esm/temporalUndefined.js",
- "default": "./helpers/temporalUndefined.js"
- },
- "./helpers/temporalUndefined.js"
- ],
- "./helpers/esm/temporalUndefined": "./helpers/esm/temporalUndefined.js",
- "./helpers/tdz": [
- {
- "node": "./helpers/tdz.js",
- "import": "./helpers/esm/tdz.js",
- "default": "./helpers/tdz.js"
- },
- "./helpers/tdz.js"
- ],
- "./helpers/esm/tdz": "./helpers/esm/tdz.js",
- "./helpers/temporalRef": [
- {
- "node": "./helpers/temporalRef.js",
- "import": "./helpers/esm/temporalRef.js",
- "default": "./helpers/temporalRef.js"
- },
- "./helpers/temporalRef.js"
- ],
- "./helpers/esm/temporalRef": "./helpers/esm/temporalRef.js",
- "./helpers/slicedToArray": [
- {
- "node": "./helpers/slicedToArray.js",
- "import": "./helpers/esm/slicedToArray.js",
- "default": "./helpers/slicedToArray.js"
- },
- "./helpers/slicedToArray.js"
- ],
- "./helpers/esm/slicedToArray": "./helpers/esm/slicedToArray.js",
- "./helpers/slicedToArrayLoose": [
- {
- "node": "./helpers/slicedToArrayLoose.js",
- "import": "./helpers/esm/slicedToArrayLoose.js",
- "default": "./helpers/slicedToArrayLoose.js"
- },
- "./helpers/slicedToArrayLoose.js"
- ],
- "./helpers/esm/slicedToArrayLoose": "./helpers/esm/slicedToArrayLoose.js",
- "./helpers/toArray": [
- {
- "node": "./helpers/toArray.js",
- "import": "./helpers/esm/toArray.js",
- "default": "./helpers/toArray.js"
- },
- "./helpers/toArray.js"
- ],
- "./helpers/esm/toArray": "./helpers/esm/toArray.js",
- "./helpers/toConsumableArray": [
- {
- "node": "./helpers/toConsumableArray.js",
- "import": "./helpers/esm/toConsumableArray.js",
- "default": "./helpers/toConsumableArray.js"
- },
- "./helpers/toConsumableArray.js"
- ],
- "./helpers/esm/toConsumableArray": "./helpers/esm/toConsumableArray.js",
- "./helpers/arrayWithoutHoles": [
- {
- "node": "./helpers/arrayWithoutHoles.js",
- "import": "./helpers/esm/arrayWithoutHoles.js",
- "default": "./helpers/arrayWithoutHoles.js"
- },
- "./helpers/arrayWithoutHoles.js"
- ],
- "./helpers/esm/arrayWithoutHoles": "./helpers/esm/arrayWithoutHoles.js",
- "./helpers/arrayWithHoles": [
- {
- "node": "./helpers/arrayWithHoles.js",
- "import": "./helpers/esm/arrayWithHoles.js",
- "default": "./helpers/arrayWithHoles.js"
- },
- "./helpers/arrayWithHoles.js"
- ],
- "./helpers/esm/arrayWithHoles": "./helpers/esm/arrayWithHoles.js",
- "./helpers/maybeArrayLike": [
- {
- "node": "./helpers/maybeArrayLike.js",
- "import": "./helpers/esm/maybeArrayLike.js",
- "default": "./helpers/maybeArrayLike.js"
- },
- "./helpers/maybeArrayLike.js"
- ],
- "./helpers/esm/maybeArrayLike": "./helpers/esm/maybeArrayLike.js",
- "./helpers/iterableToArray": [
- {
- "node": "./helpers/iterableToArray.js",
- "import": "./helpers/esm/iterableToArray.js",
- "default": "./helpers/iterableToArray.js"
- },
- "./helpers/iterableToArray.js"
- ],
- "./helpers/esm/iterableToArray": "./helpers/esm/iterableToArray.js",
- "./helpers/iterableToArrayLimit": [
- {
- "node": "./helpers/iterableToArrayLimit.js",
- "import": "./helpers/esm/iterableToArrayLimit.js",
- "default": "./helpers/iterableToArrayLimit.js"
- },
- "./helpers/iterableToArrayLimit.js"
- ],
- "./helpers/esm/iterableToArrayLimit": "./helpers/esm/iterableToArrayLimit.js",
- "./helpers/iterableToArrayLimitLoose": [
- {
- "node": "./helpers/iterableToArrayLimitLoose.js",
- "import": "./helpers/esm/iterableToArrayLimitLoose.js",
- "default": "./helpers/iterableToArrayLimitLoose.js"
- },
- "./helpers/iterableToArrayLimitLoose.js"
- ],
- "./helpers/esm/iterableToArrayLimitLoose": "./helpers/esm/iterableToArrayLimitLoose.js",
- "./helpers/unsupportedIterableToArray": [
- {
- "node": "./helpers/unsupportedIterableToArray.js",
- "import": "./helpers/esm/unsupportedIterableToArray.js",
- "default": "./helpers/unsupportedIterableToArray.js"
- },
- "./helpers/unsupportedIterableToArray.js"
- ],
- "./helpers/esm/unsupportedIterableToArray": "./helpers/esm/unsupportedIterableToArray.js",
- "./helpers/arrayLikeToArray": [
- {
- "node": "./helpers/arrayLikeToArray.js",
- "import": "./helpers/esm/arrayLikeToArray.js",
- "default": "./helpers/arrayLikeToArray.js"
- },
- "./helpers/arrayLikeToArray.js"
- ],
- "./helpers/esm/arrayLikeToArray": "./helpers/esm/arrayLikeToArray.js",
- "./helpers/nonIterableSpread": [
- {
- "node": "./helpers/nonIterableSpread.js",
- "import": "./helpers/esm/nonIterableSpread.js",
- "default": "./helpers/nonIterableSpread.js"
- },
- "./helpers/nonIterableSpread.js"
- ],
- "./helpers/esm/nonIterableSpread": "./helpers/esm/nonIterableSpread.js",
- "./helpers/nonIterableRest": [
- {
- "node": "./helpers/nonIterableRest.js",
- "import": "./helpers/esm/nonIterableRest.js",
- "default": "./helpers/nonIterableRest.js"
- },
- "./helpers/nonIterableRest.js"
- ],
- "./helpers/esm/nonIterableRest": "./helpers/esm/nonIterableRest.js",
- "./helpers/createForOfIteratorHelper": [
- {
- "node": "./helpers/createForOfIteratorHelper.js",
- "import": "./helpers/esm/createForOfIteratorHelper.js",
- "default": "./helpers/createForOfIteratorHelper.js"
- },
- "./helpers/createForOfIteratorHelper.js"
- ],
- "./helpers/esm/createForOfIteratorHelper": "./helpers/esm/createForOfIteratorHelper.js",
- "./helpers/createForOfIteratorHelperLoose": [
- {
- "node": "./helpers/createForOfIteratorHelperLoose.js",
- "import": "./helpers/esm/createForOfIteratorHelperLoose.js",
- "default": "./helpers/createForOfIteratorHelperLoose.js"
- },
- "./helpers/createForOfIteratorHelperLoose.js"
- ],
- "./helpers/esm/createForOfIteratorHelperLoose": "./helpers/esm/createForOfIteratorHelperLoose.js",
- "./helpers/skipFirstGeneratorNext": [
- {
- "node": "./helpers/skipFirstGeneratorNext.js",
- "import": "./helpers/esm/skipFirstGeneratorNext.js",
- "default": "./helpers/skipFirstGeneratorNext.js"
- },
- "./helpers/skipFirstGeneratorNext.js"
- ],
- "./helpers/esm/skipFirstGeneratorNext": "./helpers/esm/skipFirstGeneratorNext.js",
- "./helpers/toPrimitive": [
- {
- "node": "./helpers/toPrimitive.js",
- "import": "./helpers/esm/toPrimitive.js",
- "default": "./helpers/toPrimitive.js"
- },
- "./helpers/toPrimitive.js"
- ],
- "./helpers/esm/toPrimitive": "./helpers/esm/toPrimitive.js",
- "./helpers/toPropertyKey": [
- {
- "node": "./helpers/toPropertyKey.js",
- "import": "./helpers/esm/toPropertyKey.js",
- "default": "./helpers/toPropertyKey.js"
- },
- "./helpers/toPropertyKey.js"
- ],
- "./helpers/esm/toPropertyKey": "./helpers/esm/toPropertyKey.js",
- "./helpers/initializerWarningHelper": [
- {
- "node": "./helpers/initializerWarningHelper.js",
- "import": "./helpers/esm/initializerWarningHelper.js",
- "default": "./helpers/initializerWarningHelper.js"
- },
- "./helpers/initializerWarningHelper.js"
- ],
- "./helpers/esm/initializerWarningHelper": "./helpers/esm/initializerWarningHelper.js",
- "./helpers/initializerDefineProperty": [
- {
- "node": "./helpers/initializerDefineProperty.js",
- "import": "./helpers/esm/initializerDefineProperty.js",
- "default": "./helpers/initializerDefineProperty.js"
- },
- "./helpers/initializerDefineProperty.js"
- ],
- "./helpers/esm/initializerDefineProperty": "./helpers/esm/initializerDefineProperty.js",
- "./helpers/applyDecoratedDescriptor": [
- {
- "node": "./helpers/applyDecoratedDescriptor.js",
- "import": "./helpers/esm/applyDecoratedDescriptor.js",
- "default": "./helpers/applyDecoratedDescriptor.js"
- },
- "./helpers/applyDecoratedDescriptor.js"
- ],
- "./helpers/esm/applyDecoratedDescriptor": "./helpers/esm/applyDecoratedDescriptor.js",
- "./helpers/classPrivateFieldLooseKey": [
- {
- "node": "./helpers/classPrivateFieldLooseKey.js",
- "import": "./helpers/esm/classPrivateFieldLooseKey.js",
- "default": "./helpers/classPrivateFieldLooseKey.js"
- },
- "./helpers/classPrivateFieldLooseKey.js"
- ],
- "./helpers/esm/classPrivateFieldLooseKey": "./helpers/esm/classPrivateFieldLooseKey.js",
- "./helpers/classPrivateFieldLooseBase": [
- {
- "node": "./helpers/classPrivateFieldLooseBase.js",
- "import": "./helpers/esm/classPrivateFieldLooseBase.js",
- "default": "./helpers/classPrivateFieldLooseBase.js"
- },
- "./helpers/classPrivateFieldLooseBase.js"
- ],
- "./helpers/esm/classPrivateFieldLooseBase": "./helpers/esm/classPrivateFieldLooseBase.js",
- "./helpers/classPrivateFieldGet": [
- {
- "node": "./helpers/classPrivateFieldGet.js",
- "import": "./helpers/esm/classPrivateFieldGet.js",
- "default": "./helpers/classPrivateFieldGet.js"
- },
- "./helpers/classPrivateFieldGet.js"
- ],
- "./helpers/esm/classPrivateFieldGet": "./helpers/esm/classPrivateFieldGet.js",
- "./helpers/classPrivateFieldSet": [
- {
- "node": "./helpers/classPrivateFieldSet.js",
- "import": "./helpers/esm/classPrivateFieldSet.js",
- "default": "./helpers/classPrivateFieldSet.js"
- },
- "./helpers/classPrivateFieldSet.js"
- ],
- "./helpers/esm/classPrivateFieldSet": "./helpers/esm/classPrivateFieldSet.js",
- "./helpers/classPrivateFieldDestructureSet": [
- {
- "node": "./helpers/classPrivateFieldDestructureSet.js",
- "import": "./helpers/esm/classPrivateFieldDestructureSet.js",
- "default": "./helpers/classPrivateFieldDestructureSet.js"
- },
- "./helpers/classPrivateFieldDestructureSet.js"
- ],
- "./helpers/esm/classPrivateFieldDestructureSet": "./helpers/esm/classPrivateFieldDestructureSet.js",
- "./helpers/classExtractFieldDescriptor": [
- {
- "node": "./helpers/classExtractFieldDescriptor.js",
- "import": "./helpers/esm/classExtractFieldDescriptor.js",
- "default": "./helpers/classExtractFieldDescriptor.js"
- },
- "./helpers/classExtractFieldDescriptor.js"
- ],
- "./helpers/esm/classExtractFieldDescriptor": "./helpers/esm/classExtractFieldDescriptor.js",
- "./helpers/classStaticPrivateFieldSpecGet": [
- {
- "node": "./helpers/classStaticPrivateFieldSpecGet.js",
- "import": "./helpers/esm/classStaticPrivateFieldSpecGet.js",
- "default": "./helpers/classStaticPrivateFieldSpecGet.js"
- },
- "./helpers/classStaticPrivateFieldSpecGet.js"
- ],
- "./helpers/esm/classStaticPrivateFieldSpecGet": "./helpers/esm/classStaticPrivateFieldSpecGet.js",
- "./helpers/classStaticPrivateFieldSpecSet": [
- {
- "node": "./helpers/classStaticPrivateFieldSpecSet.js",
- "import": "./helpers/esm/classStaticPrivateFieldSpecSet.js",
- "default": "./helpers/classStaticPrivateFieldSpecSet.js"
- },
- "./helpers/classStaticPrivateFieldSpecSet.js"
- ],
- "./helpers/esm/classStaticPrivateFieldSpecSet": "./helpers/esm/classStaticPrivateFieldSpecSet.js",
- "./helpers/classStaticPrivateMethodGet": [
- {
- "node": "./helpers/classStaticPrivateMethodGet.js",
- "import": "./helpers/esm/classStaticPrivateMethodGet.js",
- "default": "./helpers/classStaticPrivateMethodGet.js"
- },
- "./helpers/classStaticPrivateMethodGet.js"
- ],
- "./helpers/esm/classStaticPrivateMethodGet": "./helpers/esm/classStaticPrivateMethodGet.js",
- "./helpers/classStaticPrivateMethodSet": [
- {
- "node": "./helpers/classStaticPrivateMethodSet.js",
- "import": "./helpers/esm/classStaticPrivateMethodSet.js",
- "default": "./helpers/classStaticPrivateMethodSet.js"
- },
- "./helpers/classStaticPrivateMethodSet.js"
- ],
- "./helpers/esm/classStaticPrivateMethodSet": "./helpers/esm/classStaticPrivateMethodSet.js",
- "./helpers/classApplyDescriptorGet": [
- {
- "node": "./helpers/classApplyDescriptorGet.js",
- "import": "./helpers/esm/classApplyDescriptorGet.js",
- "default": "./helpers/classApplyDescriptorGet.js"
- },
- "./helpers/classApplyDescriptorGet.js"
- ],
- "./helpers/esm/classApplyDescriptorGet": "./helpers/esm/classApplyDescriptorGet.js",
- "./helpers/classApplyDescriptorSet": [
- {
- "node": "./helpers/classApplyDescriptorSet.js",
- "import": "./helpers/esm/classApplyDescriptorSet.js",
- "default": "./helpers/classApplyDescriptorSet.js"
- },
- "./helpers/classApplyDescriptorSet.js"
- ],
- "./helpers/esm/classApplyDescriptorSet": "./helpers/esm/classApplyDescriptorSet.js",
- "./helpers/classApplyDescriptorDestructureSet": [
- {
- "node": "./helpers/classApplyDescriptorDestructureSet.js",
- "import": "./helpers/esm/classApplyDescriptorDestructureSet.js",
- "default": "./helpers/classApplyDescriptorDestructureSet.js"
- },
- "./helpers/classApplyDescriptorDestructureSet.js"
- ],
- "./helpers/esm/classApplyDescriptorDestructureSet": "./helpers/esm/classApplyDescriptorDestructureSet.js",
- "./helpers/classStaticPrivateFieldDestructureSet": [
- {
- "node": "./helpers/classStaticPrivateFieldDestructureSet.js",
- "import": "./helpers/esm/classStaticPrivateFieldDestructureSet.js",
- "default": "./helpers/classStaticPrivateFieldDestructureSet.js"
- },
- "./helpers/classStaticPrivateFieldDestructureSet.js"
- ],
- "./helpers/esm/classStaticPrivateFieldDestructureSet": "./helpers/esm/classStaticPrivateFieldDestructureSet.js",
- "./helpers/classCheckPrivateStaticAccess": [
- {
- "node": "./helpers/classCheckPrivateStaticAccess.js",
- "import": "./helpers/esm/classCheckPrivateStaticAccess.js",
- "default": "./helpers/classCheckPrivateStaticAccess.js"
- },
- "./helpers/classCheckPrivateStaticAccess.js"
- ],
- "./helpers/esm/classCheckPrivateStaticAccess": "./helpers/esm/classCheckPrivateStaticAccess.js",
- "./helpers/classCheckPrivateStaticFieldDescriptor": [
- {
- "node": "./helpers/classCheckPrivateStaticFieldDescriptor.js",
- "import": "./helpers/esm/classCheckPrivateStaticFieldDescriptor.js",
- "default": "./helpers/classCheckPrivateStaticFieldDescriptor.js"
- },
- "./helpers/classCheckPrivateStaticFieldDescriptor.js"
- ],
- "./helpers/esm/classCheckPrivateStaticFieldDescriptor": "./helpers/esm/classCheckPrivateStaticFieldDescriptor.js",
- "./helpers/decorate": [
- {
- "node": "./helpers/decorate.js",
- "import": "./helpers/esm/decorate.js",
- "default": "./helpers/decorate.js"
- },
- "./helpers/decorate.js"
- ],
- "./helpers/esm/decorate": "./helpers/esm/decorate.js",
- "./helpers/classPrivateMethodGet": [
- {
- "node": "./helpers/classPrivateMethodGet.js",
- "import": "./helpers/esm/classPrivateMethodGet.js",
- "default": "./helpers/classPrivateMethodGet.js"
- },
- "./helpers/classPrivateMethodGet.js"
- ],
- "./helpers/esm/classPrivateMethodGet": "./helpers/esm/classPrivateMethodGet.js",
- "./helpers/classPrivateMethodSet": [
- {
- "node": "./helpers/classPrivateMethodSet.js",
- "import": "./helpers/esm/classPrivateMethodSet.js",
- "default": "./helpers/classPrivateMethodSet.js"
- },
- "./helpers/classPrivateMethodSet.js"
- ],
- "./helpers/esm/classPrivateMethodSet": "./helpers/esm/classPrivateMethodSet.js",
- "./package": "./package.json",
- "./package.json": "./package.json",
- "./regenerator": "./regenerator/index.js",
- "./regenerator/*.js": "./regenerator/*.js",
- "./regenerator/": "./regenerator/"
- },
- "homepage": "https://babel.dev/docs/en/next/babel-runtime",
- "license": "MIT",
- "name": "@babel/runtime",
- "publishConfig": {
- "access": "public"
- },
- "repository": {
- "type": "git",
- "url": "git+https://github.com/babel/babel.git",
- "directory": "packages/babel-runtime"
- },
- "version": "7.14.6"
-}
diff --git a/node_modules/@babel/runtime/regenerator/index.js b/node_modules/@babel/runtime/regenerator/index.js
deleted file mode 100644
index 9fd4158..0000000
--- a/node_modules/@babel/runtime/regenerator/index.js
+++ /dev/null
@@ -1 +0,0 @@
-module.exports = require("regenerator-runtime");
diff --git a/node_modules/@videojs/http-streaming/CHANGELOG.md b/node_modules/@videojs/http-streaming/CHANGELOG.md
deleted file mode 100644
index 8de917b..0000000
--- a/node_modules/@videojs/http-streaming/CHANGELOG.md
+++ /dev/null
@@ -1,782 +0,0 @@
-
-## [2.9.1](https://github.com/videojs/http-streaming/compare/v2.9.0...v2.9.1) (2021-06-22)
-
-### Bug Fixes
-
-* actually default maxPlaylistRetries to Infinity ([#1142](https://github.com/videojs/http-streaming/issues/1142)) ([4428e3a](https://github.com/videojs/http-streaming/commit/4428e3a)), closes [#1098](https://github.com/videojs/http-streaming/issues/1098)
-* don't decay average bandwidth value if system bandwidth did not change ([#1137](https://github.com/videojs/http-streaming/issues/1137)) ([c22749b](https://github.com/videojs/http-streaming/commit/c22749b))
-* ts segments that don't define all streams in the first pmt ([#1144](https://github.com/videojs/http-streaming/issues/1144)) ([36a8be4](https://github.com/videojs/http-streaming/commit/36a8be4))
-
-### Tests
-
-* moving average should not decay without new data ([#1141](https://github.com/videojs/http-streaming/issues/1141)) ([55726af](https://github.com/videojs/http-streaming/commit/55726af)), closes [#1137](https://github.com/videojs/http-streaming/issues/1137)
-
-
-# [2.9.0](https://github.com/videojs/http-streaming/compare/v2.8.2...v2.9.0) (2021-06-11)
-
-### Features
-
-* Add support for encrypted init segments ([#1132](https://github.com/videojs/http-streaming/issues/1132)) ([4449ed5](https://github.com/videojs/http-streaming/commit/4449ed5))
-* allow clients to limit the number of times a playlist attempts to reload following an error ([#1098](https://github.com/videojs/http-streaming/issues/1098)) ([44905d4](https://github.com/videojs/http-streaming/commit/44905d4))
-* Caption services (608/708) metadata ([#1138](https://github.com/videojs/http-streaming/issues/1138)) ([39782c6](https://github.com/videojs/http-streaming/commit/39782c6)), closes [/datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-08#section-4](https://github.com//datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-08/issues/section-4) [videojs/mpd-parser#131](https://github.com/videojs/mpd-parser/issues/131)
-* do fast rendition changes on fullscreen changes and user actions ([#1074](https://github.com/videojs/http-streaming/issues/1074)) ([5405c18](https://github.com/videojs/http-streaming/commit/5405c18))
-* stats for timeToLoadedData, appendsToLoadedData, mainAppendsToLoadedData, audioAppendsToLoadedData, and mediaAppends ([#1106](https://github.com/videojs/http-streaming/issues/1106)) ([3124fbc](https://github.com/videojs/http-streaming/commit/3124fbc))
-* Use ll-hls query directives: segment skipping and requesting a specific segment/part ([#1079](https://github.com/videojs/http-streaming/issues/1079)) ([458be2c](https://github.com/videojs/http-streaming/commit/458be2c))
-
-### Bug Fixes
-
-* add part level sync points, fix LL hls sync issues, add part timing info ([#1125](https://github.com/videojs/http-streaming/issues/1125)) ([ee5841d](https://github.com/videojs/http-streaming/commit/ee5841d))
-* Append valid syncRequests, better sync request choice, less getMediaInfoForTime rounding ([#1127](https://github.com/videojs/http-streaming/issues/1127)) ([ce03f66](https://github.com/videojs/http-streaming/commit/ce03f66))
-
-### Chores
-
-* fix coverage ci run ([#1135](https://github.com/videojs/http-streaming/issues/1135)) ([82b6781](https://github.com/videojs/http-streaming/commit/82b6781))
-
-
-## [2.8.2](https://github.com/videojs/http-streaming/compare/v2.8.1...v2.8.2) (2021-05-20)
-
-### Bug Fixes
-
-* add tests for data uri, fix data uri in demo page ([#1133](https://github.com/videojs/http-streaming/issues/1133)) ([0be51eb](https://github.com/videojs/http-streaming/commit/0be51eb))
-
-
-## [2.8.1](https://github.com/videojs/http-streaming/compare/v2.8.0...v2.8.1) (2021-05-19)
-
-### Bug Fixes
-
-* add master referenced id/uri for audio playlists. Add playlists to hls media groups ([#1124](https://github.com/videojs/http-streaming/issues/1124)) ([740d2ee](https://github.com/videojs/http-streaming/commit/740d2ee))
-* m3u8-parser/eme updates ([#1131](https://github.com/videojs/http-streaming/issues/1131)) ([29ece75](https://github.com/videojs/http-streaming/commit/29ece75))
-* only append/request init segments when they change ([#1128](https://github.com/videojs/http-streaming/issues/1128)) ([a4af004](https://github.com/videojs/http-streaming/commit/a4af004))
-* set audio status on loaders when setting up media groups ([#1126](https://github.com/videojs/http-streaming/issues/1126)) ([a44f984](https://github.com/videojs/http-streaming/commit/a44f984))
-
-### Chores
-
-* update vhs utils to 3.0.1 ([#1123](https://github.com/videojs/http-streaming/issues/1123)) ([552b012](https://github.com/videojs/http-streaming/commit/552b012))
-
-
-# [2.8.0](https://github.com/videojs/http-streaming/compare/v2.7.1...v2.8.0) (2021-04-28)
-
-### Features
-
-* add initialBandwidth option at the tech level ([#1122](https://github.com/videojs/http-streaming/issues/1122)) ([2071008](https://github.com/videojs/http-streaming/commit/2071008))
-
-### Bug Fixes
-
-* don't clear DASH minimum update period timeout on pause of a media loader ([#1118](https://github.com/videojs/http-streaming/issues/1118)) ([82ff4f5](https://github.com/videojs/http-streaming/commit/82ff4f5))
-* null check sidx on sidxmapping, check that end > start on remove ([#1121](https://github.com/videojs/http-streaming/issues/1121)) ([92f1333](https://github.com/videojs/http-streaming/commit/92f1333))
-
-### Code Refactoring
-
-* drop support for the partial muxer and handlePartial ([#1119](https://github.com/videojs/http-streaming/issues/1119)) ([ab305f8](https://github.com/videojs/http-streaming/commit/ab305f8))
-* offload mp4/ts probe to the web worker ([#1117](https://github.com/videojs/http-streaming/issues/1117)) ([3c9f721](https://github.com/videojs/http-streaming/commit/3c9f721))
-* segment/part choice and add more logging around the choice ([#1097](https://github.com/videojs/http-streaming/issues/1097)) ([b8a5aa5](https://github.com/videojs/http-streaming/commit/b8a5aa5))
-
-
-## [2.7.1](https://github.com/videojs/http-streaming/compare/v2.7.0...v2.7.1) (2021-04-09)
-
-### Bug Fixes
-
-* experimentalLLHLS option should always be passed ([#1114](https://github.com/videojs/http-streaming/issues/1114)) ([684fd08](https://github.com/videojs/http-streaming/commit/684fd08))
-
-### Chores
-
-* dont run tests on chromium ([#1116](https://github.com/videojs/http-streaming/issues/1116)) ([c2154d7](https://github.com/videojs/http-streaming/commit/c2154d7))
-
-
-# [2.7.0](https://github.com/videojs/http-streaming/compare/v2.6.4...v2.7.0) (2021-04-06)
-
-### Features
-
-* Add EXT-X-PART support behind a flag for LL-HLS ([#1055](https://github.com/videojs/http-streaming/issues/1055)) ([b33e109](https://github.com/videojs/http-streaming/commit/b33e109))
-* mark Video.js as a peer dependency ([#1111](https://github.com/videojs/http-streaming/issues/1111)) ([99480d5](https://github.com/videojs/http-streaming/commit/99480d5))
-* support serverControl and preloadSegment behind experimentalLLHLS flag ([#1078](https://github.com/videojs/http-streaming/issues/1078)) ([fa1b6b5](https://github.com/videojs/http-streaming/commit/fa1b6b5))
-* usage and logging on rendition change with reasons ([#1088](https://github.com/videojs/http-streaming/issues/1088)) ([1b990f1](https://github.com/videojs/http-streaming/commit/1b990f1))
-
-### Bug Fixes
-
-* audio only media group playlists, audio group playlists, and audio switches for audio only ([#1100](https://github.com/videojs/http-streaming/issues/1100)) ([6d83de3](https://github.com/videojs/http-streaming/commit/6d83de3))
-* better time to first frame for live playlists ([#1105](https://github.com/videojs/http-streaming/issues/1105)) ([1e94680](https://github.com/videojs/http-streaming/commit/1e94680))
-* catch remove errors, remove all data on QUOTA_EXCEEDED ([#1101](https://github.com/videojs/http-streaming/issues/1101)) ([86f77fe](https://github.com/videojs/http-streaming/commit/86f77fe))
-* Only add sidxMapping on successful sidx request and parse. ([#1099](https://github.com/videojs/http-streaming/issues/1099)) ([de0b55b](https://github.com/videojs/http-streaming/commit/de0b55b)), closes [#1107](https://github.com/videojs/http-streaming/issues/1107)
-* support automatic configuration of audio and video only DRM sources ([#1090](https://github.com/videojs/http-streaming/issues/1090)) ([9b116ce](https://github.com/videojs/http-streaming/commit/9b116ce))
-
-### Chores
-
-* never skip main ci runs ([#1108](https://github.com/videojs/http-streaming/issues/1108)) ([b2d2c91](https://github.com/videojs/http-streaming/commit/b2d2c91))
-* turn checkWatch back on for rollup ([87947fc](https://github.com/videojs/http-streaming/commit/87947fc))
-* update to mux.js[@5](https://github.com/5).11.0 ([#1109](https://github.com/videojs/http-streaming/issues/1109)) ([af5841c](https://github.com/videojs/http-streaming/commit/af5841c))
-
-
-## [2.6.4](https://github.com/videojs/http-streaming/compare/v2.6.3...v2.6.4) (2021-03-12)
-
-### Bug Fixes
-
-* Monitor playback for stalls due to gaps in the beginning of stream when a new source is loaded ([#1087](https://github.com/videojs/http-streaming/issues/1087)) ([64a1f35](https://github.com/videojs/http-streaming/commit/64a1f35))
-* retry appends on QUOTA_EXCEEDED_ERR ([#1093](https://github.com/videojs/http-streaming/issues/1093)) ([008aeaf](https://github.com/videojs/http-streaming/commit/008aeaf))
-
-### Chores
-
-* Get test coverage working again with mock/sync worker ([#1094](https://github.com/videojs/http-streaming/issues/1094)) ([035e8c0](https://github.com/videojs/http-streaming/commit/035e8c0))
-* pin CI to ubuntu 18.04 ([#1091](https://github.com/videojs/http-streaming/issues/1091)) ([01ca182](https://github.com/videojs/http-streaming/commit/01ca182))
-
-
-## [2.6.3](https://github.com/videojs/http-streaming/compare/v2.6.2...v2.6.3) (2021-03-05)
-
-### Bug Fixes
-
-* **playback-watcher:** Skip over playback gaps that occur in the beginning of streams ([#1085](https://github.com/videojs/http-streaming/issues/1085)) ([ccd9352](https://github.com/videojs/http-streaming/commit/ccd9352))
-* Add exclude reason and skip duplicate playlist-unchanged ([#1082](https://github.com/videojs/http-streaming/issues/1082)) ([0dceb5b](https://github.com/videojs/http-streaming/commit/0dceb5b))
-* prevent changing undefined baseStartTime to NaN ([#1086](https://github.com/videojs/http-streaming/issues/1086)) ([43aa69a](https://github.com/videojs/http-streaming/commit/43aa69a))
-* update to mux.js 5.10.0 ([#1089](https://github.com/videojs/http-streaming/issues/1089)) ([1cfdab6](https://github.com/videojs/http-streaming/commit/1cfdab6))
-
-### Chores
-
-* ie 11 demo fixes ([0760d45](https://github.com/videojs/http-streaming/commit/0760d45))
-* use deferred scripts for faster demo startup ([#1083](https://github.com/videojs/http-streaming/issues/1083)) ([c348174](https://github.com/videojs/http-streaming/commit/c348174))
-
-
-## [2.6.2](https://github.com/videojs/http-streaming/compare/v2.6.1...v2.6.2) (2021-02-24)
-
-### Bug Fixes
-
-* update to mux.js[@5](https://github.com/5).9.2 and mpd-parser[@0](https://github.com/0).15.4 ([#1081](https://github.com/videojs/http-streaming/issues/1081)) ([f5c060f](https://github.com/videojs/http-streaming/commit/f5c060f))
-
-### Tests
-
-* add playback-min as a unit test type ([#1077](https://github.com/videojs/http-streaming/issues/1077)) ([327a572](https://github.com/videojs/http-streaming/commit/327a572))
-
-
-## [2.6.1](https://github.com/videojs/http-streaming/compare/v2.6.0...v2.6.1) (2021-02-19)
-
-### Bug Fixes
-
-* allow buffer removes when there's no current media info in loader ([#1070](https://github.com/videojs/http-streaming/issues/1070)) ([97ab712](https://github.com/videojs/http-streaming/commit/97ab712))
-* live dash segment changes should be considered a playlist update ([#1065](https://github.com/videojs/http-streaming/issues/1065)) ([1ce7838](https://github.com/videojs/http-streaming/commit/1ce7838))
-* sometimes subtitlesTrack_.cues is null ([#1073](https://github.com/videojs/http-streaming/issues/1073)) ([6778ca1](https://github.com/videojs/http-streaming/commit/6778ca1))
-* unbreak the minified build by updating rollup-plugin-worker-factory ([#1072](https://github.com/videojs/http-streaming/issues/1072)) ([e583b26](https://github.com/videojs/http-streaming/commit/e583b26))
-
-### Chores
-
-* mirror player.src on the demo page using sourceset ([#1071](https://github.com/videojs/http-streaming/issues/1071)) ([fee7309](https://github.com/videojs/http-streaming/commit/fee7309))
-
-### Documentation
-
-* **README:** fix useBandwidthFromLocalStorage and limitRenditionByPlayerDimensions ([#1075](https://github.com/videojs/http-streaming/issues/1075)) ([cf2efcb](https://github.com/videojs/http-streaming/commit/cf2efcb))
-
-
-# [2.6.0](https://github.com/videojs/http-streaming/compare/v2.5.0...v2.6.0) (2021-02-11)
-
-### Features
-
-* allow xhr override globally, for super advanced use cases only ([#1059](https://github.com/videojs/http-streaming/issues/1059)) ([6279675](https://github.com/videojs/http-streaming/commit/6279675))
-* expose m3u8-parser logging in debug log ([#1048](https://github.com/videojs/http-streaming/issues/1048)) ([0e8bd4b](https://github.com/videojs/http-streaming/commit/0e8bd4b))
-
-### Bug Fixes
-
-* do not request manifests until play when preload is none ([#1060](https://github.com/videojs/http-streaming/issues/1060)) ([49249d5](https://github.com/videojs/http-streaming/commit/49249d5)), closes [#126](https://github.com/videojs/http-streaming/issues/126)
-* store `transmuxQueue` and `currentTransmux` on `transmuxer` instead of globally ([#1045](https://github.com/videojs/http-streaming/issues/1045)) ([a34b4da](https://github.com/videojs/http-streaming/commit/a34b4da))
-* use a separate ProgramDateTime mapping to player time per timeline ([#1063](https://github.com/videojs/http-streaming/issues/1063)) ([5e9b4f1](https://github.com/videojs/http-streaming/commit/5e9b4f1))
-* wait for endedtimeline event from transmuxer when reaching the end of a timeline ([#1058](https://github.com/videojs/http-streaming/issues/1058)) ([b01ab72](https://github.com/videojs/http-streaming/commit/b01ab72))
-
-### Chores
-
-* add legacy avc source ([#1050](https://github.com/videojs/http-streaming/issues/1050)) ([b34a770](https://github.com/videojs/http-streaming/commit/b34a770))
-* add pdt test sources ([#1067](https://github.com/videojs/http-streaming/issues/1067)) ([112148b](https://github.com/videojs/http-streaming/commit/112148b))
-* better worker build and synchronous web worker ([#1033](https://github.com/videojs/http-streaming/issues/1033)) ([f0732af](https://github.com/videojs/http-streaming/commit/f0732af))
-
-### Documentation
-
-* sample-aes encryption isn't currently supported ([#923](https://github.com/videojs/http-streaming/issues/923)) ([30f9b14](https://github.com/videojs/http-streaming/commit/30f9b14))
-
-### Tests
-
-* for IE11, add colon to timezone in Date strings of PDT mapping tests ([#1068](https://github.com/videojs/http-streaming/issues/1068)) ([f81c5a9](https://github.com/videojs/http-streaming/commit/f81c5a9))
-
-
-# [2.5.0](https://github.com/videojs/http-streaming/compare/v2.4.2...v2.5.0) (2021-01-20)
-
-### Features
-
-* add flag to turn off 708 captions ([#1047](https://github.com/videojs/http-streaming/issues/1047)) ([ab5b4dc](https://github.com/videojs/http-streaming/commit/ab5b4dc))
-
-### Chores
-
-* update [@videojs](https://github.com/videojs)/vhs-utils to v3.0.0 ([#1036](https://github.com/videojs/http-streaming/issues/1036)) ([b072c93](https://github.com/videojs/http-streaming/commit/b072c93))
-
-### Tests
-
-* clear segment transmuxer in media segment request tests ([#1043](https://github.com/videojs/http-streaming/issues/1043)) ([83057a8](https://github.com/videojs/http-streaming/commit/83057a8))
-* don't show QUnit UI in regular test runs ([#1044](https://github.com/videojs/http-streaming/issues/1044)) ([25c7f64](https://github.com/videojs/http-streaming/commit/25c7f64))
-
-
-## [2.4.2](https://github.com/videojs/http-streaming/compare/v2.4.1...v2.4.2) (2021-01-07)
-
-### Bug Fixes
-
-* handle rollover and don't set wrong timing info for segments with high PTS/DTS values ([#1040](https://github.com/videojs/http-streaming/issues/1040)) ([9919b85](https://github.com/videojs/http-streaming/commit/9919b85))
-
-
-## [2.4.1](https://github.com/videojs/http-streaming/compare/v2.4.0...v2.4.1) (2020-12-22)
-
-### Bug Fixes
-
-* if a playlist was last requested less than half target duration, delay retry ([#1038](https://github.com/videojs/http-streaming/issues/1038)) ([2e237ee](https://github.com/videojs/http-streaming/commit/2e237ee))
-* programmatically create Config getters/setters ([8454da5](https://github.com/videojs/http-streaming/commit/8454da5))
-
-### Chores
-
-* **demo:** clear type on manual source change ([#1030](https://github.com/videojs/http-streaming/issues/1030)) ([d39276d](https://github.com/videojs/http-streaming/commit/d39276d))
-* mark many more sources as working ([#1035](https://github.com/videojs/http-streaming/issues/1035)) ([904153f](https://github.com/videojs/http-streaming/commit/904153f))
-* move playback tests to a separate ci run ([#1028](https://github.com/videojs/http-streaming/issues/1028)) ([f1d9f6e](https://github.com/videojs/http-streaming/commit/f1d9f6e))
-* remove replace and update packages ([#1031](https://github.com/videojs/http-streaming/issues/1031)) ([0976212](https://github.com/videojs/http-streaming/commit/0976212))
-
-
-# [2.4.0](https://github.com/videojs/http-streaming/compare/v2.3.0...v2.4.0) (2020-12-07)
-
-### Features
-
-* **playback watcher:** Configurable live seekable window ([#997](https://github.com/videojs/http-streaming/issues/997)) ([ad5c270](https://github.com/videojs/http-streaming/commit/ad5c270))
-* log on mislabeled segment durations for HLS ([#1010](https://github.com/videojs/http-streaming/issues/1010)) ([4109a7f](https://github.com/videojs/http-streaming/commit/4109a7f))
-* update to mux.js 5.7.0 ([#1014](https://github.com/videojs/http-streaming/issues/1014)) ([5f14909](https://github.com/videojs/http-streaming/commit/5f14909)), closes [#1001](https://github.com/videojs/http-streaming/issues/1001) [#909](https://github.com/videojs/http-streaming/issues/909)
-
-### Bug Fixes
-
-* abort all loaders on earlyabort ([#965](https://github.com/videojs/http-streaming/issues/965)) ([e7cb63a](https://github.com/videojs/http-streaming/commit/e7cb63a))
-* don't save bandwidth and throughput for really small segments ([#1024](https://github.com/videojs/http-streaming/issues/1024)) ([a29e241](https://github.com/videojs/http-streaming/commit/a29e241))
-* filter out unsupported subtitles for dash ([#962](https://github.com/videojs/http-streaming/issues/962)) ([124834a](https://github.com/videojs/http-streaming/commit/124834a))
-* keep running the minimumUpdatePeriod unless cancelled or changed ([#1016](https://github.com/videojs/http-streaming/issues/1016)) ([f7b528c](https://github.com/videojs/http-streaming/commit/f7b528c))
-* prevent double source buffer ready on IE11 ([#1015](https://github.com/videojs/http-streaming/issues/1015)) ([b1c2969](https://github.com/videojs/http-streaming/commit/b1c2969))
-* remove duplicate cues with same time interval and text ([#1005](https://github.com/videojs/http-streaming/issues/1005)) ([6db2b6a](https://github.com/videojs/http-streaming/commit/6db2b6a))
-* support tracks with id 0 for fmp4 playlists ([#1018](https://github.com/videojs/http-streaming/issues/1018)) ([bf63692](https://github.com/videojs/http-streaming/commit/bf63692))
-* Wait for EME initialization before appending content ([#1002](https://github.com/videojs/http-streaming/issues/1002)) ([93132b7](https://github.com/videojs/http-streaming/commit/93132b7))
-* when changing renditions over a discontinuity, don't use buffered end as segment start ([#1023](https://github.com/videojs/http-streaming/issues/1023)) ([40caa45](https://github.com/videojs/http-streaming/commit/40caa45))
-* **experimentalBufferBasedABR:** start ABR timer on main playlist load ([#1026](https://github.com/videojs/http-streaming/issues/1026)) ([27de9a5](https://github.com/videojs/http-streaming/commit/27de9a5)), closes [#1025](https://github.com/videojs/http-streaming/issues/1025)
-
-### Chores
-
-* add multiple soon-to-work sources ([#1007](https://github.com/videojs/http-streaming/issues/1007)) ([030469f](https://github.com/videojs/http-streaming/commit/030469f))
-* don't run tests on release ([#1006](https://github.com/videojs/http-streaming/issues/1006)) ([d13b737](https://github.com/videojs/http-streaming/commit/d13b737))
-* skip duplicate ci workflows ([#1021](https://github.com/videojs/http-streaming/issues/1021)) ([20cc4a3](https://github.com/videojs/http-streaming/commit/20cc4a3))
-* switch from travis to github actions for ci ([#989](https://github.com/videojs/http-streaming/issues/989)) ([c9b195b](https://github.com/videojs/http-streaming/commit/c9b195b))
-* **demo page:** add an overrideNative button (default on) ([#1027](https://github.com/videojs/http-streaming/issues/1027)) ([197daab](https://github.com/videojs/http-streaming/commit/197daab))
-
-### Code Refactoring
-
-* Add a better distinction between master and child dash loaders ([#992](https://github.com/videojs/http-streaming/issues/992)) ([56592bc](https://github.com/videojs/http-streaming/commit/56592bc))
-* add sidx segments to playlist object instead of re-parsing xml ([#994](https://github.com/videojs/http-streaming/issues/994)) ([e41f856](https://github.com/videojs/http-streaming/commit/e41f856))
-* unify sidx/master/error request logic ([#998](https://github.com/videojs/http-streaming/issues/998)) ([fe57e60](https://github.com/videojs/http-streaming/commit/fe57e60))
-
-### Tests
-
-* fix tests on firefox 83 ([#1004](https://github.com/videojs/http-streaming/issues/1004)) ([00d9b1d](https://github.com/videojs/http-streaming/commit/00d9b1d))
-
-
-# [2.3.0](https://github.com/videojs/http-streaming/compare/v2.2.0...v2.3.0) (2020-11-05)
-
-### Features
-
-* add experimental buffer based ABR ([#886](https://github.com/videojs/http-streaming/issues/886)) ([a05d032](https://github.com/videojs/http-streaming/commit/a05d032))
-
-### Bug Fixes
-
-* appendsdone abort and handle multiple id3 sections. ([#971](https://github.com/videojs/http-streaming/issues/971)) ([329d50a](https://github.com/videojs/http-streaming/commit/329d50a))
-* check tech error before pause loaders ([#969](https://github.com/videojs/http-streaming/issues/969)) ([0c7b2cb](https://github.com/videojs/http-streaming/commit/0c7b2cb))
-* inline json version ([#967](https://github.com/videojs/http-streaming/issues/967)) ([326ce1c](https://github.com/videojs/http-streaming/commit/326ce1c))
-* **experimentalBufferBasedABR:** call selectPlaylist and change media on an interval ([#978](https://github.com/videojs/http-streaming/issues/978)) ([200c87b](https://github.com/videojs/http-streaming/commit/200c87b)), closes [#886](https://github.com/videojs/http-streaming/issues/886) [#966](https://github.com/videojs/http-streaming/issues/966) [#964](https://github.com/videojs/http-streaming/issues/964)
-* only prevent audio group creation if no other playlists are using it ([#981](https://github.com/videojs/http-streaming/issues/981)) ([645e979](https://github.com/videojs/http-streaming/commit/645e979))
-* **playback-watcher:** ignore subtitles ([#980](https://github.com/videojs/http-streaming/issues/980)) ([ca7655e](https://github.com/videojs/http-streaming/commit/ca7655e))
-
-### Chores
-
-* **package:** update aes-decrypter, m3u8 and mpd parser for vhs-utils ([#988](https://github.com/videojs/http-streaming/issues/988)) ([c31dee2](https://github.com/videojs/http-streaming/commit/c31dee2))
-
-### Tests
-
-* **playback-watcher:** subtitle test refactor ([#986](https://github.com/videojs/http-streaming/issues/986)) ([0f66d8e](https://github.com/videojs/http-streaming/commit/0f66d8e)), closes [#980](https://github.com/videojs/http-streaming/issues/980)
-
-
-# [2.2.0](https://github.com/videojs/http-streaming/compare/v2.1.0...v2.2.0) (2020-09-25)
-
-### Features
-
-* default handleManfiestRedirect to true ([#927](https://github.com/videojs/http-streaming/issues/927)) ([556321f](https://github.com/videojs/http-streaming/commit/556321f))
-* support MPD.Location ([#926](https://github.com/videojs/http-streaming/issues/926)) ([c4a43d7](https://github.com/videojs/http-streaming/commit/c4a43d7))
-* Update minimumUpdatePeriod handling ([#942](https://github.com/videojs/http-streaming/issues/942)) ([8648e76](https://github.com/videojs/http-streaming/commit/8648e76))
-
-### Bug Fixes
-
-* audio groups with the same uri as media do not count ([#952](https://github.com/videojs/http-streaming/issues/952)) ([3927c0c](https://github.com/videojs/http-streaming/commit/3927c0c))
-* dash manifest not refreshed if only some playlists are updated ([#949](https://github.com/videojs/http-streaming/issues/949)) ([31d3441](https://github.com/videojs/http-streaming/commit/31d3441))
-* detect demuxed video underflow gaps ([#948](https://github.com/videojs/http-streaming/issues/948)) ([d0ef298](https://github.com/videojs/http-streaming/commit/d0ef298))
-* MPD not refreshed if minimumUpdatePeriod is 0 ([#954](https://github.com/videojs/http-streaming/issues/954)) ([3a0682f](https://github.com/videojs/http-streaming/commit/3a0682f)), closes [#942](https://github.com/videojs/http-streaming/issues/942)
-* noop vtt segment loader handle data ([#959](https://github.com/videojs/http-streaming/issues/959)) ([d1dcd7b](https://github.com/videojs/http-streaming/commit/d1dcd7b))
-* report the correct buffered regardless of playlist change ([#950](https://github.com/videojs/http-streaming/issues/950)) ([043ccc6](https://github.com/videojs/http-streaming/commit/043ccc6))
-* Throw a player error when trying to play DRM content without eme ([#938](https://github.com/videojs/http-streaming/issues/938)) ([ce4d6fd](https://github.com/videojs/http-streaming/commit/ce4d6fd))
-* use playlist NAME when available as its ID ([#929](https://github.com/videojs/http-streaming/issues/929)) ([2269464](https://github.com/videojs/http-streaming/commit/2269464))
-* use TIME_FUDGE_FACTOR rather than rounding by decimal digits ([#881](https://github.com/videojs/http-streaming/issues/881)) ([7eb112d](https://github.com/videojs/http-streaming/commit/7eb112d))
-
-### Chores
-
-* **package:** remove engine check in pkcs7 ([#947](https://github.com/videojs/http-streaming/issues/947)) ([89392fa](https://github.com/videojs/http-streaming/commit/89392fa))
-* mark angel one dash subs as broken ([#956](https://github.com/videojs/http-streaming/issues/956)) ([56a0970](https://github.com/videojs/http-streaming/commit/56a0970))
-* mediaConfig_ -> staringMediaInfo_, startingMedia_ -> currentMediaInfo_ ([#953](https://github.com/videojs/http-streaming/issues/953)) ([8801d1c](https://github.com/videojs/http-streaming/commit/8801d1c))
-* playlist selector logging ([#921](https://github.com/videojs/http-streaming/issues/921)) ([ccdbaef](https://github.com/videojs/http-streaming/commit/ccdbaef))
-* update m3u8-parser to v4.4.3 ([#928](https://github.com/videojs/http-streaming/issues/928)) ([af5b4ee](https://github.com/videojs/http-streaming/commit/af5b4ee))
-
-### Reverts
-
-* fix: use playlist NAME when available as its ID ([#929](https://github.com/videojs/http-streaming/issues/929)) ([#957](https://github.com/videojs/http-streaming/issues/957)) ([fe8376b](https://github.com/videojs/http-streaming/commit/fe8376b))
-
-
-# [2.1.0](https://github.com/videojs/http-streaming/compare/v2.0.0...v2.1.0) (2020-07-28)
-
-### Features
-
-* Easier manual playlist switching, add codecs to renditions ([#850](https://github.com/videojs/http-streaming/issues/850)) ([f60fa1f](https://github.com/videojs/http-streaming/commit/f60fa1f))
-* exclude all incompatable browser/muxer codecs ([#903](https://github.com/videojs/http-streaming/issues/903)) ([2d0f0d7](https://github.com/videojs/http-streaming/commit/2d0f0d7))
-* expose canChangeType on the VHS property ([#911](https://github.com/videojs/http-streaming/issues/911)) ([a4ab285](https://github.com/videojs/http-streaming/commit/a4ab285))
-* let back buffer be configurable ([8c96e6c](https://github.com/videojs/http-streaming/commit/8c96e6c))
-* Support codecs switching when possible via sourceBuffer.changeType ([#841](https://github.com/videojs/http-streaming/issues/841)) ([267cc34](https://github.com/videojs/http-streaming/commit/267cc34))
-
-### Bug Fixes
-
-* always append init segment after trackinfo change ([#913](https://github.com/videojs/http-streaming/issues/913)) ([ea3650a](https://github.com/videojs/http-streaming/commit/ea3650a))
-* cleanup mediasource listeners on dispose ([#871](https://github.com/videojs/http-streaming/issues/871)) ([e50f4c9](https://github.com/videojs/http-streaming/commit/e50f4c9))
-* do not try to use unsupported audio ([#896](https://github.com/videojs/http-streaming/issues/896)) ([7711b26](https://github.com/videojs/http-streaming/commit/7711b26))
-* do not use remove source buffer on ie 11 ([#904](https://github.com/videojs/http-streaming/issues/904)) ([1ab0f07](https://github.com/videojs/http-streaming/commit/1ab0f07))
-* do not wait for audio appends for muxed segments ([#894](https://github.com/videojs/http-streaming/issues/894)) ([406cbcd](https://github.com/videojs/http-streaming/commit/406cbcd))
-* Fixed issue with MPEG-Dash MPD Playlist Finalisation during Live Play. ([#874](https://github.com/videojs/http-streaming/issues/874)) ([c807930](https://github.com/videojs/http-streaming/commit/c807930))
-* handle null return value from CaptionParser.parse ([#890](https://github.com/videojs/http-streaming/issues/890)) ([7b8fff2](https://github.com/videojs/http-streaming/commit/7b8fff2)), closes [#863](https://github.com/videojs/http-streaming/issues/863)
-* have reloadSourceOnError get src from player ([#893](https://github.com/videojs/http-streaming/issues/893)) ([1e50bc5](https://github.com/videojs/http-streaming/commit/1e50bc5)), closes [videojs/video.js#6744](https://github.com/videojs/video.js/issues/6744)
-* initialize EME for all playlists and PSSH values ([#872](https://github.com/videojs/http-streaming/issues/872)) ([e0e497f](https://github.com/videojs/http-streaming/commit/e0e497f))
-* more conservative stalled download check, better logging ([#884](https://github.com/videojs/http-streaming/issues/884)) ([615e77f](https://github.com/videojs/http-streaming/commit/615e77f))
-* pause/abort loaders before an exclude, preventing bad appends ([#902](https://github.com/videojs/http-streaming/issues/902)) ([c9126e1](https://github.com/videojs/http-streaming/commit/c9126e1))
-* stop alt loaders on main mediachanging to prevent append race ([#895](https://github.com/videojs/http-streaming/issues/895)) ([8690c78](https://github.com/videojs/http-streaming/commit/8690c78))
-* Support aac data with or without id3 tags by using mux.js[@5](https://github.com/5).6.6 ([#899](https://github.com/videojs/http-streaming/issues/899)) ([9c742ce](https://github.com/videojs/http-streaming/commit/9c742ce))
-* Use revokeObjectURL dispose for created MSE blob urls ([#849](https://github.com/videojs/http-streaming/issues/849)) ([ca73cac](https://github.com/videojs/http-streaming/commit/ca73cac))
-* Wait for sourceBuffer creation so drm setup uses valid codecs ([#878](https://github.com/videojs/http-streaming/issues/878)) ([f879563](https://github.com/videojs/http-streaming/commit/f879563))
-
-### Chores
-
-* Add vhs & mpc (vhs.masterPlaylistController_) to window of index.html ([#875](https://github.com/videojs/http-streaming/issues/875)) ([bab61d6](https://github.com/videojs/http-streaming/commit/bab61d6))
-* **demo:** add a representations selector to the demo page ([#901](https://github.com/videojs/http-streaming/issues/901)) ([0a54ae2](https://github.com/videojs/http-streaming/commit/0a54ae2))
-* fix tears of steal playready on the demo page ([#915](https://github.com/videojs/http-streaming/issues/915)) ([29a10d0](https://github.com/videojs/http-streaming/commit/29a10d0))
-* keep window vhs/mpc up to date on source switch ([#883](https://github.com/videojs/http-streaming/issues/883)) ([3ba85fd](https://github.com/videojs/http-streaming/commit/3ba85fd))
-* update DASH stream urls ([#918](https://github.com/videojs/http-streaming/issues/918)) ([902c2a5](https://github.com/videojs/http-streaming/commit/902c2a5))
-* update local video.js ([#876](https://github.com/videojs/http-streaming/issues/876)) ([c2cc9aa](https://github.com/videojs/http-streaming/commit/c2cc9aa))
-* use playready license server ([#916](https://github.com/videojs/http-streaming/issues/916)) ([6728837](https://github.com/videojs/http-streaming/commit/6728837))
-
-### Code Refactoring
-
-* remove duplicate bufferIntersection code in util/buffer.js ([#880](https://github.com/videojs/http-streaming/issues/880)) ([0ca43bd](https://github.com/videojs/http-streaming/commit/0ca43bd))
-* simplify setupEmeOptions and add tests ([#869](https://github.com/videojs/http-streaming/issues/869)) ([e3921ed](https://github.com/videojs/http-streaming/commit/e3921ed))
-
-
-# [2.0.0](https://github.com/videojs/http-streaming/compare/v2.0.0-rc.2...v2.0.0) (2020-06-16)
-
-### Features
-
-* add external vhs properties and deprecate hls and dash references ([#859](https://github.com/videojs/http-streaming/issues/859)) ([22af0b2](https://github.com/videojs/http-streaming/commit/22af0b2))
-* Use VHS playback on any non-Safari browser ([#843](https://github.com/videojs/http-streaming/issues/843)) ([225d127](https://github.com/videojs/http-streaming/commit/225d127))
-
-### Chores
-
-* fix demo page on firefox, always use vhs on safari ([#851](https://github.com/videojs/http-streaming/issues/851)) ([d567b7d](https://github.com/videojs/http-streaming/commit/d567b7d))
-* **stats:** update vhs usage in the stats page ([#867](https://github.com/videojs/http-streaming/issues/867)) ([4dda42a](https://github.com/videojs/http-streaming/commit/4dda42a))
-
-### Code Refactoring
-
-* Move caption parser to webworker, saving 5732b offloading work ([#863](https://github.com/videojs/http-streaming/issues/863)) ([491d194](https://github.com/videojs/http-streaming/commit/491d194))
-* remove aes-decrypter objects from Hls saving 1415gz bytes ([#860](https://github.com/videojs/http-streaming/issues/860)) ([a4f8302](https://github.com/videojs/http-streaming/commit/a4f8302))
-
-### Documentation
-
-* add supported features doc ([#848](https://github.com/videojs/http-streaming/issues/848)) ([38f5860](https://github.com/videojs/http-streaming/commit/38f5860))
-
-### Reverts
-
-* "fix: Use middleware and a wrapped function for seeking instead of relying on unreliable 'seeking' events ([#161](https://github.com/videojs/http-streaming/issues/161))"([#856](https://github.com/videojs/http-streaming/issues/856)) ([1165f8e](https://github.com/videojs/http-streaming/commit/1165f8e))
-
-
-### BREAKING CHANGES
-
-* The Hls object which was exposed on videojs no longer has Decrypter, AsyncStream, and decrypt from aes-decrypter.
-
-
-## [1.10.2](https://github.com/videojs/http-streaming/compare/v1.10.1...v1.10.2) (2019-05-13)
-
-### Bug Fixes
-
-* clear the blacklist for other playlists if final rendition errors ([#479](https://github.com/videojs/http-streaming/issues/479)) ([fe3b378](https://github.com/videojs/http-streaming/commit/fe3b378)), closes [#396](https://github.com/videojs/http-streaming/issues/396) [#471](https://github.com/videojs/http-streaming/issues/471)
-* **development:** rollup watch, via `npm run watch`, should work for es/cjs ([#484](https://github.com/videojs/http-streaming/issues/484)) ([ad6f292](https://github.com/videojs/http-streaming/commit/ad6f292))
-* **HLSe:** slice keys properly on IE11 ([#506](https://github.com/videojs/http-streaming/issues/506)) ([681cd6f](https://github.com/videojs/http-streaming/commit/681cd6f))
-* **package:** update mpd-parser to version 0.8.1 🚀 ([#490](https://github.com/videojs/http-streaming/issues/490)) ([a49ad3a](https://github.com/videojs/http-streaming/commit/a49ad3a))
-* **package:** update mux.js to version 5.1.2 🚀 ([#477](https://github.com/videojs/http-streaming/issues/477)) ([57a38e9](https://github.com/videojs/http-streaming/commit/57a38e9)), closes [#503](https://github.com/videojs/http-streaming/issues/503) [#504](https://github.com/videojs/http-streaming/issues/504)
-* **source-updater:** run callbacks after setting timestampOffset ([#480](https://github.com/videojs/http-streaming/issues/480)) ([6ecf859](https://github.com/videojs/http-streaming/commit/6ecf859))
-* livestream timeout issues ([#469](https://github.com/videojs/http-streaming/issues/469)) ([cf3fafc](https://github.com/videojs/http-streaming/commit/cf3fafc)), closes [segment#16](https://github.com/segment/issues/16) [segment#15](https://github.com/segment/issues/15) [segment#16](https://github.com/segment/issues/16) [segment#15](https://github.com/segment/issues/15) [segment#16](https://github.com/segment/issues/16)
-* remove both vttjs listeners to prevent leaking one of them ([#495](https://github.com/videojs/http-streaming/issues/495)) ([1db1e72](https://github.com/videojs/http-streaming/commit/1db1e72))
-
-### Performance Improvements
-
-* don't enable captionParser for audio or subtitle loaders ([#487](https://github.com/videojs/http-streaming/issues/487)) ([358877f](https://github.com/videojs/http-streaming/commit/358877f))
-
-
-## [1.10.1](https://github.com/videojs/http-streaming/compare/v1.10.0...v1.10.1) (2019-04-16)
-
-### Bug Fixes
-
-* **dash-playlist-loader:** clear out timers on dispose ([#472](https://github.com/videojs/http-streaming/issues/472)) ([2f1c222](https://github.com/videojs/http-streaming/commit/2f1c222))
-
-### Reverts
-
-* "fix: clear the blacklist for other playlists if final rendition errors ([#396](https://github.com/videojs/http-streaming/issues/396))" ([#471](https://github.com/videojs/http-streaming/issues/471)) ([dd55028](https://github.com/videojs/http-streaming/commit/dd55028))
-
-
-# [1.10.0](https://github.com/videojs/http-streaming/compare/v1.9.3...v1.10.0) (2019-04-12)
-
-### Features
-
-* add option to cache encrpytion keys in the player ([#446](https://github.com/videojs/http-streaming/issues/446)) ([599b94d](https://github.com/videojs/http-streaming/commit/599b94d)), closes [#140](https://github.com/videojs/http-streaming/issues/140)
-* add support for dash manifests describing sidx boxes ([#455](https://github.com/videojs/http-streaming/issues/455)) ([80dde16](https://github.com/videojs/http-streaming/commit/80dde16))
-
-### Bug Fixes
-
-* clear the blacklist for other playlists if final rendition errors ([#396](https://github.com/videojs/http-streaming/issues/396)) ([6e6c8c2](https://github.com/videojs/http-streaming/commit/6e6c8c2))
-* on dispose, don't call abort on SourceBuffer until after remove() has finished ([3806750](https://github.com/videojs/http-streaming/commit/3806750))
-
-### Documentation
-
-* **README:** update broken link to full docs ([#440](https://github.com/videojs/http-streaming/issues/440)) ([fbd615c](https://github.com/videojs/http-streaming/commit/fbd615c))
-
-
-## [1.9.3](https://github.com/videojs/http-streaming/compare/v1.9.2...v1.9.3) (2019-03-21)
-
-### Bug Fixes
-
-* **id3:** ignore unsupported id3 frames ([#437](https://github.com/videojs/http-streaming/issues/437)) ([7040b7d](https://github.com/videojs/http-streaming/commit/7040b7d)), closes [videojs/video.js#5823](https://github.com/videojs/video.js/issues/5823)
-
-### Documentation
-
-* add diagrams for playlist loaders ([#426](https://github.com/videojs/http-streaming/issues/426)) ([52201f9](https://github.com/videojs/http-streaming/commit/52201f9))
-
-
-## [1.9.2](https://github.com/videojs/http-streaming/compare/v1.9.1...v1.9.2) (2019-03-14)
-
-### Bug Fixes
-
-* expose `custom` segment property in the segment metadata track ([#429](https://github.com/videojs/http-streaming/issues/429)) ([17510da](https://github.com/videojs/http-streaming/commit/17510da))
-
-
-## [1.9.1](https://github.com/videojs/http-streaming/compare/v1.9.0...v1.9.1) (2019-03-05)
-
-### Bug Fixes
-
-* fix for streams that would occasionally never fire an `ended` event ([fc09926](https://github.com/videojs/http-streaming/commit/fc09926))
-* Fix video playback freezes caused by not using absolute current time ([#401](https://github.com/videojs/http-streaming/issues/401)) ([957ecfd](https://github.com/videojs/http-streaming/commit/957ecfd))
-* only fire seekablechange when values of seekable ranges actually change ([#415](https://github.com/videojs/http-streaming/issues/415)) ([a4c056e](https://github.com/videojs/http-streaming/commit/a4c056e))
-* Prevent infinite buffering at the start of looped video on edge ([#392](https://github.com/videojs/http-streaming/issues/392)) ([b6d1b97](https://github.com/videojs/http-streaming/commit/b6d1b97))
-
-### Code Refactoring
-
-* align DashPlaylistLoader closer to PlaylistLoader states ([#386](https://github.com/videojs/http-streaming/issues/386)) ([5d80fe7](https://github.com/videojs/http-streaming/commit/5d80fe7))
-
-
-# [1.9.0](https://github.com/videojs/http-streaming/compare/v1.8.0...v1.9.0) (2019-02-07)
-
-### Features
-
-* Use exposed transmuxer time modifications for more accurate conversion between program and player times ([#371](https://github.com/videojs/http-streaming/issues/371)) ([41df5c0](https://github.com/videojs/http-streaming/commit/41df5c0))
-
-### Bug Fixes
-
-* m3u8 playlist is not updating when only endList changes ([#373](https://github.com/videojs/http-streaming/issues/373)) ([c7d1306](https://github.com/videojs/http-streaming/commit/c7d1306))
-* Prevent exceptions from being thrown by the MediaSource ([#389](https://github.com/videojs/http-streaming/issues/389)) ([8c06366](https://github.com/videojs/http-streaming/commit/8c06366))
-
-### Chores
-
-* Update mux.js to the latest version 🚀 ([#397](https://github.com/videojs/http-streaming/issues/397)) ([38ec2a5](https://github.com/videojs/http-streaming/commit/38ec2a5))
-
-### Tests
-
-* added test for playlist not updating when only endList changes ([#394](https://github.com/videojs/http-streaming/issues/394)) ([39d0be2](https://github.com/videojs/http-streaming/commit/39d0be2))
-
-
-# [1.8.0](https://github.com/videojs/http-streaming/compare/v1.7.0...v1.8.0) (2019-01-10)
-
-### Features
-
-* expose custom M3U8 mapper API ([#325](https://github.com/videojs/http-streaming/issues/325)) ([609beb3](https://github.com/videojs/http-streaming/commit/609beb3))
-
-### Bug Fixes
-
-* **id3:** cuechange event not being triggered on audio-only HLS streams ([#334](https://github.com/videojs/http-streaming/issues/334)) ([bab70fd](https://github.com/videojs/http-streaming/commit/bab70fd)), closes [#130](https://github.com/videojs/http-streaming/issues/130)
-
-
-# [1.7.0](https://github.com/videojs/http-streaming/compare/v1.6.0...v1.7.0) (2019-01-04)
-
-### Features
-
-* expose custom M3U8 parser API ([#331](https://github.com/videojs/http-streaming/issues/331)) ([b0643a4](https://github.com/videojs/http-streaming/commit/b0643a4))
-
-
-# [1.6.0](https://github.com/videojs/http-streaming/compare/v1.5.1...v1.6.0) (2018-12-21)
-
-### Features
-
-* Add allowSeeksWithinUnsafeLiveWindow property ([#320](https://github.com/videojs/http-streaming/issues/320)) ([74b28e8](https://github.com/videojs/http-streaming/commit/74b28e8))
-
-### Chores
-
-* add clock.ticks to now async operations in tests ([#315](https://github.com/videojs/http-streaming/issues/315)) ([895c86a](https://github.com/videojs/http-streaming/commit/895c86a))
-
-### Documentation
-
-* Add README entry on DRM and videojs-contrib-eme ([#307](https://github.com/videojs/http-streaming/issues/307)) ([93b6167](https://github.com/videojs/http-streaming/commit/93b6167))
-
-
-## [1.5.1](https://github.com/videojs/http-streaming/compare/v1.5.0...v1.5.1) (2018-12-06)
-
-### Bug Fixes
-
-* added missing manifest information on to segments (EXT-X-PROGRAM-DATE-TIME) ([#236](https://github.com/videojs/http-streaming/issues/236)) ([a35dd09](https://github.com/videojs/http-streaming/commit/a35dd09))
-* remove player props on dispose to stop middleware ([#229](https://github.com/videojs/http-streaming/issues/229)) ([cd13f9f](https://github.com/videojs/http-streaming/commit/cd13f9f))
-
-### Documentation
-
-* add dash to package.json description ([#267](https://github.com/videojs/http-streaming/issues/267)) ([3296c68](https://github.com/videojs/http-streaming/commit/3296c68))
-* add documentation for reloadSourceOnError ([#266](https://github.com/videojs/http-streaming/issues/266)) ([7448b37](https://github.com/videojs/http-streaming/commit/7448b37))
-
-
-# [1.5.0](https://github.com/videojs/http-streaming/compare/v1.4.2...v1.5.0) (2018-11-13)
-
-### Features
-
-* Add useBandwidthFromLocalStorage option ([#275](https://github.com/videojs/http-streaming/issues/275)) ([60c88ae](https://github.com/videojs/http-streaming/commit/60c88ae))
-
-### Bug Fixes
-
-* don't wait for requests to finish when encountering an error in media-segment-request ([#286](https://github.com/videojs/http-streaming/issues/286)) ([970e3ce](https://github.com/videojs/http-streaming/commit/970e3ce))
-* throttle final playlist reloads when using DASH ([#277](https://github.com/videojs/http-streaming/issues/277)) ([1c2887a](https://github.com/videojs/http-streaming/commit/1c2887a))
-
-
-## [1.4.2](https://github.com/videojs/http-streaming/compare/v1.4.1...v1.4.2) (2018-11-01)
-
-### Chores
-
-* pin to node 8 for now ([#279](https://github.com/videojs/http-streaming/issues/279)) ([f900dc4](https://github.com/videojs/http-streaming/commit/f900dc4))
-* update mux.js to 5.0.1 ([#282](https://github.com/videojs/http-streaming/issues/282)) ([af6ee4f](https://github.com/videojs/http-streaming/commit/af6ee4f))
-
-
-## [1.4.1](https://github.com/videojs/http-streaming/compare/v1.4.0...v1.4.1) (2018-10-25)
-
-### Bug Fixes
-
-* **subtitles:** set default property if default and autoselect are both enabled ([#239](https://github.com/videojs/http-streaming/issues/239)) ([ee594e5](https://github.com/videojs/http-streaming/commit/ee594e5))
-
-
-# [1.4.0](https://github.com/videojs/http-streaming/compare/v1.3.1...v1.4.0) (2018-10-24)
-
-### Features
-
-* limited experimental DASH multiperiod support ([#268](https://github.com/videojs/http-streaming/issues/268)) ([a213807](https://github.com/videojs/http-streaming/commit/a213807))
-* smoothQualityChange flag ([#235](https://github.com/videojs/http-streaming/issues/235)) ([0e4fdf9](https://github.com/videojs/http-streaming/commit/0e4fdf9))
-
-### Bug Fixes
-
-* immediately setup EME if available ([#263](https://github.com/videojs/http-streaming/issues/263)) ([7577e90](https://github.com/videojs/http-streaming/commit/7577e90))
-
-
-## [1.3.1](https://github.com/videojs/http-streaming/compare/v1.3.0...v1.3.1) (2018-10-15)
-
-### Bug Fixes
-
-* ensure content loops ([#259](https://github.com/videojs/http-streaming/issues/259)) ([26300df](https://github.com/videojs/http-streaming/commit/26300df))
-
-
-# [1.3.0](https://github.com/videojs/http-streaming/compare/v1.2.6...v1.3.0) (2018-10-05)
-
-### Features
-
-* add an option to ignore player size in selection logic ([#238](https://github.com/videojs/http-streaming/issues/238)) ([7ae42b1](https://github.com/videojs/http-streaming/commit/7ae42b1))
-
-### Documentation
-
-* Update CONTRIBUTING.md ([#242](https://github.com/videojs/http-streaming/issues/242)) ([9d83e9d](https://github.com/videojs/http-streaming/commit/9d83e9d))
-
-
-## [1.2.6](https://github.com/videojs/http-streaming/compare/v1.2.5...v1.2.6) (2018-09-21)
-
-### Bug Fixes
-
-* stutter after fast quality change in IE/Edge ([#213](https://github.com/videojs/http-streaming/issues/213)) ([2c0d9b2](https://github.com/videojs/http-streaming/commit/2c0d9b2))
-
-### Documentation
-
-* update issue template to link to the troubleshooting guide ([#215](https://github.com/videojs/http-streaming/issues/215)) ([413f0e8](https://github.com/videojs/http-streaming/commit/413f0e8))
-* update README notes for video.js 7 ([#200](https://github.com/videojs/http-streaming/issues/200)) ([d68ce0c](https://github.com/videojs/http-streaming/commit/d68ce0c))
-* update troubleshooting guide for Edge/mobile Chrome ([#216](https://github.com/videojs/http-streaming/issues/216)) ([21e5335](https://github.com/videojs/http-streaming/commit/21e5335))
-
-
-## [1.2.5](https://github.com/videojs/http-streaming/compare/v1.2.4...v1.2.5) (2018-08-24)
-
-### Bug Fixes
-
-* fix replay functionality ([#204](https://github.com/videojs/http-streaming/issues/204)) ([fd6be83](https://github.com/videojs/http-streaming/commit/fd6be83))
-
-
-## [1.2.4](https://github.com/videojs/http-streaming/compare/v1.2.3...v1.2.4) (2018-08-13)
-
-### Bug Fixes
-
-* Remove buffered data on fast quality switches ([#113](https://github.com/videojs/http-streaming/issues/113)) ([bc94fbb](https://github.com/videojs/http-streaming/commit/bc94fbb))
-
-
-## [1.2.3](https://github.com/videojs/http-streaming/compare/v1.2.2...v1.2.3) (2018-08-09)
-
-### Chores
-
-* link to minified example in main page ([#189](https://github.com/videojs/http-streaming/issues/189)) ([15a7f92](https://github.com/videojs/http-streaming/commit/15a7f92))
-* use netlify for easier testing ([#188](https://github.com/videojs/http-streaming/issues/188)) ([d2e0d35](https://github.com/videojs/http-streaming/commit/d2e0d35))
-
-
-## [1.2.2](https://github.com/videojs/http-streaming/compare/v1.2.1...v1.2.2) (2018-08-07)
-
-### Bug Fixes
-
-* typeof minification ([#182](https://github.com/videojs/http-streaming/issues/182)) ([7c68335](https://github.com/videojs/http-streaming/commit/7c68335))
-* Use middleware and a wrapped function for seeking instead of relying on unreliable 'seeking' events ([#161](https://github.com/videojs/http-streaming/issues/161)) ([6c68761](https://github.com/videojs/http-streaming/commit/6c68761))
-
-### Chores
-
-* add logo ([#184](https://github.com/videojs/http-streaming/issues/184)) ([a55626c](https://github.com/videojs/http-streaming/commit/a55626c))
-
-### Documentation
-
-* add note for Safari captions error ([#174](https://github.com/videojs/http-streaming/issues/174)) ([7b03530](https://github.com/videojs/http-streaming/commit/7b03530))
-
-### Tests
-
-* add support for real segments in tests ([#178](https://github.com/videojs/http-streaming/issues/178)) ([2b07fca](https://github.com/videojs/http-streaming/commit/2b07fca))
-
-
-## [1.2.1](https://github.com/videojs/http-streaming/compare/v1.2.0...v1.2.1) (2018-07-17)
-
-### Bug Fixes
-
-* convert non-latin characters in IE ([#157](https://github.com/videojs/http-streaming/issues/157)) ([17678fb](https://github.com/videojs/http-streaming/commit/17678fb))
-
-
-# [1.2.0](https://github.com/videojs/http-streaming/compare/v1.1.0...v1.2.0) (2018-07-16)
-
-### Features
-
-* **captions:** write in-band captions from DASH fmp4 segments to the textTrack API ([#108](https://github.com/videojs/http-streaming/issues/108)) ([7c11911](https://github.com/videojs/http-streaming/commit/7c11911))
-
-### Chores
-
-* add welcome bot config from video.js ([#150](https://github.com/videojs/http-streaming/issues/150)) ([922cfee](https://github.com/videojs/http-streaming/commit/922cfee))
-
-
-# [1.1.0](https://github.com/videojs/http-streaming/compare/v1.0.2...v1.1.0) (2018-06-06)
-
-### Features
-
-* Utilize option to override native on tech ([#76](https://github.com/videojs/http-streaming/issues/76)) ([5c7ab4c](https://github.com/videojs/http-streaming/commit/5c7ab4c))
-
-### Chores
-
-* update tests and pages for video.js 7 ([#102](https://github.com/videojs/http-streaming/issues/102)) ([d6f5005](https://github.com/videojs/http-streaming/commit/d6f5005))
-
-
-## [1.0.2](https://github.com/videojs/http-streaming/compare/v1.0.1...v1.0.2) (2018-05-17)
-
-### Bug Fixes
-
-* make project Video.js 7 ready ([#92](https://github.com/videojs/http-streaming/issues/92)) ([decad87](https://github.com/videojs/http-streaming/commit/decad87))
-* make sure that es build is babelified ([#97](https://github.com/videojs/http-streaming/issues/97)) ([5f0428d](https://github.com/videojs/http-streaming/commit/5f0428d))
-
-### Documentation
-
-* update documentation with a glossary and intro page, added DASH background ([#94](https://github.com/videojs/http-streaming/issues/94)) ([4b0fde9](https://github.com/videojs/http-streaming/commit/4b0fde9))
-
-
-## [1.0.1](https://github.com/videojs/http-streaming/compare/v1.0.0...v1.0.1) (2018-04-12)
-
-### Bug Fixes
-
-* minified build ([#84](https://github.com/videojs/http-streaming/issues/84)) ([2402ac6](https://github.com/videojs/http-streaming/commit/2402ac6))
-
-
-# [1.0.0](https://github.com/videojs/http-streaming/compare/v0.9.0...v1.0.0) (2018-04-10)
-
-### Chores
-
-* sync videojs-contrib-hls updates ([#75](https://github.com/videojs/http-streaming/issues/75)) ([9223588](https://github.com/videojs/http-streaming/commit/9223588))
-* update the aes-decrypter ([#71](https://github.com/videojs/http-streaming/issues/71)) ([27ed914](https://github.com/videojs/http-streaming/commit/27ed914))
-
-### Documentation
-
-* update docs for overrideNative ([#77](https://github.com/videojs/http-streaming/issues/77)) ([98ca6d3](https://github.com/videojs/http-streaming/commit/98ca6d3))
-* update known issues for fmp4 captions ([#79](https://github.com/videojs/http-streaming/issues/79)) ([c418301](https://github.com/videojs/http-streaming/commit/c418301))
-
-
-# [0.9.0](https://github.com/videojs/http-streaming/compare/v0.8.0...v0.9.0) (2018-03-30)
-
-### Features
-
-* support in-manifest DRM data ([#60](https://github.com/videojs/http-streaming/issues/60)) ([a1cad82](https://github.com/videojs/http-streaming/commit/a1cad82))
-
-
-# [0.8.0](https://github.com/videojs/http-streaming/compare/v0.7.2...v0.8.0) (2018-03-30)
-
-### Code Refactoring
-
-* export corrections ([#68](https://github.com/videojs/http-streaming/issues/68)) ([aab3b90](https://github.com/videojs/http-streaming/commit/aab3b90))
-* use rollup for build ([#69](https://github.com/videojs/http-streaming/issues/69)) ([c28c25c](https://github.com/videojs/http-streaming/commit/c28c25c))
-
-# 0.7.0
-* feat: Live support for DASH
-
-# 0.6.1
-* use webwackify for webworkers to support webpack bundle ([#50](https://github.com/videojs/http-streaming/pull/45))
-
-# 0.5.3
-* fix: program date time handling ([#45](https://github.com/videojs/http-streaming/pull/45))
- * update m3u8-parser to v4.2.0
- * use segment program date time info
-* feat: Adding support for segments in Period and Representation ([#47](https://github.com/videojs/http-streaming/pull/47))
-* wait for both main and audio loaders for endOfStream if main starting media unknown ([#44](https://github.com/videojs/http-streaming/pull/44))
-
-# 0.5.2
-* add debug logging statement for seekable updates ([#40](https://github.com/videojs/http-streaming/pull/40))
-
-# 0.5.1
-* Fix audio only streams with EXT-X-MEDIA tags ([#34](https://github.com/videojs/http-streaming/pull/34))
-* Merge videojs-contrib-hls master into http-streaming master ([#35](https://github.com/videojs/http-streaming/pull/35))
- * Update sinon to 1.10.3=
- * Update videojs-contrib-quality-levels to ^2.0.4
- * Fix test for event handler cleanup on dispose by calling event handling methods
-* fix: Don't reset eme options ([#32](https://github.com/videojs/http-streaming/pull/32))
-
-# 0.5.0
-* update mpd-parser to support more segment list types ([#27](https://github.com/videojs/http-streaming/issues/27))
-
-# 0.4.0
-* Removed Flash support ([#15](https://github.com/videojs/http-streaming/issues/15))
-* Blacklist playlists not supported by browser media source before initial selection ([#17](https://github.com/videojs/http-streaming/issues/17))
-
-# 0.3.1
-* Skip flash-based source handler with DASH sources ([#14](https://github.com/videojs/http-streaming/issues/14))
-
-# 0.3.0
-* Added additional properties to the stats object ([#10](https://github.com/videojs/http-streaming/issues/10))
-
-# 0.2.1
-* Updated the mpd-parser to fix IE11 DASH support ([#12](https://github.com/videojs/http-streaming/issues/12))
-
-# 0.2.0
-* Initial DASH Support ([#8](https://github.com/videojs/http-streaming/issues/8))
-
-# 0.1.0
-* Initial release, based on [videojs-contrib-hls 5.12.2](https://github.com/videojs/videojs-contrib-hls)
-
diff --git a/node_modules/@videojs/http-streaming/CONTRIBUTING.md b/node_modules/@videojs/http-streaming/CONTRIBUTING.md
deleted file mode 100644
index 175d976..0000000
--- a/node_modules/@videojs/http-streaming/CONTRIBUTING.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# CONTRIBUTING
-
-We welcome contributions from everyone!
-
-## Getting Started
-
-Make sure you have Node.js 8 or higher and npm installed.
-
-1. Fork this repository and clone your fork
-1. Install dependencies: `npm install`
-1. Run a development server: `npm start`
-
-### Making Changes
-
-Refer to the [video.js plugin conventions][conventions] for more detail on best practices and tooling for video.js plugin authorship.
-
-When you've made your changes, push your commit(s) to your fork and issue a pull request against the original repository.
-
-### Running Tests
-
-Testing is a crucial part of any software project. For all but the most trivial changes (typos, etc) test cases are expected. Tests are run in actual browsers using [Karma][karma].
-
-- In all available and supported browsers: `npm test`
-- In a specific browser: `npm run test:chrome`, `npm run test:firefox`, etc.
-- While development server is running (`npm start`), navigate to [`http://localhost:9999/test/`][local]
-
-
-[karma]: http://karma-runner.github.io/
-[local]: http://localhost:9999/test/
-[conventions]: https://github.com/videojs/generator-videojs-plugin/blob/master/docs/conventions.md
diff --git a/node_modules/@videojs/http-streaming/LICENSE b/node_modules/@videojs/http-streaming/LICENSE
deleted file mode 100644
index ae93385..0000000
--- a/node_modules/@videojs/http-streaming/LICENSE
+++ /dev/null
@@ -1,49 +0,0 @@
-Copyright Brightcove, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-
-The AES decryption implementation in this project is derived from the
-Stanford Javascript Cryptography Library
-(http://bitwiseshiftleft.github.io/sjcl/). That work is covered by the
-following copyright and permission notice:
-
-Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- 2. 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 AUTHORS ``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
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.
-
-The views and conclusions contained in the software and documentation
-are those of the authors and should not be interpreted as representing
-official policies, either expressed or implied, of the authors.
diff --git a/node_modules/@videojs/http-streaming/README.md b/node_modules/@videojs/http-streaming/README.md
deleted file mode 100644
index e42829a..0000000
--- a/node_modules/@videojs/http-streaming/README.md
+++ /dev/null
@@ -1,1000 +0,0 @@
-
-
-# videojs-http-streaming (VHS)
-
-[![Build Status][travis-icon]][travis-link]
-[![Slack Status][slack-icon]][slack-link]
-[![Greenkeeper badge][greenkeeper-icon]][greenkeeper-link]
-
-Play HLS, DASH, and future HTTP streaming protocols with video.js, even where they're not
-natively supported.
-
-Included in video.js 7 by default! See the [video.js 7 blog post](https://blog.videojs.com/video-js-7-is-here/)
-
-Maintenance Status: Stable
-
-Video.js Compatibility: 6.0, 7.0
-
-
-
-
-
-- [Installation](#installation)
- - [NPM](#npm)
- - [CDN](#cdn)
- - [Releases](#releases)
- - [Manual Build](#manual-build)
-- [Contributing](#contributing)
-- [Troubleshooting](#troubleshooting)
-- [Talk to us](#talk-to-us)
-- [Getting Started](#getting-started)
-- [Compatibility](#compatibility)
- - [Browsers which support MSE](#browsers-which-support-mse)
- - [Native only](#native-only)
- - [Flash Support](#flash-support)
- - [DRM](#drm)
-- [Documentation](#documentation)
- - [Options](#options)
- - [How to use](#how-to-use)
- - [Initialization](#initialization)
- - [Source](#source)
- - [List](#list)
- - [withCredentials](#withcredentials)
- - [handleManifestRedirects](#handlemanifestredirects)
- - [useCueTags](#usecuetags)
- - [parse708captions](#parse708captions)
- - [overrideNative](#overridenative)
- - [blacklistDuration](#blacklistduration)
- - [maxPlaylistRetries](#maxplaylistretries)
- - [bandwidth](#bandwidth)
- - [useBandwidthFromLocalStorage](#usebandwidthfromlocalstorage)
- - [enableLowInitialPlaylist](#enablelowinitialplaylist)
- - [limitRenditionByPlayerDimensions](#limitrenditionbyplayerdimensions)
- - [useDevicePixelRatio](#usedevicepixelratio)
- - [smoothQualityChange](#smoothqualitychange)
- - [allowSeeksWithinUnsafeLiveWindow](#allowseekswithinunsafelivewindow)
- - [customTagParsers](#customtagparsers)
- - [customTagMappers](#customtagmappers)
- - [cacheEncryptionKeys](#cacheencryptionkeys)
- - [handlePartialData](#handlepartialdata)
- - [liveRangeSafeTimeDelta](#liverangesafetimedelta)
- - [captionServices](#captionservices)
- - [Format](#format)
- - [Example](#example)
- - [Runtime Properties](#runtime-properties)
- - [vhs.playlists.master](#vhsplaylistsmaster)
- - [vhs.playlists.media](#vhsplaylistsmedia)
- - [vhs.systemBandwidth](#vhssystembandwidth)
- - [vhs.bandwidth](#vhsbandwidth)
- - [vhs.throughput](#vhsthroughput)
- - [vhs.selectPlaylist](#vhsselectplaylist)
- - [vhs.representations](#vhsrepresentations)
- - [vhs.xhr](#vhsxhr)
- - [vhs.stats](#vhsstats)
- - [Events](#events)
- - [loadedmetadata](#loadedmetadata)
- - [VHS Usage Events](#vhs-usage-events)
- - [Presence Stats](#presence-stats)
- - [Use Stats](#use-stats)
- - [In-Band Metadata](#in-band-metadata)
- - [Segment Metadata](#segment-metadata)
- - [Object as Source](#object-as-source)
-- [Hosting Considerations](#hosting-considerations)
-- [Known Issues and Workarounds](#known-issues-and-workarounds)
- - [Fragmented MP4 Support](#fragmented-mp4-support)
- - [Assets with an Audio-Only Rate Get Stuck in Audio-Only](#assets-with-an-audio-only-rate-get-stuck-in-audio-only)
- - [DASH Assets with `$Time` Interpolation and `SegmentTimeline`s with No `t`](#dash-assets-with-time-interpolation-and-segmenttimelines-with-no-t)
-- [Testing](#testing)
-- [Debugging](#debugging)
-- [Release History](#release-history)
-- [Building](#building)
-- [Development](#development)
- - [Tools](#tools)
- - [Commands](#commands)
-
-
-
-## Installation
-### NPM
-To install `videojs-http-streaming` with npm run
-
-```bash
-npm install --save @videojs/http-streaming
-```
-
-### CDN
-Select a version of VHS from the [CDN](https://unpkg.com/@videojs/http-streaming/dist/)
-
-### Releases
-Download a release of [videojs-http-streaming](https://github.com/videojs/http-streaming/releases)
-
-### Manual Build
-Download a copy of this git repository and then follow the steps in [Building](#building)
-
-## Contributing
-See [CONTRIBUTING.md](/CONTRIBUTING.md)
-
-## Troubleshooting
-See [our troubleshooting guide](/docs/troubleshooting.md)
-
-## Talk to us
-Drop by our slack channel (#playback) on the [Video.js slack][slack-link].
-
-## Getting Started
-This library is included in video.js 7 by default, if you are using an older version of video.js then
-get a copy of [videojs-http-streaming](#installation) and include it in your page along with video.js:
-
-```html
-
-
-
-
-
-
-```
-
-Check out our [live example](https://jsbin.com/gejugat/edit?html,output) if you're having trouble.
-
-Is it recommended to use the `` element or load a source with `player.src(sourceObject)` in order to prevent the video element from playing the source natively where HLS is supported.
-
-## Compatibility
-
-The [Media Source Extensions](http://caniuse.com/#feat=mediasource) API is required for http-streaming to play HLS or MPEG-DASH.
-
-### Browsers which support MSE
-
-- Chrome
-- Firefox
-- Internet Explorer 11 Windows 10 or 8.1
-
-These browsers have some level of native HLS support, which will be used unless the [overrideNative](#overridenative) option is used:
-
-- Chrome Android
-- Firefox Android
-- Edge
-
-### Native only
-
-- Mac Safari
-- iOS Safari
-
-Mac Safari does have MSE support, but native HLS is recommended
-
-### Flash Support
-This plugin does not support Flash playback. Instead, it is recommended that users use the [videojs-flashls-source-handler](https://github.com/brightcove/videojs-flashls-source-handler) plugin as a fallback option for browsers that don't have a native
-[HLS](https://caniuse.com/#feat=http-live-streaming)/[DASH](https://caniuse.com/#feat=mpeg-dash) player or support for [Media Source Extensions](http://caniuse.com/#feat=mediasource).
-
-### DRM
-
-DRM is supported through [videojs-contrib-eme](https://github.com/videojs/videojs-contrib-eme). In order to use DRM, include the videojs-contrib-eme plug, [initialize it](https://github.com/videojs/videojs-contrib-eme#initialization), and add options to either the [plugin](https://github.com/videojs/videojs-contrib-eme#plugin-options) or the [source](https://github.com/videojs/videojs-contrib-eme#source-options).
-
-Detailed option information can be found in the [videojs-contrib-eme README](https://github.com/videojs/videojs-contrib-eme/blob/master/README.md).
-
-## Documentation
-[HTTP Live Streaming](https://developer.apple.com/streaming/) (HLS) has
-become a de-facto standard for streaming video on mobile devices
-thanks to its native support on iOS and Android. There are a number of
-reasons independent of platform to recommend the format, though:
-
-- Supports (client-driven) adaptive bitrate selection
-- Delivered over standard HTTP ports
-- Simple, text-based manifest format
-- No proprietary streaming servers required
-
-Unfortunately, all the major desktop browsers except for Safari are
-missing HLS support. That leaves web developers in the unfortunate
-position of having to maintain alternate renditions of the same video
-and potentially having to forego HTML-based video entirely to provide
-the best desktop viewing experience.
-
-This project addresses that situation by providing a polyfill for HLS
-on browsers that have support for [Media Source
-Extensions](http://caniuse.com/#feat=mediasource).
-You can deploy a single HLS stream, code against the
-regular HTML5 video APIs, and create a fast, high-quality video
-experience across all the big web device categories.
-
-Check out the [full documentation](docs/README.md) for details on how HLS works
-and advanced configuration. A description of the [adaptive switching
-behavior](docs/bitrate-switching.md) is available, too.
-
-videojs-http-streaming supports a bunch of HLS features. Here
-are some highlights:
-
-- video-on-demand and live playback modes
-- backup or redundant streams
-- mid-segment quality switching
-- AES-128 segment encryption
-- CEA-608 captions are automatically translated into standard HTML5
- [caption text tracks][0]
-- In-Manifest WebVTT subtitles are automatically translated into standard HTML5
- subtitle tracks
-- Timed ID3 Metadata is automatically translated into HTML5 metedata
- text tracks
-- Highly customizable adaptive bitrate selection
-- Automatic bandwidth tracking
-- Cross-domain credentials support with CORS
-- Tight integration with video.js and a philosophy of exposing as much
- as possible with standard HTML APIs
-- Stream with multiple audio tracks and switching to those audio tracks
- (see the docs folder) for info
-- Media content in
- [fragmented MP4s](https://developer.apple.com/videos/play/wwdc2016/504/)
- instead of the MPEG2-TS container format.
-
-[0]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track
-
-For a more complete list of supported and missing features, refer to
-[this doc](docs/supported-features.md).
-
-### Options
-#### How to use
-
-##### Initialization
-You may pass in an options object to the hls source handler at player
-initialization. You can pass in options just like you would for other
-parts of video.js:
-
-```javascript
-// html5 for html hls
-videojs(video, {
- html5: {
- vhs: {
- withCredentials: true
- }
- }
-});
-```
-
-##### Source
-Some options, such as `withCredentials` can be passed in to vhs during
-`player.src`
-
-```javascript
-
-var player = videojs('some-video-id');
-
-player.src({
- src: 'https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8',
- type: 'application/x-mpegURL',
- withCredentials: true
-});
-```
-
-#### List
-##### withCredentials
-* Type: `boolean`
-* can be used as a source option
-* can be used as an initialization option
-
-When the `withCredentials` property is set to `true`, all XHR requests for
-manifests and segments would have `withCredentials` set to `true` as well. This
-enables storing and passing cookies from the server that the manifests and
-segments live on. This has some implications on CORS because when set, the
-`Access-Control-Allow-Origin` header cannot be set to `*`, also, the response
-headers require the addition of `Access-Control-Allow-Credentials` header which
-is set to `true`.
-See html5rocks's [article](http://www.html5rocks.com/en/tutorials/cors/)
-for more info.
-
-##### handleManifestRedirects
-* Type: `boolean`
-* Default: `false`
-* can be used as a source option
-* can be used as an initialization option
-
-When the `handleManifestRedirects` property is set to `true`, manifest requests
-which are redirected will have their URL updated to the new URL for future
-requests.
-
-##### useCueTags
-* Type: `boolean`
-* can be used as an initialization option
-
-When the `useCueTags` property is set to `true,` a text track is created with
-label 'ad-cues' and kind 'metadata'. The track is then added to
-`player.textTracks()`. Changes in active cue may be
-tracked by following the Video.js cue points API for text tracks. For example:
-
-```javascript
-let textTracks = player.textTracks();
-let cuesTrack;
-
-for (let i = 0; i < textTracks.length; i++) {
- if (textTracks[i].label === 'ad-cues') {
- cuesTrack = textTracks[i];
- }
-}
-
-cuesTrack.addEventListener('cuechange', function() {
- let activeCues = cuesTrack.activeCues;
-
- for (let i = 0; i < activeCues.length; i++) {
- let activeCue = activeCues[i];
-
- console.log('Cue runs from ' + activeCue.startTime +
- ' to ' + activeCue.endTime);
- }
-});
-```
-
-##### parse708captions
-* Type: `boolean`
-* Default: `true`
-* can be used as an initialization option
-
-When set to `false`, 708 captions in the stream are not parsed and will not show up in text track lists or the captions menu.
-
-##### overrideNative
-* Type: `boolean`
-* can be used as an initialization option
-
-Try to use videojs-http-streaming even on platforms that provide some
-level of HLS support natively. There are a number of platforms that
-*technically* play back HLS content but aren't very reliable or are
-missing features like CEA-608 captions support. When `overrideNative`
-is true, if the platform supports Media Source Extensions
-videojs-http-streaming will take over HLS playback to provide a more
-consistent experience.
-
-```javascript
-// via the constructor
-var player = videojs('playerId', {
- html5: {
- vhs: {
- overrideNative: true
- },
- nativeAudioTracks: false,
- nativeVideoTracks: false
- }
-});
-```
-
-Since MSE playback may be desirable on all browsers with some native support other than Safari, `overrideNative: !videojs.browser.IS_SAFARI` could be used.
-
-##### blacklistDuration
-* Type: `number`
-* can be used as an initialization option
-
-When the `blacklistDuration` property is set to a time duration in seconds,
-if a playlist is blacklisted, it will be blacklisted for a period of that
-customized duration. This enables the blacklist duration to be configured
-by the user.
-
-#### maxPlaylistRetries
-* Type: `number`
-* Default: `Infinity`
-* can be used as an initialization option
-
-The max number of times that a playlist will retry loading following an error
-before being indefinitely excluded from the rendition selection algorithm. Note: the number of retry attempts needs to _exceed_ this value before a playlist will be excluded.
-
-##### bandwidth
-* Type: `number`
-* can be used as an initialization option
-
-When the `bandwidth` property is set (bits per second), it will be used in
-the calculation for initial playlist selection, before more bandwidth
-information is seen by the player.
-
-##### useBandwidthFromLocalStorage
-* Type: `boolean`
-* can be used as an initialization option
-
-If true, `bandwidth` and `throughput` values are stored in and retrieved from local
-storage on startup (for initial rendition selection). This setting is `false` by default.
-
-##### enableLowInitialPlaylist
-* Type: `boolean`
-* can be used as an initialization option
-
-When `enableLowInitialPlaylist` is set to true, it will be used to select
-the lowest bitrate playlist initially. This helps to decrease playback start time.
-This setting is `false` by default.
-
-##### limitRenditionByPlayerDimensions
-* Type: `boolean`
-* can be used as an initialization option
-
-When `limitRenditionByPlayerDimensions` is set to true, rendition
-selection logic will take into account the player size and rendition
-resolutions when making a decision.
-This setting is `true` by default.
-
-##### useDevicePixelRatio
-* Type: `boolean`
-* can be used as an initialization option.
-
-If true, this will take the device pixel ratio into account when doing rendition switching. This means that if you have a player with the width of `540px` in a high density display with a device pixel ratio of 2, a rendition of `1080p` will be allowed.
-This setting is `false` by default.
-
-##### smoothQualityChange
-* NOTE: DEPRECATED
-* Type: `boolean`
-* can be used as a source option
-* can be used as an initialization option
-
-smoothQualityChange is deprecated and will be removed in the next major version of VHS.
-
-Instead of its prior behavior, smoothQualityChange will now call fastQualityChange, which
-clears the buffer, chooses a new rendition, and starts loading content from the current
-playhead position.
-
-##### allowSeeksWithinUnsafeLiveWindow
-* Type: `boolean`
-* can be used as a source option
-
-When `allowSeeksWithinUnsafeLiveWindow` is set to `true`, if the active playlist is live
-and a seek is made to a time between the safe live point (end of manifest minus three
-times the target duration,
-see [the hls spec](https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.3.3)
-for details) and the end of the playlist, the seek is allowed, rather than corrected to
-the safe live point.
-
-This option can help in instances where the live stream's target duration is greater than
-the segment durations, playback ends up in the unsafe live window, and there are gaps in
-the content. In this case the player will attempt to seek past the gaps but end up seeking
-inside of the unsafe range, leading to a correction and seek back into a previously played
-content.
-
-The property defaults to `false`.
-
-##### customTagParsers
-* Type: `Array`
-* can be used as a source option
-
-With `customTagParsers` you can pass an array of custom m3u8 tag parser objects. See https://github.com/videojs/m3u8-parser#custom-parsers
-
-##### customTagMappers
-* Type: `Array`
-* can be used as a source option
-
-Similar to `customTagParsers`, with `customTagMappers` you can pass an array of custom m3u8 tag mapper objects. See https://github.com/videojs/m3u8-parser#custom-parsers
-
-##### cacheEncryptionKeys
-* Type: `boolean`
-* can be used as a source option
-* can be used as an initialization option
-
-This option forces the player to cache AES-128 encryption keys internally instead of requesting the key alongside every segment request.
-This option defaults to `false`.
-
-##### handlePartialData
-* Type: `boolean`,
-* Default: `false`
-* Use partial appends in the transmuxer and segment loader
-
-##### liveRangeSafeTimeDelta
-* Type: `number`,
-* Default: [`SAFE_TIME_DELTA`](https://github.com/videojs/http-streaming/blob/e7cb63af010779108336eddb5c8fd138d6390e95/src/ranges.js#L17)
-* Allow to re-define length (in seconds) of time delta when you compare current time and the end of the buffered range.
-
-##### captionServices
-* Type: `object`
-* Default: undefined
-* Provide extra information, like a label or a language, for instream (608 and 708) captions.
-
-The captionServices options object has properties that map to the caption services. Each property is an object itself that includes several properties, like a label or language.
-
-For 608 captions, the service names are `CC1`, `CC2`, `CC3`, and `CC4`. For 708 captions, the service names are `SERVICEn` where `n` is a digit between `1` and `63`.
-###### Format
-```js
-{
- vhs: {
- captionServices: {
- [serviceName]: {
- language: String, // optional
- label: String, // optional
- default: boolean // optional
- }
- }
- }
-}
-```
-###### Example
-```js
-{
- vhs: {
- captionServices: {
- CC1: {
- language: 'en',
- label: 'English'
- },
- SERVICE1: {
- langauge: 'kr',
- label: 'Korean',
- default: true
- }
- }
- }
-}
-```
-
-### Runtime Properties
-Runtime properties are attached to the tech object when HLS is in
-use. You can get a reference to the VHS source handler like this:
-
-```javascript
-var vhs = player.tech().vhs;
-```
-
-If you *were* thinking about modifying runtime properties in a
-video.js plugin, we'd recommend you avoid it. Your plugin won't work
-with videos that don't use videojs-http-streaming and the best plugins
-work across all the media types that video.js supports. If you're
-deploying videojs-http-streaming on your own website and want to make a
-couple tweaks though, go for it!
-
-#### vhs.playlists.master
-Type: `object`
-
-An object representing the parsed master playlist. If a media playlist
-is loaded directly, a master playlist with only one entry will be
-created.
-
-#### vhs.playlists.media
-Type: `function`
-
-A function that can be used to retrieve or modify the currently active
-media playlist. The active media playlist is referred to when
-additional video data needs to be downloaded. Calling this function
-with no arguments returns the parsed playlist object for the active
-media playlist. Calling this function with a playlist object from the
-master playlist or a URI string as specified in the master playlist
-will kick off an asynchronous load of the specified media
-playlist. Once it has been retreived, it will become the active media
-playlist.
-
-#### vhs.systemBandwidth
-Type: `number`
-
-`systemBandwidth` is a combination of two serial processes' bitrates. The first
-is the network bitrate provided by `bandwidth` and the second is the bitrate of
-the entire process after that (decryption, transmuxing, and appending) provided
-by `throughput`. This value is used by the default implementation of `selectPlaylist`
-to select an appropriate bitrate to play.
-
-Since the two process are serial, the overall system bandwidth is given by:
-`systemBandwidth = 1 / (1 / bandwidth + 1 / throughput)`
-
-#### vhs.bandwidth
-Type: `number`
-
-The number of bits downloaded per second in the last segment download.
-
-Before the first video segment has been downloaded, it's hard to
-estimate bandwidth accurately. The HLS tech uses a starting value of 4194304 or 0.5 MB/s. If you
-have a more accurate source of bandwidth information, you can override
-this value as soon as the HLS tech has loaded to provide an initial
-bandwidth estimate.
-
-#### vhs.throughput
-Type: `number`
-
-The number of bits decrypted, transmuxed, and appended per second as a cumulative average across active processing time.
-
-#### vhs.selectPlaylist
-Type: `function`
-
-A function that returns the media playlist object to use to download
-the next segment. It is invoked by the tech immediately before a new
-segment is downloaded. You can override this function to provide your
-adaptive streaming logic. You must, however, be sure to return a valid
-media playlist object that is present in `player.tech().vhs.master`.
-
-Overridding this function with your own is very powerful but is overkill
-for many purposes. Most of the time, you should use the much simpler
-function below to selectively enable or disable a playlist from the
-adaptive streaming logic.
-
-#### vhs.representations
-Type: `function`
-
-It is recommended to include the [videojs-contrib-quality-levels](https://github.com/videojs/videojs-contrib-quality-levels) plugin to your page so that videojs-http-streaming will automatically populate the QualityLevelList exposed on the player by the plugin. You can access this list by calling `player.qualityLevels()`. See the [videojs-contrib-quality-levels project page](https://github.com/videojs/videojs-contrib-quality-levels) for more information on how to use the api.
-
-Example, only enabling representations with a width greater than or equal to 720:
-
-```javascript
-var qualityLevels = player.qualityLevels();
-
-for (var i = 0; i < qualityLevels.length; i++) {
- var quality = qualityLevels[i];
- if (quality.width >= 720) {
- quality.enabled = true;
- } else {
- quality.enabled = false;
- }
-}
-```
-
-If including [videojs-contrib-quality-levels](https://github.com/videojs/videojs-contrib-quality-levels) is not an option, you can use the representations api. To get all of the available representations, call the `representations()` method on `player.tech().vhs`. This will return a list of plain objects, each with `width`, `height`, `bandwidth`, and `id` properties, and an `enabled()` method.
-
-```javascript
-player.tech().vhs.representations();
-```
-
-To see whether the representation is enabled or disabled, call its `enabled()` method with no arguments. To set whether it is enabled/disabled, call its `enabled()` method and pass in a boolean value. Calling `.enabled(true)` will allow the adaptive bitrate algorithm to select the representation while calling `.enabled(false)` will disallow any selection of that representation.
-
-Example, only enabling representations with a width greater than or equal to 720:
-
-```javascript
-player.tech().vhs.representations().forEach(function(rep) {
- if (rep.width >= 720) {
- rep.enabled(true);
- } else {
- rep.enabled(false);
- }
-});
-```
-
-#### vhs.xhr
-Type: `function`
-
-The xhr function that is used by HLS internally is exposed on the per-
-player `vhs` object. While it is possible, we do not recommend replacing
-the function with your own implementation. Instead, the `xhr` provides
-the ability to specify a `beforeRequest` function that will be called
-with an object containing the options that will be used to create the
-xhr request.
-
-Example:
-```javascript
-player.tech().vhs.xhr.beforeRequest = function(options) {
- options.uri = options.uri.replace('example.com', 'foo.com');
-
- return options;
-};
-```
-
-The global `videojs.Vhs` also exposes an `xhr` property. Specifying a
-`beforeRequest` function on that will allow you to intercept the options
-for *all* requests in every player on a page. For consistency across
-browsers the video source should be set at runtime once the video player
-is ready.
-
-Example
-```javascript
-videojs.Vhs.xhr.beforeRequest = function(options) {
- /*
- * Modifications to requests that will affect every player.
- */
-
- return options;
-};
-
-var player = videojs('video-player-id');
-player.ready(function() {
- this.src({
- src: 'https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8',
- type: 'application/x-mpegURL',
- });
-});
-```
-
-For information on the type of options that you can modify see the
-documentation at [https://github.com/Raynos/xhr](https://github.com/Raynos/xhr).
-
-#### vhs.stats
-Type: `object`
-
-This object contains a summary of HLS and player related stats.
-
-| Property Name | Type | Description |
-| --------------------- | ------ | ----------- |
-| bandwidth | number | Rate of the last segment download in bits/second |
-| mediaRequests | number | Total number of media segment requests |
-| mediaRequestsAborted | number | Total number of aborted media segment requests |
-| mediaRequestsTimedout | number | Total number of timedout media segment requests |
-| mediaRequestsErrored | number | Total number of errored media segment requests |
-| mediaTransferDuration | number | Total time spent downloading media segments in milliseconds |
-| mediaBytesTransferred | number | Total number of content bytes downloaded |
-| mediaSecondsLoaded | number | Total number of content seconds downloaded |
-| buffered | array | List of time ranges of content that are in the SourceBuffer |
-| currentTime | number | The current position of the player |
-| currentSource | object | The source object. Has the structure `{src: 'url', type: 'mimetype'}` |
-| currentTech | string | The name of the tech in use |
-| duration | number | Duration of the video in seconds |
-| master | object | The [master playlist object](#vhsplaylistsmaster) |
-| playerDimensions | object | Contains the width and height of the player |
-| seekable | array | List of time ranges that the player can seek to |
-| timestamp | number | Timestamp of when `vhs.stats` was accessed |
-| videoPlaybackQuality | object | Media playback quality metrics as specified by the [W3C's Media Playback Quality API](https://wicg.github.io/media-playback-quality/) |
-
-
-### Events
-Standard HTML video events are handled by video.js automatically and
-are triggered on the player object.
-
-#### loadedmetadata
-
-Fired after the first segment is downloaded for a playlist. This will not happen
-until playback if video.js's `metadata` setting is `none`
-
-### VHS Usage Events
-
-Usage tracking events are fired when we detect a certain HLS feature, encoding setting,
-or API is used. These can be helpful for analytics, and to pinpoint the cause of HLS errors.
-For instance, if errors are being fired in tandem with a usage event indicating that the
-player was playing an AES encrypted stream, then we have a possible avenue to explore when
-debugging the error.
-
-Note that although these usage events are listed below, they may change at any time without
-a major version change.
-
-VHS usage events are triggered on the tech with the exception of the 3 vhs-reload-error
-events, which are triggered on the player.
-
-To listen for usage events triggered on the tech, listen for the event type of `'usage'`:
-
-```javascript
-player.on('ready', () => {
- player.tech().on('usage', (e) => {
- console.log(e.name);
- });
-});
-```
-
-Note that these events are triggered as soon as a case is encountered, and often only
-once. For example, the `vhs-demuxed` usage event will be triggered as soon as the master
-manifest is downloaded and parsed, and will not be triggered again.
-
-#### Presence Stats
-
-Each of the following usage events are fired once per source if (and when) detected:
-
-| Name | Description |
-| ------------- | ------------- |
-| vhs-webvtt | master manifest has at least one segmented WebVTT playlist |
-| vhs-aes | a playlist is AES encrypted |
-| vhs-fmp4 | a playlist used fMP4 segments |
-| vhs-demuxed | audio and video are demuxed by default |
-| vhs-alternate-audio | alternate audio available in the master manifest |
-| vhs-playlist-cue-tags | a playlist used cue tags (see useCueTags(#usecuetags) for details) |
-| vhs-bandwidth-from-local-storage | starting bandwidth was retrieved from local storage (see useBandwidthFromLocalStorage(#useBandwidthFromLocalStorage) for details) |
-| vhs-throughput-from-local-storage | starting throughput was retrieved from local storage (see useBandwidthFromLocalStorage(#useBandwidthFromLocalStorage) for details) |
-
-#### Use Stats
-
-Each of the following usage events are fired per use:
-
-| Name | Description |
-| ------------- | ------------- |
-| vhs-gap-skip | player skipped a gap in the buffer |
-| vhs-player-access | player.vhs was accessed |
-| vhs-audio-change | a user selected an alternate audio stream |
-| vhs-rendition-disabled | a rendition was disabled |
-| vhs-rendition-enabled | a rendition was enabled |
-| vhs-rendition-blacklisted | a rendition was blacklisted |
-| vhs-timestamp-offset | a timestamp offset was set in HLS (can identify discontinuities) |
-| vhs-unknown-waiting | the player stopped for an unknown reason and we seeked to current time try to address it |
-| vhs-live-resync | playback fell off the back of a live playlist and we resynced to the live point |
-| vhs-video-underflow | we seeked to current time to address video underflow |
-| vhs-error-reload-initialized | the reloadSourceOnError plugin was initialized |
-| vhs-error-reload | the reloadSourceOnError plugin reloaded a source |
-| vhs-error-reload-canceled | an error occurred too soon after the last reload, so we didn't reload again (to prevent error loops) |
-
-
-### In-Band Metadata
-The HLS tech supports [timed
-metadata](https://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/HTTP_Live_Streaming_Metadata_Spec/Introduction/Introduction.html)
-embedded as [ID3 tags](http://id3.org/id3v2.3.0). When a stream is
-encountered with embedded metadata, an [in-band metadata text
-track](https://html.spec.whatwg.org/multipage/embedded-content.html#text-track-in-band-metadata-track-dispatch-type)
-will automatically be created and populated with cues as they are
-encountered in the stream. UTF-8 encoded
-[TXXX](http://id3.org/id3v2.3.0#User_defined_text_information_frame)
-and [WXXX](http://id3.org/id3v2.3.0#User_defined_URL_link_frame) ID3
-frames are mapped to cue points and their values set as the cue
-text. Cues are created for all other frame types and the data is
-attached to the generated cue:
-
-```javascript
-cue.value.data
-```
-
-There are lots of guides and references to using text tracks [around
-the web](http://www.html5rocks.com/en/tutorials/track/basics/).
-
-### Segment Metadata
-You can get metadata about the segments currently in the buffer by using the `segment-metadata`
-text track. You can get the metadata of the currently rendered segment by looking at the
-track's `activeCues` array. The metadata will be attached to the `cue.value` property and
-will have this structure
-
-```javascript
-cue.value = {
- byteLength, // The size of the segment in bytes
- bandwidth, // The peak bitrate reported by the segment's playlist
- resolution, // The resolution reported by the segment's playlist
- codecs, // The codecs reported by the segment's playlist
- uri, // The Segment uri
- timeline, // Timeline of the segment for detecting discontinuities
- playlist, // The Playlist uri
- start, // Segment start time
- end // Segment end time
-};
-```
-
-Example:
-Detect when a change in quality is rendered on screen
-```javascript
-let tracks = player.textTracks();
-let segmentMetadataTrack;
-
-for (let i = 0; i < tracks.length; i++) {
- if (tracks[i].label === 'segment-metadata') {
- segmentMetadataTrack = tracks[i];
- }
-}
-
-let previousPlaylist;
-
-if (segmentMetadataTrack) {
- segmentMetadataTrack.on('cuechange', function() {
- let activeCue = segmentMetadataTrack.activeCues[0];
-
- if (activeCue) {
- if (previousPlaylist !== activeCue.value.playlist) {
- console.log('Switched from rendition ' + previousPlaylist +
- ' to rendition ' + activeCue.value.playlist);
- }
- previousPlaylist = activeCue.value.playlist;
- }
- });
-}
-```
-
-### Object as Source
-
-*Note* that this is an advanced use-case, and may be more fragile for production
-environments, as the schema for a VHS object and how it's used internally are not set in
-stone and may change in future releases.
-
-In normal use, VHS accepts a URL as the source of the video. But VHS also has the ability
-to accept a JSON object as the source.
-
-Passing a JSON object as the source has many uses. A couple of examples include:
-* The manifest has already been downloaded, so there's no need to make another request
-* You want to change some aspect of the manifest, e.g., add a segment, without modifying
- the manifest itself
-
-In order to pass a JSON object as the source, provide a parsed manifest object in via a
-[data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs),
-and using the "vnd.videojs.vhs+json" media type when setting the source type. For instance:
-
-```
-var player = videojs('some-video-id');
-const parser = new M3u8Parser();
-
-parser.push(manifestString);
-parser.end();
-
-player.src({
- src: `data:application/vnd.videojs.vhs+json,${JSON.stringify(parser.manifest)}`,
- type: 'application/vnd.videojs.vhs+json'
-});
-```
-
-The manifest object should follow the "VHS manifest object schema" (a somewhat flexible
-and informally documented structure) provided in the README of
-[m3u8-parser](https://github.com/videojs/m3u8-parser) and
-[mpd-parser](https://github.com/videojs/mpd-parser). This may be referred to in the
-project as `vhs-json`.
-
-## Hosting Considerations
-Unlike a native HLS implementation, the HLS tech has to comply with
-the browser's security policies. That means that all the files that
-make up the stream must be served from the same domain as the page
-hosting the video player or from a server that has appropriate [CORS
-headers](https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS)
-configured. Easy [instructions are
-available](http://enable-cors.org/server.html) for popular webservers
-and most CDNs should have no trouble turning CORS on for your account.
-
-
-## Known Issues and Workarounds
-Issues that are currenty known. If you want to
-help find a solution that would be appreciated!
-
-### Fragmented MP4 Support
-Edge has native support for HLS but only in the MPEG2-TS container. If
-you attempt to play an HLS stream with fragmented MP4 segments (without
-[overriding native playback](#overridenative)), Edge will stall.
-Fragmented MP4s are only supported on browsers that have
-[Media Source Extensions](http://caniuse.com/#feat=mediasource) available.
-
-### Assets with an Audio-Only Rate Get Stuck in Audio-Only
-Some assets which have an audio-only rate and the lowest-bandwidth
-audio + video rate isn't that low get stuck in audio-only mode. This is
-because the initial bandwidth calculation thinks it there's insufficient
-bandwidth for selecting the lowest-quality audio+video playlist, so it picks
-the only-audio one, which unfortunately locks it to being audio-only forever,
-preventing a switch to the audio+video playlist when it gets a better
-estimation of bandwidth.
-
-Until we've implemented a full fix, it is recommended to set the
-[`enableLowInitialPlaylist` option](#enablelowinitialplaylist) for any assets
-that include an audio-only rate; it should always select the lowest-bandwidth
-audio+video playlist for its first playlist.
-
-It's also worth mentioning that Apple no longer requires having an audio-only
-rate; instead, they require a 192kbps audio+video rate (see Apple's current
-[HLS Authoring Specification][]). Removing the audio-only rate would of course
-eliminate this problem since there would be only audio+video playlists to
-choose from.
-
-Follow progress on this in issue [#175](https://github.com/videojs/http-streaming/issues/175).
-
-[HLS Authoring Specification]: https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices
-
-### DASH Assets with `$Time` Interpolation and `SegmentTimeline`s with No `t`
-
-DASH assets which use `$Time` in a `SegmentTemplate`, and also have a
-`SegmentTimeline` where only the first `S` has a `t` and the rest only have a
-`d`, do not load currently.
-
-There is currently no workaround for this, but you can track progress on this
-in issue [#256](https://github.com/videojs/http-streaming/issues/256).
-
-## Testing
-
-For testing, you run `npm run test`. You will need Chrome and Firefox for running the tests.
-
-_videojs-http-streaming uses [BrowserStack](https://browserstack.com) for compatibility testing._
-
-## Debugging
-
-videojs-http-streaming makes use of `videojs.log` for debug logging. You can enable these logs
-by setting the log level to `debug` using `videojs.log.level('debug')`. You can access a complete
-history of the logs using `videojs.log.history()`. This history is maintained even when the
-log level is not set to `debug`.
-
-`vhs.stats` can also be helpful when debugging. Accessing this object will give you
-a snapshot summary of various HLS and player stats. See [vhs.stats](#vhsstats) for details
-about what this object contains.
-
-__NOTE__: The `debug` level is only available in video.js v6.6.0+. With earlier versions of
-video.js, no debug messages will be logged to console.
-
-## Release History
-Check out the [changelog](CHANGELOG.md) for a summary of each release.
-
-## Building
-To build a copy of videojs-http-streaming run the following commands
-
-```bash
-git clone https://github.com/videojs/http-streaming
-cd http-streaming
-npm i
-npm run build
-```
-
-videojs-http-streaming will have created all of the files for using it in a dist folder
-
-## Development
-
-### Tools
-* Download stream locally with the [HLS Fetcher](https://github.com/videojs/hls-fetcher)
-* Simulate errors with [Murphy](https://github.com/videojs/murphy)
-* Inspect content with [Thumbcoil](http://thumb.co.il)
-
-### Commands
-All commands for development are listed in the `package.json` file and are run using
-```bash
-npm run
-```
-
-[slack-icon]: http://slack.videojs.com/badge.svg
-[slack-link]: http://slack.videojs.com
-[travis-icon]: https://travis-ci.org/videojs/http-streaming.svg?branch=main
-[travis-link]: https://travis-ci.org/videojs/http-streaming
-[issue-stats-link]: http://issuestats.com/github/videojs/http-streaming
-[issue-stats-pr-icon]: http://issuestats.com/github/videojs/http-streaming/badge/pr
-[issue-stats-issues-icon]: http://issuestats.com/github/videojs/http-streaming/badge/issue
-[greenkeeper-icon]: https://badges.greenkeeper.io/videojs/http-streaming.svg
-[greenkeeper-link]: https://greenkeeper.io/
diff --git a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming-sync-workers.js b/node_modules/@videojs/http-streaming/dist/videojs-http-streaming-sync-workers.js
deleted file mode 100644
index e0baef8..0000000
--- a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming-sync-workers.js
+++ /dev/null
@@ -1,30919 +0,0 @@
-/*! @name @videojs/http-streaming @version 2.9.1 @license Apache-2.0 */
-(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('global/document'), require('global/window'), require('video.js'), require('xmldom')) :
- typeof define === 'function' && define.amd ? define(['exports', 'global/document', 'global/window', 'video.js', 'xmldom'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.httpStreaming = {}, global.document, global.window, global.videojs, global.window));
-}(this, (function (exports, document, window, videojs, xmldom) { 'use strict';
-
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
-
- var document__default = /*#__PURE__*/_interopDefaultLegacy(document);
- var window__default = /*#__PURE__*/_interopDefaultLegacy(window);
- var videojs__default = /*#__PURE__*/_interopDefaultLegacy(videojs);
-
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
-
- function commonjsRequire () {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
-
- var assertThisInitialized = createCommonjsModule(function (module) {
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
-
- return self;
- }
-
- module.exports = _assertThisInitialized;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
-
- var setPrototypeOf = createCommonjsModule(function (module) {
- function _setPrototypeOf(o, p) {
- module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _setPrototypeOf(o, p);
- }
-
- module.exports = _setPrototypeOf;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
-
- var inheritsLoose = createCommonjsModule(function (module) {
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- setPrototypeOf(subClass, superClass);
- }
-
- module.exports = _inheritsLoose;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
-
- var urlToolkit = createCommonjsModule(function (module, exports) {
- // see https://tools.ietf.org/html/rfc1808
- (function (root) {
- var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/;
- var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
- var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
- var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
- var URLToolkit = {
- // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
- // E.g
- // With opts.alwaysNormalize = false (default, spec compliant)
- // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
- // With opts.alwaysNormalize = true (not spec compliant)
- // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
- buildAbsoluteURL: function buildAbsoluteURL(baseURL, relativeURL, opts) {
- opts = opts || {}; // remove any remaining space and CRLF
-
- baseURL = baseURL.trim();
- relativeURL = relativeURL.trim();
-
- if (!relativeURL) {
- // 2a) If the embedded URL is entirely empty, it inherits the
- // entire base URL (i.e., is set equal to the base URL)
- // and we are done.
- if (!opts.alwaysNormalize) {
- return baseURL;
- }
-
- var basePartsForNormalise = URLToolkit.parseURL(baseURL);
-
- if (!basePartsForNormalise) {
- throw new Error('Error trying to parse base URL.');
- }
-
- basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
- return URLToolkit.buildURLFromParts(basePartsForNormalise);
- }
-
- var relativeParts = URLToolkit.parseURL(relativeURL);
-
- if (!relativeParts) {
- throw new Error('Error trying to parse relative URL.');
- }
-
- if (relativeParts.scheme) {
- // 2b) If the embedded URL starts with a scheme name, it is
- // interpreted as an absolute URL and we are done.
- if (!opts.alwaysNormalize) {
- return relativeURL;
- }
-
- relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
- return URLToolkit.buildURLFromParts(relativeParts);
- }
-
- var baseParts = URLToolkit.parseURL(baseURL);
-
- if (!baseParts) {
- throw new Error('Error trying to parse base URL.');
- }
-
- if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
- // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
- // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
- var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
- baseParts.netLoc = pathParts[1];
- baseParts.path = pathParts[2];
- }
-
- if (baseParts.netLoc && !baseParts.path) {
- baseParts.path = '/';
- }
-
- var builtParts = {
- // 2c) Otherwise, the embedded URL inherits the scheme of
- // the base URL.
- scheme: baseParts.scheme,
- netLoc: relativeParts.netLoc,
- path: null,
- params: relativeParts.params,
- query: relativeParts.query,
- fragment: relativeParts.fragment
- };
-
- if (!relativeParts.netLoc) {
- // 3) If the embedded URL's is non-empty, we skip to
- // Step 7. Otherwise, the embedded URL inherits the
- // (if any) of the base URL.
- builtParts.netLoc = baseParts.netLoc; // 4) If the embedded URL path is preceded by a slash "/", the
- // path is not relative and we skip to Step 7.
-
- if (relativeParts.path[0] !== '/') {
- if (!relativeParts.path) {
- // 5) If the embedded URL path is empty (and not preceded by a
- // slash), then the embedded URL inherits the base URL path
- builtParts.path = baseParts.path; // 5a) if the embedded URL's is non-empty, we skip to
- // step 7; otherwise, it inherits the of the base
- // URL (if any) and
-
- if (!relativeParts.params) {
- builtParts.params = baseParts.params; // 5b) if the embedded URL's is non-empty, we skip to
- // step 7; otherwise, it inherits the of the base
- // URL (if any) and we skip to step 7.
-
- if (!relativeParts.query) {
- builtParts.query = baseParts.query;
- }
- }
- } else {
- // 6) The last segment of the base URL's path (anything
- // following the rightmost slash "/", or the entire path if no
- // slash is present) is removed and the embedded URL's path is
- // appended in its place.
- var baseURLPath = baseParts.path;
- var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
- builtParts.path = URLToolkit.normalizePath(newPath);
- }
- }
- }
-
- if (builtParts.path === null) {
- builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
- }
-
- return URLToolkit.buildURLFromParts(builtParts);
- },
- parseURL: function parseURL(url) {
- var parts = URL_REGEX.exec(url);
-
- if (!parts) {
- return null;
- }
-
- return {
- scheme: parts[1] || '',
- netLoc: parts[2] || '',
- path: parts[3] || '',
- params: parts[4] || '',
- query: parts[5] || '',
- fragment: parts[6] || ''
- };
- },
- normalizePath: function normalizePath(path) {
- // The following operations are
- // then applied, in order, to the new path:
- // 6a) All occurrences of "./", where "." is a complete path
- // segment, are removed.
- // 6b) If the path ends with "." as a complete path segment,
- // that "." is removed.
- path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "/../", where is a
- // complete path segment not equal to "..", are removed.
- // Removal of these path segments is performed iteratively,
- // removing the leftmost matching pattern on each iteration,
- // until no matching pattern remains.
- // 6d) If the path ends with "/..", where is a
- // complete path segment not equal to "..", that
- // "/.." is removed.
-
- while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
-
- return path.split('').reverse().join('');
- },
- buildURLFromParts: function buildURLFromParts(parts) {
- return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
- }
- };
- module.exports = URLToolkit;
- })();
- });
-
- var DEFAULT_LOCATION = 'http://example.com';
-
- var resolveUrl$1 = function resolveUrl(baseUrl, relativeUrl) {
- // return early if we don't need to resolve
- if (/^[a-z]+:/i.test(relativeUrl)) {
- return relativeUrl;
- } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
-
-
- if (/^data:/.test(baseUrl)) {
- baseUrl = window__default['default'].location && window__default['default'].location.href || '';
- } // IE11 supports URL but not the URL constructor
- // feature detect the behavior we want
-
-
- var nativeURL = typeof window__default['default'].URL === 'function';
- var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
- // and if baseUrl isn't an absolute url
-
- var removeLocation = !window__default['default'].location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
-
- if (nativeURL) {
- baseUrl = new window__default['default'].URL(baseUrl, window__default['default'].location || DEFAULT_LOCATION);
- } else if (!/\/\//i.test(baseUrl)) {
- baseUrl = urlToolkit.buildAbsoluteURL(window__default['default'].location && window__default['default'].location.href || '', baseUrl);
- }
-
- if (nativeURL) {
- var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
- // and if we're location-less, remove the location
- // otherwise, return the url unmodified
-
- if (removeLocation) {
- return newUrl.href.slice(DEFAULT_LOCATION.length);
- } else if (protocolLess) {
- return newUrl.href.slice(newUrl.protocol.length);
- }
-
- return newUrl.href;
- }
-
- return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
- };
-
- /**
- * @file resolve-url.js - Handling how URLs are resolved and manipulated
- */
- var resolveUrl = resolveUrl$1;
- /**
- * Checks whether xhr request was redirected and returns correct url depending
- * on `handleManifestRedirects` option
- *
- * @api private
- *
- * @param {string} url - an url being requested
- * @param {XMLHttpRequest} req - xhr request result
- *
- * @return {string}
- */
-
- var resolveManifestRedirect = function resolveManifestRedirect(handleManifestRedirect, url, req) {
- // To understand how the responseURL below is set and generated:
- // - https://fetch.spec.whatwg.org/#concept-response-url
- // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
- if (handleManifestRedirect && req && req.responseURL && url !== req.responseURL) {
- return req.responseURL;
- }
-
- return url;
- };
-
- var logger = function logger(source) {
- if (videojs__default['default'].log.debug) {
- return videojs__default['default'].log.debug.bind(videojs__default['default'], 'VHS:', source + " >");
- }
-
- return function () {};
- };
-
- var _extends_1 = createCommonjsModule(function (module) {
- function _extends() {
- module.exports = _extends = Object.assign || function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
-
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
-
- return target;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _extends.apply(this, arguments);
- }
-
- module.exports = _extends;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
-
- /**
- * @file stream.js
- */
-
- /**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
- var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
- }();
-
- var atob = function atob(s) {
- return window__default['default'].atob ? window__default['default'].atob(s) : Buffer.from(s, 'base64').toString('binary');
- };
-
- function decodeB64ToUint8Array(b64Text) {
- var decodedString = atob(b64Text);
- var array = new Uint8Array(decodedString.length);
-
- for (var i = 0; i < decodedString.length; i++) {
- array[i] = decodedString.charCodeAt(i);
- }
-
- return array;
- }
-
- /*! @name m3u8-parser @version 4.7.0 @license Apache-2.0 */
- /**
- * A stream that buffers string input and generates a `data` event for each
- * line.
- *
- * @class LineStream
- * @extends Stream
- */
-
- var LineStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(LineStream, _Stream);
-
- function LineStream() {
- var _this;
-
- _this = _Stream.call(this) || this;
- _this.buffer = '';
- return _this;
- }
- /**
- * Add new data to be parsed.
- *
- * @param {string} data the text to process
- */
-
-
- var _proto = LineStream.prototype;
-
- _proto.push = function push(data) {
- var nextNewline;
- this.buffer += data;
- nextNewline = this.buffer.indexOf('\n');
-
- for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
- this.trigger('data', this.buffer.substring(0, nextNewline));
- this.buffer = this.buffer.substring(nextNewline + 1);
- }
- };
-
- return LineStream;
- }(Stream);
-
- var TAB = String.fromCharCode(0x09);
-
- var parseByterange = function parseByterange(byterangeString) {
- // optionally match and capture 0+ digits before `@`
- // optionally match and capture 0+ digits after `@`
- var match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || '');
- var result = {};
-
- if (match[1]) {
- result.length = parseInt(match[1], 10);
- }
-
- if (match[2]) {
- result.offset = parseInt(match[2], 10);
- }
-
- return result;
- };
- /**
- * "forgiving" attribute list psuedo-grammar:
- * attributes -> keyvalue (',' keyvalue)*
- * keyvalue -> key '=' value
- * key -> [^=]*
- * value -> '"' [^"]* '"' | [^,]*
- */
-
-
- var attributeSeparator = function attributeSeparator() {
- var key = '[^=]*';
- var value = '"[^"]*"|[^,]*';
- var keyvalue = '(?:' + key + ')=(?:' + value + ')';
- return new RegExp('(?:^|,)(' + keyvalue + ')');
- };
- /**
- * Parse attributes from a line given the separator
- *
- * @param {string} attributes the attribute line to parse
- */
-
-
- var parseAttributes$1 = function parseAttributes(attributes) {
- // split the string using attributes as the separator
- var attrs = attributes.split(attributeSeparator());
- var result = {};
- var i = attrs.length;
- var attr;
-
- while (i--) {
- // filter out unmatched portions of the string
- if (attrs[i] === '') {
- continue;
- } // split the key and value
-
-
- attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
-
- attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
- attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
- attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
- result[attr[0]] = attr[1];
- }
-
- return result;
- };
- /**
- * A line-level M3U8 parser event stream. It expects to receive input one
- * line at a time and performs a context-free parse of its contents. A stream
- * interpretation of a manifest can be useful if the manifest is expected to
- * be too large to fit comfortably into memory or the entirety of the input
- * is not immediately available. Otherwise, it's probably much easier to work
- * with a regular `Parser` object.
- *
- * Produces `data` events with an object that captures the parser's
- * interpretation of the input. That object has a property `tag` that is one
- * of `uri`, `comment`, or `tag`. URIs only have a single additional
- * property, `line`, which captures the entirety of the input without
- * interpretation. Comments similarly have a single additional property
- * `text` which is the input without the leading `#`.
- *
- * Tags always have a property `tagType` which is the lower-cased version of
- * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
- * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
- * tags are given the tag type `unknown` and a single additional property
- * `data` with the remainder of the input.
- *
- * @class ParseStream
- * @extends Stream
- */
-
-
- var ParseStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(ParseStream, _Stream);
-
- function ParseStream() {
- var _this;
-
- _this = _Stream.call(this) || this;
- _this.customParsers = [];
- _this.tagMappers = [];
- return _this;
- }
- /**
- * Parses an additional line of input.
- *
- * @param {string} line a single line of an M3U8 file to parse
- */
-
-
- var _proto = ParseStream.prototype;
-
- _proto.push = function push(line) {
- var _this2 = this;
-
- var match;
- var event; // strip whitespace
-
- line = line.trim();
-
- if (line.length === 0) {
- // ignore empty lines
- return;
- } // URIs
-
-
- if (line[0] !== '#') {
- this.trigger('data', {
- type: 'uri',
- uri: line
- });
- return;
- } // map tags
-
-
- var newLines = this.tagMappers.reduce(function (acc, mapper) {
- var mappedLine = mapper(line); // skip if unchanged
-
- if (mappedLine === line) {
- return acc;
- }
-
- return acc.concat([mappedLine]);
- }, [line]);
- newLines.forEach(function (newLine) {
- for (var i = 0; i < _this2.customParsers.length; i++) {
- if (_this2.customParsers[i].call(_this2, newLine)) {
- return;
- }
- } // Comments
-
-
- if (newLine.indexOf('#EXT') !== 0) {
- _this2.trigger('data', {
- type: 'comment',
- text: newLine.slice(1)
- });
-
- return;
- } // strip off any carriage returns here so the regex matching
- // doesn't have to account for them.
-
-
- newLine = newLine.replace('\r', ''); // Tags
-
- match = /^#EXTM3U/.exec(newLine);
-
- if (match) {
- _this2.trigger('data', {
- type: 'tag',
- tagType: 'm3u'
- });
-
- return;
- }
-
- match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'inf'
- };
-
- if (match[1]) {
- event.duration = parseFloat(match[1]);
- }
-
- if (match[2]) {
- event.title = match[2];
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'targetduration'
- };
-
- if (match[1]) {
- event.duration = parseInt(match[1], 10);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-VERSION:?([0-9.]*)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'version'
- };
-
- if (match[1]) {
- event.version = parseInt(match[1], 10);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'media-sequence'
- };
-
- if (match[1]) {
- event.number = parseInt(match[1], 10);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'discontinuity-sequence'
- };
-
- if (match[1]) {
- event.number = parseInt(match[1], 10);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'playlist-type'
- };
-
- if (match[1]) {
- event.playlistType = match[1];
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-BYTERANGE:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = _extends_1(parseByterange(match[1]), {
- type: 'tag',
- tagType: 'byterange'
- });
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'allow-cache'
- };
-
- if (match[1]) {
- event.allowed = !/NO/.test(match[1]);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-MAP:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'map'
- };
-
- if (match[1]) {
- var attributes = parseAttributes$1(match[1]);
-
- if (attributes.URI) {
- event.uri = attributes.URI;
- }
-
- if (attributes.BYTERANGE) {
- event.byterange = parseByterange(attributes.BYTERANGE);
- }
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-STREAM-INF:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'stream-inf'
- };
-
- if (match[1]) {
- event.attributes = parseAttributes$1(match[1]);
-
- if (event.attributes.RESOLUTION) {
- var split = event.attributes.RESOLUTION.split('x');
- var resolution = {};
-
- if (split[0]) {
- resolution.width = parseInt(split[0], 10);
- }
-
- if (split[1]) {
- resolution.height = parseInt(split[1], 10);
- }
-
- event.attributes.RESOLUTION = resolution;
- }
-
- if (event.attributes.BANDWIDTH) {
- event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
- }
-
- if (event.attributes['PROGRAM-ID']) {
- event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
- }
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-MEDIA:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'media'
- };
-
- if (match[1]) {
- event.attributes = parseAttributes$1(match[1]);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-ENDLIST/.exec(newLine);
-
- if (match) {
- _this2.trigger('data', {
- type: 'tag',
- tagType: 'endlist'
- });
-
- return;
- }
-
- match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
-
- if (match) {
- _this2.trigger('data', {
- type: 'tag',
- tagType: 'discontinuity'
- });
-
- return;
- }
-
- match = /^#EXT-X-PROGRAM-DATE-TIME:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'program-date-time'
- };
-
- if (match[1]) {
- event.dateTimeString = match[1];
- event.dateTimeObject = new Date(match[1]);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-KEY:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'key'
- };
-
- if (match[1]) {
- event.attributes = parseAttributes$1(match[1]); // parse the IV string into a Uint32Array
-
- if (event.attributes.IV) {
- if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
- event.attributes.IV = event.attributes.IV.substring(2);
- }
-
- event.attributes.IV = event.attributes.IV.match(/.{8}/g);
- event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
- event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
- event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
- event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
- event.attributes.IV = new Uint32Array(event.attributes.IV);
- }
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-START:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'start'
- };
-
- if (match[1]) {
- event.attributes = parseAttributes$1(match[1]);
- event.attributes['TIME-OFFSET'] = parseFloat(event.attributes['TIME-OFFSET']);
- event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-CUE-OUT-CONT:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'cue-out-cont'
- };
-
- if (match[1]) {
- event.data = match[1];
- } else {
- event.data = '';
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-CUE-OUT:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'cue-out'
- };
-
- if (match[1]) {
- event.data = match[1];
- } else {
- event.data = '';
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-CUE-IN:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'cue-in'
- };
-
- if (match[1]) {
- event.data = match[1];
- } else {
- event.data = '';
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'skip'
- };
- event.attributes = parseAttributes$1(match[1]);
-
- if (event.attributes.hasOwnProperty('SKIPPED-SEGMENTS')) {
- event.attributes['SKIPPED-SEGMENTS'] = parseInt(event.attributes['SKIPPED-SEGMENTS'], 10);
- }
-
- if (event.attributes.hasOwnProperty('RECENTLY-REMOVED-DATERANGES')) {
- event.attributes['RECENTLY-REMOVED-DATERANGES'] = event.attributes['RECENTLY-REMOVED-DATERANGES'].split(TAB);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-PART:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'part'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['DURATION'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseFloat(event.attributes[key]);
- }
- });
- ['INDEPENDENT', 'GAP'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = /YES/.test(event.attributes[key]);
- }
- });
-
- if (event.attributes.hasOwnProperty('BYTERANGE')) {
- event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'server-control'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['CAN-SKIP-UNTIL', 'PART-HOLD-BACK', 'HOLD-BACK'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseFloat(event.attributes[key]);
- }
- });
- ['CAN-SKIP-DATERANGES', 'CAN-BLOCK-RELOAD'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = /YES/.test(event.attributes[key]);
- }
- });
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'part-inf'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['PART-TARGET'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseFloat(event.attributes[key]);
- }
- });
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'preload-hint'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['BYTERANGE-START', 'BYTERANGE-LENGTH'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseInt(event.attributes[key], 10);
- var subkey = key === 'BYTERANGE-LENGTH' ? 'length' : 'offset';
- event.attributes.byterange = event.attributes.byterange || {};
- event.attributes.byterange[subkey] = event.attributes[key]; // only keep the parsed byterange object.
-
- delete event.attributes[key];
- }
- });
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'rendition-report'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['LAST-MSN', 'LAST-PART'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseInt(event.attributes[key], 10);
- }
- });
-
- _this2.trigger('data', event);
-
- return;
- } // unknown tag type
-
-
- _this2.trigger('data', {
- type: 'tag',
- data: newLine.slice(4)
- });
- });
- }
- /**
- * Add a parser for custom headers
- *
- * @param {Object} options a map of options for the added parser
- * @param {RegExp} options.expression a regular expression to match the custom header
- * @param {string} options.customType the custom type to register to the output
- * @param {Function} [options.dataParser] function to parse the line into an object
- * @param {boolean} [options.segment] should tag data be attached to the segment object
- */
- ;
-
- _proto.addParser = function addParser(_ref) {
- var _this3 = this;
-
- var expression = _ref.expression,
- customType = _ref.customType,
- dataParser = _ref.dataParser,
- segment = _ref.segment;
-
- if (typeof dataParser !== 'function') {
- dataParser = function dataParser(line) {
- return line;
- };
- }
-
- this.customParsers.push(function (line) {
- var match = expression.exec(line);
-
- if (match) {
- _this3.trigger('data', {
- type: 'custom',
- data: dataParser(line),
- customType: customType,
- segment: segment
- });
-
- return true;
- }
- });
- }
- /**
- * Add a custom header mapper
- *
- * @param {Object} options
- * @param {RegExp} options.expression a regular expression to match the custom header
- * @param {Function} options.map function to translate tag into a different tag
- */
- ;
-
- _proto.addTagMapper = function addTagMapper(_ref2) {
- var expression = _ref2.expression,
- map = _ref2.map;
-
- var mapFn = function mapFn(line) {
- if (expression.test(line)) {
- return map(line);
- }
-
- return line;
- };
-
- this.tagMappers.push(mapFn);
- };
-
- return ParseStream;
- }(Stream);
-
- var camelCase = function camelCase(str) {
- return str.toLowerCase().replace(/-(\w)/g, function (a) {
- return a[1].toUpperCase();
- });
- };
-
- var camelCaseKeys = function camelCaseKeys(attributes) {
- var result = {};
- Object.keys(attributes).forEach(function (key) {
- result[camelCase(key)] = attributes[key];
- });
- return result;
- }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
- // we need this helper because defaults are based upon targetDuration and
- // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
- // target durations are set.
-
-
- var setHoldBack = function setHoldBack(manifest) {
- var serverControl = manifest.serverControl,
- targetDuration = manifest.targetDuration,
- partTargetDuration = manifest.partTargetDuration;
-
- if (!serverControl) {
- return;
- }
-
- var tag = '#EXT-X-SERVER-CONTROL';
- var hb = 'holdBack';
- var phb = 'partHoldBack';
- var minTargetDuration = targetDuration && targetDuration * 3;
- var minPartDuration = partTargetDuration && partTargetDuration * 2;
-
- if (targetDuration && !serverControl.hasOwnProperty(hb)) {
- serverControl[hb] = minTargetDuration;
- this.trigger('info', {
- message: tag + " defaulting HOLD-BACK to targetDuration * 3 (" + minTargetDuration + ")."
- });
- }
-
- if (minTargetDuration && serverControl[hb] < minTargetDuration) {
- this.trigger('warn', {
- message: tag + " clamping HOLD-BACK (" + serverControl[hb] + ") to targetDuration * 3 (" + minTargetDuration + ")"
- });
- serverControl[hb] = minTargetDuration;
- } // default no part hold back to part target duration * 3
-
-
- if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
- serverControl[phb] = partTargetDuration * 3;
- this.trigger('info', {
- message: tag + " defaulting PART-HOLD-BACK to partTargetDuration * 3 (" + serverControl[phb] + ")."
- });
- } // if part hold back is too small default it to part target duration * 2
-
-
- if (partTargetDuration && serverControl[phb] < minPartDuration) {
- this.trigger('warn', {
- message: tag + " clamping PART-HOLD-BACK (" + serverControl[phb] + ") to partTargetDuration * 2 (" + minPartDuration + ")."
- });
- serverControl[phb] = minPartDuration;
- }
- };
- /**
- * A parser for M3U8 files. The current interpretation of the input is
- * exposed as a property `manifest` on parser objects. It's just two lines to
- * create and parse a manifest once you have the contents available as a string:
- *
- * ```js
- * var parser = new m3u8.Parser();
- * parser.push(xhr.responseText);
- * ```
- *
- * New input can later be applied to update the manifest object by calling
- * `push` again.
- *
- * The parser attempts to create a usable manifest object even if the
- * underlying input is somewhat nonsensical. It emits `info` and `warning`
- * events during the parse if it encounters input that seems invalid or
- * requires some property of the manifest object to be defaulted.
- *
- * @class Parser
- * @extends Stream
- */
-
-
- var Parser = /*#__PURE__*/function (_Stream) {
- inheritsLoose(Parser, _Stream);
-
- function Parser() {
- var _this;
-
- _this = _Stream.call(this) || this;
- _this.lineStream = new LineStream();
- _this.parseStream = new ParseStream();
-
- _this.lineStream.pipe(_this.parseStream);
- /* eslint-disable consistent-this */
-
-
- var self = assertThisInitialized(_this);
- /* eslint-enable consistent-this */
-
-
- var uris = [];
- var currentUri = {}; // if specified, the active EXT-X-MAP definition
-
- var currentMap; // if specified, the active decryption key
-
- var _key;
-
- var hasParts = false;
-
- var noop = function noop() {};
-
- var defaultMediaGroups = {
- 'AUDIO': {},
- 'VIDEO': {},
- 'CLOSED-CAPTIONS': {},
- 'SUBTITLES': {}
- }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
- // used in MPDs with Widevine encrypted streams.
-
- var widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
-
- var currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
-
- _this.manifest = {
- allowCache: true,
- discontinuityStarts: [],
- segments: []
- }; // keep track of the last seen segment's byte range end, as segments are not required
- // to provide the offset, in which case it defaults to the next byte after the
- // previous segment
-
- var lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
-
- var lastPartByterangeEnd = 0;
-
- _this.on('end', function () {
- // only add preloadSegment if we don't yet have a uri for it.
- // and we actually have parts/preloadHints
- if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
- return;
- }
-
- if (!currentUri.map && currentMap) {
- currentUri.map = currentMap;
- }
-
- if (!currentUri.key && _key) {
- currentUri.key = _key;
- }
-
- if (!currentUri.timeline && typeof currentTimeline === 'number') {
- currentUri.timeline = currentTimeline;
- }
-
- _this.manifest.preloadSegment = currentUri;
- }); // update the manifest with the m3u8 entry from the parse stream
-
-
- _this.parseStream.on('data', function (entry) {
- var mediaGroup;
- var rendition;
- ({
- tag: function tag() {
- // switch based on the tag type
- (({
- version: function version() {
- if (entry.version) {
- this.manifest.version = entry.version;
- }
- },
- 'allow-cache': function allowCache() {
- this.manifest.allowCache = entry.allowed;
-
- if (!('allowed' in entry)) {
- this.trigger('info', {
- message: 'defaulting allowCache to YES'
- });
- this.manifest.allowCache = true;
- }
- },
- byterange: function byterange() {
- var byterange = {};
-
- if ('length' in entry) {
- currentUri.byterange = byterange;
- byterange.length = entry.length;
-
- if (!('offset' in entry)) {
- /*
- * From the latest spec (as of this writing):
- * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
- *
- * Same text since EXT-X-BYTERANGE's introduction in draft 7:
- * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
- *
- * "If o [offset] is not present, the sub-range begins at the next byte
- * following the sub-range of the previous media segment."
- */
- entry.offset = lastByterangeEnd;
- }
- }
-
- if ('offset' in entry) {
- currentUri.byterange = byterange;
- byterange.offset = entry.offset;
- }
-
- lastByterangeEnd = byterange.offset + byterange.length;
- },
- endlist: function endlist() {
- this.manifest.endList = true;
- },
- inf: function inf() {
- if (!('mediaSequence' in this.manifest)) {
- this.manifest.mediaSequence = 0;
- this.trigger('info', {
- message: 'defaulting media sequence to zero'
- });
- }
-
- if (!('discontinuitySequence' in this.manifest)) {
- this.manifest.discontinuitySequence = 0;
- this.trigger('info', {
- message: 'defaulting discontinuity sequence to zero'
- });
- }
-
- if (entry.duration > 0) {
- currentUri.duration = entry.duration;
- }
-
- if (entry.duration === 0) {
- currentUri.duration = 0.01;
- this.trigger('info', {
- message: 'updating zero segment duration to a small value'
- });
- }
-
- this.manifest.segments = uris;
- },
- key: function key() {
- if (!entry.attributes) {
- this.trigger('warn', {
- message: 'ignoring key declaration without attribute list'
- });
- return;
- } // clear the active encryption key
-
-
- if (entry.attributes.METHOD === 'NONE') {
- _key = null;
- return;
- }
-
- if (!entry.attributes.URI) {
- this.trigger('warn', {
- message: 'ignoring key declaration without URI'
- });
- return;
- }
-
- if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
- this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
-
- this.manifest.contentProtection['com.apple.fps.1_0'] = {
- attributes: entry.attributes
- };
- return;
- } // check if the content is encrypted for Widevine
- // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
-
-
- if (entry.attributes.KEYFORMAT === widevineUuid) {
- var VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
-
- if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
- this.trigger('warn', {
- message: 'invalid key method provided for Widevine'
- });
- return;
- }
-
- if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
- this.trigger('warn', {
- message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
- });
- }
-
- if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
- this.trigger('warn', {
- message: 'invalid key URI provided for Widevine'
- });
- return;
- }
-
- if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
- this.trigger('warn', {
- message: 'invalid key ID provided for Widevine'
- });
- return;
- } // if Widevine key attributes are valid, store them as `contentProtection`
- // on the manifest to emulate Widevine tag structure in a DASH mpd
-
-
- this.manifest.contentProtection = this.manifest.contentProtection || {};
- this.manifest.contentProtection['com.widevine.alpha'] = {
- attributes: {
- schemeIdUri: entry.attributes.KEYFORMAT,
- // remove '0x' from the key id string
- keyId: entry.attributes.KEYID.substring(2)
- },
- // decode the base64-encoded PSSH box
- pssh: decodeB64ToUint8Array(entry.attributes.URI.split(',')[1])
- };
- return;
- }
-
- if (!entry.attributes.METHOD) {
- this.trigger('warn', {
- message: 'defaulting key method to AES-128'
- });
- } // setup an encryption key for upcoming segments
-
-
- _key = {
- method: entry.attributes.METHOD || 'AES-128',
- uri: entry.attributes.URI
- };
-
- if (typeof entry.attributes.IV !== 'undefined') {
- _key.iv = entry.attributes.IV;
- }
- },
- 'media-sequence': function mediaSequence() {
- if (!isFinite(entry.number)) {
- this.trigger('warn', {
- message: 'ignoring invalid media sequence: ' + entry.number
- });
- return;
- }
-
- this.manifest.mediaSequence = entry.number;
- },
- 'discontinuity-sequence': function discontinuitySequence() {
- if (!isFinite(entry.number)) {
- this.trigger('warn', {
- message: 'ignoring invalid discontinuity sequence: ' + entry.number
- });
- return;
- }
-
- this.manifest.discontinuitySequence = entry.number;
- currentTimeline = entry.number;
- },
- 'playlist-type': function playlistType() {
- if (!/VOD|EVENT/.test(entry.playlistType)) {
- this.trigger('warn', {
- message: 'ignoring unknown playlist type: ' + entry.playlist
- });
- return;
- }
-
- this.manifest.playlistType = entry.playlistType;
- },
- map: function map() {
- currentMap = {};
-
- if (entry.uri) {
- currentMap.uri = entry.uri;
- }
-
- if (entry.byterange) {
- currentMap.byterange = entry.byterange;
- }
-
- if (_key) {
- currentMap.key = _key;
- }
- },
- 'stream-inf': function streamInf() {
- this.manifest.playlists = uris;
- this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
-
- if (!entry.attributes) {
- this.trigger('warn', {
- message: 'ignoring empty stream-inf attributes'
- });
- return;
- }
-
- if (!currentUri.attributes) {
- currentUri.attributes = {};
- }
-
- _extends_1(currentUri.attributes, entry.attributes);
- },
- media: function media() {
- this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
-
- if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
- this.trigger('warn', {
- message: 'ignoring incomplete or missing media group'
- });
- return;
- } // find the media group, creating defaults as necessary
-
-
- var mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
- mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
- mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
-
- rendition = {
- default: /yes/i.test(entry.attributes.DEFAULT)
- };
-
- if (rendition.default) {
- rendition.autoselect = true;
- } else {
- rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
- }
-
- if (entry.attributes.LANGUAGE) {
- rendition.language = entry.attributes.LANGUAGE;
- }
-
- if (entry.attributes.URI) {
- rendition.uri = entry.attributes.URI;
- }
-
- if (entry.attributes['INSTREAM-ID']) {
- rendition.instreamId = entry.attributes['INSTREAM-ID'];
- }
-
- if (entry.attributes.CHARACTERISTICS) {
- rendition.characteristics = entry.attributes.CHARACTERISTICS;
- }
-
- if (entry.attributes.FORCED) {
- rendition.forced = /yes/i.test(entry.attributes.FORCED);
- } // insert the new rendition
-
-
- mediaGroup[entry.attributes.NAME] = rendition;
- },
- discontinuity: function discontinuity() {
- currentTimeline += 1;
- currentUri.discontinuity = true;
- this.manifest.discontinuityStarts.push(uris.length);
- },
- 'program-date-time': function programDateTime() {
- if (typeof this.manifest.dateTimeString === 'undefined') {
- // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
- // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
- // to the manifest object
- // TODO: Consider removing this in future major version
- this.manifest.dateTimeString = entry.dateTimeString;
- this.manifest.dateTimeObject = entry.dateTimeObject;
- }
-
- currentUri.dateTimeString = entry.dateTimeString;
- currentUri.dateTimeObject = entry.dateTimeObject;
- },
- targetduration: function targetduration() {
- if (!isFinite(entry.duration) || entry.duration < 0) {
- this.trigger('warn', {
- message: 'ignoring invalid target duration: ' + entry.duration
- });
- return;
- }
-
- this.manifest.targetDuration = entry.duration;
- setHoldBack.call(this, this.manifest);
- },
- start: function start() {
- if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
- this.trigger('warn', {
- message: 'ignoring start declaration without appropriate attribute list'
- });
- return;
- }
-
- this.manifest.start = {
- timeOffset: entry.attributes['TIME-OFFSET'],
- precise: entry.attributes.PRECISE
- };
- },
- 'cue-out': function cueOut() {
- currentUri.cueOut = entry.data;
- },
- 'cue-out-cont': function cueOutCont() {
- currentUri.cueOutCont = entry.data;
- },
- 'cue-in': function cueIn() {
- currentUri.cueIn = entry.data;
- },
- 'skip': function skip() {
- this.manifest.skip = camelCaseKeys(entry.attributes);
- this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
- },
- 'part': function part() {
- var _this2 = this;
-
- hasParts = true; // parts are always specifed before a segment
-
- var segmentIndex = this.manifest.segments.length;
- var part = camelCaseKeys(entry.attributes);
- currentUri.parts = currentUri.parts || [];
- currentUri.parts.push(part);
-
- if (part.byterange) {
- if (!part.byterange.hasOwnProperty('offset')) {
- part.byterange.offset = lastPartByterangeEnd;
- }
-
- lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
- }
-
- var partIndex = currentUri.parts.length - 1;
- this.warnOnMissingAttributes_("#EXT-X-PART #" + partIndex + " for segment #" + segmentIndex, entry.attributes, ['URI', 'DURATION']);
-
- if (this.manifest.renditionReports) {
- this.manifest.renditionReports.forEach(function (r, i) {
- if (!r.hasOwnProperty('lastPart')) {
- _this2.trigger('warn', {
- message: "#EXT-X-RENDITION-REPORT #" + i + " lacks required attribute(s): LAST-PART"
- });
- }
- });
- }
- },
- 'server-control': function serverControl() {
- var attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
-
- if (!attrs.hasOwnProperty('canBlockReload')) {
- attrs.canBlockReload = false;
- this.trigger('info', {
- message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
- });
- }
-
- setHoldBack.call(this, this.manifest);
-
- if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
- this.trigger('warn', {
- message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
- });
- }
- },
- 'preload-hint': function preloadHint() {
- // parts are always specifed before a segment
- var segmentIndex = this.manifest.segments.length;
- var hint = camelCaseKeys(entry.attributes);
- var isPart = hint.type && hint.type === 'PART';
- currentUri.preloadHints = currentUri.preloadHints || [];
- currentUri.preloadHints.push(hint);
-
- if (hint.byterange) {
- if (!hint.byterange.hasOwnProperty('offset')) {
- // use last part byterange end or zero if not a part.
- hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
-
- if (isPart) {
- lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
- }
- }
- }
-
- var index = currentUri.preloadHints.length - 1;
- this.warnOnMissingAttributes_("#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex, entry.attributes, ['TYPE', 'URI']);
-
- if (!hint.type) {
- return;
- } // search through all preload hints except for the current one for
- // a duplicate type.
-
-
- for (var i = 0; i < currentUri.preloadHints.length - 1; i++) {
- var otherHint = currentUri.preloadHints[i];
-
- if (!otherHint.type) {
- continue;
- }
-
- if (otherHint.type === hint.type) {
- this.trigger('warn', {
- message: "#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex + " has the same TYPE " + hint.type + " as preload hint #" + i
- });
- }
- }
- },
- 'rendition-report': function renditionReport() {
- var report = camelCaseKeys(entry.attributes);
- this.manifest.renditionReports = this.manifest.renditionReports || [];
- this.manifest.renditionReports.push(report);
- var index = this.manifest.renditionReports.length - 1;
- var required = ['LAST-MSN', 'URI'];
-
- if (hasParts) {
- required.push('LAST-PART');
- }
-
- this.warnOnMissingAttributes_("#EXT-X-RENDITION-REPORT #" + index, entry.attributes, required);
- },
- 'part-inf': function partInf() {
- this.manifest.partInf = camelCaseKeys(entry.attributes);
- this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
-
- if (this.manifest.partInf.partTarget) {
- this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
- }
-
- setHoldBack.call(this, this.manifest);
- }
- })[entry.tagType] || noop).call(self);
- },
- uri: function uri() {
- currentUri.uri = entry.uri;
- uris.push(currentUri); // if no explicit duration was declared, use the target duration
-
- if (this.manifest.targetDuration && !('duration' in currentUri)) {
- this.trigger('warn', {
- message: 'defaulting segment duration to the target duration'
- });
- currentUri.duration = this.manifest.targetDuration;
- } // annotate with encryption information, if necessary
-
-
- if (_key) {
- currentUri.key = _key;
- }
-
- currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
-
- if (currentMap) {
- currentUri.map = currentMap;
- } // reset the last byterange end as it needs to be 0 between parts
-
-
- lastPartByterangeEnd = 0; // prepare for the next URI
-
- currentUri = {};
- },
- comment: function comment() {// comments are not important for playback
- },
- custom: function custom() {
- // if this is segment-level data attach the output to the segment
- if (entry.segment) {
- currentUri.custom = currentUri.custom || {};
- currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
- } else {
- this.manifest.custom = this.manifest.custom || {};
- this.manifest.custom[entry.customType] = entry.data;
- }
- }
- })[entry.type].call(self);
- });
-
- return _this;
- }
-
- var _proto = Parser.prototype;
-
- _proto.warnOnMissingAttributes_ = function warnOnMissingAttributes_(identifier, attributes, required) {
- var missing = [];
- required.forEach(function (key) {
- if (!attributes.hasOwnProperty(key)) {
- missing.push(key);
- }
- });
-
- if (missing.length) {
- this.trigger('warn', {
- message: identifier + " lacks required attribute(s): " + missing.join(', ')
- });
- }
- }
- /**
- * Parse the input string and update the manifest object.
- *
- * @param {string} chunk a potentially incomplete portion of the manifest
- */
- ;
-
- _proto.push = function push(chunk) {
- this.lineStream.push(chunk);
- }
- /**
- * Flush any remaining input. This can be handy if the last line of an M3U8
- * manifest did not contain a trailing newline but the file has been
- * completely received.
- */
- ;
-
- _proto.end = function end() {
- // flush any buffered input
- this.lineStream.push('\n');
- this.trigger('end');
- }
- /**
- * Add an additional parser for non-standard tags
- *
- * @param {Object} options a map of options for the added parser
- * @param {RegExp} options.expression a regular expression to match the custom header
- * @param {string} options.type the type to register to the output
- * @param {Function} [options.dataParser] function to parse the line into an object
- * @param {boolean} [options.segment] should tag data be attached to the segment object
- */
- ;
-
- _proto.addParser = function addParser(options) {
- this.parseStream.addParser(options);
- }
- /**
- * Add a custom header mapper
- *
- * @param {Object} options
- * @param {RegExp} options.expression a regular expression to match the custom header
- * @param {Function} options.map function to translate tag into a different tag
- */
- ;
-
- _proto.addTagMapper = function addTagMapper(options) {
- this.parseStream.addTagMapper(options);
- };
-
- return Parser;
- }(Stream);
-
- var regexs = {
- // to determine mime types
- mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
- webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
- ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
- // to determine if a codec is audio or video
- video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
- audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
- text: /^(stpp.ttml.im1t)/,
- // mux.js support regex
- muxerVideo: /^(avc0?1)/,
- muxerAudio: /^(mp4a)/,
- // match nothing as muxer does not support text right now.
- // there cannot never be a character before the start of a string
- // so this matches nothing.
- muxerText: /a^/
- };
- var mediaTypes = ['video', 'audio', 'text'];
- var upperMediaTypes = ['Video', 'Audio', 'Text'];
- /**
- * Replace the old apple-style `avc1..` codec string with the standard
- * `avc1.`
- *
- * @param {string} codec
- * Codec string to translate
- * @return {string}
- * The translated codec string
- */
-
- var translateLegacyCodec = function translateLegacyCodec(codec) {
- if (!codec) {
- return codec;
- }
-
- return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
- var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
- var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
- return 'avc1.' + profileHex + '00' + avcLevelHex;
- });
- };
- /**
- * @typedef {Object} ParsedCodecInfo
- * @property {number} codecCount
- * Number of codecs parsed
- * @property {string} [videoCodec]
- * Parsed video codec (if found)
- * @property {string} [videoObjectTypeIndicator]
- * Video object type indicator (if found)
- * @property {string|null} audioProfile
- * Audio profile
- */
-
- /**
- * Parses a codec string to retrieve the number of codecs specified, the video codec and
- * object type indicator, and the audio profile.
- *
- * @param {string} [codecString]
- * The codec string to parse
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
- var parseCodecs = function parseCodecs(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- var codecs = codecString.split(',');
- var result = [];
- codecs.forEach(function (codec) {
- codec = codec.trim();
- var codecType;
- mediaTypes.forEach(function (name) {
- var match = regexs[name].exec(codec.toLowerCase());
-
- if (!match || match.length <= 1) {
- return;
- }
-
- codecType = name; // maintain codec case
-
- var type = codec.substring(0, match[1].length);
- var details = codec.replace(type, '');
- result.push({
- type: type,
- details: details,
- mediaType: name
- });
- });
-
- if (!codecType) {
- result.push({
- type: codec,
- details: '',
- mediaType: 'unknown'
- });
- }
- });
- return result;
- };
- /**
- * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
- * a default alternate audio playlist for the provided audio group.
- *
- * @param {Object} master
- * The master playlist
- * @param {string} audioGroupId
- * ID of the audio group for which to find the default codec info
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
- var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
- if (!master.mediaGroups.AUDIO || !audioGroupId) {
- return null;
- }
-
- var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
-
- if (!audioGroup) {
- return null;
- }
-
- for (var name in audioGroup) {
- var audioType = audioGroup[name];
-
- if (audioType.default && audioType.playlists) {
- // codec should be the same for all playlists within the audio type
- return parseCodecs(audioType.playlists[0].attributes.CODECS);
- }
- }
-
- return null;
- };
- var isAudioCodec = function isAudioCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.audio.test(codec.trim().toLowerCase());
- };
- var isTextCodec = function isTextCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.text.test(codec.trim().toLowerCase());
- };
- var getMimeForCodec = function getMimeForCodec(codecString) {
- if (!codecString || typeof codecString !== 'string') {
- return;
- }
-
- var codecs = codecString.toLowerCase().split(',').map(function (c) {
- return translateLegacyCodec(c.trim());
- }); // default to video type
-
- var type = 'video'; // only change to audio type if the only codec we have is
- // audio
-
- if (codecs.length === 1 && isAudioCodec(codecs[0])) {
- type = 'audio';
- } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
- // text uses application/ for now
- type = 'application';
- } // default the container to mp4
-
-
- var container = 'mp4'; // every codec must be able to go into the container
- // for that container to be the correct one
-
- if (codecs.every(function (c) {
- return regexs.mp4.test(c);
- })) {
- container = 'mp4';
- } else if (codecs.every(function (c) {
- return regexs.webm.test(c);
- })) {
- container = 'webm';
- } else if (codecs.every(function (c) {
- return regexs.ogg.test(c);
- })) {
- container = 'ogg';
- }
-
- return type + "/" + container + ";codecs=\"" + codecString + "\"";
- };
- var browserSupportsCodec = function browserSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return window__default['default'].MediaSource && window__default['default'].MediaSource.isTypeSupported && window__default['default'].MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
- };
- var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return codecString.toLowerCase().split(',').every(function (codec) {
- codec = codec.trim(); // any match is supported.
-
- for (var i = 0; i < upperMediaTypes.length; i++) {
- var type = upperMediaTypes[i];
-
- if (regexs["muxer" + type].test(codec)) {
- return true;
- }
- }
-
- return false;
- });
- };
- var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
- var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
-
- /**
- * ranges
- *
- * Utilities for working with TimeRanges.
- *
- */
-
- var TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
- // can be misleading because of precision differences or when the current media has poorly
- // aligned audio and video, which can cause values to be slightly off from what you would
- // expect. This value is what we consider to be safe to use in such comparisons to account
- // for these scenarios.
-
- var SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
-
- var filterRanges = function filterRanges(timeRanges, predicate) {
- var results = [];
- var i;
-
- if (timeRanges && timeRanges.length) {
- // Search for ranges that match the predicate
- for (i = 0; i < timeRanges.length; i++) {
- if (predicate(timeRanges.start(i), timeRanges.end(i))) {
- results.push([timeRanges.start(i), timeRanges.end(i)]);
- }
- }
- }
-
- return videojs__default['default'].createTimeRanges(results);
- };
- /**
- * Attempts to find the buffered TimeRange that contains the specified
- * time.
- *
- * @param {TimeRanges} buffered - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object
- */
-
-
- var findRange = function findRange(buffered, time) {
- return filterRanges(buffered, function (start, end) {
- return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
- });
- };
- /**
- * Returns the TimeRanges that begin later than the specified time.
- *
- * @param {TimeRanges} timeRanges - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object.
- */
-
- var findNextRange = function findNextRange(timeRanges, time) {
- return filterRanges(timeRanges, function (start) {
- return start - TIME_FUDGE_FACTOR >= time;
- });
- };
- /**
- * Returns gaps within a list of TimeRanges
- *
- * @param {TimeRanges} buffered - the TimeRanges object
- * @return {TimeRanges} a TimeRanges object of gaps
- */
-
- var findGaps = function findGaps(buffered) {
- if (buffered.length < 2) {
- return videojs__default['default'].createTimeRanges();
- }
-
- var ranges = [];
-
- for (var i = 1; i < buffered.length; i++) {
- var start = buffered.end(i - 1);
- var end = buffered.start(i);
- ranges.push([start, end]);
- }
-
- return videojs__default['default'].createTimeRanges(ranges);
- };
- /**
- * Calculate the intersection of two TimeRanges
- *
- * @param {TimeRanges} bufferA
- * @param {TimeRanges} bufferB
- * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
- */
-
- var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
- var start = null;
- var end = null;
- var arity = 0;
- var extents = [];
- var ranges = [];
-
- if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
- return videojs__default['default'].createTimeRange();
- } // Handle the case where we have both buffers and create an
- // intersection of the two
-
-
- var count = bufferA.length; // A) Gather up all start and end times
-
- while (count--) {
- extents.push({
- time: bufferA.start(count),
- type: 'start'
- });
- extents.push({
- time: bufferA.end(count),
- type: 'end'
- });
- }
-
- count = bufferB.length;
-
- while (count--) {
- extents.push({
- time: bufferB.start(count),
- type: 'start'
- });
- extents.push({
- time: bufferB.end(count),
- type: 'end'
- });
- } // B) Sort them by time
-
-
- extents.sort(function (a, b) {
- return a.time - b.time;
- }); // C) Go along one by one incrementing arity for start and decrementing
- // arity for ends
-
- for (count = 0; count < extents.length; count++) {
- if (extents[count].type === 'start') {
- arity++; // D) If arity is ever incremented to 2 we are entering an
- // overlapping range
-
- if (arity === 2) {
- start = extents[count].time;
- }
- } else if (extents[count].type === 'end') {
- arity--; // E) If arity is ever decremented to 1 we leaving an
- // overlapping range
-
- if (arity === 1) {
- end = extents[count].time;
- }
- } // F) Record overlapping ranges
-
-
- if (start !== null && end !== null) {
- ranges.push([start, end]);
- start = null;
- end = null;
- }
- }
-
- return videojs__default['default'].createTimeRanges(ranges);
- };
- /**
- * Gets a human readable string for a TimeRange
- *
- * @param {TimeRange} range
- * @return {string} a human readable string
- */
-
- var printableRange = function printableRange(range) {
- var strArr = [];
-
- if (!range || !range.length) {
- return '';
- }
-
- for (var i = 0; i < range.length; i++) {
- strArr.push(range.start(i) + ' => ' + range.end(i));
- }
-
- return strArr.join(', ');
- };
- /**
- * Calculates the amount of time left in seconds until the player hits the end of the
- * buffer and causes a rebuffer
- *
- * @param {TimeRange} buffered
- * The state of the buffer
- * @param {Numnber} currentTime
- * The current time of the player
- * @param {number} playbackRate
- * The current playback rate of the player. Defaults to 1.
- * @return {number}
- * Time until the player has to start rebuffering in seconds.
- * @function timeUntilRebuffer
- */
-
- var timeUntilRebuffer = function timeUntilRebuffer(buffered, currentTime, playbackRate) {
- if (playbackRate === void 0) {
- playbackRate = 1;
- }
-
- var bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
- return (bufferedEnd - currentTime) / playbackRate;
- };
- /**
- * Converts a TimeRanges object into an array representation
- *
- * @param {TimeRanges} timeRanges
- * @return {Array}
- */
-
- var timeRangesToArray = function timeRangesToArray(timeRanges) {
- var timeRangesList = [];
-
- for (var i = 0; i < timeRanges.length; i++) {
- timeRangesList.push({
- start: timeRanges.start(i),
- end: timeRanges.end(i)
- });
- }
-
- return timeRangesList;
- };
- /**
- * Determines if two time range objects are different.
- *
- * @param {TimeRange} a
- * the first time range object to check
- *
- * @param {TimeRange} b
- * the second time range object to check
- *
- * @return {Boolean}
- * Whether the time range objects differ
- */
-
- var isRangeDifferent = function isRangeDifferent(a, b) {
- // same object
- if (a === b) {
- return false;
- } // one or the other is undefined
-
-
- if (!a && b || !b && a) {
- return true;
- } // length is different
-
-
- if (a.length !== b.length) {
- return true;
- } // see if any start/end pair is different
-
-
- for (var i = 0; i < a.length; i++) {
- if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
- return true;
- }
- } // if the length and every pair is the same
- // this is the same time range
-
-
- return false;
- };
- var lastBufferedEnd = function lastBufferedEnd(a) {
- if (!a || !a.length || !a.end) {
- return;
- }
-
- return a.end(a.length - 1);
- };
-
- /**
- * @file playlist.js
- *
- * Playlist related utilities.
- */
- var createTimeRange = videojs__default['default'].createTimeRange;
- /**
- * A function to get a combined list of parts and segments with durations
- * and indexes.
- *
- * @param {Playlist} playlist the playlist to get the list for.
- *
- * @return {Array} The part/segment list.
- */
-
- var getPartsAndSegments = function getPartsAndSegments(playlist) {
- return (playlist.segments || []).reduce(function (acc, segment, si) {
- if (segment.parts) {
- segment.parts.forEach(function (part, pi) {
- acc.push({
- duration: part.duration,
- segmentIndex: si,
- partIndex: pi,
- part: part,
- segment: segment
- });
- });
- } else {
- acc.push({
- duration: segment.duration,
- segmentIndex: si,
- partIndex: null,
- segment: segment,
- part: null
- });
- }
-
- return acc;
- }, []);
- };
- var getLastParts = function getLastParts(media) {
- var lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
- return lastSegment && lastSegment.parts || [];
- };
- var getKnownPartCount = function getKnownPartCount(_ref) {
- var preloadSegment = _ref.preloadSegment;
-
- if (!preloadSegment) {
- return;
- }
-
- var parts = preloadSegment.parts,
- preloadHints = preloadSegment.preloadHints;
- var partCount = (preloadHints || []).reduce(function (count, hint) {
- return count + (hint.type === 'PART' ? 1 : 0);
- }, 0);
- partCount += parts && parts.length ? parts.length : 0;
- return partCount;
- };
- /**
- * Get the number of seconds to delay from the end of a
- * live playlist.
- *
- * @param {Playlist} master the master playlist
- * @param {Playlist} media the media playlist
- * @return {number} the hold back in seconds.
- */
-
- var liveEdgeDelay = function liveEdgeDelay(master, media) {
- if (media.endList) {
- return 0;
- } // dash suggestedPresentationDelay trumps everything
-
-
- if (master && master.suggestedPresentationDelay) {
- return master.suggestedPresentationDelay;
- }
-
- var hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
-
- if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
- return media.serverControl.partHoldBack;
- } else if (hasParts && media.partTargetDuration) {
- return media.partTargetDuration * 3; // finally look for full segment delays
- } else if (media.serverControl && media.serverControl.holdBack) {
- return media.serverControl.holdBack;
- } else if (media.targetDuration) {
- return media.targetDuration * 3;
- }
-
- return 0;
- };
- /**
- * walk backward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {Number} endSequence the mediaSequence to stop walking on
- */
-
- var backwardDuration = function backwardDuration(playlist, endSequence) {
- var result = 0;
- var i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
- // the interval, use it
-
- var segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
- // information that is earlier than endSequence
-
- if (segment) {
- if (typeof segment.start !== 'undefined') {
- return {
- result: segment.start,
- precise: true
- };
- }
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - segment.duration,
- precise: true
- };
- }
- }
-
- while (i--) {
- segment = playlist.segments[i];
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: result + segment.end,
- precise: true
- };
- }
-
- result += segment.duration;
-
- if (typeof segment.start !== 'undefined') {
- return {
- result: result + segment.start,
- precise: true
- };
- }
- }
-
- return {
- result: result,
- precise: false
- };
- };
- /**
- * walk forward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {number} endSequence the mediaSequence to stop walking on
- */
-
-
- var forwardDuration = function forwardDuration(playlist, endSequence) {
- var result = 0;
- var segment;
- var i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
- // information
-
- for (; i < playlist.segments.length; i++) {
- segment = playlist.segments[i];
-
- if (typeof segment.start !== 'undefined') {
- return {
- result: segment.start - result,
- precise: true
- };
- }
-
- result += segment.duration;
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - result,
- precise: true
- };
- }
- } // indicate we didn't find a useful duration estimate
-
-
- return {
- result: -1,
- precise: false
- };
- };
- /**
- * Calculate the media duration from the segments associated with a
- * playlist. The duration of a subinterval of the available segments
- * may be calculated by specifying an end index.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper boundary
- * for the playlist. Defaults to playlist length.
- * @param {number} expired the amount of time that has dropped
- * off the front of the playlist in a live scenario
- * @return {number} the duration between the first available segment
- * and end index.
- */
-
-
- var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
- if (typeof endSequence === 'undefined') {
- endSequence = playlist.mediaSequence + playlist.segments.length;
- }
-
- if (endSequence < playlist.mediaSequence) {
- return 0;
- } // do a backward walk to estimate the duration
-
-
- var backward = backwardDuration(playlist, endSequence);
-
- if (backward.precise) {
- // if we were able to base our duration estimate on timing
- // information provided directly from the Media Source, return
- // it
- return backward.result;
- } // walk forward to see if a precise duration estimate can be made
- // that way
-
-
- var forward = forwardDuration(playlist, endSequence);
-
- if (forward.precise) {
- // we found a segment that has been buffered and so it's
- // position is known precisely
- return forward.result;
- } // return the less-precise, playlist-based duration estimate
-
-
- return backward.result + expired;
- };
- /**
- * Calculates the duration of a playlist. If a start and end index
- * are specified, the duration will be for the subset of the media
- * timeline between those two indices. The total duration for live
- * playlists is always Infinity.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper
- * boundary for the playlist. Defaults to the playlist media
- * sequence number plus its length.
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @return {number} the duration between the start index and end
- * index.
- */
-
-
- var duration = function duration(playlist, endSequence, expired) {
- if (!playlist) {
- return 0;
- }
-
- if (typeof expired !== 'number') {
- expired = 0;
- } // if a slice of the total duration is not requested, use
- // playlist-level duration indicators when they're present
-
-
- if (typeof endSequence === 'undefined') {
- // if present, use the duration specified in the playlist
- if (playlist.totalDuration) {
- return playlist.totalDuration;
- } // duration should be Infinity for live playlists
-
-
- if (!playlist.endList) {
- return window__default['default'].Infinity;
- }
- } // calculate the total duration based on the segment durations
-
-
- return intervalDuration(playlist, endSequence, expired);
- };
- /**
- * Calculate the time between two indexes in the current playlist
- * neight the start- nor the end-index need to be within the current
- * playlist in which case, the targetDuration of the playlist is used
- * to approximate the durations of the segments
- *
- * @param {Array} options.durationList list to iterate over for durations.
- * @param {number} options.defaultDuration duration to use for elements before or after the durationList
- * @param {number} options.startIndex partsAndSegments index to start
- * @param {number} options.endIndex partsAndSegments index to end.
- * @return {number} the number of seconds between startIndex and endIndex
- */
-
- var sumDurations = function sumDurations(_ref2) {
- var defaultDuration = _ref2.defaultDuration,
- durationList = _ref2.durationList,
- startIndex = _ref2.startIndex,
- endIndex = _ref2.endIndex;
- var durations = 0;
-
- if (startIndex > endIndex) {
- var _ref3 = [endIndex, startIndex];
- startIndex = _ref3[0];
- endIndex = _ref3[1];
- }
-
- if (startIndex < 0) {
- for (var i = startIndex; i < Math.min(0, endIndex); i++) {
- durations += defaultDuration;
- }
-
- startIndex = 0;
- }
-
- for (var _i = startIndex; _i < endIndex; _i++) {
- durations += durationList[_i].duration;
- }
-
- return durations;
- };
- /**
- * Calculates the playlist end time
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
- * playlist end calculation should consider the safe live end
- * (truncate the playlist end by three segments). This is normally
- * used for calculating the end of the playlist's seekable range.
- * This takes into account the value of liveEdgePadding.
- * Setting liveEdgePadding to 0 is equivalent to setting this to false.
- * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
- * If this is provided, it is used in the safe live end calculation.
- * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {number} the end time of playlist
- * @function playlistEnd
- */
-
- var playlistEnd = function playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding) {
- if (!playlist || !playlist.segments) {
- return null;
- }
-
- if (playlist.endList) {
- return duration(playlist);
- }
-
- if (expired === null) {
- return null;
- }
-
- expired = expired || 0;
- var lastSegmentTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
-
- if (useSafeLiveEnd) {
- liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
- lastSegmentTime -= liveEdgePadding;
- } // don't return a time less than zero
-
-
- return Math.max(0, lastSegmentTime);
- };
- /**
- * Calculates the interval of time that is currently seekable in a
- * playlist. The returned time ranges are relative to the earliest
- * moment in the specified playlist that is still available. A full
- * seekable implementation for live streams would need to offset
- * these values by the duration of content that has expired from the
- * stream.
- *
- * @param {Object} playlist a media playlist object
- * dropped off the front of the playlist in a live scenario
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {TimeRanges} the periods of time that are valid targets
- * for seeking
- */
-
- var seekable = function seekable(playlist, expired, liveEdgePadding) {
- var useSafeLiveEnd = true;
- var seekableStart = expired || 0;
- var seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
-
- if (seekableEnd === null) {
- return createTimeRange();
- }
-
- return createTimeRange(seekableStart, seekableEnd);
- };
- /**
- * Determine the index and estimated starting time of the segment that
- * contains a specified playback position in a media playlist.
- *
- * @param {Object} options.playlist the media playlist to query
- * @param {number} options.currentTime The number of seconds since the earliest
- * possible position to determine the containing segment for
- * @param {number} options.startTime the time when the segment/part starts
- * @param {number} options.startingSegmentIndex the segment index to start looking at.
- * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
- *
- * @return {Object} an object with partIndex, segmentIndex, and startTime.
- */
-
- var getMediaInfoForTime = function getMediaInfoForTime(_ref4) {
- var playlist = _ref4.playlist,
- currentTime = _ref4.currentTime,
- startingSegmentIndex = _ref4.startingSegmentIndex,
- startingPartIndex = _ref4.startingPartIndex,
- startTime = _ref4.startTime;
- var time = currentTime - startTime;
- var partsAndSegments = getPartsAndSegments(playlist);
- var startIndex = 0;
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- var partAndSegment = partsAndSegments[i];
-
- if (startingSegmentIndex !== partAndSegment.segmentIndex) {
- continue;
- } // skip this if part index does not match.
-
-
- if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
- continue;
- }
-
- startIndex = i;
- break;
- }
-
- if (time < 0) {
- // Walk backward from startIndex in the playlist, adding durations
- // until we find a segment that contains `time` and return it
- if (startIndex > 0) {
- for (var _i2 = startIndex - 1; _i2 >= 0; _i2--) {
- var _partAndSegment = partsAndSegments[_i2];
- time += _partAndSegment.duration; // TODO: consider not using TIME_FUDGE_FACTOR at all here
-
- if (time + TIME_FUDGE_FACTOR > 0) {
- return {
- partIndex: _partAndSegment.partIndex,
- segmentIndex: _partAndSegment.segmentIndex,
- startTime: startTime - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex: startIndex,
- endIndex: _i2
- })
- };
- }
- }
- } // We were unable to find a good segment within the playlist
- // so select the first segment
-
-
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- } // When startIndex is negative, we first walk forward to first segment
- // adding target durations. If we "run out of time" before getting to
- // the first segment, return the first segment
-
-
- if (startIndex < 0) {
- for (var _i3 = startIndex; _i3 < 0; _i3++) {
- time -= playlist.targetDuration;
-
- if (time < 0) {
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- }
- }
-
- startIndex = 0;
- } // Walk forward from startIndex in the playlist, subtracting durations
- // until we find a segment that contains `time` and return it
-
-
- for (var _i4 = startIndex; _i4 < partsAndSegments.length; _i4++) {
- var _partAndSegment2 = partsAndSegments[_i4];
- time -= _partAndSegment2.duration; // TODO: consider not using TIME_FUDGE_FACTOR at all here
-
- if (time - TIME_FUDGE_FACTOR < 0) {
- return {
- partIndex: _partAndSegment2.partIndex,
- segmentIndex: _partAndSegment2.segmentIndex,
- startTime: startTime + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex: startIndex,
- endIndex: _i4
- })
- };
- }
- } // We are out of possible candidates so load the last one...
-
-
- return {
- segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
- partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
- startTime: currentTime
- };
- };
- /**
- * Check whether the playlist is blacklisted or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is blacklisted or not
- * @function isBlacklisted
- */
-
- var isBlacklisted = function isBlacklisted(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil > Date.now();
- };
- /**
- * Check whether the playlist is compatible with current playback configuration or has
- * been blacklisted permanently for being incompatible.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is incompatible or not
- * @function isIncompatible
- */
-
- var isIncompatible = function isIncompatible(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil === Infinity;
- };
- /**
- * Check whether the playlist is enabled or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is enabled or not
- * @function isEnabled
- */
-
- var isEnabled = function isEnabled(playlist) {
- var blacklisted = isBlacklisted(playlist);
- return !playlist.disabled && !blacklisted;
- };
- /**
- * Check whether the playlist has been manually disabled through the representations api.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is disabled manually or not
- * @function isDisabled
- */
-
- var isDisabled = function isDisabled(playlist) {
- return playlist.disabled;
- };
- /**
- * Returns whether the current playlist is an AES encrypted HLS stream
- *
- * @return {boolean} true if it's an AES encrypted HLS stream
- */
-
- var isAes = function isAes(media) {
- for (var i = 0; i < media.segments.length; i++) {
- if (media.segments[i].key) {
- return true;
- }
- }
-
- return false;
- };
- /**
- * Checks if the playlist has a value for the specified attribute
- *
- * @param {string} attr
- * Attribute to check for
- * @param {Object} playlist
- * The media playlist object
- * @return {boolean}
- * Whether the playlist contains a value for the attribute or not
- * @function hasAttribute
- */
-
- var hasAttribute = function hasAttribute(attr, playlist) {
- return playlist.attributes && playlist.attributes[attr];
- };
- /**
- * Estimates the time required to complete a segment download from the specified playlist
- *
- * @param {number} segmentDuration
- * Duration of requested segment
- * @param {number} bandwidth
- * Current measured bandwidth of the player
- * @param {Object} playlist
- * The media playlist object
- * @param {number=} bytesReceived
- * Number of bytes already received for the request. Defaults to 0
- * @return {number|NaN}
- * The estimated time to request the segment. NaN if bandwidth information for
- * the given playlist is unavailable
- * @function estimateSegmentRequestTime
- */
-
- var estimateSegmentRequestTime = function estimateSegmentRequestTime(segmentDuration, bandwidth, playlist, bytesReceived) {
- if (bytesReceived === void 0) {
- bytesReceived = 0;
- }
-
- if (!hasAttribute('BANDWIDTH', playlist)) {
- return NaN;
- }
-
- var size = segmentDuration * playlist.attributes.BANDWIDTH;
- return (size - bytesReceived * 8) / bandwidth;
- };
- /*
- * Returns whether the current playlist is the lowest rendition
- *
- * @return {Boolean} true if on lowest rendition
- */
-
- var isLowestEnabledRendition = function isLowestEnabledRendition(master, media) {
- if (master.playlists.length === 1) {
- return true;
- }
-
- var currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
- return master.playlists.filter(function (playlist) {
- if (!isEnabled(playlist)) {
- return false;
- }
-
- return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
- }).length === 0;
- };
- var playlistMatch = function playlistMatch(a, b) {
- // both playlits are null
- // or only one playlist is non-null
- // no match
- if (!a && !b || !a && b || a && !b) {
- return false;
- } // playlist objects are the same, match
-
-
- if (a === b) {
- return true;
- } // first try to use id as it should be the most
- // accurate
-
-
- if (a.id && b.id && a.id === b.id) {
- return true;
- } // next try to use reslovedUri as it should be the
- // second most accurate.
-
-
- if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
- return true;
- } // finally try to use uri as it should be accurate
- // but might miss a few cases for relative uris
-
-
- if (a.uri && b.uri && a.uri === b.uri) {
- return true;
- }
-
- return false;
- };
-
- var someAudioVariant = function someAudioVariant(master, callback) {
- var AUDIO = master && master.mediaGroups && master.mediaGroups.AUDIO || {};
- var found = false;
-
- for (var groupName in AUDIO) {
- for (var label in AUDIO[groupName]) {
- found = callback(AUDIO[groupName][label]);
-
- if (found) {
- break;
- }
- }
-
- if (found) {
- break;
- }
- }
-
- return !!found;
- };
-
- var isAudioOnly = function isAudioOnly(master) {
- // we are audio only if we have no main playlists but do
- // have media group playlists.
- if (!master || !master.playlists || !master.playlists.length) {
- // without audio variants or playlists this
- // is not an audio only master.
- var found = someAudioVariant(master, function (variant) {
- return variant.playlists && variant.playlists.length || variant.uri;
- });
- return found;
- } // if every playlist has only an audio codec it is audio only
-
-
- var _loop = function _loop(i) {
- var playlist = master.playlists[i];
- var CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
-
- if (CODECS && CODECS.split(',').every(function (c) {
- return isAudioCodec(c);
- })) {
- return "continue";
- } // playlist is in an audio group it is audio only
-
-
- var found = someAudioVariant(master, function (variant) {
- return playlistMatch(playlist, variant);
- });
-
- if (found) {
- return "continue";
- } // if we make it here this playlist isn't audio and we
- // are not audio only
-
-
- return {
- v: false
- };
- };
-
- for (var i = 0; i < master.playlists.length; i++) {
- var _ret = _loop(i);
-
- if (_ret === "continue") continue;
- if (typeof _ret === "object") return _ret.v;
- } // if we make it past every playlist without returning, then
- // this is an audio only playlist.
-
-
- return true;
- }; // exports
-
- var Playlist = {
- liveEdgeDelay: liveEdgeDelay,
- duration: duration,
- seekable: seekable,
- getMediaInfoForTime: getMediaInfoForTime,
- isEnabled: isEnabled,
- isDisabled: isDisabled,
- isBlacklisted: isBlacklisted,
- isIncompatible: isIncompatible,
- playlistEnd: playlistEnd,
- isAes: isAes,
- hasAttribute: hasAttribute,
- estimateSegmentRequestTime: estimateSegmentRequestTime,
- isLowestEnabledRendition: isLowestEnabledRendition,
- isAudioOnly: isAudioOnly,
- playlistMatch: playlistMatch
- };
-
- var log = videojs__default['default'].log;
- var createPlaylistID = function createPlaylistID(index, uri) {
- return index + "-" + uri;
- };
- /**
- * Parses a given m3u8 playlist
- *
- * @param {Function} [onwarn]
- * a function to call when the parser triggers a warning event.
- * @param {Function} [oninfo]
- * a function to call when the parser triggers an info event.
- * @param {string} manifestString
- * The downloaded manifest string
- * @param {Object[]} [customTagParsers]
- * An array of custom tag parsers for the m3u8-parser instance
- * @param {Object[]} [customTagMappers]
- * An array of custom tag mappers for the m3u8-parser instance
- * @param {boolean} [experimentalLLHLS=false]
- * Whether to keep ll-hls features in the manifest after parsing.
- * @return {Object}
- * The manifest object
- */
-
- var parseManifest = function parseManifest(_ref) {
- var onwarn = _ref.onwarn,
- oninfo = _ref.oninfo,
- manifestString = _ref.manifestString,
- _ref$customTagParsers = _ref.customTagParsers,
- customTagParsers = _ref$customTagParsers === void 0 ? [] : _ref$customTagParsers,
- _ref$customTagMappers = _ref.customTagMappers,
- customTagMappers = _ref$customTagMappers === void 0 ? [] : _ref$customTagMappers,
- experimentalLLHLS = _ref.experimentalLLHLS;
- var parser = new Parser();
-
- if (onwarn) {
- parser.on('warn', onwarn);
- }
-
- if (oninfo) {
- parser.on('info', oninfo);
- }
-
- customTagParsers.forEach(function (customParser) {
- return parser.addParser(customParser);
- });
- customTagMappers.forEach(function (mapper) {
- return parser.addTagMapper(mapper);
- });
- parser.push(manifestString);
- parser.end();
- var manifest = parser.manifest; // remove llhls features from the parsed manifest
- // if we don't want llhls support.
-
- if (!experimentalLLHLS) {
- ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
- if (manifest.hasOwnProperty(k)) {
- delete manifest[k];
- }
- });
-
- if (manifest.segments) {
- manifest.segments.forEach(function (segment) {
- ['parts', 'preloadHints'].forEach(function (k) {
- if (segment.hasOwnProperty(k)) {
- delete segment[k];
- }
- });
- });
- }
- }
-
- if (!manifest.targetDuration) {
- var targetDuration = 10;
-
- if (manifest.segments && manifest.segments.length) {
- targetDuration = manifest.segments.reduce(function (acc, s) {
- return Math.max(acc, s.duration);
- }, 0);
- }
-
- if (onwarn) {
- onwarn("manifest has no targetDuration defaulting to " + targetDuration);
- }
-
- manifest.targetDuration = targetDuration;
- }
-
- var parts = getLastParts(manifest);
-
- if (parts.length && !manifest.partTargetDuration) {
- var partTargetDuration = parts.reduce(function (acc, p) {
- return Math.max(acc, p.duration);
- }, 0);
-
- if (onwarn) {
- onwarn("manifest has no partTargetDuration defaulting to " + partTargetDuration);
- log.error('LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.');
- }
-
- manifest.partTargetDuration = partTargetDuration;
- }
-
- return manifest;
- };
- /**
- * Loops through all supported media groups in master and calls the provided
- * callback for each group
- *
- * @param {Object} master
- * The parsed master manifest object
- * @param {Function} callback
- * Callback to call for each media group
- */
-
- var forEachMediaGroup = function forEachMediaGroup(master, callback) {
- if (!master.mediaGroups) {
- return;
- }
-
- ['AUDIO', 'SUBTITLES'].forEach(function (mediaType) {
- if (!master.mediaGroups[mediaType]) {
- return;
- }
-
- for (var groupKey in master.mediaGroups[mediaType]) {
- for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
- var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
- callback(mediaProperties, mediaType, groupKey, labelKey);
- }
- }
- });
- };
- /**
- * Adds properties and attributes to the playlist to keep consistent functionality for
- * playlists throughout VHS.
- *
- * @param {Object} config
- * Arguments object
- * @param {Object} config.playlist
- * The media playlist
- * @param {string} [config.uri]
- * The uri to the media playlist (if media playlist is not from within a master
- * playlist)
- * @param {string} id
- * ID to use for the playlist
- */
-
- var setupMediaPlaylist = function setupMediaPlaylist(_ref2) {
- var playlist = _ref2.playlist,
- uri = _ref2.uri,
- id = _ref2.id;
- playlist.id = id;
- playlist.playlistErrors_ = 0;
-
- if (uri) {
- // For media playlists, m3u8-parser does not have access to a URI, as HLS media
- // playlists do not contain their own source URI, but one is needed for consistency in
- // VHS.
- playlist.uri = uri;
- } // For HLS master playlists, even though certain attributes MUST be defined, the
- // stream may still be played without them.
- // For HLS media playlists, m3u8-parser does not attach an attributes object to the
- // manifest.
- //
- // To avoid undefined reference errors through the project, and make the code easier
- // to write/read, add an empty attributes object for these cases.
-
-
- playlist.attributes = playlist.attributes || {};
- };
- /**
- * Adds ID, resolvedUri, and attributes properties to each playlist of the master, where
- * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
- * playlist references to the playlists array.
- *
- * @param {Object} master
- * The master playlist
- */
-
- var setupMediaPlaylists = function setupMediaPlaylists(master) {
- var i = master.playlists.length;
-
- while (i--) {
- var playlist = master.playlists[i];
- setupMediaPlaylist({
- playlist: playlist,
- id: createPlaylistID(i, playlist.uri)
- });
- playlist.resolvedUri = resolveUrl(master.uri, playlist.uri);
- master.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
-
- master.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
- // the stream can be played without it. Although an attributes property may have been
- // added to the playlist to prevent undefined references, issue a warning to fix the
- // manifest.
-
- if (!playlist.attributes.BANDWIDTH) {
- log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
- }
- }
- };
- /**
- * Adds resolvedUri properties to each media group.
- *
- * @param {Object} master
- * The master playlist
- */
-
- var resolveMediaGroupUris = function resolveMediaGroupUris(master) {
- forEachMediaGroup(master, function (properties) {
- if (properties.uri) {
- properties.resolvedUri = resolveUrl(master.uri, properties.uri);
- }
- });
- };
- /**
- * Creates a master playlist wrapper to insert a sole media playlist into.
- *
- * @param {Object} media
- * Media playlist
- * @param {string} uri
- * The media URI
- *
- * @return {Object}
- * Master playlist
- */
-
- var masterForMedia = function masterForMedia(media, uri) {
- var id = createPlaylistID(0, uri);
- var master = {
- mediaGroups: {
- 'AUDIO': {},
- 'VIDEO': {},
- 'CLOSED-CAPTIONS': {},
- 'SUBTITLES': {}
- },
- uri: window__default['default'].location.href,
- resolvedUri: window__default['default'].location.href,
- playlists: [{
- uri: uri,
- id: id,
- resolvedUri: uri,
- // m3u8-parser does not attach an attributes property to media playlists so make
- // sure that the property is attached to avoid undefined reference errors
- attributes: {}
- }]
- }; // set up ID reference
-
- master.playlists[id] = master.playlists[0]; // URI reference added for backwards compatibility
-
- master.playlists[uri] = master.playlists[0];
- return master;
- };
- /**
- * Does an in-place update of the master manifest to add updated playlist URI references
- * as well as other properties needed by VHS that aren't included by the parser.
- *
- * @param {Object} master
- * Master manifest object
- * @param {string} uri
- * The source URI
- */
-
- var addPropertiesToMaster = function addPropertiesToMaster(master, uri) {
- master.uri = uri;
-
- for (var i = 0; i < master.playlists.length; i++) {
- if (!master.playlists[i].uri) {
- // Set up phony URIs for the playlists since playlists are referenced by their URIs
- // throughout VHS, but some formats (e.g., DASH) don't have external URIs
- // TODO: consider adding dummy URIs in mpd-parser
- var phonyUri = "placeholder-uri-" + i;
- master.playlists[i].uri = phonyUri;
- }
- }
-
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- var groupId = "placeholder-uri-" + mediaType + "-" + groupKey + "-" + labelKey;
-
- if (!properties.playlists || !properties.playlists.length) {
- properties.playlists = [_extends_1({}, properties)];
- }
-
- properties.playlists.forEach(function (p, i) {
- var id = createPlaylistID(i, groupId);
-
- if (p.uri) {
- p.resolvedUri = p.resolvedUri || resolveUrl(master.uri, p.uri);
- } else {
- // DEPRECATED, this has been added to prevent a breaking change.
- // previously we only ever had a single media group playlist, so
- // we mark the first playlist uri without prepending the index as we used to
- // ideally we would do all of the playlists the same way.
- p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
- // the placeholder again
-
- p.resolvedUri = p.uri;
- }
-
- p.id = p.id || id; // add an empty attributes object, all playlists are
- // expected to have this.
-
- p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
-
- master.playlists[p.id] = p;
- master.playlists[p.uri] = p;
- });
- });
- setupMediaPlaylists(master);
- resolveMediaGroupUris(master);
- };
-
- var mergeOptions$2 = videojs__default['default'].mergeOptions,
- EventTarget$1 = videojs__default['default'].EventTarget;
-
- var addLLHLSQueryDirectives = function addLLHLSQueryDirectives(uri, media) {
- if (media.endList) {
- return uri;
- }
-
- var query = [];
-
- if (media.serverControl && media.serverControl.canBlockReload) {
- var preloadSegment = media.preloadSegment; // next msn is a zero based value, length is not.
-
- var nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
- // that we are going to request a part of that preload segment.
- // the logic below is used to determine that.
-
- if (preloadSegment) {
- var parts = preloadSegment.parts || []; // _HLS_part is a zero based index
-
- var nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
- // length of parts, then we know we had part preload hints
- // and we need to add the _HLS_part= query
-
- if (nextPart > -1 && nextPart !== parts.length - 1) {
- // add existing parts to our preload hints
- query.push("_HLS_part=" + nextPart);
- } // this if statement makes sure that we request the msn
- // of the preload segment if:
- // 1. the preload segment had parts (and was not yet a full segment)
- // but was added to our segments array
- // 2. the preload segment had preload hints for parts that are not in
- // the manifest yet.
- // in all other cases we want the segment after the preload segment
- // which will be given by using media.segments.length because it is 1 based
- // rather than 0 based.
-
-
- if (nextPart > -1 || parts.length) {
- nextMSN--;
- }
- } // add _HLS_msn= in front of any _HLS_part query
-
-
- query.unshift("_HLS_msn=" + nextMSN);
- }
-
- if (media.serverControl && media.serverControl.canSkipUntil) {
- // add _HLS_skip= infront of all other queries.
- query.unshift('_HLS_skip=' + (media.serverControl.canSkipDateranges ? 'v2' : 'YES'));
- }
-
- query.forEach(function (str, i) {
- var symbol = i === 0 ? '?' : '&';
- uri += "" + symbol + str;
- });
- return uri;
- };
- /**
- * Returns a new segment object with properties and
- * the parts array merged.
- *
- * @param {Object} a the old segment
- * @param {Object} b the new segment
- *
- * @return {Object} the merged segment
- */
-
-
- var updateSegment = function updateSegment(a, b) {
- if (!a) {
- return b;
- }
-
- var result = mergeOptions$2(a, b); // if only the old segment has preload hints
- // and the new one does not, remove preload hints.
-
- if (a.preloadHints && !b.preloadHints) {
- delete result.preloadHints;
- } // if only the old segment has parts
- // then the parts are no longer valid
-
-
- if (a.parts && !b.parts) {
- delete result.parts; // if both segments have parts
- // copy part propeties from the old segment
- // to the new one.
- } else if (a.parts && b.parts) {
- for (var i = 0; i < b.parts.length; i++) {
- if (a.parts && a.parts[i]) {
- result.parts[i] = mergeOptions$2(a.parts[i], b.parts[i]);
- }
- }
- } // set skipped to false for segments that have
- // have had information merged from the old segment.
-
-
- if (!a.skipped && b.skipped) {
- result.skipped = false;
- } // set preload to false for segments that have
- // had information added in the new segment.
-
-
- if (a.preload && !b.preload) {
- result.preload = false;
- }
-
- return result;
- };
- /**
- * Returns a new array of segments that is the result of merging
- * properties from an older list of segments onto an updated
- * list. No properties on the updated playlist will be ovewritten.
- *
- * @param {Array} original the outdated list of segments
- * @param {Array} update the updated list of segments
- * @param {number=} offset the index of the first update
- * segment in the original segment list. For non-live playlists,
- * this should always be zero and does not need to be
- * specified. For live playlists, it should be the difference
- * between the media sequence numbers in the original and updated
- * playlists.
- * @return {Array} a list of merged segment objects
- */
-
- var updateSegments = function updateSegments(original, update, offset) {
- var oldSegments = original.slice();
- var newSegments = update.slice();
- offset = offset || 0;
- var result = [];
- var currentMap;
-
- for (var newIndex = 0; newIndex < newSegments.length; newIndex++) {
- var oldSegment = oldSegments[newIndex + offset];
- var newSegment = newSegments[newIndex];
-
- if (oldSegment) {
- currentMap = oldSegment.map || currentMap;
- result.push(updateSegment(oldSegment, newSegment));
- } else {
- // carry over map to new segment if it is missing
- if (currentMap && !newSegment.map) {
- newSegment.map = currentMap;
- }
-
- result.push(newSegment);
- }
- }
-
- return result;
- };
- var resolveSegmentUris = function resolveSegmentUris(segment, baseUri) {
- // preloadSegment will not have a uri at all
- // as the segment isn't actually in the manifest yet, only parts
- if (!segment.resolvedUri && segment.uri) {
- segment.resolvedUri = resolveUrl(baseUri, segment.uri);
- }
-
- if (segment.key && !segment.key.resolvedUri) {
- segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
- }
-
- if (segment.map && !segment.map.resolvedUri) {
- segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
- }
-
- if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
- segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
- }
-
- if (segment.parts && segment.parts.length) {
- segment.parts.forEach(function (p) {
- if (p.resolvedUri) {
- return;
- }
-
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
-
- if (segment.preloadHints && segment.preloadHints.length) {
- segment.preloadHints.forEach(function (p) {
- if (p.resolvedUri) {
- return;
- }
-
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
- };
-
- var getAllSegments = function getAllSegments(media) {
- var segments = media.segments || [];
- var preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
- // a usable segment, only include a preloadSegment that has
- // parts.
-
- if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
- // if preloadHints has a MAP that means that the
- // init segment is going to change. We cannot use any of the parts
- // from this preload segment.
- if (preloadSegment.preloadHints) {
- for (var i = 0; i < preloadSegment.preloadHints.length; i++) {
- if (preloadSegment.preloadHints[i].type === 'MAP') {
- return segments;
- }
- }
- } // set the duration for our preload segment to target duration.
-
-
- preloadSegment.duration = media.targetDuration;
- preloadSegment.preload = true;
- segments.push(preloadSegment);
- }
-
- return segments;
- }; // consider the playlist unchanged if the playlist object is the same or
- // the number of segments is equal, the media sequence number is unchanged,
- // and this playlist hasn't become the end of the playlist
-
-
- var isPlaylistUnchanged = function isPlaylistUnchanged(a, b) {
- return a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence;
- };
- /**
- * Returns a new master playlist that is the result of merging an
- * updated media playlist into the original version. If the
- * updated media playlist does not match any of the playlist
- * entries in the original master playlist, null is returned.
- *
- * @param {Object} master a parsed master M3U8 object
- * @param {Object} media a parsed media M3U8 object
- * @return {Object} a new object that represents the original
- * master playlist with the updated media playlist merged in, or
- * null if the merge produced no change.
- */
-
- var updateMaster$1 = function updateMaster(master, newMedia, unchangedCheck) {
- if (unchangedCheck === void 0) {
- unchangedCheck = isPlaylistUnchanged;
- }
-
- var result = mergeOptions$2(master, {});
- var oldMedia = result.playlists[newMedia.id];
-
- if (!oldMedia) {
- return null;
- }
-
- if (unchangedCheck(oldMedia, newMedia)) {
- return null;
- }
-
- newMedia.segments = getAllSegments(newMedia);
- var mergedPlaylist = mergeOptions$2(oldMedia, newMedia); // always use the new media's preload segment
-
- if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
- delete mergedPlaylist.preloadSegment;
- } // if the update could overlap existing segment information, merge the two segment lists
-
-
- if (oldMedia.segments) {
- if (newMedia.skip) {
- newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
- // old properties into the new segments
-
- for (var i = 0; i < newMedia.skip.skippedSegments; i++) {
- newMedia.segments.unshift({
- skipped: true
- });
- }
- }
-
- mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
- } // resolve any segment URIs to prevent us from having to do it later
-
-
- mergedPlaylist.segments.forEach(function (segment) {
- resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
- }); // TODO Right now in the playlists array there are two references to each playlist, one
- // that is referenced by index, and one by URI. The index reference may no longer be
- // necessary.
-
- for (var _i = 0; _i < result.playlists.length; _i++) {
- if (result.playlists[_i].id === newMedia.id) {
- result.playlists[_i] = mergedPlaylist;
- }
- }
-
- result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
-
- result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
-
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- if (!properties.playlists) {
- return;
- }
-
- for (var _i2 = 0; _i2 < properties.playlists.length; _i2++) {
- if (newMedia.id === properties.playlists[_i2].id) {
- properties.playlists[_i2] = newMedia;
- }
- }
- });
- return result;
- };
- /**
- * Calculates the time to wait before refreshing a live playlist
- *
- * @param {Object} media
- * The current media
- * @param {boolean} update
- * True if there were any updates from the last refresh, false otherwise
- * @return {number}
- * The time in ms to wait before refreshing the live playlist
- */
-
- var refreshDelay = function refreshDelay(media, update) {
- var lastSegment = media.segments[media.segments.length - 1];
- var lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
- var lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
-
- if (update && lastDuration) {
- return lastDuration * 1000;
- } // if the playlist is unchanged since the last reload or last segment duration
- // cannot be determined, try again after half the target duration
-
-
- return (media.partTargetDuration || media.targetDuration || 10) * 500;
- };
- /**
- * Load a playlist from a remote location
- *
- * @class PlaylistLoader
- * @extends Stream
- * @param {string|Object} src url or object of manifest
- * @param {boolean} withCredentials the withCredentials xhr option
- * @class
- */
-
- var PlaylistLoader = /*#__PURE__*/function (_EventTarget) {
- inheritsLoose(PlaylistLoader, _EventTarget);
-
- function PlaylistLoader(src, vhs, options) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _EventTarget.call(this) || this;
-
- if (!src) {
- throw new Error('A non-empty playlist URL or object is required');
- }
-
- _this.logger_ = logger('PlaylistLoader');
- var _options = options,
- _options$withCredenti = _options.withCredentials,
- withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
- _options$handleManife = _options.handleManifestRedirects,
- handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
- _this.src = src;
- _this.vhs_ = vhs;
- _this.withCredentials = withCredentials;
- _this.handleManifestRedirects = handleManifestRedirects;
- var vhsOptions = vhs.options_;
- _this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
- _this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
- _this.experimentalLLHLS = vhsOptions && vhsOptions.experimentalLLHLS || false; // initialize the loader state
-
- _this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
-
- _this.handleMediaupdatetimeout_ = _this.handleMediaupdatetimeout_.bind(assertThisInitialized(_this));
-
- _this.on('mediaupdatetimeout', _this.handleMediaupdatetimeout_);
-
- return _this;
- }
-
- var _proto = PlaylistLoader.prototype;
-
- _proto.handleMediaupdatetimeout_ = function handleMediaupdatetimeout_() {
- var _this2 = this;
-
- if (this.state !== 'HAVE_METADATA') {
- // only refresh the media playlist if no other activity is going on
- return;
- }
-
- var media = this.media();
- var uri = resolveUrl(this.master.uri, media.uri);
-
- if (this.experimentalLLHLS) {
- uri = addLLHLSQueryDirectives(uri, media);
- }
-
- this.state = 'HAVE_CURRENT_METADATA';
- this.request = this.vhs_.xhr({
- uri: uri,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this2.request) {
- return;
- }
-
- if (error) {
- return _this2.playlistRequestError(_this2.request, _this2.media(), 'HAVE_METADATA');
- }
-
- _this2.haveMetadata({
- playlistString: _this2.request.responseText,
- url: _this2.media().uri,
- id: _this2.media().id
- });
- });
- };
-
- _proto.playlistRequestError = function playlistRequestError(xhr, playlist, startingState) {
- var uri = playlist.uri,
- id = playlist.id; // any in-flight request is now finished
-
- this.request = null;
-
- if (startingState) {
- this.state = startingState;
- }
-
- this.error = {
- playlist: this.master.playlists[id],
- status: xhr.status,
- message: "HLS playlist request error at URL: " + uri + ".",
- responseText: xhr.responseText,
- code: xhr.status >= 500 ? 4 : 2
- };
- this.trigger('error');
- };
-
- _proto.parseManifest_ = function parseManifest_(_ref) {
- var _this3 = this;
-
- var url = _ref.url,
- manifestString = _ref.manifestString;
- return parseManifest({
- onwarn: function onwarn(_ref2) {
- var message = _ref2.message;
- return _this3.logger_("m3u8-parser warn for " + url + ": " + message);
- },
- oninfo: function oninfo(_ref3) {
- var message = _ref3.message;
- return _this3.logger_("m3u8-parser info for " + url + ": " + message);
- },
- manifestString: manifestString,
- customTagParsers: this.customTagParsers,
- customTagMappers: this.customTagMappers,
- experimentalLLHLS: this.experimentalLLHLS
- });
- }
- /**
- * Update the playlist loader's state in response to a new or updated playlist.
- *
- * @param {string} [playlistString]
- * Playlist string (if playlistObject is not provided)
- * @param {Object} [playlistObject]
- * Playlist object (if playlistString is not provided)
- * @param {string} url
- * URL of playlist
- * @param {string} id
- * ID to use for playlist
- */
- ;
-
- _proto.haveMetadata = function haveMetadata(_ref4) {
- var _this4 = this;
-
- var playlistString = _ref4.playlistString,
- playlistObject = _ref4.playlistObject,
- url = _ref4.url,
- id = _ref4.id;
- // any in-flight request is now finished
- this.request = null;
- this.state = 'HAVE_METADATA';
- var playlist = playlistObject || this.parseManifest_({
- url: url,
- manifestString: playlistString
- });
- playlist.lastRequest = Date.now();
- setupMediaPlaylist({
- playlist: playlist,
- uri: url,
- id: id
- }); // merge this playlist into the master
-
- var update = updateMaster$1(this.master, playlist);
- this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
-
- if (update) {
- this.master = update;
- this.media_ = this.master.playlists[id];
- } else {
- this.trigger('playlistunchanged');
- } // refresh live playlists after a target duration passes
-
-
- if (!this.media().endList) {
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- _this4.trigger('mediaupdatetimeout');
- }, refreshDelay(this.media(), !!update));
- }
-
- this.trigger('loadedplaylist');
- }
- /**
- * Abort any outstanding work and clean up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.stopRequest();
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- window__default['default'].clearTimeout(this.finalRenditionTimeout);
- this.off();
- };
-
- _proto.stopRequest = function stopRequest() {
- if (this.request) {
- var oldRequest = this.request;
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- }
- /**
- * When called without any arguments, returns the currently
- * active media playlist. When called with a single argument,
- * triggers the playlist loader to asynchronously switch to the
- * specified media playlist. Calling this method while the
- * loader is in the HAVE_NOTHING causes an error to be emitted
- * but otherwise has no effect.
- *
- * @param {Object=} playlist the parsed media playlist
- * object to switch to
- * @param {boolean=} shouldDelay whether we should delay the request by half target duration
- *
- * @return {Playlist} the current loaded media
- */
- ;
-
- _proto.media = function media(playlist, shouldDelay) {
- var _this5 = this;
-
- // getter
- if (!playlist) {
- return this.media_;
- } // setter
-
-
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- } // find the playlist object if the target playlist has been
- // specified by URI
-
-
- if (typeof playlist === 'string') {
- if (!this.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
-
- playlist = this.master.playlists[playlist];
- }
-
- window__default['default'].clearTimeout(this.finalRenditionTimeout);
-
- if (shouldDelay) {
- var delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
- this.finalRenditionTimeout = window__default['default'].setTimeout(this.media.bind(this, playlist, false), delay);
- return;
- }
-
- var startingState = this.state;
- var mediaChange = !this.media_ || playlist.id !== this.media_.id;
- var masterPlaylistRef = this.master.playlists[playlist.id]; // switch to fully loaded playlists immediately
-
- if (masterPlaylistRef && masterPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
- // media playlist or, for the case of demuxed audio, a resolved audio media group)
- playlist.endList && playlist.segments.length) {
- // abort outstanding playlist requests
- if (this.request) {
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- }
-
- this.state = 'HAVE_METADATA';
- this.media_ = playlist; // trigger media change if the active media has been updated
-
- if (mediaChange) {
- this.trigger('mediachanging');
-
- if (startingState === 'HAVE_MASTER') {
- // The initial playlist was a master manifest, and the first media selected was
- // also provided (in the form of a resolved playlist object) as part of the
- // source object (rather than just a URL). Therefore, since the media playlist
- // doesn't need to be requested, loadedmetadata won't trigger as part of the
- // normal flow, and needs an explicit trigger here.
- this.trigger('loadedmetadata');
- } else {
- this.trigger('mediachange');
- }
- }
-
- return;
- } // switching to the active playlist is a no-op
-
-
- if (!mediaChange) {
- return;
- }
-
- this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
-
- if (this.request) {
- if (playlist.resolvedUri === this.request.url) {
- // requesting to switch to the same playlist multiple times
- // has no effect after the first
- return;
- }
-
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- } // request the new playlist
-
-
- if (this.media_) {
- this.trigger('mediachanging');
- }
-
- this.request = this.vhs_.xhr({
- uri: playlist.resolvedUri,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this5.request) {
- return;
- }
-
- playlist.lastRequest = Date.now();
- playlist.resolvedUri = resolveManifestRedirect(_this5.handleManifestRedirects, playlist.resolvedUri, req);
-
- if (error) {
- return _this5.playlistRequestError(_this5.request, playlist, startingState);
- }
-
- _this5.haveMetadata({
- playlistString: req.responseText,
- url: playlist.uri,
- id: playlist.id
- }); // fire loadedmetadata the first time a media playlist is loaded
-
-
- if (startingState === 'HAVE_MASTER') {
- _this5.trigger('loadedmetadata');
- } else {
- _this5.trigger('mediachange');
- }
- });
- }
- /**
- * pause loading of the playlist
- */
- ;
-
- _proto.pause = function pause() {
- this.stopRequest();
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
-
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- } // Need to restore state now that no activity is happening
-
-
- if (this.state === 'SWITCHING_MEDIA') {
- // if the loader was in the process of switching media, it should either return to
- // HAVE_MASTER or HAVE_METADATA depending on if the loader has loaded a media
- // playlist yet. This is determined by the existence of loader.media_
- if (this.media_) {
- this.state = 'HAVE_METADATA';
- } else {
- this.state = 'HAVE_MASTER';
- }
- } else if (this.state === 'HAVE_CURRENT_METADATA') {
- this.state = 'HAVE_METADATA';
- }
- }
- /**
- * start loading of the playlist
- */
- ;
-
- _proto.load = function load(shouldDelay) {
- var _this6 = this;
-
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- var media = this.media();
-
- if (shouldDelay) {
- var delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
- this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- return _this6.load();
- }, delay);
- return;
- }
-
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- }
- /**
- * start loading of the playlist
- */
- ;
-
- _proto.start = function start() {
- var _this7 = this;
-
- this.started = true;
-
- if (typeof this.src === 'object') {
- // in the case of an entirely constructed manifest object (meaning there's no actual
- // manifest on a server), default the uri to the page's href
- if (!this.src.uri) {
- this.src.uri = window__default['default'].location.href;
- } // resolvedUri is added on internally after the initial request. Since there's no
- // request for pre-resolved manifests, add on resolvedUri here.
-
-
- this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
- // request can be skipped (since the top level of the manifest, at a minimum, is
- // already available as a parsed manifest object). However, if the manifest object
- // represents a master playlist, some media playlists may need to be resolved before
- // the starting segment list is available. Therefore, go directly to setup of the
- // initial playlist, and let the normal flow continue from there.
- //
- // Note that the call to setup is asynchronous, as other sections of VHS may assume
- // that the first request is asynchronous.
-
- setTimeout(function () {
- _this7.setupInitialPlaylist(_this7.src);
- }, 0);
- return;
- } // request the specified URL
-
-
- this.request = this.vhs_.xhr({
- uri: this.src,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this7.request) {
- return;
- } // clear the loader's request reference
-
-
- _this7.request = null;
-
- if (error) {
- _this7.error = {
- status: req.status,
- message: "HLS playlist request error at URL: " + _this7.src + ".",
- responseText: req.responseText,
- // MEDIA_ERR_NETWORK
- code: 2
- };
-
- if (_this7.state === 'HAVE_NOTHING') {
- _this7.started = false;
- }
-
- return _this7.trigger('error');
- }
-
- _this7.src = resolveManifestRedirect(_this7.handleManifestRedirects, _this7.src, req);
-
- var manifest = _this7.parseManifest_({
- manifestString: req.responseText,
- url: _this7.src
- });
-
- _this7.setupInitialPlaylist(manifest);
- });
- };
-
- _proto.srcUri = function srcUri() {
- return typeof this.src === 'string' ? this.src : this.src.uri;
- }
- /**
- * Given a manifest object that's either a master or media playlist, trigger the proper
- * events and set the state of the playlist loader.
- *
- * If the manifest object represents a master playlist, `loadedplaylist` will be
- * triggered to allow listeners to select a playlist. If none is selected, the loader
- * will default to the first one in the playlists array.
- *
- * If the manifest object represents a media playlist, `loadedplaylist` will be
- * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
- *
- * In the case of a media playlist, a master playlist object wrapper with one playlist
- * will be created so that all logic can handle playlists in the same fashion (as an
- * assumed manifest object schema).
- *
- * @param {Object} manifest
- * The parsed manifest object
- */
- ;
-
- _proto.setupInitialPlaylist = function setupInitialPlaylist(manifest) {
- this.state = 'HAVE_MASTER';
-
- if (manifest.playlists) {
- this.master = manifest;
- addPropertiesToMaster(this.master, this.srcUri()); // If the initial master playlist has playlists wtih segments already resolved,
- // then resolve URIs in advance, as they are usually done after a playlist request,
- // which may not happen if the playlist is resolved.
-
- manifest.playlists.forEach(function (playlist) {
- playlist.segments = getAllSegments(playlist);
- playlist.segments.forEach(function (segment) {
- resolveSegmentUris(segment, playlist.resolvedUri);
- });
- });
- this.trigger('loadedplaylist');
-
- if (!this.request) {
- // no media playlist was specifically selected so start
- // from the first listed one
- this.media(this.master.playlists[0]);
- }
-
- return;
- } // In order to support media playlists passed in as vhs-json, the case where the uri
- // is not provided as part of the manifest should be considered, and an appropriate
- // default used.
-
-
- var uri = this.srcUri() || window__default['default'].location.href;
- this.master = masterForMedia(manifest, uri);
- this.haveMetadata({
- playlistObject: manifest,
- url: uri,
- id: this.master.playlists[0].id
- });
- this.trigger('loadedmetadata');
- };
-
- return PlaylistLoader;
- }(EventTarget$1);
-
- /**
- * @file xhr.js
- */
- var videojsXHR = videojs__default['default'].xhr,
- mergeOptions$1 = videojs__default['default'].mergeOptions;
-
- var callbackWrapper = function callbackWrapper(request, error, response, callback) {
- var reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
-
- if (!error && reqResponse) {
- request.responseTime = Date.now();
- request.roundTripTime = request.responseTime - request.requestTime;
- request.bytesReceived = reqResponse.byteLength || reqResponse.length;
-
- if (!request.bandwidth) {
- request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
- }
- }
-
- if (response.headers) {
- request.responseHeaders = response.headers;
- } // videojs.xhr now uses a specific code on the error
- // object to signal that a request has timed out instead
- // of setting a boolean on the request object
-
-
- if (error && error.code === 'ETIMEDOUT') {
- request.timedout = true;
- } // videojs.xhr no longer considers status codes outside of 200 and 0
- // (for file uris) to be errors, but the old XHR did, so emulate that
- // behavior. Status 206 may be used in response to byterange requests.
-
-
- if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
- error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
- }
-
- callback(error, request);
- };
-
- var xhrFactory = function xhrFactory() {
- var xhr = function XhrFunction(options, callback) {
- // Add a default timeout
- options = mergeOptions$1({
- timeout: 45e3
- }, options); // Allow an optional user-specified function to modify the option
- // object before we construct the xhr request
-
- var beforeRequest = XhrFunction.beforeRequest || videojs__default['default'].Vhs.xhr.beforeRequest;
-
- if (beforeRequest && typeof beforeRequest === 'function') {
- var newOptions = beforeRequest(options);
-
- if (newOptions) {
- options = newOptions;
- }
- } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
- // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
-
-
- var xhrMethod = videojs__default['default'].Vhs.xhr.original === true ? videojsXHR : videojs__default['default'].Vhs.xhr;
- var request = xhrMethod(options, function (error, response) {
- return callbackWrapper(request, error, response, callback);
- });
- var originalAbort = request.abort;
-
- request.abort = function () {
- request.aborted = true;
- return originalAbort.apply(request, arguments);
- };
-
- request.uri = options.uri;
- request.requestTime = Date.now();
- return request;
- };
-
- xhr.original = true;
- return xhr;
- };
- /**
- * Turns segment byterange into a string suitable for use in
- * HTTP Range requests
- *
- * @param {Object} byterange - an object with two values defining the start and end
- * of a byte-range
- */
-
-
- var byterangeStr = function byterangeStr(byterange) {
- // `byterangeEnd` is one less than `offset + length` because the HTTP range
- // header uses inclusive ranges
- var byterangeEnd = byterange.offset + byterange.length - 1;
- var byterangeStart = byterange.offset;
- return 'bytes=' + byterangeStart + '-' + byterangeEnd;
- };
- /**
- * Defines headers for use in the xhr request for a particular segment.
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- */
-
-
- var segmentXhrHeaders = function segmentXhrHeaders(segment) {
- var headers = {};
-
- if (segment.byterange) {
- headers.Range = byterangeStr(segment.byterange);
- }
-
- return headers;
- };
-
- var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
- var DASH_REGEX = /^application\/dash\+xml/i;
- /**
- * Returns a string that describes the type of source based on a video source object's
- * media type.
- *
- * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
- *
- * @param {string} type
- * Video source object media type
- * @return {('hls'|'dash'|'vhs-json'|null)}
- * VHS source type string
- */
-
- var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
- if (MPEGURL_REGEX.test(type)) {
- return 'hls';
- }
-
- if (DASH_REGEX.test(type)) {
- return 'dash';
- } // Denotes the special case of a manifest object passed to http-streaming instead of a
- // source URL.
- //
- // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
- //
- // In this case, vnd stands for vendor, video.js for the organization, VHS for this
- // project, and the +json suffix identifies the structure of the media type.
-
-
- if (type === 'application/vnd.videojs.vhs+json') {
- return 'vhs-json';
- }
-
- return null;
- };
-
- /**
- * @file bin-utils.js
- */
-
- /**
- * convert a TimeRange to text
- *
- * @param {TimeRange} range the timerange to use for conversion
- * @param {number} i the iterator on the range to convert
- * @return {string} the range in string format
- */
- var textRange = function textRange(range, i) {
- return range.start(i) + '-' + range.end(i);
- };
- /**
- * format a number as hex string
- *
- * @param {number} e The number
- * @param {number} i the iterator
- * @return {string} the hex formatted number as a string
- */
-
-
- var formatHexString = function formatHexString(e, i) {
- var value = e.toString(16);
- return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
- };
-
- var formatAsciiString = function formatAsciiString(e) {
- if (e >= 0x20 && e < 0x7e) {
- return String.fromCharCode(e);
- }
-
- return '.';
- };
- /**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-
-
- var createTransferableMessage = function createTransferableMessage(message) {
- var transferable = {};
- Object.keys(message).forEach(function (key) {
- var value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
- return transferable;
- };
- /**
- * Returns a unique string identifier for a media initialization
- * segment.
- *
- * @param {Object} initSegment
- * the init segment object.
- *
- * @return {string} the generated init segment id
- */
-
- var initSegmentId = function initSegmentId(initSegment) {
- var byterange = initSegment.byterange || {
- length: Infinity,
- offset: 0
- };
- return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
- };
- /**
- * Returns a unique string identifier for a media segment key.
- *
- * @param {Object} key the encryption key
- * @return {string} the unique id for the media segment key.
- */
-
- var segmentKeyId = function segmentKeyId(key) {
- return key.resolvedUri;
- };
- /**
- * utils to help dump binary data to the console
- *
- * @param {Array|TypedArray} data
- * data to dump to a string
- *
- * @return {string} the data as a hex string.
- */
-
- var hexDump = function hexDump(data) {
- var bytes = Array.prototype.slice.call(data);
- var step = 16;
- var result = '';
- var hex;
- var ascii;
-
- for (var j = 0; j < bytes.length / step; j++) {
- hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
- ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
- result += hex + ' ' + ascii + '\n';
- }
-
- return result;
- };
- var tagDump = function tagDump(_ref) {
- var bytes = _ref.bytes;
- return hexDump(bytes);
- };
- var textRanges = function textRanges(ranges) {
- var result = '';
- var i;
-
- for (i = 0; i < ranges.length; i++) {
- result += textRange(ranges, i) + ' ';
- }
-
- return result;
- };
-
- var utils = /*#__PURE__*/Object.freeze({
- __proto__: null,
- createTransferableMessage: createTransferableMessage,
- initSegmentId: initSegmentId,
- segmentKeyId: segmentKeyId,
- hexDump: hexDump,
- tagDump: tagDump,
- textRanges: textRanges
- });
-
- // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
- // 25% was arbitrarily chosen, and may need to be refined over time.
-
- var SEGMENT_END_FUDGE_PERCENT = 0.25;
- /**
- * Converts a player time (any time that can be gotten/set from player.currentTime(),
- * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
- * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
- *
- * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
- * point" (a point where we have a mapping from program time to player time, with player
- * time being the post transmux start of the segment).
- *
- * For more details, see [this doc](../../docs/program-time-from-player-time.md).
- *
- * @param {number} playerTime the player time
- * @param {Object} segment the segment which contains the player time
- * @return {Date} program time
- */
-
- var playerTimeToProgramTime = function playerTimeToProgramTime(playerTime, segment) {
- if (!segment.dateTimeObject) {
- // Can't convert without an "anchor point" for the program time (i.e., a time that can
- // be used to map the start of a segment with a real world time).
- return null;
- }
-
- var transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
- var transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
-
- var startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
- var offsetFromSegmentStart = playerTime - startOfSegment;
- return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
- };
- var originalSegmentVideoDuration = function originalSegmentVideoDuration(videoTimingInfo) {
- return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
- };
- /**
- * Finds a segment that contains the time requested given as an ISO-8601 string. The
- * returned segment might be an estimate or an accurate match.
- *
- * @param {string} programTime The ISO-8601 programTime to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-
- var findSegmentForProgramTime = function findSegmentForProgramTime(programTime, playlist) {
- // Assumptions:
- // - verifyProgramDateTimeTags has already been run
- // - live streams have been started
- var dateTimeObject;
-
- try {
- dateTimeObject = new Date(programTime);
- } catch (e) {
- return null;
- }
-
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- var segment = playlist.segments[0];
-
- if (dateTimeObject < segment.dateTimeObject) {
- // Requested time is before stream start.
- return null;
- }
-
- for (var i = 0; i < playlist.segments.length - 1; i++) {
- segment = playlist.segments[i];
- var nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
-
- if (dateTimeObject < nextSegmentStart) {
- break;
- }
- }
-
- var lastSegment = playlist.segments[playlist.segments.length - 1];
- var lastSegmentStart = lastSegment.dateTimeObject;
- var lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
- var lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
-
- if (dateTimeObject > lastSegmentEnd) {
- // Beyond the end of the stream, or our best guess of the end of the stream.
- return null;
- }
-
- if (dateTimeObject > lastSegmentStart) {
- segment = lastSegment;
- }
-
- return {
- segment: segment,
- estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
- // Although, given that all segments have accurate date time objects, the segment
- // selected should be accurate, unless the video has been transmuxed at some point
- // (determined by the presence of the videoTimingInfo object), the segment's "player
- // time" (the start time in the player) can't be considered accurate.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
- };
- /**
- * Finds a segment that contains the given player time(in seconds).
- *
- * @param {number} time The player time to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-
- var findSegmentForPlayerTime = function findSegmentForPlayerTime(time, playlist) {
- // Assumptions:
- // - there will always be a segment.duration
- // - we can start from zero
- // - segments are in time order
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- var segmentEnd = 0;
- var segment;
-
- for (var i = 0; i < playlist.segments.length; i++) {
- segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
- // should contain the most accurate values we have for the segment's player times.
- //
- // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
- // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
- // calculate an end value.
-
- segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
-
- if (time <= segmentEnd) {
- break;
- }
- }
-
- var lastSegment = playlist.segments[playlist.segments.length - 1];
-
- if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
- // The time requested is beyond the stream end.
- return null;
- }
-
- if (time > segmentEnd) {
- // The time is within or beyond the last segment.
- //
- // Check to see if the time is beyond a reasonable guess of the end of the stream.
- if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
- // Technically, because the duration value is only an estimate, the time may still
- // exist in the last segment, however, there isn't enough information to make even
- // a reasonable estimate.
- return null;
- }
-
- segment = lastSegment;
- }
-
- return {
- segment: segment,
- estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
- // Because videoTimingInfo is only set after transmux, it is the only way to get
- // accurate timing values.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
- };
- /**
- * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
- * If the offset returned is positive, the programTime occurs after the
- * comparisonTimestamp.
- * If the offset is negative, the programTime occurs before the comparisonTimestamp.
- *
- * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
- * @param {string} programTime The programTime as an ISO-8601 string
- * @return {number} offset
- */
-
- var getOffsetFromTimestamp = function getOffsetFromTimestamp(comparisonTimeStamp, programTime) {
- var segmentDateTime;
- var programDateTime;
-
- try {
- segmentDateTime = new Date(comparisonTimeStamp);
- programDateTime = new Date(programTime);
- } catch (e) {// TODO handle error
- }
-
- var segmentTimeEpoch = segmentDateTime.getTime();
- var programTimeEpoch = programDateTime.getTime();
- return (programTimeEpoch - segmentTimeEpoch) / 1000;
- };
- /**
- * Checks that all segments in this playlist have programDateTime tags.
- *
- * @param {Object} playlist A playlist object
- */
-
- var verifyProgramDateTimeTags = function verifyProgramDateTimeTags(playlist) {
- if (!playlist.segments || playlist.segments.length === 0) {
- return false;
- }
-
- for (var i = 0; i < playlist.segments.length; i++) {
- var segment = playlist.segments[i];
-
- if (!segment.dateTimeObject) {
- return false;
- }
- }
-
- return true;
- };
- /**
- * Returns the programTime of the media given a playlist and a playerTime.
- * The playlist must have programDateTime tags for a programDateTime tag to be returned.
- * If the segments containing the time requested have not been buffered yet, an estimate
- * may be returned to the callback.
- *
- * @param {Object} args
- * @param {Object} args.playlist A playlist object to search within
- * @param {number} time A playerTime in seconds
- * @param {Function} callback(err, programTime)
- * @return {string} err.message A detailed error message
- * @return {Object} programTime
- * @return {number} programTime.mediaSeconds The streamTime in seconds
- * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
- */
-
- var getProgramTime = function getProgramTime(_ref) {
- var playlist = _ref.playlist,
- _ref$time = _ref.time,
- time = _ref$time === void 0 ? undefined : _ref$time,
- callback = _ref.callback;
-
- if (!callback) {
- throw new Error('getProgramTime: callback must be provided');
- }
-
- if (!playlist || time === undefined) {
- return callback({
- message: 'getProgramTime: playlist and time must be provided'
- });
- }
-
- var matchedSegment = findSegmentForPlayerTime(time, playlist);
-
- if (!matchedSegment) {
- return callback({
- message: 'valid programTime was not found'
- });
- }
-
- if (matchedSegment.type === 'estimate') {
- return callback({
- message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
- seekTime: matchedSegment.estimatedStart
- });
- }
-
- var programTimeObject = {
- mediaSeconds: time
- };
- var programTime = playerTimeToProgramTime(time, matchedSegment.segment);
-
- if (programTime) {
- programTimeObject.programDateTime = programTime.toISOString();
- }
-
- return callback(null, programTimeObject);
- };
- /**
- * Seeks in the player to a time that matches the given programTime ISO-8601 string.
- *
- * @param {Object} args
- * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
- * @param {Object} args.playlist A playlist to look within
- * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
- * @param {Function} args.seekTo A method to perform a seek
- * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
- * @param {Object} args.tech The tech to seek on
- * @param {Function} args.callback(err, newTime) A callback to return the new time to
- * @return {string} err.message A detailed error message
- * @return {number} newTime The exact time that was seeked to in seconds
- */
-
- var seekToProgramTime = function seekToProgramTime(_ref2) {
- var programTime = _ref2.programTime,
- playlist = _ref2.playlist,
- _ref2$retryCount = _ref2.retryCount,
- retryCount = _ref2$retryCount === void 0 ? 2 : _ref2$retryCount,
- seekTo = _ref2.seekTo,
- _ref2$pauseAfterSeek = _ref2.pauseAfterSeek,
- pauseAfterSeek = _ref2$pauseAfterSeek === void 0 ? true : _ref2$pauseAfterSeek,
- tech = _ref2.tech,
- callback = _ref2.callback;
-
- if (!callback) {
- throw new Error('seekToProgramTime: callback must be provided');
- }
-
- if (typeof programTime === 'undefined' || !playlist || !seekTo) {
- return callback({
- message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
- });
- }
-
- if (!playlist.endList && !tech.hasStarted_) {
- return callback({
- message: 'player must be playing a live stream to start buffering'
- });
- }
-
- if (!verifyProgramDateTimeTags(playlist)) {
- return callback({
- message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
- });
- }
-
- var matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
-
- if (!matchedSegment) {
- return callback({
- message: programTime + " was not found in the stream"
- });
- }
-
- var segment = matchedSegment.segment;
- var mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
-
- if (matchedSegment.type === 'estimate') {
- // we've run out of retries
- if (retryCount === 0) {
- return callback({
- message: programTime + " is not buffered yet. Try again"
- });
- }
-
- seekTo(matchedSegment.estimatedStart + mediaOffset);
- tech.one('seeked', function () {
- seekToProgramTime({
- programTime: programTime,
- playlist: playlist,
- retryCount: retryCount - 1,
- seekTo: seekTo,
- pauseAfterSeek: pauseAfterSeek,
- tech: tech,
- callback: callback
- });
- });
- return;
- } // Since the segment.start value is determined from the buffered end or ending time
- // of the prior segment, the seekToTime doesn't need to account for any transmuxer
- // modifications.
-
-
- var seekToTime = segment.start + mediaOffset;
-
- var seekedCallback = function seekedCallback() {
- return callback(null, tech.currentTime());
- }; // listen for seeked event
-
-
- tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
-
- if (pauseAfterSeek) {
- tech.pause();
- }
-
- seekTo(seekToTime);
- };
-
- /*! @name mpd-parser @version 0.17.0 @license Apache-2.0 */
-
- var isObject = function isObject(obj) {
- return !!obj && typeof obj === 'object';
- };
-
- var merge = function merge() {
- for (var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++) {
- objects[_key] = arguments[_key];
- }
-
- return objects.reduce(function (result, source) {
- if (typeof source !== 'object') {
- return result;
- }
-
- Object.keys(source).forEach(function (key) {
- if (Array.isArray(result[key]) && Array.isArray(source[key])) {
- result[key] = result[key].concat(source[key]);
- } else if (isObject(result[key]) && isObject(source[key])) {
- result[key] = merge(result[key], source[key]);
- } else {
- result[key] = source[key];
- }
- });
- return result;
- }, {});
- };
-
- var values = function values(o) {
- return Object.keys(o).map(function (k) {
- return o[k];
- });
- };
-
- var range = function range(start, end) {
- var result = [];
-
- for (var i = start; i < end; i++) {
- result.push(i);
- }
-
- return result;
- };
-
- var flatten = function flatten(lists) {
- return lists.reduce(function (x, y) {
- return x.concat(y);
- }, []);
- };
-
- var from = function from(list) {
- if (!list.length) {
- return [];
- }
-
- var result = [];
-
- for (var i = 0; i < list.length; i++) {
- result.push(list[i]);
- }
-
- return result;
- };
-
- var findIndexes = function findIndexes(l, key) {
- return l.reduce(function (a, e, i) {
- if (e[key]) {
- a.push(i);
- }
-
- return a;
- }, []);
- };
-
- var errors = {
- INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',
- DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',
- DASH_INVALID_XML: 'DASH_INVALID_XML',
- NO_BASE_URL: 'NO_BASE_URL',
- MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',
- SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',
- UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'
- };
- /**
- * @typedef {Object} SingleUri
- * @property {string} uri - relative location of segment
- * @property {string} resolvedUri - resolved location of segment
- * @property {Object} byterange - Object containing information on how to make byte range
- * requests following byte-range-spec per RFC2616.
- * @property {String} byterange.length - length of range request
- * @property {String} byterange.offset - byte offset of range request
- *
- * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
- */
-
- /**
- * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object
- * that conforms to how m3u8-parser is structured
- *
- * @see https://github.com/videojs/m3u8-parser
- *
- * @param {string} baseUrl - baseUrl provided by nodes
- * @param {string} source - source url for segment
- * @param {string} range - optional range used for range calls,
- * follows RFC 2616, Clause 14.35.1
- * @return {SingleUri} full segment information transformed into a format similar
- * to m3u8-parser
- */
-
- var urlTypeToSegment = function urlTypeToSegment(_ref) {
- var _ref$baseUrl = _ref.baseUrl,
- baseUrl = _ref$baseUrl === void 0 ? '' : _ref$baseUrl,
- _ref$source = _ref.source,
- source = _ref$source === void 0 ? '' : _ref$source,
- _ref$range = _ref.range,
- range = _ref$range === void 0 ? '' : _ref$range,
- _ref$indexRange = _ref.indexRange,
- indexRange = _ref$indexRange === void 0 ? '' : _ref$indexRange;
- var segment = {
- uri: source,
- resolvedUri: resolveUrl$1(baseUrl || '', source)
- };
-
- if (range || indexRange) {
- var rangeStr = range ? range : indexRange;
- var ranges = rangeStr.split('-');
- var startRange = parseInt(ranges[0], 10);
- var endRange = parseInt(ranges[1], 10); // byterange should be inclusive according to
- // RFC 2616, Clause 14.35.1
-
- segment.byterange = {
- length: endRange - startRange + 1,
- offset: startRange
- };
- }
-
- return segment;
- };
-
- var byteRangeToString = function byteRangeToString(byterange) {
- // `endRange` is one less than `offset + length` because the HTTP range
- // header uses inclusive ranges
- var endRange = byterange.offset + byterange.length - 1;
- return byterange.offset + "-" + endRange;
- };
- /**
- * parse the end number attribue that can be a string
- * number, or undefined.
- *
- * @param {string|number|undefined} endNumber
- * The end number attribute.
- *
- * @return {number|null}
- * The result of parsing the end number.
- */
-
-
- var parseEndNumber = function parseEndNumber(endNumber) {
- if (endNumber && typeof endNumber !== 'number') {
- endNumber = parseInt(endNumber, 10);
- }
-
- if (isNaN(endNumber)) {
- return null;
- }
-
- return endNumber;
- };
- /**
- * Functions for calculating the range of available segments in static and dynamic
- * manifests.
- */
-
-
- var segmentRange = {
- /**
- * Returns the entire range of available segments for a static MPD
- *
- * @param {Object} attributes
- * Inheritied MPD attributes
- * @return {{ start: number, end: number }}
- * The start and end numbers for available segments
- */
- static: function _static(attributes) {
- var duration = attributes.duration,
- _attributes$timescale = attributes.timescale,
- timescale = _attributes$timescale === void 0 ? 1 : _attributes$timescale,
- sourceDuration = attributes.sourceDuration;
- var endNumber = parseEndNumber(attributes.endNumber);
- return {
- start: 0,
- end: typeof endNumber === 'number' ? endNumber : Math.ceil(sourceDuration / (duration / timescale))
- };
- },
-
- /**
- * Returns the current live window range of available segments for a dynamic MPD
- *
- * @param {Object} attributes
- * Inheritied MPD attributes
- * @return {{ start: number, end: number }}
- * The start and end numbers for available segments
- */
- dynamic: function dynamic(attributes) {
- var NOW = attributes.NOW,
- clientOffset = attributes.clientOffset,
- availabilityStartTime = attributes.availabilityStartTime,
- _attributes$timescale2 = attributes.timescale,
- timescale = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2,
- duration = attributes.duration,
- _attributes$start = attributes.start,
- start = _attributes$start === void 0 ? 0 : _attributes$start,
- _attributes$minimumUp = attributes.minimumUpdatePeriod,
- minimumUpdatePeriod = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp,
- _attributes$timeShift = attributes.timeShiftBufferDepth,
- timeShiftBufferDepth = _attributes$timeShift === void 0 ? Infinity : _attributes$timeShift;
- var endNumber = parseEndNumber(attributes.endNumber);
- var now = (NOW + clientOffset) / 1000;
- var periodStartWC = availabilityStartTime + start;
- var periodEndWC = now + minimumUpdatePeriod;
- var periodDuration = periodEndWC - periodStartWC;
- var segmentCount = Math.ceil(periodDuration * timescale / duration);
- var availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);
- var availableEnd = Math.floor((now - periodStartWC) * timescale / duration);
- return {
- start: Math.max(0, availableStart),
- end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)
- };
- }
- };
- /**
- * Maps a range of numbers to objects with information needed to build the corresponding
- * segment list
- *
- * @name toSegmentsCallback
- * @function
- * @param {number} number
- * Number of the segment
- * @param {number} index
- * Index of the number in the range list
- * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}
- * Object with segment timing and duration info
- */
-
- /**
- * Returns a callback for Array.prototype.map for mapping a range of numbers to
- * information needed to build the segment list.
- *
- * @param {Object} attributes
- * Inherited MPD attributes
- * @return {toSegmentsCallback}
- * Callback map function
- */
-
- var toSegments = function toSegments(attributes) {
- return function (number, index) {
- var duration = attributes.duration,
- _attributes$timescale3 = attributes.timescale,
- timescale = _attributes$timescale3 === void 0 ? 1 : _attributes$timescale3,
- periodIndex = attributes.periodIndex,
- _attributes$startNumb = attributes.startNumber,
- startNumber = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb;
- return {
- number: startNumber + number,
- duration: duration / timescale,
- timeline: periodIndex,
- time: index * duration
- };
- };
- };
- /**
- * Returns a list of objects containing segment timing and duration info used for
- * building the list of segments. This uses the @duration attribute specified
- * in the MPD manifest to derive the range of segments.
- *
- * @param {Object} attributes
- * Inherited MPD attributes
- * @return {{number: number, duration: number, time: number, timeline: number}[]}
- * List of Objects with segment timing and duration info
- */
-
-
- var parseByDuration = function parseByDuration(attributes) {
- var _attributes$type = attributes.type,
- type = _attributes$type === void 0 ? 'static' : _attributes$type,
- duration = attributes.duration,
- _attributes$timescale4 = attributes.timescale,
- timescale = _attributes$timescale4 === void 0 ? 1 : _attributes$timescale4,
- sourceDuration = attributes.sourceDuration;
-
- var _segmentRange$type = segmentRange[type](attributes),
- start = _segmentRange$type.start,
- end = _segmentRange$type.end;
-
- var segments = range(start, end).map(toSegments(attributes));
-
- if (type === 'static') {
- var index = segments.length - 1; // final segment may be less than full segment duration
-
- segments[index].duration = sourceDuration - duration / timescale * index;
- }
-
- return segments;
- };
- /**
- * Translates SegmentBase into a set of segments.
- * (DASH SPEC Section 5.3.9.3.2) contains a set of nodes. Each
- * node should be translated into segment.
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @return {Object.} list of segments
- */
-
-
- var segmentsFromBase = function segmentsFromBase(attributes) {
- var baseUrl = attributes.baseUrl,
- _attributes$initializ = attributes.initialization,
- initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ,
- sourceDuration = attributes.sourceDuration,
- _attributes$indexRang = attributes.indexRange,
- indexRange = _attributes$indexRang === void 0 ? '' : _attributes$indexRang,
- duration = attributes.duration; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)
-
- if (!baseUrl) {
- throw new Error(errors.NO_BASE_URL);
- }
-
- var initSegment = urlTypeToSegment({
- baseUrl: baseUrl,
- source: initialization.sourceURL,
- range: initialization.range
- });
- var segment = urlTypeToSegment({
- baseUrl: baseUrl,
- source: baseUrl,
- indexRange: indexRange
- });
- segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source
- // (since SegmentBase is only for one total segment)
-
- if (duration) {
- var segmentTimeInfo = parseByDuration(attributes);
-
- if (segmentTimeInfo.length) {
- segment.duration = segmentTimeInfo[0].duration;
- segment.timeline = segmentTimeInfo[0].timeline;
- }
- } else if (sourceDuration) {
- segment.duration = sourceDuration;
- segment.timeline = 0;
- } // This is used for mediaSequence
-
-
- segment.number = 0;
- return [segment];
- };
- /**
- * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist
- * according to the sidx information given.
- *
- * playlist.sidx has metadadata about the sidx where-as the sidx param
- * is the parsed sidx box itself.
- *
- * @param {Object} playlist the playlist to update the sidx information for
- * @param {Object} sidx the parsed sidx box
- * @return {Object} the playlist object with the updated sidx information
- */
-
-
- var addSidxSegmentsToPlaylist = function addSidxSegmentsToPlaylist(playlist, sidx, baseUrl) {
- // Retain init segment information
- var initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial master manifest parsing
-
- var sourceDuration = playlist.sidx.duration; // Retain source timeline
-
- var timeline = playlist.timeline || 0;
- var sidxByteRange = playlist.sidx.byterange;
- var sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx
-
- var timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes
-
- var mediaReferences = sidx.references.filter(function (r) {
- return r.referenceType !== 1;
- });
- var segments = []; // firstOffset is the offset from the end of the sidx box
-
- var startIndex = sidxEnd + sidx.firstOffset;
-
- for (var i = 0; i < mediaReferences.length; i++) {
- var reference = sidx.references[i]; // size of the referenced (sub)segment
-
- var size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale
- // this will be converted to seconds when generating segments
-
- var duration = reference.subsegmentDuration; // should be an inclusive range
-
- var endIndex = startIndex + size - 1;
- var indexRange = startIndex + "-" + endIndex;
- var attributes = {
- baseUrl: baseUrl,
- timescale: timescale,
- timeline: timeline,
- // this is used in parseByDuration
- periodIndex: timeline,
- duration: duration,
- sourceDuration: sourceDuration,
- indexRange: indexRange
- };
- var segment = segmentsFromBase(attributes)[0];
-
- if (initSegment) {
- segment.map = initSegment;
- }
-
- segments.push(segment);
- startIndex += size;
- }
-
- playlist.segments = segments;
- return playlist;
- };
-
- var generateSidxKey = function generateSidxKey(sidx) {
- return sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);
- };
-
- var mergeDiscontiguousPlaylists = function mergeDiscontiguousPlaylists(playlists) {
- var mergedPlaylists = values(playlists.reduce(function (acc, playlist) {
- // assuming playlist IDs are the same across periods
- // TODO: handle multiperiod where representation sets are not the same
- // across periods
- var name = playlist.attributes.id + (playlist.attributes.lang || ''); // Periods after first
-
- if (acc[name]) {
- var _acc$name$segments; // first segment of subsequent periods signal a discontinuity
-
-
- if (playlist.segments[0]) {
- playlist.segments[0].discontinuity = true;
- }
-
- (_acc$name$segments = acc[name].segments).push.apply(_acc$name$segments, playlist.segments); // bubble up contentProtection, this assumes all DRM content
- // has the same contentProtection
-
-
- if (playlist.attributes.contentProtection) {
- acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
- }
- } else {
- // first Period
- acc[name] = playlist;
- }
-
- return acc;
- }, {}));
- return mergedPlaylists.map(function (playlist) {
- playlist.discontinuityStarts = findIndexes(playlist.segments, 'discontinuity');
- return playlist;
- });
- };
-
- var addSidxSegmentsToPlaylist$1 = function addSidxSegmentsToPlaylist$1(playlist, sidxMapping) {
- var sidxKey = generateSidxKey(playlist.sidx);
- var sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
-
- if (sidxMatch) {
- addSidxSegmentsToPlaylist(playlist, sidxMatch, playlist.sidx.resolvedUri);
- }
-
- return playlist;
- };
-
- var addSidxSegmentsToPlaylists = function addSidxSegmentsToPlaylists(playlists, sidxMapping) {
- if (sidxMapping === void 0) {
- sidxMapping = {};
- }
-
- if (!Object.keys(sidxMapping).length) {
- return playlists;
- }
-
- for (var i in playlists) {
- playlists[i] = addSidxSegmentsToPlaylist$1(playlists[i], sidxMapping);
- }
-
- return playlists;
- };
-
- var formatAudioPlaylist = function formatAudioPlaylist(_ref, isAudioOnly) {
- var _attributes;
-
- var attributes = _ref.attributes,
- segments = _ref.segments,
- sidx = _ref.sidx;
- var playlist = {
- attributes: (_attributes = {
- NAME: attributes.id,
- BANDWIDTH: attributes.bandwidth,
- CODECS: attributes.codecs
- }, _attributes['PROGRAM-ID'] = 1, _attributes),
- uri: '',
- endList: (attributes.type || 'static') === 'static',
- timeline: attributes.periodIndex,
- resolvedUri: '',
- targetDuration: attributes.duration,
- segments: segments,
- mediaSequence: segments.length ? segments[0].number : 1
- };
-
- if (attributes.contentProtection) {
- playlist.contentProtection = attributes.contentProtection;
- }
-
- if (sidx) {
- playlist.sidx = sidx;
- }
-
- if (isAudioOnly) {
- playlist.attributes.AUDIO = 'audio';
- playlist.attributes.SUBTITLES = 'subs';
- }
-
- return playlist;
- };
-
- var formatVttPlaylist = function formatVttPlaylist(_ref2) {
- var _m3u8Attributes;
-
- var attributes = _ref2.attributes,
- segments = _ref2.segments;
-
- if (typeof segments === 'undefined') {
- // vtt tracks may use single file in BaseURL
- segments = [{
- uri: attributes.baseUrl,
- timeline: attributes.periodIndex,
- resolvedUri: attributes.baseUrl || '',
- duration: attributes.sourceDuration,
- number: 0
- }]; // targetDuration should be the same duration as the only segment
-
- attributes.duration = attributes.sourceDuration;
- }
-
- var m3u8Attributes = (_m3u8Attributes = {
- NAME: attributes.id,
- BANDWIDTH: attributes.bandwidth
- }, _m3u8Attributes['PROGRAM-ID'] = 1, _m3u8Attributes);
-
- if (attributes.codecs) {
- m3u8Attributes.CODECS = attributes.codecs;
- }
-
- return {
- attributes: m3u8Attributes,
- uri: '',
- endList: (attributes.type || 'static') === 'static',
- timeline: attributes.periodIndex,
- resolvedUri: attributes.baseUrl || '',
- targetDuration: attributes.duration,
- segments: segments,
- mediaSequence: segments.length ? segments[0].number : 1
- };
- };
-
- var organizeAudioPlaylists = function organizeAudioPlaylists(playlists, sidxMapping, isAudioOnly) {
- if (sidxMapping === void 0) {
- sidxMapping = {};
- }
-
- if (isAudioOnly === void 0) {
- isAudioOnly = false;
- }
-
- var mainPlaylist;
- var formattedPlaylists = playlists.reduce(function (a, playlist) {
- var role = playlist.attributes.role && playlist.attributes.role.value || '';
- var language = playlist.attributes.lang || '';
- var label = playlist.attributes.label || 'main';
-
- if (language && !playlist.attributes.label) {
- var roleLabel = role ? " (" + role + ")" : '';
- label = "" + playlist.attributes.lang + roleLabel;
- }
-
- if (!a[label]) {
- a[label] = {
- language: language,
- autoselect: true,
- default: role === 'main',
- playlists: [],
- uri: ''
- };
- }
-
- var formatted = addSidxSegmentsToPlaylist$1(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);
- a[label].playlists.push(formatted);
-
- if (typeof mainPlaylist === 'undefined' && role === 'main') {
- mainPlaylist = playlist;
- mainPlaylist.default = true;
- }
-
- return a;
- }, {}); // if no playlists have role "main", mark the first as main
-
- if (!mainPlaylist) {
- var firstLabel = Object.keys(formattedPlaylists)[0];
- formattedPlaylists[firstLabel].default = true;
- }
-
- return formattedPlaylists;
- };
-
- var organizeVttPlaylists = function organizeVttPlaylists(playlists, sidxMapping) {
- if (sidxMapping === void 0) {
- sidxMapping = {};
- }
-
- return playlists.reduce(function (a, playlist) {
- var label = playlist.attributes.lang || 'text';
-
- if (!a[label]) {
- a[label] = {
- language: label,
- default: false,
- autoselect: false,
- playlists: [],
- uri: ''
- };
- }
-
- a[label].playlists.push(addSidxSegmentsToPlaylist$1(formatVttPlaylist(playlist), sidxMapping));
- return a;
- }, {});
- };
-
- var organizeCaptionServices = function organizeCaptionServices(captionServices) {
- return captionServices.reduce(function (svcObj, svc) {
- if (!svc) {
- return svcObj;
- }
-
- svc.forEach(function (service) {
- var channel = service.channel,
- language = service.language;
- svcObj[language] = {
- autoselect: false,
- default: false,
- instreamId: channel,
- language: language
- };
-
- if (service.hasOwnProperty('aspectRatio')) {
- svcObj[language].aspectRatio = service.aspectRatio;
- }
-
- if (service.hasOwnProperty('easyReader')) {
- svcObj[language].easyReader = service.easyReader;
- }
-
- if (service.hasOwnProperty('3D')) {
- svcObj[language]['3D'] = service['3D'];
- }
- });
- return svcObj;
- }, {});
- };
-
- var formatVideoPlaylist = function formatVideoPlaylist(_ref3) {
- var _attributes2;
-
- var attributes = _ref3.attributes,
- segments = _ref3.segments,
- sidx = _ref3.sidx;
- var playlist = {
- attributes: (_attributes2 = {
- NAME: attributes.id,
- AUDIO: 'audio',
- SUBTITLES: 'subs',
- RESOLUTION: {
- width: attributes.width,
- height: attributes.height
- },
- CODECS: attributes.codecs,
- BANDWIDTH: attributes.bandwidth
- }, _attributes2['PROGRAM-ID'] = 1, _attributes2),
- uri: '',
- endList: (attributes.type || 'static') === 'static',
- timeline: attributes.periodIndex,
- resolvedUri: '',
- targetDuration: attributes.duration,
- segments: segments,
- mediaSequence: segments.length ? segments[0].number : 1
- };
-
- if (attributes.contentProtection) {
- playlist.contentProtection = attributes.contentProtection;
- }
-
- if (sidx) {
- playlist.sidx = sidx;
- }
-
- return playlist;
- };
-
- var videoOnly = function videoOnly(_ref4) {
- var attributes = _ref4.attributes;
- return attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';
- };
-
- var audioOnly = function audioOnly(_ref5) {
- var attributes = _ref5.attributes;
- return attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';
- };
-
- var vttOnly = function vttOnly(_ref6) {
- var attributes = _ref6.attributes;
- return attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';
- };
-
- var toM3u8 = function toM3u8(dashPlaylists, locations, sidxMapping) {
- var _mediaGroups;
-
- if (sidxMapping === void 0) {
- sidxMapping = {};
- }
-
- if (!dashPlaylists.length) {
- return {};
- } // grab all master attributes
-
-
- var _dashPlaylists$0$attr = dashPlaylists[0].attributes,
- duration = _dashPlaylists$0$attr.sourceDuration,
- _dashPlaylists$0$attr2 = _dashPlaylists$0$attr.type,
- type = _dashPlaylists$0$attr2 === void 0 ? 'static' : _dashPlaylists$0$attr2,
- suggestedPresentationDelay = _dashPlaylists$0$attr.suggestedPresentationDelay,
- minimumUpdatePeriod = _dashPlaylists$0$attr.minimumUpdatePeriod;
- var videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
- var audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
- var vttPlaylists = dashPlaylists.filter(vttOnly);
- var captions = dashPlaylists.map(function (playlist) {
- return playlist.attributes.captionServices;
- }).filter(Boolean);
- var master = {
- allowCache: true,
- discontinuityStarts: [],
- segments: [],
- endList: true,
- mediaGroups: (_mediaGroups = {
- AUDIO: {},
- VIDEO: {}
- }, _mediaGroups['CLOSED-CAPTIONS'] = {}, _mediaGroups.SUBTITLES = {}, _mediaGroups),
- uri: '',
- duration: duration,
- playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
- };
-
- if (minimumUpdatePeriod >= 0) {
- master.minimumUpdatePeriod = minimumUpdatePeriod * 1000;
- }
-
- if (locations) {
- master.locations = locations;
- }
-
- if (type === 'dynamic') {
- master.suggestedPresentationDelay = suggestedPresentationDelay;
- }
-
- var isAudioOnly = master.playlists.length === 0;
-
- if (audioPlaylists.length) {
- master.mediaGroups.AUDIO.audio = organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly);
- }
-
- if (vttPlaylists.length) {
- master.mediaGroups.SUBTITLES.subs = organizeVttPlaylists(vttPlaylists, sidxMapping);
- }
-
- if (captions.length) {
- master.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);
- }
-
- return master;
- };
- /**
- * Calculates the R (repetition) value for a live stream (for the final segment
- * in a manifest where the r value is negative 1)
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {number} time
- * current time (typically the total time up until the final segment)
- * @param {number} duration
- * duration property for the given
- *
- * @return {number}
- * R value to reach the end of the given period
- */
-
-
- var getLiveRValue = function getLiveRValue(attributes, time, duration) {
- var NOW = attributes.NOW,
- clientOffset = attributes.clientOffset,
- availabilityStartTime = attributes.availabilityStartTime,
- _attributes$timescale = attributes.timescale,
- timescale = _attributes$timescale === void 0 ? 1 : _attributes$timescale,
- _attributes$start = attributes.start,
- start = _attributes$start === void 0 ? 0 : _attributes$start,
- _attributes$minimumUp = attributes.minimumUpdatePeriod,
- minimumUpdatePeriod = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp;
- var now = (NOW + clientOffset) / 1000;
- var periodStartWC = availabilityStartTime + start;
- var periodEndWC = now + minimumUpdatePeriod;
- var periodDuration = periodEndWC - periodStartWC;
- return Math.ceil((periodDuration * timescale - time) / duration);
- };
- /**
- * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment
- * timing and duration
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object[]} segmentTimeline
- * List of objects representing the attributes of each S element contained within
- *
- * @return {{number: number, duration: number, time: number, timeline: number}[]}
- * List of Objects with segment timing and duration info
- */
-
-
- var parseByTimeline = function parseByTimeline(attributes, segmentTimeline) {
- var _attributes$type = attributes.type,
- type = _attributes$type === void 0 ? 'static' : _attributes$type,
- _attributes$minimumUp2 = attributes.minimumUpdatePeriod,
- minimumUpdatePeriod = _attributes$minimumUp2 === void 0 ? 0 : _attributes$minimumUp2,
- _attributes$media = attributes.media,
- media = _attributes$media === void 0 ? '' : _attributes$media,
- sourceDuration = attributes.sourceDuration,
- _attributes$timescale2 = attributes.timescale,
- timescale = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2,
- _attributes$startNumb = attributes.startNumber,
- startNumber = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb,
- timeline = attributes.periodIndex;
- var segments = [];
- var time = -1;
-
- for (var sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
- var S = segmentTimeline[sIndex];
- var duration = S.d;
- var repeat = S.r || 0;
- var segmentTime = S.t || 0;
-
- if (time < 0) {
- // first segment
- time = segmentTime;
- }
-
- if (segmentTime && segmentTime > time) {
- // discontinuity
- // TODO: How to handle this type of discontinuity
- // timeline++ here would treat it like HLS discontuity and content would
- // get appended without gap
- // E.G.
- //
- //
- //
- //
- // would have $Time$ values of [0, 1, 2, 5]
- // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)
- // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)
- // does the value of sourceDuration consider this when calculating arbitrary
- // negative @r repeat value?
- // E.G. Same elements as above with this added at the end
- //
- // with a sourceDuration of 10
- // Would the 2 gaps be included in the time duration calculations resulting in
- // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments
- // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?
- time = segmentTime;
- }
-
- var count = void 0;
-
- if (repeat < 0) {
- var nextS = sIndex + 1;
-
- if (nextS === segmentTimeline.length) {
- // last segment
- if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {
- count = getLiveRValue(attributes, time, duration);
- } else {
- // TODO: This may be incorrect depending on conclusion of TODO above
- count = (sourceDuration * timescale - time) / duration;
- }
- } else {
- count = (segmentTimeline[nextS].t - time) / duration;
- }
- } else {
- count = repeat + 1;
- }
-
- var end = startNumber + segments.length + count;
- var number = startNumber + segments.length;
-
- while (number < end) {
- segments.push({
- number: number,
- duration: duration / timescale,
- time: time,
- timeline: timeline
- });
- time += duration;
- number++;
- }
- }
-
- return segments;
- };
-
- var identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
- /**
- * Replaces template identifiers with corresponding values. To be used as the callback
- * for String.prototype.replace
- *
- * @name replaceCallback
- * @function
- * @param {string} match
- * Entire match of identifier
- * @param {string} identifier
- * Name of matched identifier
- * @param {string} format
- * Format tag string. Its presence indicates that padding is expected
- * @param {string} width
- * Desired length of the replaced value. Values less than this width shall be left
- * zero padded
- * @return {string}
- * Replacement for the matched identifier
- */
-
- /**
- * Returns a function to be used as a callback for String.prototype.replace to replace
- * template identifiers
- *
- * @param {Obect} values
- * Object containing values that shall be used to replace known identifiers
- * @param {number} values.RepresentationID
- * Value of the Representation@id attribute
- * @param {number} values.Number
- * Number of the corresponding segment
- * @param {number} values.Bandwidth
- * Value of the Representation@bandwidth attribute.
- * @param {number} values.Time
- * Timestamp value of the corresponding segment
- * @return {replaceCallback}
- * Callback to be used with String.prototype.replace to replace identifiers
- */
-
- var identifierReplacement = function identifierReplacement(values) {
- return function (match, identifier, format, width) {
- if (match === '$$') {
- // escape sequence
- return '$';
- }
-
- if (typeof values[identifier] === 'undefined') {
- return match;
- }
-
- var value = '' + values[identifier];
-
- if (identifier === 'RepresentationID') {
- // Format tag shall not be present with RepresentationID
- return value;
- }
-
- if (!format) {
- width = 1;
- } else {
- width = parseInt(width, 10);
- }
-
- if (value.length >= width) {
- return value;
- }
-
- return "" + new Array(width - value.length + 1).join('0') + value;
- };
- };
- /**
- * Constructs a segment url from a template string
- *
- * @param {string} url
- * Template string to construct url from
- * @param {Obect} values
- * Object containing values that shall be used to replace known identifiers
- * @param {number} values.RepresentationID
- * Value of the Representation@id attribute
- * @param {number} values.Number
- * Number of the corresponding segment
- * @param {number} values.Bandwidth
- * Value of the Representation@bandwidth attribute.
- * @param {number} values.Time
- * Timestamp value of the corresponding segment
- * @return {string}
- * Segment url with identifiers replaced
- */
-
-
- var constructTemplateUrl = function constructTemplateUrl(url, values) {
- return url.replace(identifierPattern, identifierReplacement(values));
- };
- /**
- * Generates a list of objects containing timing and duration information about each
- * segment needed to generate segment uris and the complete segment object
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object[]|undefined} segmentTimeline
- * List of objects representing the attributes of each S element contained within
- * the SegmentTimeline element
- * @return {{number: number, duration: number, time: number, timeline: number}[]}
- * List of Objects with segment timing and duration info
- */
-
-
- var parseTemplateInfo = function parseTemplateInfo(attributes, segmentTimeline) {
- if (!attributes.duration && !segmentTimeline) {
- // if neither @duration or SegmentTimeline are present, then there shall be exactly
- // one media segment
- return [{
- number: attributes.startNumber || 1,
- duration: attributes.sourceDuration,
- time: 0,
- timeline: attributes.periodIndex
- }];
- }
-
- if (attributes.duration) {
- return parseByDuration(attributes);
- }
-
- return parseByTimeline(attributes, segmentTimeline);
- };
- /**
- * Generates a list of segments using information provided by the SegmentTemplate element
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object[]|undefined} segmentTimeline
- * List of objects representing the attributes of each S element contained within
- * the SegmentTimeline element
- * @return {Object[]}
- * List of segment objects
- */
-
-
- var segmentsFromTemplate = function segmentsFromTemplate(attributes, segmentTimeline) {
- var templateValues = {
- RepresentationID: attributes.id,
- Bandwidth: attributes.bandwidth || 0
- };
- var _attributes$initializ = attributes.initialization,
- initialization = _attributes$initializ === void 0 ? {
- sourceURL: '',
- range: ''
- } : _attributes$initializ;
- var mapSegment = urlTypeToSegment({
- baseUrl: attributes.baseUrl,
- source: constructTemplateUrl(initialization.sourceURL, templateValues),
- range: initialization.range
- });
- var segments = parseTemplateInfo(attributes, segmentTimeline);
- return segments.map(function (segment) {
- templateValues.Number = segment.number;
- templateValues.Time = segment.time;
- var uri = constructTemplateUrl(attributes.media || '', templateValues);
- var map = {
- uri: uri,
- timeline: segment.timeline,
- duration: segment.duration,
- resolvedUri: resolveUrl$1(attributes.baseUrl || '', uri),
- map: mapSegment,
- number: segment.number
- };
-
- if (attributes.presentationTimeOffset) {
- map.presentationTimeOffset = attributes.presentationTimeOffset;
- }
-
- return map;
- });
- };
- /**
- * Converts a (of type URLType from the DASH spec 5.3.9.2 Table 14)
- * to an object that matches the output of a segment in videojs/mpd-parser
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object} segmentUrl
- * node to translate into a segment object
- * @return {Object} translated segment object
- */
-
-
- var SegmentURLToSegmentObject = function SegmentURLToSegmentObject(attributes, segmentUrl) {
- var baseUrl = attributes.baseUrl,
- _attributes$initializ = attributes.initialization,
- initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ;
- var initSegment = urlTypeToSegment({
- baseUrl: baseUrl,
- source: initialization.sourceURL,
- range: initialization.range
- });
- var segment = urlTypeToSegment({
- baseUrl: baseUrl,
- source: segmentUrl.media,
- range: segmentUrl.mediaRange
- });
- segment.map = initSegment;
- return segment;
- };
- /**
- * Generates a list of segments using information provided by the SegmentList element
- * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of nodes. Each
- * node should be translated into segment.
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object[]|undefined} segmentTimeline
- * List of objects representing the attributes of each S element contained within
- * the SegmentTimeline element
- * @return {Object.} list of segments
- */
-
-
- var segmentsFromList = function segmentsFromList(attributes, segmentTimeline) {
- var duration = attributes.duration,
- _attributes$segmentUr = attributes.segmentUrls,
- segmentUrls = _attributes$segmentUr === void 0 ? [] : _attributes$segmentUr; // Per spec (5.3.9.2.1) no way to determine segment duration OR
- // if both SegmentTimeline and @duration are defined, it is outside of spec.
-
- if (!duration && !segmentTimeline || duration && segmentTimeline) {
- throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
- }
-
- var segmentUrlMap = segmentUrls.map(function (segmentUrlObject) {
- return SegmentURLToSegmentObject(attributes, segmentUrlObject);
- });
- var segmentTimeInfo;
-
- if (duration) {
- segmentTimeInfo = parseByDuration(attributes);
- }
-
- if (segmentTimeline) {
- segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
- }
-
- var segments = segmentTimeInfo.map(function (segmentTime, index) {
- if (segmentUrlMap[index]) {
- var segment = segmentUrlMap[index];
- segment.timeline = segmentTime.timeline;
- segment.duration = segmentTime.duration;
- segment.number = segmentTime.number;
- return segment;
- } // Since we're mapping we should get rid of any blank segments (in case
- // the given SegmentTimeline is handling for more elements than we have
- // SegmentURLs for).
-
- }).filter(function (segment) {
- return segment;
- });
- return segments;
- };
-
- var generateSegments = function generateSegments(_ref) {
- var attributes = _ref.attributes,
- segmentInfo = _ref.segmentInfo;
- var segmentAttributes;
- var segmentsFn;
-
- if (segmentInfo.template) {
- segmentsFn = segmentsFromTemplate;
- segmentAttributes = merge(attributes, segmentInfo.template);
-
- if (segmentInfo.template.presentationTimeOffset) {
- segmentAttributes.presentationTimeOffset = segmentInfo.template.presentationTimeOffset / segmentInfo.template.timescale;
- }
- } else if (segmentInfo.base) {
- segmentsFn = segmentsFromBase;
- segmentAttributes = merge(attributes, segmentInfo.base);
- } else if (segmentInfo.list) {
- segmentsFn = segmentsFromList;
- segmentAttributes = merge(attributes, segmentInfo.list);
- }
-
- var segmentsInfo = {
- attributes: attributes
- };
-
- if (!segmentsFn) {
- return segmentsInfo;
- }
-
- var segments = segmentsFn(segmentAttributes, segmentInfo.timeline); // The @duration attribute will be used to determin the playlist's targetDuration which
- // must be in seconds. Since we've generated the segment list, we no longer need
- // @duration to be in @timescale units, so we can convert it here.
-
- if (segmentAttributes.duration) {
- var _segmentAttributes = segmentAttributes,
- duration = _segmentAttributes.duration,
- _segmentAttributes$ti = _segmentAttributes.timescale,
- timescale = _segmentAttributes$ti === void 0 ? 1 : _segmentAttributes$ti;
- segmentAttributes.duration = duration / timescale;
- } else if (segments.length) {
- // if there is no @duration attribute, use the largest segment duration as
- // as target duration
- segmentAttributes.duration = segments.reduce(function (max, segment) {
- return Math.max(max, Math.ceil(segment.duration));
- }, 0);
- } else {
- segmentAttributes.duration = 0;
- }
-
- segmentsInfo.attributes = segmentAttributes;
- segmentsInfo.segments = segments; // This is a sidx box without actual segment information
-
- if (segmentInfo.base && segmentAttributes.indexRange) {
- segmentsInfo.sidx = segments[0];
- segmentsInfo.segments = [];
- }
-
- return segmentsInfo;
- };
-
- var toPlaylists = function toPlaylists(representations) {
- return representations.map(generateSegments);
- };
-
- var findChildren = function findChildren(element, name) {
- return from(element.childNodes).filter(function (_ref) {
- var tagName = _ref.tagName;
- return tagName === name;
- });
- };
-
- var getContent = function getContent(element) {
- return element.textContent.trim();
- };
-
- var parseDuration = function parseDuration(str) {
- var SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
- var SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
- var SECONDS_IN_DAY = 24 * 60 * 60;
- var SECONDS_IN_HOUR = 60 * 60;
- var SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S
-
- var durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
- var match = durationRegex.exec(str);
-
- if (!match) {
- return 0;
- }
-
- var _match$slice = match.slice(1),
- year = _match$slice[0],
- month = _match$slice[1],
- day = _match$slice[2],
- hour = _match$slice[3],
- minute = _match$slice[4],
- second = _match$slice[5];
-
- return parseFloat(year || 0) * SECONDS_IN_YEAR + parseFloat(month || 0) * SECONDS_IN_MONTH + parseFloat(day || 0) * SECONDS_IN_DAY + parseFloat(hour || 0) * SECONDS_IN_HOUR + parseFloat(minute || 0) * SECONDS_IN_MIN + parseFloat(second || 0);
- };
-
- var parseDate = function parseDate(str) {
- // Date format without timezone according to ISO 8601
- // YYY-MM-DDThh:mm:ss.ssssss
- var dateRegex = /^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/; // If the date string does not specifiy a timezone, we must specifiy UTC. This is
- // expressed by ending with 'Z'
-
- if (dateRegex.test(str)) {
- str += 'Z';
- }
-
- return Date.parse(str);
- };
-
- var parsers = {
- /**
- * Specifies the duration of the entire Media Presentation. Format is a duration string
- * as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- mediaPresentationDuration: function mediaPresentationDuration(value) {
- return parseDuration(value);
- },
-
- /**
- * Specifies the Segment availability start time for all Segments referred to in this
- * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
- * time. Format is a date string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The date as seconds from unix epoch
- */
- availabilityStartTime: function availabilityStartTime(value) {
- return parseDate(value) / 1000;
- },
-
- /**
- * Specifies the smallest period between potential changes to the MPD. Format is a
- * duration string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- minimumUpdatePeriod: function minimumUpdatePeriod(value) {
- return parseDuration(value);
- },
-
- /**
- * Specifies the suggested presentation delay. Format is a
- * duration string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- suggestedPresentationDelay: function suggestedPresentationDelay(value) {
- return parseDuration(value);
- },
-
- /**
- * specifices the type of mpd. Can be either "static" or "dynamic"
- *
- * @param {string} value
- * value of attribute as a string
- *
- * @return {string}
- * The type as a string
- */
- type: function type(value) {
- return value;
- },
-
- /**
- * Specifies the duration of the smallest time shifting buffer for any Representation
- * in the MPD. Format is a duration string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- timeShiftBufferDepth: function timeShiftBufferDepth(value) {
- return parseDuration(value);
- },
-
- /**
- * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
- * Format is a duration string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- start: function start(value) {
- return parseDuration(value);
- },
-
- /**
- * Specifies the width of the visual presentation
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed width
- */
- width: function width(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the height of the visual presentation
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed height
- */
- height: function height(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the bitrate of the representation
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed bandwidth
- */
- bandwidth: function bandwidth(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the number of the first Media Segment in this Representation in the Period
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed number
- */
- startNumber: function startNumber(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the timescale in units per seconds
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed timescale
- */
- timescale: function timescale(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the presentationTimeOffset.
- *
- * @param {string} value
- * value of the attribute as a string
- *
- * @return {number}
- * The parsed presentationTimeOffset
- */
- presentationTimeOffset: function presentationTimeOffset(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the constant approximate Segment duration
- * NOTE: The element also contains an @duration attribute. This duration
- * specifies the duration of the Period. This attribute is currently not
- * supported by the rest of the parser, however we still check for it to prevent
- * errors.
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed duration
- */
- duration: function duration(value) {
- var parsedValue = parseInt(value, 10);
-
- if (isNaN(parsedValue)) {
- return parseDuration(value);
- }
-
- return parsedValue;
- },
-
- /**
- * Specifies the Segment duration, in units of the value of the @timescale.
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed duration
- */
- d: function d(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the MPD start time, in @timescale units, the first Segment in the series
- * starts relative to the beginning of the Period
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed time
- */
- t: function t(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the repeat count of the number of following contiguous Segments with the
- * same duration expressed by the value of @d
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed number
- */
- r: function r(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Default parser for all other attributes. Acts as a no-op and just returns the value
- * as a string
- *
- * @param {string} value
- * value of attribute as a string
- * @return {string}
- * Unparsed value
- */
- DEFAULT: function DEFAULT(value) {
- return value;
- }
- };
- /**
- * Gets all the attributes and values of the provided node, parses attributes with known
- * types, and returns an object with attribute names mapped to values.
- *
- * @param {Node} el
- * The node to parse attributes from
- * @return {Object}
- * Object with all attributes of el parsed
- */
-
- var parseAttributes = function parseAttributes(el) {
- if (!(el && el.attributes)) {
- return {};
- }
-
- return from(el.attributes).reduce(function (a, e) {
- var parseFn = parsers[e.name] || parsers.DEFAULT;
- a[e.name] = parseFn(e.value);
- return a;
- }, {});
- };
-
- var keySystemsMap = {
- 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',
- 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',
- 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',
- 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime'
- };
- /**
- * Builds a list of urls that is the product of the reference urls and BaseURL values
- *
- * @param {string[]} referenceUrls
- * List of reference urls to resolve to
- * @param {Node[]} baseUrlElements
- * List of BaseURL nodes from the mpd
- * @return {string[]}
- * List of resolved urls
- */
-
- var buildBaseUrls = function buildBaseUrls(referenceUrls, baseUrlElements) {
- if (!baseUrlElements.length) {
- return referenceUrls;
- }
-
- return flatten(referenceUrls.map(function (reference) {
- return baseUrlElements.map(function (baseUrlElement) {
- return resolveUrl$1(reference, getContent(baseUrlElement));
- });
- }));
- };
- /**
- * Contains all Segment information for its containing AdaptationSet
- *
- * @typedef {Object} SegmentInformation
- * @property {Object|undefined} template
- * Contains the attributes for the SegmentTemplate node
- * @property {Object[]|undefined} timeline
- * Contains a list of atrributes for each S node within the SegmentTimeline node
- * @property {Object|undefined} list
- * Contains the attributes for the SegmentList node
- * @property {Object|undefined} base
- * Contains the attributes for the SegmentBase node
- */
-
- /**
- * Returns all available Segment information contained within the AdaptationSet node
- *
- * @param {Node} adaptationSet
- * The AdaptationSet node to get Segment information from
- * @return {SegmentInformation}
- * The Segment information contained within the provided AdaptationSet
- */
-
-
- var getSegmentInformation = function getSegmentInformation(adaptationSet) {
- var segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];
- var segmentList = findChildren(adaptationSet, 'SegmentList')[0];
- var segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(function (s) {
- return merge({
- tag: 'SegmentURL'
- }, parseAttributes(s));
- });
- var segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];
- var segmentTimelineParentNode = segmentList || segmentTemplate;
- var segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];
- var segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
- var segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both
- // @initialization and an node. @initialization can be templated,
- // while the node can have a url and range specified. If the has
- // both @initialization and an subelement we opt to override with
- // the node, as this interaction is not defined in the spec.
-
- var template = segmentTemplate && parseAttributes(segmentTemplate);
-
- if (template && segmentInitialization) {
- template.initialization = segmentInitialization && parseAttributes(segmentInitialization);
- } else if (template && template.initialization) {
- // If it is @initialization we convert it to an object since this is the format that
- // later functions will rely on for the initialization segment. This is only valid
- // for
- template.initialization = {
- sourceURL: template.initialization
- };
- }
-
- var segmentInfo = {
- template: template,
- timeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(function (s) {
- return parseAttributes(s);
- }),
- list: segmentList && merge(parseAttributes(segmentList), {
- segmentUrls: segmentUrls,
- initialization: parseAttributes(segmentInitialization)
- }),
- base: segmentBase && merge(parseAttributes(segmentBase), {
- initialization: parseAttributes(segmentInitialization)
- })
- };
- Object.keys(segmentInfo).forEach(function (key) {
- if (!segmentInfo[key]) {
- delete segmentInfo[key];
- }
- });
- return segmentInfo;
- };
- /**
- * Contains Segment information and attributes needed to construct a Playlist object
- * from a Representation
- *
- * @typedef {Object} RepresentationInformation
- * @property {SegmentInformation} segmentInfo
- * Segment information for this Representation
- * @property {Object} attributes
- * Inherited attributes for this Representation
- */
-
- /**
- * Maps a Representation node to an object containing Segment information and attributes
- *
- * @name inheritBaseUrlsCallback
- * @function
- * @param {Node} representation
- * Representation node from the mpd
- * @return {RepresentationInformation}
- * Representation information needed to construct a Playlist object
- */
-
- /**
- * Returns a callback for Array.prototype.map for mapping Representation nodes to
- * Segment information and attributes using inherited BaseURL nodes.
- *
- * @param {Object} adaptationSetAttributes
- * Contains attributes inherited by the AdaptationSet
- * @param {string[]} adaptationSetBaseUrls
- * Contains list of resolved base urls inherited by the AdaptationSet
- * @param {SegmentInformation} adaptationSetSegmentInfo
- * Contains Segment information for the AdaptationSet
- * @return {inheritBaseUrlsCallback}
- * Callback map function
- */
-
-
- var inheritBaseUrls = function inheritBaseUrls(adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) {
- return function (representation) {
- var repBaseUrlElements = findChildren(representation, 'BaseURL');
- var repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
- var attributes = merge(adaptationSetAttributes, parseAttributes(representation));
- var representationSegmentInfo = getSegmentInformation(representation);
- return repBaseUrls.map(function (baseUrl) {
- return {
- segmentInfo: merge(adaptationSetSegmentInfo, representationSegmentInfo),
- attributes: merge(attributes, {
- baseUrl: baseUrl
- })
- };
- });
- };
- };
- /**
- * Tranforms a series of content protection nodes to
- * an object containing pssh data by key system
- *
- * @param {Node[]} contentProtectionNodes
- * Content protection nodes
- * @return {Object}
- * Object containing pssh data by key system
- */
-
-
- var generateKeySystemInformation = function generateKeySystemInformation(contentProtectionNodes) {
- return contentProtectionNodes.reduce(function (acc, node) {
- var attributes = parseAttributes(node);
- var keySystem = keySystemsMap[attributes.schemeIdUri];
-
- if (keySystem) {
- acc[keySystem] = {
- attributes: attributes
- };
- var psshNode = findChildren(node, 'cenc:pssh')[0];
-
- if (psshNode) {
- var pssh = getContent(psshNode);
- var psshBuffer = pssh && decodeB64ToUint8Array(pssh);
- acc[keySystem].pssh = psshBuffer;
- }
- }
-
- return acc;
- }, {});
- }; // defined in ANSI_SCTE 214-1 2016
-
-
- var parseCaptionServiceMetadata = function parseCaptionServiceMetadata(service) {
- // 608 captions
- if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {
- var values = service.value.split(';');
- return values.map(function (value) {
- var channel;
- var language; // default language to value
-
- language = value;
-
- if (/^CC\d=/.test(value)) {
- var _value$split = value.split('=');
-
- channel = _value$split[0];
- language = _value$split[1];
- } else if (/^CC\d$/.test(value)) {
- channel = value;
- }
-
- return {
- channel: channel,
- language: language
- };
- });
- } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {
- var _values = service.value.split(';');
-
- return _values.map(function (value) {
- var flags = {
- // service or channel number 1-63
- 'channel': undefined,
- // language is a 3ALPHA per ISO 639.2/B
- // field is required
- 'language': undefined,
- // BIT 1/0 or ?
- // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
- 'aspectRatio': 1,
- // BIT 1/0
- // easy reader flag indicated the text is tailed to the needs of beginning readers
- // default 0, or off
- 'easyReader': 0,
- // BIT 1/0
- // If 3d metadata is present (CEA-708.1) then 1
- // default 0
- '3D': 0
- };
-
- if (/=/.test(value)) {
- var _value$split2 = value.split('='),
- channel = _value$split2[0],
- _value$split2$ = _value$split2[1],
- opts = _value$split2$ === void 0 ? '' : _value$split2$;
-
- flags.channel = channel;
- flags.language = value;
- opts.split(',').forEach(function (opt) {
- var _opt$split = opt.split(':'),
- name = _opt$split[0],
- val = _opt$split[1];
-
- if (name === 'lang') {
- flags.language = val; // er for easyReadery
- } else if (name === 'er') {
- flags.easyReader = Number(val); // war for wide aspect ratio
- } else if (name === 'war') {
- flags.aspectRatio = Number(val);
- } else if (name === '3D') {
- flags['3D'] = Number(val);
- }
- });
- } else {
- flags.language = value;
- }
-
- if (flags.channel) {
- flags.channel = 'SERVICE' + flags.channel;
- }
-
- return flags;
- });
- }
- };
- /**
- * Maps an AdaptationSet node to a list of Representation information objects
- *
- * @name toRepresentationsCallback
- * @function
- * @param {Node} adaptationSet
- * AdaptationSet node from the mpd
- * @return {RepresentationInformation[]}
- * List of objects containing Representaion information
- */
-
- /**
- * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of
- * Representation information objects
- *
- * @param {Object} periodAttributes
- * Contains attributes inherited by the Period
- * @param {string[]} periodBaseUrls
- * Contains list of resolved base urls inherited by the Period
- * @param {string[]} periodSegmentInfo
- * Contains Segment Information at the period level
- * @return {toRepresentationsCallback}
- * Callback map function
- */
-
-
- var toRepresentations = function toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo) {
- return function (adaptationSet) {
- var adaptationSetAttributes = parseAttributes(adaptationSet);
- var adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));
- var role = findChildren(adaptationSet, 'Role')[0];
- var roleAttributes = {
- role: parseAttributes(role)
- };
- var attrs = merge(periodAttributes, adaptationSetAttributes, roleAttributes);
- var accessibility = findChildren(adaptationSet, 'Accessibility')[0];
- var captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));
-
- if (captionServices) {
- attrs = merge(attrs, {
- captionServices: captionServices
- });
- }
-
- var label = findChildren(adaptationSet, 'Label')[0];
-
- if (label && label.childNodes.length) {
- var labelVal = label.childNodes[0].nodeValue.trim();
- attrs = merge(attrs, {
- label: labelVal
- });
- }
-
- var contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));
-
- if (Object.keys(contentProtection).length) {
- attrs = merge(attrs, {
- contentProtection: contentProtection
- });
- }
-
- var segmentInfo = getSegmentInformation(adaptationSet);
- var representations = findChildren(adaptationSet, 'Representation');
- var adaptationSetSegmentInfo = merge(periodSegmentInfo, segmentInfo);
- return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
- };
- };
- /**
- * Maps an Period node to a list of Representation inforamtion objects for all
- * AdaptationSet nodes contained within the Period
- *
- * @name toAdaptationSetsCallback
- * @function
- * @param {Node} period
- * Period node from the mpd
- * @param {number} periodIndex
- * Index of the Period within the mpd
- * @return {RepresentationInformation[]}
- * List of objects containing Representaion information
- */
-
- /**
- * Returns a callback for Array.prototype.map for mapping Period nodes to a list of
- * Representation information objects
- *
- * @param {Object} mpdAttributes
- * Contains attributes inherited by the mpd
- * @param {string[]} mpdBaseUrls
- * Contains list of resolved base urls inherited by the mpd
- * @return {toAdaptationSetsCallback}
- * Callback map function
- */
-
-
- var toAdaptationSets = function toAdaptationSets(mpdAttributes, mpdBaseUrls) {
- return function (period, index) {
- var periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period, 'BaseURL'));
- var periodAtt = parseAttributes(period);
- var parsedPeriodId = parseInt(periodAtt.id, 10); // fallback to mapping index if Period@id is not a number
-
- var periodIndex = window__default['default'].isNaN(parsedPeriodId) ? index : parsedPeriodId;
- var periodAttributes = merge(mpdAttributes, {
- periodIndex: periodIndex
- });
- var adaptationSets = findChildren(period, 'AdaptationSet');
- var periodSegmentInfo = getSegmentInformation(period);
- return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
- };
- };
- /**
- * Traverses the mpd xml tree to generate a list of Representation information objects
- * that have inherited attributes from parent nodes
- *
- * @param {Node} mpd
- * The root node of the mpd
- * @param {Object} options
- * Available options for inheritAttributes
- * @param {string} options.manifestUri
- * The uri source of the mpd
- * @param {number} options.NOW
- * Current time per DASH IOP. Default is current time in ms since epoch
- * @param {number} options.clientOffset
- * Client time difference from NOW (in milliseconds)
- * @return {RepresentationInformation[]}
- * List of objects containing Representation information
- */
-
-
- var inheritAttributes = function inheritAttributes(mpd, options) {
- if (options === void 0) {
- options = {};
- }
-
- var _options = options,
- _options$manifestUri = _options.manifestUri,
- manifestUri = _options$manifestUri === void 0 ? '' : _options$manifestUri,
- _options$NOW = _options.NOW,
- NOW = _options$NOW === void 0 ? Date.now() : _options$NOW,
- _options$clientOffset = _options.clientOffset,
- clientOffset = _options$clientOffset === void 0 ? 0 : _options$clientOffset;
- var periods = findChildren(mpd, 'Period');
-
- if (!periods.length) {
- throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
- }
-
- var locations = findChildren(mpd, 'Location');
- var mpdAttributes = parseAttributes(mpd);
- var mpdBaseUrls = buildBaseUrls([manifestUri], findChildren(mpd, 'BaseURL'));
- mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
- mpdAttributes.NOW = NOW;
- mpdAttributes.clientOffset = clientOffset;
-
- if (locations.length) {
- mpdAttributes.locations = locations.map(getContent);
- }
-
- return {
- locations: mpdAttributes.locations,
- representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls)))
- };
- };
-
- var stringToMpdXml = function stringToMpdXml(manifestString) {
- if (manifestString === '') {
- throw new Error(errors.DASH_EMPTY_MANIFEST);
- }
-
- var parser = new xmldom.DOMParser();
- var xml;
- var mpd;
-
- try {
- xml = parser.parseFromString(manifestString, 'application/xml');
- mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;
- } catch (e) {// ie 11 throwsw on invalid xml
- }
-
- if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {
- throw new Error(errors.DASH_INVALID_XML);
- }
-
- return mpd;
- };
- /**
- * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
- *
- * @param {string} mpd
- * XML string of the MPD manifest
- * @return {Object|null}
- * Attributes of UTCTiming node specified in the manifest. Null if none found
- */
-
-
- var parseUTCTimingScheme = function parseUTCTimingScheme(mpd) {
- var UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];
-
- if (!UTCTimingNode) {
- return null;
- }
-
- var attributes = parseAttributes(UTCTimingNode);
-
- switch (attributes.schemeIdUri) {
- case 'urn:mpeg:dash:utc:http-head:2014':
- case 'urn:mpeg:dash:utc:http-head:2012':
- attributes.method = 'HEAD';
- break;
-
- case 'urn:mpeg:dash:utc:http-xsdate:2014':
- case 'urn:mpeg:dash:utc:http-iso:2014':
- case 'urn:mpeg:dash:utc:http-xsdate:2012':
- case 'urn:mpeg:dash:utc:http-iso:2012':
- attributes.method = 'GET';
- break;
-
- case 'urn:mpeg:dash:utc:direct:2014':
- case 'urn:mpeg:dash:utc:direct:2012':
- attributes.method = 'DIRECT';
- attributes.value = Date.parse(attributes.value);
- break;
-
- case 'urn:mpeg:dash:utc:http-ntp:2014':
- case 'urn:mpeg:dash:utc:ntp:2014':
- case 'urn:mpeg:dash:utc:sntp:2014':
- default:
- throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
- }
-
- return attributes;
- };
-
- var parse = function parse(manifestString, options) {
- if (options === void 0) {
- options = {};
- }
-
- var parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
- var playlists = toPlaylists(parsedManifestInfo.representationInfo);
- return toM3u8(playlists, parsedManifestInfo.locations, options.sidxMapping);
- };
- /**
- * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
- *
- * @param {string} manifestString
- * XML string of the MPD manifest
- * @return {Object|null}
- * Attributes of UTCTiming node specified in the manifest. Null if none found
- */
-
-
- var parseUTCTiming = function parseUTCTiming(manifestString) {
- return parseUTCTimingScheme(stringToMpdXml(manifestString));
- };
-
- var MAX_UINT32 = Math.pow(2, 32);
-
- var parseSidx = function parseSidx(data) {
- var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- references: [],
- referenceId: view.getUint32(4),
- timescale: view.getUint32(8)
- },
- i = 12;
-
- if (result.version === 0) {
- result.earliestPresentationTime = view.getUint32(i);
- result.firstOffset = view.getUint32(i + 4);
- i += 8;
- } else {
- // read 64 bits
- result.earliestPresentationTime = view.getUint32(i) * MAX_UINT32 + view.getUint32(i + 4);
- result.firstOffset = view.getUint32(i + 8) * MAX_UINT32 + view.getUint32(i + 12);
- i += 16;
- }
-
- i += 2; // reserved
-
- var referenceCount = view.getUint16(i);
- i += 2; // start of references
-
- for (; referenceCount > 0; i += 12, referenceCount--) {
- result.references.push({
- referenceType: (data[i] & 0x80) >>> 7,
- referencedSize: view.getUint32(i) & 0x7FFFFFFF,
- subsegmentDuration: view.getUint32(i + 4),
- startsWithSap: !!(data[i + 8] & 0x80),
- sapType: (data[i + 8] & 0x70) >>> 4,
- sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
- });
- }
-
- return result;
- };
-
- var parseSidx_1 = parseSidx;
-
- // we used to do this with log2 but BigInt does not support builtin math
- // Math.ceil(log2(x));
-
-
- var countBits = function countBits(x) {
- return x.toString(2).length;
- }; // count the number of whole bytes it would take to represent a number
-
- var countBytes = function countBytes(x) {
- return Math.ceil(countBits(x) / 8);
- };
- var isTypedArray = function isTypedArray(obj) {
- return ArrayBuffer.isView(obj);
- };
- var toUint8 = function toUint8(bytes) {
- if (bytes instanceof Uint8Array) {
- return bytes;
- }
-
- if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
- // any non-number or NaN leads to empty uint8array
- // eslint-disable-next-line
- if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
- bytes = 0;
- } else {
- bytes = [bytes];
- }
- }
-
- return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
- };
- var BigInt = window__default['default'].BigInt || Number;
- var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
- var bytesToNumber = function bytesToNumber(bytes, _temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- _ref$signed = _ref.signed,
- signed = _ref$signed === void 0 ? false : _ref$signed,
- _ref$le = _ref.le,
- le = _ref$le === void 0 ? false : _ref$le;
-
- bytes = toUint8(bytes);
- var fn = le ? 'reduce' : 'reduceRight';
- var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
- var number = obj.call(bytes, function (total, byte, i) {
- var exponent = le ? i : Math.abs(i + 1 - bytes.length);
- return total + BigInt(byte) * BYTE_TABLE[exponent];
- }, BigInt(0));
-
- if (signed) {
- var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
- number = BigInt(number);
-
- if (number > max) {
- number -= max;
- number -= max;
- number -= BigInt(2);
- }
- }
-
- return Number(number);
- };
- var numberToBytes = function numberToBytes(number, _temp2) {
- var _ref2 = _temp2 === void 0 ? {} : _temp2,
- _ref2$le = _ref2.le,
- le = _ref2$le === void 0 ? false : _ref2$le; // eslint-disable-next-line
-
-
- if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
- number = 0;
- }
-
- number = BigInt(number);
- var byteCount = countBytes(number);
- var bytes = new Uint8Array(new ArrayBuffer(byteCount));
-
- for (var i = 0; i < byteCount; i++) {
- var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
- bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
-
- if (number < 0) {
- bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
- bytes[byteIndex] -= i === 0 ? 1 : 2;
- }
- }
-
- return bytes;
- };
- var stringToBytes = function stringToBytes(string, stringIsBytes) {
- if (typeof string !== 'string' && string && typeof string.toString === 'function') {
- string = string.toString();
- }
-
- if (typeof string !== 'string') {
- return new Uint8Array();
- } // If the string already is bytes, we don't have to do this
- // otherwise we do this so that we split multi length characters
- // into individual bytes
-
-
- if (!stringIsBytes) {
- string = unescape(encodeURIComponent(string));
- }
-
- var view = new Uint8Array(string.length);
-
- for (var i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view;
- };
- var concatTypedArrays = function concatTypedArrays() {
- for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
- buffers[_key] = arguments[_key];
- }
-
- buffers = buffers.filter(function (b) {
- return b && (b.byteLength || b.length) && typeof b !== 'string';
- });
-
- if (buffers.length <= 1) {
- // for 0 length we will return empty uint8
- // for 1 length we return the first uint8
- return toUint8(buffers[0]);
- }
-
- var totalLen = buffers.reduce(function (total, buf, i) {
- return total + (buf.byteLength || buf.length);
- }, 0);
- var tempBuffer = new Uint8Array(totalLen);
- var offset = 0;
- buffers.forEach(function (buf) {
- buf = toUint8(buf);
- tempBuffer.set(buf, offset);
- offset += buf.byteLength;
- });
- return tempBuffer;
- };
- /**
- * Check if the bytes "b" are contained within bytes "a".
- *
- * @param {Uint8Array|Array} a
- * Bytes to check in
- *
- * @param {Uint8Array|Array} b
- * Bytes to check for
- *
- * @param {Object} options
- * options
- *
- * @param {Array|Uint8Array} [offset=0]
- * offset to use when looking at bytes in a
- *
- * @param {Array|Uint8Array} [mask=[]]
- * mask to use on bytes before comparison.
- *
- * @return {boolean}
- * If all bytes in b are inside of a, taking into account
- * bit masks.
- */
-
- var bytesMatch = function bytesMatch(a, b, _temp3) {
- var _ref3 = _temp3 === void 0 ? {} : _temp3,
- _ref3$offset = _ref3.offset,
- offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
- _ref3$mask = _ref3.mask,
- mask = _ref3$mask === void 0 ? [] : _ref3$mask;
-
- a = toUint8(a);
- b = toUint8(b); // ie 11 does not support uint8 every
-
- var fn = b.every ? b.every : Array.prototype.every;
- return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
- fn.call(b, function (bByte, i) {
- var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
- return bByte === aByte;
- });
- };
-
- var ID3 = toUint8([0x49, 0x44, 0x33]);
- var getId3Size = function getId3Size(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = toUint8(bytes);
- var flags = bytes[offset + 5];
- var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
- var footerPresent = (flags & 16) >> 4;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
- };
- var getId3Offset = function getId3Offset(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = toUint8(bytes);
-
- if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
- offset: offset
- })) {
- return offset;
- }
-
- offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
- // have multiple ID3 tag sections even though
- // they should not.
-
- return getId3Offset(bytes, offset);
- };
-
- var normalizePath$1 = function normalizePath(path) {
- if (typeof path === 'string') {
- return stringToBytes(path);
- }
-
- if (typeof path === 'number') {
- return path;
- }
-
- return path;
- };
-
- var normalizePaths$1 = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath$1(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath$1(p);
- });
- };
- /**
- * find any number of boxes by name given a path to it in an iso bmff
- * such as mp4.
- *
- * @param {TypedArray} bytes
- * bytes for the iso bmff to search for boxes in
- *
- * @param {Uint8Array[]|string[]|string|Uint8Array} name
- * An array of paths or a single path representing the name
- * of boxes to search through in bytes. Paths may be
- * uint8 (character codes) or strings.
- *
- * @param {boolean} [complete=false]
- * Should we search only for complete boxes on the final path.
- * This is very useful when you do not want to get back partial boxes
- * in the case of streaming files.
- *
- * @return {Uint8Array[]}
- * An array of the end paths that we found.
- */
-
- var findBox = function findBox(bytes, paths, complete) {
- if (complete === void 0) {
- complete = false;
- }
-
- paths = normalizePaths$1(paths);
- bytes = toUint8(bytes);
- var results = [];
-
- if (!paths.length) {
- // short-circuit the search for empty paths
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
- var type = bytes.subarray(i + 4, i + 8); // invalid box format.
-
- if (size === 0) {
- break;
- }
-
- var end = i + size;
-
- if (end > bytes.length) {
- // this box is bigger than the number of bytes we have
- // and complete is set, we cannot find any more boxes.
- if (complete) {
- break;
- }
-
- end = bytes.length;
- }
-
- var data = bytes.subarray(i + 8, end);
-
- if (bytesMatch(type, paths[0])) {
- if (paths.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next box along the path
- results.push.apply(results, findBox(data, paths.slice(1), complete));
- }
- }
-
- i = end;
- } // we've finished searching all of bytes
-
-
- return results;
- };
-
- // https://matroska-org.github.io/libebml/specs.html
- // https://www.matroska.org/technical/elements.html
- // https://www.webmproject.org/docs/container/
-
- var EBML_TAGS = {
- EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
- DocType: toUint8([0x42, 0x82]),
- Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
- SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
- Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
- Track: toUint8([0xAE]),
- TrackNumber: toUint8([0xd7]),
- DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
- TrackEntry: toUint8([0xAE]),
- TrackType: toUint8([0x83]),
- FlagDefault: toUint8([0x88]),
- CodecID: toUint8([0x86]),
- CodecPrivate: toUint8([0x63, 0xA2]),
- VideoTrack: toUint8([0xe0]),
- AudioTrack: toUint8([0xe1]),
- // Not used yet, but will be used for live webm/mkv
- // see https://www.matroska.org/technical/basics.html#block-structure
- // see https://www.matroska.org/technical/basics.html#simpleblock-structure
- Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
- Timestamp: toUint8([0xE7]),
- TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
- BlockGroup: toUint8([0xA0]),
- BlockDuration: toUint8([0x9B]),
- Block: toUint8([0xA1]),
- SimpleBlock: toUint8([0xA3])
- };
- /**
- * This is a simple table to determine the length
- * of things in ebml. The length is one based (starts at 1,
- * rather than zero) and for every zero bit before a one bit
- * we add one to length. We also need this table because in some
- * case we have to xor all the length bits from another value.
- */
-
- var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
-
- var getLength = function getLength(byte) {
- var len = 1;
-
- for (var i = 0; i < LENGTH_TABLE.length; i++) {
- if (byte & LENGTH_TABLE[i]) {
- break;
- }
-
- len++;
- }
-
- return len;
- }; // length in ebml is stored in the first 4 to 8 bits
- // of the first byte. 4 for the id length and 8 for the
- // data size length. Length is measured by converting the number to binary
- // then 1 + the number of zeros before a 1 is encountered starting
- // from the left.
-
-
- var getvint = function getvint(bytes, offset, removeLength, signed) {
- if (removeLength === void 0) {
- removeLength = true;
- }
-
- if (signed === void 0) {
- signed = false;
- }
-
- var length = getLength(bytes[offset]);
- var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
- // as they will be modified below to remove the dataSizeLen bits and we do not
- // want to modify the original data. normally we could just call slice on
- // uint8array but ie 11 does not support that...
-
- if (removeLength) {
- valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
- valueBytes[0] ^= LENGTH_TABLE[length - 1];
- }
-
- return {
- length: length,
- value: bytesToNumber(valueBytes, {
- signed: signed
- }),
- bytes: valueBytes
- };
- };
-
- var normalizePath = function normalizePath(path) {
- if (typeof path === 'string') {
- return path.match(/.{1,2}/g).map(function (p) {
- return normalizePath(p);
- });
- }
-
- if (typeof path === 'number') {
- return numberToBytes(path);
- }
-
- return path;
- };
-
- var normalizePaths = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath(p);
- });
- };
-
- var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
- if (offset >= bytes.length) {
- return bytes.length;
- }
-
- var innerid = getvint(bytes, offset, false);
-
- if (bytesMatch(id.bytes, innerid.bytes)) {
- return offset;
- }
-
- var dataHeader = getvint(bytes, offset + innerid.length);
- return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
- };
- /**
- * Notes on the EBLM format.
- *
- * EBLM uses "vints" tags. Every vint tag contains
- * two parts
- *
- * 1. The length from the first byte. You get this by
- * converting the byte to binary and counting the zeros
- * before a 1. Then you add 1 to that. Examples
- * 00011111 = length 4 because there are 3 zeros before a 1.
- * 00100000 = length 3 because there are 2 zeros before a 1.
- * 00000011 = length 7 because there are 6 zeros before a 1.
- *
- * 2. The bits used for length are removed from the first byte
- * Then all the bytes are merged into a value. NOTE: this
- * is not the case for id ebml tags as there id includes
- * length bits.
- *
- */
-
-
- var findEbml = function findEbml(bytes, paths) {
- paths = normalizePaths(paths);
- bytes = toUint8(bytes);
- var results = [];
-
- if (!paths.length) {
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var id = getvint(bytes, i, false);
- var dataHeader = getvint(bytes, i + id.length);
- var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
-
- if (dataHeader.value === 0x7f) {
- dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
-
- if (dataHeader.value !== bytes.length) {
- dataHeader.value -= dataStart;
- }
- }
-
- var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
- var data = bytes.subarray(dataStart, dataEnd);
-
- if (bytesMatch(paths[0], id.bytes)) {
- if (paths.length === 1) {
- // this is the end of the paths and we've found the tag we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next tag inside of the data
- // of this one
- results = results.concat(findEbml(data, paths.slice(1)));
- }
- }
-
- var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
-
- i += totalLength;
- }
-
- return results;
- }; // see https://www.matroska.org/technical/basics.html#block-structure
-
- var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
- var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
- var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
- /**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- *
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
- var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
- var positions = [];
- var i = 1; // Find all `Emulation Prevention Bytes`
-
- while (i < bytes.length - 2) {
- if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
- positions.push(i + 2);
- i++;
- }
-
- i++;
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (positions.length === 0) {
- return bytes;
- } // Create a new array to hold the NAL unit data
-
-
- var newLength = bytes.length - positions.length;
- var newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === positions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- positions.shift();
- }
-
- newData[i] = bytes[sourceIndex];
- }
-
- return newData;
- };
- var findNal = function findNal(bytes, dataType, types, nalLimit) {
- if (nalLimit === void 0) {
- nalLimit = Infinity;
- }
-
- bytes = toUint8(bytes);
- types = [].concat(types);
- var i = 0;
- var nalStart;
- var nalsFound = 0; // keep searching until:
- // we reach the end of bytes
- // we reach the maximum number of nals they want to seach
- // NOTE: that we disregard nalLimit when we have found the start
- // of the nal we want so that we can find the end of the nal we want.
-
- while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
- var nalOffset = void 0;
-
- if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
- nalOffset = 4;
- } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
- nalOffset = 3;
- } // we are unsynced,
- // find the next nal unit
-
-
- if (!nalOffset) {
- i++;
- continue;
- }
-
- nalsFound++;
-
- if (nalStart) {
- return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
- }
-
- var nalType = void 0;
-
- if (dataType === 'h264') {
- nalType = bytes[i + nalOffset] & 0x1f;
- } else if (dataType === 'h265') {
- nalType = bytes[i + nalOffset] >> 1 & 0x3f;
- }
-
- if (types.indexOf(nalType) !== -1) {
- nalStart = i + nalOffset;
- } // nal header is 1 length for h264, and 2 for h265
-
-
- i += nalOffset + (dataType === 'h264' ? 1 : 2);
- }
-
- return bytes.subarray(0, 0);
- };
- var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h264', type, nalLimit);
- };
- var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h265', type, nalLimit);
- };
-
- var CONSTANTS = {
- // "webm" string literal in hex
- 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
- // "matroska" string literal in hex
- 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
- // "fLaC" string literal in hex
- 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
- // "OggS" string literal in hex
- 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
- // ac-3 sync byte, also works for ec-3 as that is simply a codec
- // of ac-3
- 'ac3': toUint8([0x0b, 0x77]),
- // "RIFF" string literal in hex used for wav and avi
- 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
- // "AVI" string literal in hex
- 'avi': toUint8([0x41, 0x56, 0x49]),
- // "WAVE" string literal in hex
- 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
- // "ftyp3g" string literal in hex
- '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
- // "ftyp" string literal in hex
- 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
- // "styp" string literal in hex
- 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
- // "ftyp" string literal in hex
- 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74])
- };
- var _isLikely = {
- aac: function aac(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, [0xFF, 0x10], {
- offset: offset,
- mask: [0xFF, 0x16]
- });
- },
- mp3: function mp3(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, [0xFF, 0x02], {
- offset: offset,
- mask: [0xFF, 0x06]
- });
- },
- webm: function webm(bytes) {
- var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
-
- return bytesMatch(docType, CONSTANTS.webm);
- },
- mkv: function mkv(bytes) {
- var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
-
- return bytesMatch(docType, CONSTANTS.matroska);
- },
- mp4: function mp4(bytes) {
- return !_isLikely['3gp'](bytes) && !_isLikely.mov(bytes) && (bytesMatch(bytes, CONSTANTS.mp4, {
- offset: 4
- }) || bytesMatch(bytes, CONSTANTS.fmp4, {
- offset: 4
- }));
- },
- mov: function mov(bytes) {
- return bytesMatch(bytes, CONSTANTS.mov, {
- offset: 4
- });
- },
- '3gp': function gp(bytes) {
- return bytesMatch(bytes, CONSTANTS['3gp'], {
- offset: 4
- });
- },
- ac3: function ac3(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, CONSTANTS.ac3, {
- offset: offset
- });
- },
- ts: function ts(bytes) {
- if (bytes.length < 189 && bytes.length >= 1) {
- return bytes[0] === 0x47;
- }
-
- var i = 0; // check the first 376 bytes for two matching sync bytes
-
- while (i + 188 < bytes.length && i < 188) {
- if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
- return true;
- }
-
- i += 1;
- }
-
- return false;
- },
- flac: function flac(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, CONSTANTS.flac, {
- offset: offset
- });
- },
- ogg: function ogg(bytes) {
- return bytesMatch(bytes, CONSTANTS.ogg);
- },
- avi: function avi(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
- offset: 8
- });
- },
- wav: function wav(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
- offset: 8
- });
- },
- 'h264': function h264(bytes) {
- // find seq_parameter_set_rbsp
- return findH264Nal(bytes, 7, 3).length;
- },
- 'h265': function h265(bytes) {
- // find video_parameter_set_rbsp or seq_parameter_set_rbsp
- return findH265Nal(bytes, [32, 33], 3).length;
- }
- }; // get all the isLikely functions
- // but make sure 'ts' is above h264 and h265
- // but below everything else as it is the least specific
-
- var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
- .filter(function (t) {
- return t !== 'ts' && t !== 'h264' && t !== 'h265';
- }) // add it back to the bottom
- .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
-
- isLikelyTypes.forEach(function (type) {
- var isLikelyFn = _isLikely[type];
-
- _isLikely[type] = function (bytes) {
- return isLikelyFn(toUint8(bytes));
- };
- }); // export after wrapping
-
- var isLikely = _isLikely; // A useful list of file signatures can be found here
- // https://en.wikipedia.org/wiki/List_of_file_signatures
-
- var detectContainerForBytes = function detectContainerForBytes(bytes) {
- bytes = toUint8(bytes);
-
- for (var i = 0; i < isLikelyTypes.length; i++) {
- var type = isLikelyTypes[i];
-
- if (isLikely[type](bytes)) {
- return type;
- }
- }
-
- return '';
- }; // fmp4 is not a container
-
- var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
- return findBox(bytes, ['moof']).length > 0;
- };
-
- // which will only happen if the request is complete.
-
- var callbackOnCompleted = function callbackOnCompleted(request, cb) {
- if (request.readyState === 4) {
- return cb();
- }
-
- return;
- };
-
- var containerRequest = function containerRequest(uri, xhr, cb) {
- var bytes = [];
- var id3Offset;
- var finished = false;
-
- var endRequestAndCallback = function endRequestAndCallback(err, req, type, _bytes) {
- req.abort();
- finished = true;
- return cb(err, req, type, _bytes);
- };
-
- var progressListener = function progressListener(error, request) {
- if (finished) {
- return;
- }
-
- if (error) {
- return endRequestAndCallback(error, request, '', bytes);
- } // grap the new part of content that was just downloaded
-
-
- var newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
-
- bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
- id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
- // or we need at least two bytes after an id3Offset
-
- if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- }
-
- var type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
- // to see the second sync byte, wait until we have enough data
- // before declaring it ts
-
- if (type === 'ts' && bytes.length < 188) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- } // this may be an unsynced ts segment
- // wait for 376 bytes before detecting no container
-
-
- if (!type && bytes.length < 376) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- }
-
- return endRequestAndCallback(null, request, type, bytes);
- };
-
- var options = {
- uri: uri,
- beforeSend: function beforeSend(request) {
- // this forces the browser to pass the bytes to us unprocessed
- request.overrideMimeType('text/plain; charset=x-user-defined');
- request.addEventListener('progress', function (_ref) {
- _ref.total;
- _ref.loaded;
- return callbackWrapper(request, null, {
- statusCode: request.status
- }, progressListener);
- });
- }
- };
- var request = xhr(options, function (error, response) {
- return callbackWrapper(request, error, response, progressListener);
- });
- return request;
- };
-
- var EventTarget = videojs__default['default'].EventTarget,
- mergeOptions = videojs__default['default'].mergeOptions;
-
- var dashPlaylistUnchanged = function dashPlaylistUnchanged(a, b) {
- if (!isPlaylistUnchanged(a, b)) {
- return false;
- } // for dash the above check will often return true in scenarios where
- // the playlist actually has changed because mediaSequence isn't a
- // dash thing, and we often set it to 1. So if the playlists have the same amount
- // of segments we return true.
- // So for dash we need to make sure that the underlying segments are different.
- // if sidx changed then the playlists are different.
-
-
- if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
- return false;
- } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
- return false;
- } // one or the other does not have segments
- // there was a change.
-
-
- if (a.segments && !b.segments || !a.segments && b.segments) {
- return false;
- } // neither has segments nothing changed
-
-
- if (!a.segments && !b.segments) {
- return true;
- } // check segments themselves
-
-
- for (var i = 0; i < a.segments.length; i++) {
- var aSegment = a.segments[i];
- var bSegment = b.segments[i]; // if uris are different between segments there was a change
-
- if (aSegment.uri !== bSegment.uri) {
- return false;
- } // neither segment has a byterange, there will be no byterange change.
-
-
- if (!aSegment.byterange && !bSegment.byterange) {
- continue;
- }
-
- var aByterange = aSegment.byterange;
- var bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
-
- if (aByterange && !bByterange || !aByterange && bByterange) {
- return false;
- } // if both segments have byterange with different offsets, there was a change.
-
-
- if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
- return false;
- }
- } // if everything was the same with segments, this is the same playlist.
-
-
- return true;
- };
- /**
- * Parses the master XML string and updates playlist URI references.
- *
- * @param {Object} config
- * Object of arguments
- * @param {string} config.masterXml
- * The mpd XML
- * @param {string} config.srcUrl
- * The mpd URL
- * @param {Date} config.clientOffset
- * A time difference between server and client
- * @param {Object} config.sidxMapping
- * SIDX mappings for moof/mdat URIs and byte ranges
- * @return {Object}
- * The parsed mpd manifest object
- */
-
-
- var parseMasterXml = function parseMasterXml(_ref) {
- var masterXml = _ref.masterXml,
- srcUrl = _ref.srcUrl,
- clientOffset = _ref.clientOffset,
- sidxMapping = _ref.sidxMapping;
- var master = parse(masterXml, {
- manifestUri: srcUrl,
- clientOffset: clientOffset,
- sidxMapping: sidxMapping
- });
- addPropertiesToMaster(master, srcUrl);
- return master;
- };
- /**
- * Returns a new master manifest that is the result of merging an updated master manifest
- * into the original version.
- *
- * @param {Object} oldMaster
- * The old parsed mpd object
- * @param {Object} newMaster
- * The updated parsed mpd object
- * @return {Object}
- * A new object representing the original master manifest with the updated media
- * playlists merged in
- */
-
- var updateMaster = function updateMaster(oldMaster, newMaster, sidxMapping) {
- var noChanges = true;
- var update = mergeOptions(oldMaster, {
- // These are top level properties that can be updated
- duration: newMaster.duration,
- minimumUpdatePeriod: newMaster.minimumUpdatePeriod
- }); // First update the playlists in playlist list
-
- for (var i = 0; i < newMaster.playlists.length; i++) {
- var playlist = newMaster.playlists[i];
-
- if (playlist.sidx) {
- var sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
-
- if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
- addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
- }
- }
-
- var playlistUpdate = updateMaster$1(update, playlist, dashPlaylistUnchanged);
-
- if (playlistUpdate) {
- update = playlistUpdate;
- noChanges = false;
- }
- } // Then update media group playlists
-
-
- forEachMediaGroup(newMaster, function (properties, type, group, label) {
- if (properties.playlists && properties.playlists.length) {
- var id = properties.playlists[0].id;
-
- var _playlistUpdate = updateMaster$1(update, properties.playlists[0], dashPlaylistUnchanged);
-
- if (_playlistUpdate) {
- update = _playlistUpdate; // update the playlist reference within media groups
-
- update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
- noChanges = false;
- }
- }
- });
-
- if (newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
- noChanges = false;
- }
-
- if (noChanges) {
- return null;
- }
-
- return update;
- }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
- // If the SIDXs have maps, the two maps should match,
- // both `a` and `b` missing SIDXs is considered matching.
- // If `a` or `b` but not both have a map, they aren't matching.
-
- var equivalentSidx = function equivalentSidx(a, b) {
- var neitherMap = Boolean(!a.map && !b.map);
- var equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
- return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
- }; // exported for testing
-
-
- var compareSidxEntry = function compareSidxEntry(playlists, oldSidxMapping) {
- var newSidxMapping = {};
-
- for (var id in playlists) {
- var playlist = playlists[id];
- var currentSidxInfo = playlist.sidx;
-
- if (currentSidxInfo) {
- var key = generateSidxKey(currentSidxInfo);
-
- if (!oldSidxMapping[key]) {
- break;
- }
-
- var savedSidxInfo = oldSidxMapping[key].sidxInfo;
-
- if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
- newSidxMapping[key] = oldSidxMapping[key];
- }
- }
- }
-
- return newSidxMapping;
- };
- /**
- * A function that filters out changed items as they need to be requested separately.
- *
- * The method is exported for testing
- *
- * @param {Object} master the parsed mpd XML returned via mpd-parser
- * @param {Object} oldSidxMapping the SIDX to compare against
- */
-
- var filterChangedSidxMappings = function filterChangedSidxMappings(master, oldSidxMapping) {
- var videoSidx = compareSidxEntry(master.playlists, oldSidxMapping);
- var mediaGroupSidx = videoSidx;
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- if (properties.playlists && properties.playlists.length) {
- var playlists = properties.playlists;
- mediaGroupSidx = mergeOptions(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
- }
- });
- return mediaGroupSidx;
- };
-
- var DashPlaylistLoader = /*#__PURE__*/function (_EventTarget) {
- inheritsLoose(DashPlaylistLoader, _EventTarget);
-
- // DashPlaylistLoader must accept either a src url or a playlist because subsequent
- // playlist loader setups from media groups will expect to be able to pass a playlist
- // (since there aren't external URLs to media playlists with DASH)
- function DashPlaylistLoader(srcUrlOrPlaylist, vhs, options, masterPlaylistLoader) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _EventTarget.call(this) || this;
- _this.masterPlaylistLoader_ = masterPlaylistLoader || assertThisInitialized(_this);
-
- if (!masterPlaylistLoader) {
- _this.isMaster_ = true;
- }
-
- var _options = options,
- _options$withCredenti = _options.withCredentials,
- withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
- _options$handleManife = _options.handleManifestRedirects,
- handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
- _this.vhs_ = vhs;
- _this.withCredentials = withCredentials;
- _this.handleManifestRedirects = handleManifestRedirects;
-
- if (!srcUrlOrPlaylist) {
- throw new Error('A non-empty playlist URL or object is required');
- } // event naming?
-
-
- _this.on('minimumUpdatePeriod', function () {
- _this.refreshXml_();
- }); // live playlist staleness timeout
-
-
- _this.on('mediaupdatetimeout', function () {
- _this.refreshMedia_(_this.media().id);
- });
-
- _this.state = 'HAVE_NOTHING';
- _this.loadedPlaylists_ = {};
- _this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
- // The masterPlaylistLoader will be created with a string
-
- if (_this.isMaster_) {
- _this.masterPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
- // once multi-period is refactored
-
- _this.masterPlaylistLoader_.sidxMapping_ = {};
- } else {
- _this.childPlaylist_ = srcUrlOrPlaylist;
- }
-
- return _this;
- }
-
- var _proto = DashPlaylistLoader.prototype;
-
- _proto.requestErrored_ = function requestErrored_(err, request, startingState) {
- // disposed
- if (!this.request) {
- return true;
- } // pending request is cleared
-
-
- this.request = null;
-
- if (err) {
- // use the provided error object or create one
- // based on the request/response
- this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
- status: request.status,
- message: 'DASH request error at URL: ' + request.uri,
- response: request.response,
- // MEDIA_ERR_NETWORK
- code: 2
- };
-
- if (startingState) {
- this.state = startingState;
- }
-
- this.trigger('error');
- return true;
- }
- }
- /**
- * Verify that the container of the sidx segment can be parsed
- * and if it can, get and parse that segment.
- */
- ;
-
- _proto.addSidxSegments_ = function addSidxSegments_(playlist, startingState, cb) {
- var _this2 = this;
-
- var sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
-
- if (!playlist.sidx || !sidxKey || this.masterPlaylistLoader_.sidxMapping_[sidxKey]) {
- // keep this function async
- this.mediaRequest_ = window__default['default'].setTimeout(function () {
- return cb(false);
- }, 0);
- return;
- } // resolve the segment URL relative to the playlist
-
-
- var uri = resolveManifestRedirect(this.handleManifestRedirects, playlist.sidx.resolvedUri);
-
- var fin = function fin(err, request) {
- if (_this2.requestErrored_(err, request, startingState)) {
- return;
- }
-
- var sidxMapping = _this2.masterPlaylistLoader_.sidxMapping_;
- var sidx;
-
- try {
- sidx = parseSidx_1(toUint8(request.response).subarray(8));
- } catch (e) {
- // sidx parsing failed.
- _this2.requestErrored_(e, request, startingState);
-
- return;
- }
-
- sidxMapping[sidxKey] = {
- sidxInfo: playlist.sidx,
- sidx: sidx
- };
- addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
- return cb(true);
- };
-
- this.request = containerRequest(uri, this.vhs_.xhr, function (err, request, container, bytes) {
- if (err) {
- return fin(err, request);
- }
-
- if (!container || container !== 'mp4') {
- return fin({
- status: request.status,
- message: "Unsupported " + (container || 'unknown') + " container type for sidx segment at URL: " + uri,
- // response is just bytes in this case
- // but we really don't want to return that.
- response: '',
- playlist: playlist,
- internal: true,
- blacklistDuration: Infinity,
- // MEDIA_ERR_NETWORK
- code: 2
- }, request);
- } // if we already downloaded the sidx bytes in the container request, use them
-
-
- var _playlist$sidx$bytera = playlist.sidx.byterange,
- offset = _playlist$sidx$bytera.offset,
- length = _playlist$sidx$bytera.length;
-
- if (bytes.length >= length + offset) {
- return fin(err, {
- response: bytes.subarray(offset, offset + length),
- status: request.status,
- uri: request.uri
- });
- } // otherwise request sidx bytes
-
-
- _this2.request = _this2.vhs_.xhr({
- uri: uri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders({
- byterange: playlist.sidx.byterange
- })
- }, fin);
- });
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.stopRequest();
- this.loadedPlaylists_ = {};
- window__default['default'].clearTimeout(this.minimumUpdatePeriodTimeout_);
- window__default['default'].clearTimeout(this.mediaRequest_);
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- this.mediaRequest_ = null;
- this.minimumUpdatePeriodTimeout_ = null;
-
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
-
- this.off();
- };
-
- _proto.hasPendingRequest = function hasPendingRequest() {
- return this.request || this.mediaRequest_;
- };
-
- _proto.stopRequest = function stopRequest() {
- if (this.request) {
- var oldRequest = this.request;
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- };
-
- _proto.media = function media(playlist) {
- var _this3 = this;
-
- // getter
- if (!playlist) {
- return this.media_;
- } // setter
-
-
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- }
-
- var startingState = this.state; // find the playlist object if the target playlist has been specified by URI
-
- if (typeof playlist === 'string') {
- if (!this.masterPlaylistLoader_.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
-
- playlist = this.masterPlaylistLoader_.master.playlists[playlist];
- }
-
- var mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
-
- if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
- this.state = 'HAVE_METADATA';
- this.media_ = playlist; // trigger media change if the active media has been updated
-
- if (mediaChange) {
- this.trigger('mediachanging');
- this.trigger('mediachange');
- }
-
- return;
- } // switching to the active playlist is a no-op
-
-
- if (!mediaChange) {
- return;
- } // switching from an already loaded playlist
-
-
- if (this.media_) {
- this.trigger('mediachanging');
- }
-
- this.addSidxSegments_(playlist, startingState, function (sidxChanged) {
- // everything is ready just continue to haveMetadata
- _this3.haveMetadata({
- startingState: startingState,
- playlist: playlist
- });
- });
- };
-
- _proto.haveMetadata = function haveMetadata(_ref2) {
- var startingState = _ref2.startingState,
- playlist = _ref2.playlist;
- this.state = 'HAVE_METADATA';
- this.loadedPlaylists_[playlist.id] = playlist;
- this.mediaRequest_ = null; // This will trigger loadedplaylist
-
- this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
- // to resolve setup of media groups
-
- if (startingState === 'HAVE_MASTER') {
- this.trigger('loadedmetadata');
- } else {
- // trigger media change if the active media has been updated
- this.trigger('mediachange');
- }
- };
-
- _proto.pause = function pause() {
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
-
- this.stopRequest();
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
-
- if (this.isMaster_) {
- window__default['default'].clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_);
- this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
- }
-
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- }
- };
-
- _proto.load = function load(isFinalRendition) {
- var _this4 = this;
-
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- var media = this.media();
-
- if (isFinalRendition) {
- var delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
- this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- return _this4.load();
- }, delay);
- return;
- } // because the playlists are internal to the manifest, load should either load the
- // main manifest, or do nothing but trigger an event
-
-
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- // Check to see if this is the master loader and the MUP was cleared (this happens
- // when the loader was paused). `media` should be set at this point since one is always
- // set during `start()`.
- if (this.isMaster_ && !this.minimumUpdatePeriodTimeout_) {
- // Trigger minimumUpdatePeriod to refresh the master manifest
- this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
-
- this.updateMinimumUpdatePeriodTimeout_();
- }
-
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- };
-
- _proto.start = function start() {
- var _this5 = this;
-
- this.started = true; // We don't need to request the master manifest again
- // Call this asynchronously to match the xhr request behavior below
-
- if (!this.isMaster_) {
- this.mediaRequest_ = window__default['default'].setTimeout(function () {
- return _this5.haveMaster_();
- }, 0);
- return;
- }
-
- this.requestMaster_(function (req, masterChanged) {
- _this5.haveMaster_();
-
- if (!_this5.hasPendingRequest() && !_this5.media_) {
- _this5.media(_this5.masterPlaylistLoader_.master.playlists[0]);
- }
- });
- };
-
- _proto.requestMaster_ = function requestMaster_(cb) {
- var _this6 = this;
-
- this.request = this.vhs_.xhr({
- uri: this.masterPlaylistLoader_.srcUrl,
- withCredentials: this.withCredentials
- }, function (error, req) {
- if (_this6.requestErrored_(error, req)) {
- if (_this6.state === 'HAVE_NOTHING') {
- _this6.started = false;
- }
-
- return;
- }
-
- var masterChanged = req.responseText !== _this6.masterPlaylistLoader_.masterXml_;
- _this6.masterPlaylistLoader_.masterXml_ = req.responseText;
-
- if (req.responseHeaders && req.responseHeaders.date) {
- _this6.masterLoaded_ = Date.parse(req.responseHeaders.date);
- } else {
- _this6.masterLoaded_ = Date.now();
- }
-
- _this6.masterPlaylistLoader_.srcUrl = resolveManifestRedirect(_this6.handleManifestRedirects, _this6.masterPlaylistLoader_.srcUrl, req);
-
- if (masterChanged) {
- _this6.handleMaster_();
-
- _this6.syncClientServerClock_(function () {
- return cb(req, masterChanged);
- });
-
- return;
- }
-
- return cb(req, masterChanged);
- });
- }
- /**
- * Parses the master xml for UTCTiming node to sync the client clock to the server
- * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
- *
- * @param {Function} done
- * Function to call when clock sync has completed
- */
- ;
-
- _proto.syncClientServerClock_ = function syncClientServerClock_(done) {
- var _this7 = this;
-
- var utcTiming = parseUTCTiming(this.masterPlaylistLoader_.masterXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
- // server clock
-
- if (utcTiming === null) {
- this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
- return done();
- }
-
- if (utcTiming.method === 'DIRECT') {
- this.masterPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
- return done();
- }
-
- this.request = this.vhs_.xhr({
- uri: resolveUrl(this.masterPlaylistLoader_.srcUrl, utcTiming.value),
- method: utcTiming.method,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this7.request) {
- return;
- }
-
- if (error) {
- // sync request failed, fall back to using date header from mpd
- // TODO: log warning
- _this7.masterPlaylistLoader_.clientOffset_ = _this7.masterLoaded_ - Date.now();
- return done();
- }
-
- var serverTime;
-
- if (utcTiming.method === 'HEAD') {
- if (!req.responseHeaders || !req.responseHeaders.date) {
- // expected date header not preset, fall back to using date header from mpd
- // TODO: log warning
- serverTime = _this7.masterLoaded_;
- } else {
- serverTime = Date.parse(req.responseHeaders.date);
- }
- } else {
- serverTime = Date.parse(req.responseText);
- }
-
- _this7.masterPlaylistLoader_.clientOffset_ = serverTime - Date.now();
- done();
- });
- };
-
- _proto.haveMaster_ = function haveMaster_() {
- this.state = 'HAVE_MASTER';
-
- if (this.isMaster_) {
- // We have the master playlist at this point, so
- // trigger this to allow MasterPlaylistController
- // to make an initial playlist selection
- this.trigger('loadedplaylist');
- } else if (!this.media_) {
- // no media playlist was specifically selected so select
- // the one the child playlist loader was created with
- this.media(this.childPlaylist_);
- }
- };
-
- _proto.handleMaster_ = function handleMaster_() {
- // clear media request
- this.mediaRequest_ = null;
- var newMaster = parseMasterXml({
- masterXml: this.masterPlaylistLoader_.masterXml_,
- srcUrl: this.masterPlaylistLoader_.srcUrl,
- clientOffset: this.masterPlaylistLoader_.clientOffset_,
- sidxMapping: this.masterPlaylistLoader_.sidxMapping_
- });
- var oldMaster = this.masterPlaylistLoader_.master; // if we have an old master to compare the new master against
-
- if (oldMaster) {
- newMaster = updateMaster(oldMaster, newMaster, this.masterPlaylistLoader_.sidxMapping_);
- } // only update master if we have a new master
-
-
- this.masterPlaylistLoader_.master = newMaster ? newMaster : oldMaster;
- var location = this.masterPlaylistLoader_.master.locations && this.masterPlaylistLoader_.master.locations[0];
-
- if (location && location !== this.masterPlaylistLoader_.srcUrl) {
- this.masterPlaylistLoader_.srcUrl = location;
- }
-
- if (!oldMaster || newMaster && newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
- this.updateMinimumUpdatePeriodTimeout_();
- }
-
- return Boolean(newMaster);
- };
-
- _proto.updateMinimumUpdatePeriodTimeout_ = function updateMinimumUpdatePeriodTimeout_() {
- var mpl = this.masterPlaylistLoader_; // cancel any pending creation of mup on media
- // a new one will be added if needed.
-
- if (mpl.createMupOnMedia_) {
- mpl.off('loadedmetadata', mpl.createMupOnMedia_);
- mpl.createMupOnMedia_ = null;
- } // clear any pending timeouts
-
-
- if (mpl.minimumUpdatePeriodTimeout_) {
- window__default['default'].clearTimeout(mpl.minimumUpdatePeriodTimeout_);
- mpl.minimumUpdatePeriodTimeout_ = null;
- }
-
- var mup = mpl.master && mpl.master.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
- // MPD has no future validity, so a new one will need to be acquired when new
- // media segments are to be made available. Thus, we use the target duration
- // in this case
-
- if (mup === 0) {
- if (mpl.media()) {
- mup = mpl.media().targetDuration * 1000;
- } else {
- mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
- mpl.one('loadedmetadata', mpl.createMupOnMedia_);
- }
- } // if minimumUpdatePeriod is invalid or <= zero, which
- // can happen when a live video becomes VOD. skip timeout
- // creation.
-
-
- if (typeof mup !== 'number' || mup <= 0) {
- if (mup < 0) {
- this.logger_("found invalid minimumUpdatePeriod of " + mup + ", not setting a timeout");
- }
-
- return;
- }
-
- this.createMUPTimeout_(mup);
- };
-
- _proto.createMUPTimeout_ = function createMUPTimeout_(mup) {
- var mpl = this.masterPlaylistLoader_;
- mpl.minimumUpdatePeriodTimeout_ = window__default['default'].setTimeout(function () {
- mpl.minimumUpdatePeriodTimeout_ = null;
- mpl.trigger('minimumUpdatePeriod');
- mpl.createMUPTimeout_(mup);
- }, mup);
- }
- /**
- * Sends request to refresh the master xml and updates the parsed master manifest
- */
- ;
-
- _proto.refreshXml_ = function refreshXml_() {
- var _this8 = this;
-
- this.requestMaster_(function (req, masterChanged) {
- if (!masterChanged) {
- return;
- }
-
- if (_this8.media_) {
- _this8.media_ = _this8.masterPlaylistLoader_.master.playlists[_this8.media_.id];
- } // This will filter out updated sidx info from the mapping
-
-
- _this8.masterPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(_this8.masterPlaylistLoader_.master, _this8.masterPlaylistLoader_.sidxMapping_);
-
- _this8.addSidxSegments_(_this8.media(), _this8.state, function (sidxChanged) {
- // TODO: do we need to reload the current playlist?
- _this8.refreshMedia_(_this8.media().id);
- });
- });
- }
- /**
- * Refreshes the media playlist by re-parsing the master xml and updating playlist
- * references. If this is an alternate loader, the updated parsed manifest is retrieved
- * from the master loader.
- */
- ;
-
- _proto.refreshMedia_ = function refreshMedia_(mediaID) {
- var _this9 = this;
-
- if (!mediaID) {
- throw new Error('refreshMedia_ must take a media id');
- } // for master we have to reparse the master xml
- // to re-create segments based on current timing values
- // which may change media. We only skip updating master
- // if this is the first time this.media_ is being set.
- // as master was just parsed in that case.
-
-
- if (this.media_ && this.isMaster_) {
- this.handleMaster_();
- }
-
- var playlists = this.masterPlaylistLoader_.master.playlists;
- var mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
-
- if (mediaChanged) {
- this.media_ = playlists[mediaID];
- } else {
- this.trigger('playlistunchanged');
- }
-
- if (!this.mediaUpdateTimeout) {
- var createMediaUpdateTimeout = function createMediaUpdateTimeout() {
- if (_this9.media().endList) {
- return;
- }
-
- _this9.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- _this9.trigger('mediaupdatetimeout');
-
- createMediaUpdateTimeout();
- }, refreshDelay(_this9.media(), Boolean(mediaChanged)));
- };
-
- createMediaUpdateTimeout();
- }
-
- this.trigger('loadedplaylist');
- };
-
- return DashPlaylistLoader;
- }(EventTarget);
-
- var Config = {
- GOAL_BUFFER_LENGTH: 30,
- MAX_GOAL_BUFFER_LENGTH: 60,
- BACK_BUFFER_LENGTH: 30,
- GOAL_BUFFER_LENGTH_RATE: 1,
- // 0.5 MB/s
- INITIAL_BANDWIDTH: 4194304,
- // A fudge factor to apply to advertised playlist bitrates to account for
- // temporary flucations in client bandwidth
- BANDWIDTH_VARIANCE: 1.2,
- // How much of the buffer must be filled before we consider upswitching
- BUFFER_LOW_WATER_LINE: 0,
- MAX_BUFFER_LOW_WATER_LINE: 30,
- // TODO: Remove this when experimentalBufferBasedABR is removed
- EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
- BUFFER_LOW_WATER_LINE_RATE: 1,
- // If the buffer is greater than the high water line, we won't switch down
- BUFFER_HIGH_WATER_LINE: 30
- };
-
- var stringToArrayBuffer = function stringToArrayBuffer(string) {
- var view = new Uint8Array(new ArrayBuffer(string.length));
-
- for (var i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view.buffer;
- };
-
- var MockWorker = /*#__PURE__*/function () {
- function MockWorker() {
- this.listeners_ = [];
- this.remote_ = null;
- }
-
- var _proto = MockWorker.prototype;
-
- _proto.addEventListener = function addEventListener(type, fn) {
- if (type !== 'message') {
- return;
- }
-
- this.listeners_.push(fn);
- };
-
- _proto.removeEventListener = function removeEventListener(type, fn) {
- if (type !== 'message') {
- return;
- }
-
- var i = this.listeners_.indexOf(fn);
-
- if (i === -1) {
- return;
- }
-
- this.listeners_.splice(i, 1);
- };
-
- _proto.dispatchEvent = function dispatchEvent(event) {
- if (!event || event.type !== 'message') {
- return;
- }
-
- this.listeners_.forEach(function (fn) {
- fn(event);
- });
- };
-
- _proto.postMessage = function postMessage(data) {
- if (this.remote_) {
- this.remote_.recv_(data);
- }
- };
-
- _proto.recv_ = function recv_(data) {
- // the browser puts the actual message under
- var message = {
- data: data
- };
-
- if (this.onmessage) {
- this.onmessage(message);
- }
-
- this.listeners_.forEach(function (fn) {
- fn(message);
- });
- };
-
- _proto.terminate = function terminate() {
- if (this.remote_) {
- this.remote_.remote_ = null;
- this.remote_.terminate();
- this.remote_ = null;
- }
-
- this.onmessage = null;
- this.listeners_.length = 0;
- };
-
- return MockWorker;
- }();
-
- MockWorker.prototype.on = MockWorker.prototype.addEventListener;
- MockWorker.prototype.off = MockWorker.prototype.removeEventListener;
- var factory = function factory(fn) {
- return function () {
- var client = new MockWorker();
- var worker = new MockWorker();
- client.remote_ = worker;
- worker.remote_ = client;
- fn(worker);
- return client;
- };
- };
- var transform = function transform(fn) {
- // eslint-disable-next-line
- return fn;
- };
-
- /* rollup-plugin-worker-factory start for worker!/Users/gkatsevman/p/http-streaming-release/src/transmuxer-worker.js */
- var workerCode$1 = transform(function (self) {
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * A lightweight readable stream implemention that handles event dispatching.
- * Objects that inherit from streams should call init in their constructors.
- */
-
- var Stream = function Stream() {
- this.init = function () {
- var listeners = {};
- /**
- * Add a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} the callback to be invoked when an event of
- * the specified type occurs
- */
-
- this.on = function (type, listener) {
- if (!listeners[type]) {
- listeners[type] = [];
- }
-
- listeners[type] = listeners[type].concat(listener);
- };
- /**
- * Remove a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} a function previously registered for this
- * type of event through `on`
- */
-
-
- this.off = function (type, listener) {
- var index;
-
- if (!listeners[type]) {
- return false;
- }
-
- index = listeners[type].indexOf(listener);
- listeners[type] = listeners[type].slice();
- listeners[type].splice(index, 1);
- return index > -1;
- };
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- * @param type {string} the event name
- */
-
-
- this.trigger = function (type) {
- var callbacks, i, length, args;
- callbacks = listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- args = [];
- i = arguments.length;
-
- for (i = 1; i < arguments.length; ++i) {
- args.push(arguments[i]);
- }
-
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].apply(this, args);
- }
- }
- };
- /**
- * Destroys the stream and cleans up.
- */
-
-
- this.dispose = function () {
- listeners = {};
- };
- };
- };
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- * @param destination {stream} the stream that will receive all `data` events
- * @param autoFlush {boolean} if false, we will not call `flush` on the destination
- * when the current stream emits a 'done' event
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
-
-
- Stream.prototype.pipe = function (destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- this.on('done', function (flushSource) {
- destination.flush(flushSource);
- });
- this.on('partialdone', function (flushSource) {
- destination.partialFlush(flushSource);
- });
- this.on('endedtimeline', function (flushSource) {
- destination.endTimeline(flushSource);
- });
- this.on('reset', function (flushSource) {
- destination.reset(flushSource);
- });
- return destination;
- }; // Default stream functions that are expected to be overridden to perform
- // actual work. These are provided by the prototype as a sort of no-op
- // implementation so that we don't have to check for their existence in the
- // `pipe` function above.
-
-
- Stream.prototype.push = function (data) {
- this.trigger('data', data);
- };
-
- Stream.prototype.flush = function (flushSource) {
- this.trigger('done', flushSource);
- };
-
- Stream.prototype.partialFlush = function (flushSource) {
- this.trigger('partialdone', flushSource);
- };
-
- Stream.prototype.endTimeline = function (flushSource) {
- this.trigger('endedtimeline', flushSource);
- };
-
- Stream.prototype.reset = function (flushSource) {
- this.trigger('reset', flushSource);
- };
-
- var stream = Stream;
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Functions that generate fragmented MP4s suitable for use with Media
- * Source Extensions.
- */
-
- var UINT32_MAX = Math.pow(2, 32) - 1;
- var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants
-
- (function () {
- var i;
- types = {
- avc1: [],
- // codingname
- avcC: [],
- btrt: [],
- dinf: [],
- dref: [],
- esds: [],
- ftyp: [],
- hdlr: [],
- mdat: [],
- mdhd: [],
- mdia: [],
- mfhd: [],
- minf: [],
- moof: [],
- moov: [],
- mp4a: [],
- // codingname
- mvex: [],
- mvhd: [],
- pasp: [],
- sdtp: [],
- smhd: [],
- stbl: [],
- stco: [],
- stsc: [],
- stsd: [],
- stsz: [],
- stts: [],
- styp: [],
- tfdt: [],
- tfhd: [],
- traf: [],
- trak: [],
- trun: [],
- trex: [],
- tkhd: [],
- vmhd: []
- }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
- // don't throw an error
-
- if (typeof Uint8Array === 'undefined') {
- return;
- }
-
- for (i in types) {
- if (types.hasOwnProperty(i)) {
- types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
- }
- }
-
- MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
- AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
- MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
- VIDEO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
- ]);
- AUDIO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
- ]);
- HDLR_TYPES = {
- video: VIDEO_HDLR,
- audio: AUDIO_HDLR
- };
- DREF = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // entry_count
- 0x00, 0x00, 0x00, 0x0c, // entry_size
- 0x75, 0x72, 0x6c, 0x20, // 'url' type
- 0x00, // version 0
- 0x00, 0x00, 0x01 // entry_flags
- ]);
- SMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, // balance, 0 means centered
- 0x00, 0x00 // reserved
- ]);
- STCO = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00 // entry_count
- ]);
- STSC = STCO;
- STSZ = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // sample_size
- 0x00, 0x00, 0x00, 0x00 // sample_count
- ]);
- STTS = STCO;
- VMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x01, // flags
- 0x00, 0x00, // graphicsmode
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
- ]);
- })();
-
- box = function box(type) {
- var payload = [],
- size = 0,
- i,
- result,
- view;
-
- for (i = 1; i < arguments.length; i++) {
- payload.push(arguments[i]);
- }
-
- i = payload.length; // calculate the total size we need to allocate
-
- while (i--) {
- size += payload[i].byteLength;
- }
-
- result = new Uint8Array(size + 8);
- view = new DataView(result.buffer, result.byteOffset, result.byteLength);
- view.setUint32(0, result.byteLength);
- result.set(type, 4); // copy the payload into the result
-
- for (i = 0, size = 8; i < payload.length; i++) {
- result.set(payload[i], size);
- size += payload[i].byteLength;
- }
-
- return result;
- };
-
- dinf = function dinf() {
- return box(types.dinf, box(types.dref, DREF));
- };
-
- esds = function esds(track) {
- return box(types.esds, new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- // ES_Descriptor
- 0x03, // tag, ES_DescrTag
- 0x19, // length
- 0x00, 0x00, // ES_ID
- 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
- // DecoderConfigDescriptor
- 0x04, // tag, DecoderConfigDescrTag
- 0x11, // length
- 0x40, // object type
- 0x15, // streamType
- 0x00, 0x06, 0x00, // bufferSizeDB
- 0x00, 0x00, 0xda, 0xc0, // maxBitrate
- 0x00, 0x00, 0xda, 0xc0, // avgBitrate
- // DecoderSpecificInfo
- 0x05, // tag, DecoderSpecificInfoTag
- 0x02, // length
- // ISO/IEC 14496-3, AudioSpecificConfig
- // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
- track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
- ]));
- };
-
- ftyp = function ftyp() {
- return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
- };
-
- hdlr = function hdlr(type) {
- return box(types.hdlr, HDLR_TYPES[type]);
- };
-
- mdat = function mdat(data) {
- return box(types.mdat, data);
- };
-
- mdhd = function mdhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x02, // creation_time
- 0x00, 0x00, 0x00, 0x03, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
- 0x55, 0xc4, // 'und' language (undetermined)
- 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
- // defined. The sample rate can be parsed out of an ADTS header, for
- // instance.
-
- if (track.samplerate) {
- result[12] = track.samplerate >>> 24 & 0xFF;
- result[13] = track.samplerate >>> 16 & 0xFF;
- result[14] = track.samplerate >>> 8 & 0xFF;
- result[15] = track.samplerate & 0xFF;
- }
-
- return box(types.mdhd, result);
- };
-
- mdia = function mdia(track) {
- return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
- };
-
- mfhd = function mfhd(sequenceNumber) {
- return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
- (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
- ]));
- };
-
- minf = function minf(track) {
- return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
- };
-
- moof = function moof(sequenceNumber, tracks) {
- var trackFragments = [],
- i = tracks.length; // build traf boxes for each track fragment
-
- while (i--) {
- trackFragments[i] = traf(tracks[i]);
- }
-
- return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
- };
- /**
- * Returns a movie box.
- * @param tracks {array} the tracks associated with this movie
- * @see ISO/IEC 14496-12:2012(E), section 8.2.1
- */
-
-
- moov = function moov(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trak(tracks[i]);
- }
-
- return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
- };
-
- mvex = function mvex(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trex(tracks[i]);
- }
-
- return box.apply(null, [types.mvex].concat(boxes));
- };
-
- mvhd = function mvhd(duration) {
- var bytes = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // creation_time
- 0x00, 0x00, 0x00, 0x02, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
- 0x00, 0x01, 0x00, 0x00, // 1.0 rate
- 0x01, 0x00, // 1.0 volume
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0xff, 0xff, 0xff, 0xff // next_track_ID
- ]);
- return box(types.mvhd, bytes);
- };
-
- sdtp = function sdtp(track) {
- var samples = track.samples || [],
- bytes = new Uint8Array(4 + samples.length),
- flags,
- i; // leave the full box header (4 bytes) all zero
- // write the sample table
-
- for (i = 0; i < samples.length; i++) {
- flags = samples[i].flags;
- bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
- }
-
- return box(types.sdtp, bytes);
- };
-
- stbl = function stbl(track) {
- return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
- };
-
- (function () {
- var videoSample, audioSample;
-
- stsd = function stsd(track) {
- return box(types.stsd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
- };
-
- videoSample = function videoSample(track) {
- var sps = track.sps || [],
- pps = track.pps || [],
- sequenceParameterSets = [],
- pictureParameterSets = [],
- i,
- avc1Box; // assemble the SPSs
-
- for (i = 0; i < sps.length; i++) {
- sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
- sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
-
- sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
- } // assemble the PPSs
-
-
- for (i = 0; i < pps.length; i++) {
- pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
- pictureParameterSets.push(pps[i].byteLength & 0xFF);
- pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
- }
-
- avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- (track.width & 0xff00) >> 8, track.width & 0xff, // width
- (track.height & 0xff00) >> 8, track.height & 0xff, // height
- 0x00, 0x48, 0x00, 0x00, // horizresolution
- 0x00, 0x48, 0x00, 0x00, // vertresolution
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // frame_count
- 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
- 0x00, 0x18, // depth = 24
- 0x11, 0x11 // pre_defined = -1
- ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
- track.profileIdc, // AVCProfileIndication
- track.profileCompatibility, // profile_compatibility
- track.levelIdc, // AVCLevelIndication
- 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
- ].concat([sps.length], // numOfSequenceParameterSets
- sequenceParameterSets, // "SPS"
- [pps.length], // numOfPictureParameterSets
- pictureParameterSets // "PPS"
- ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
- 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
- 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
- ]))];
-
- if (track.sarRatio) {
- var hSpacing = track.sarRatio[0],
- vSpacing = track.sarRatio[1];
- avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 0xFF000000) >> 24, (hSpacing & 0xFF0000) >> 16, (hSpacing & 0xFF00) >> 8, hSpacing & 0xFF, (vSpacing & 0xFF000000) >> 24, (vSpacing & 0xFF0000) >> 16, (vSpacing & 0xFF00) >> 8, vSpacing & 0xFF])));
- }
-
- return box.apply(null, avc1Box);
- };
-
- audioSample = function audioSample(track) {
- return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- // AudioSampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
- (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
- // MP4AudioSampleEntry, ISO/IEC 14496-14
- ]), esds(track));
- };
- })();
-
- tkhd = function tkhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x07, // flags
- 0x00, 0x00, 0x00, 0x00, // creation_time
- 0x00, 0x00, 0x00, 0x00, // modification_time
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, // layer
- 0x00, 0x00, // alternate_group
- 0x01, 0x00, // non-audio track volume
- 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
- (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
- ]);
- return box(types.tkhd, result);
- };
- /**
- * Generate a track fragment (traf) box. A traf box collects metadata
- * about tracks in a movie fragment (moof) box.
- */
-
-
- traf = function traf(track) {
- var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
- trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x3a, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x00, 0x00, 0x00 // default_sample_flags
- ]));
- upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
- lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));
- trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
- 0x00, 0x00, 0x00, // flags
- // baseMediaDecodeTime
- upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])); // the data offset specifies the number of bytes from the start of
- // the containing moof to the first payload byte of the associated
- // mdat
-
- dataOffset = 32 + // tfhd
- 20 + // tfdt
- 8 + // traf header
- 16 + // mfhd
- 8 + // moof header
- 8; // mdat header
- // audio tracks require less metadata
-
- if (track.type === 'audio') {
- trackFragmentRun = trun$1(track, dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
- } // video tracks should contain an independent and disposable samples
- // box (sdtp)
- // generate one and adjust offsets to match
-
-
- sampleDependencyTable = sdtp(track);
- trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
- };
- /**
- * Generate a track box.
- * @param track {object} a track definition
- * @return {Uint8Array} the track box
- */
-
-
- trak = function trak(track) {
- track.duration = track.duration || 0xffffffff;
- return box(types.trak, tkhd(track), mdia(track));
- };
-
- trex = function trex(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x01, 0x00, 0x01 // default_sample_flags
- ]); // the last two bytes of default_sample_flags is the sample
- // degradation priority, a hint about the importance of this sample
- // relative to others. Lower the degradation priority for all sample
- // types other than video.
-
- if (track.type !== 'video') {
- result[result.length - 1] = 0x00;
- }
-
- return box(types.trex, result);
- };
-
- (function () {
- var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
- // duration is present for the first sample, it will be present for
- // all subsequent samples.
- // see ISO/IEC 14496-12:2012, Section 8.8.8.1
-
- trunHeader = function trunHeader(samples, offset) {
- var durationPresent = 0,
- sizePresent = 0,
- flagsPresent = 0,
- compositionTimeOffset = 0; // trun flag constants
-
- if (samples.length) {
- if (samples[0].duration !== undefined) {
- durationPresent = 0x1;
- }
-
- if (samples[0].size !== undefined) {
- sizePresent = 0x2;
- }
-
- if (samples[0].flags !== undefined) {
- flagsPresent = 0x4;
- }
-
- if (samples[0].compositionTimeOffset !== undefined) {
- compositionTimeOffset = 0x8;
- }
- }
-
- return [0x00, // version 0
- 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
- (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
- (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
- ];
- };
-
- videoTrun = function videoTrun(track, offset) {
- var bytesOffest, bytes, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 16 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 16);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
-
- bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
- bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
-
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
- }
-
- return box(types.trun, bytes);
- };
-
- audioTrun = function audioTrun(track, offset) {
- var bytes, bytesOffest, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 8 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 8);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
- }
-
- return box(types.trun, bytes);
- };
-
- trun$1 = function trun(track, offset) {
- if (track.type === 'audio') {
- return audioTrun(track, offset);
- }
-
- return videoTrun(track, offset);
- };
- })();
-
- var mp4Generator = {
- ftyp: ftyp,
- mdat: mdat,
- moof: moof,
- moov: moov,
- initSegment: function initSegment(tracks) {
- var fileType = ftyp(),
- movie = moov(tracks),
- result;
- result = new Uint8Array(fileType.byteLength + movie.byteLength);
- result.set(fileType);
- result.set(movie, fileType.byteLength);
- return result;
- }
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- // Convert an array of nal units into an array of frames with each frame being
- // composed of the nal units that make up that frame
- // Also keep track of cummulative data about the frame from the nal units such
- // as the frame duration, starting pts, etc.
-
- var groupNalsIntoFrames = function groupNalsIntoFrames(nalUnits) {
- var i,
- currentNal,
- currentFrame = [],
- frames = []; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength = 0;
- frames.nalCount = 0;
- frames.duration = 0;
- currentFrame.byteLength = 0;
-
- for (i = 0; i < nalUnits.length; i++) {
- currentNal = nalUnits[i]; // Split on 'aud'-type nal units
-
- if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
- // Since the very first nal unit is expected to be an AUD
- // only push to the frames array when currentFrame is not empty
- if (currentFrame.length) {
- currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- }
-
- currentFrame = [currentNal];
- currentFrame.byteLength = currentNal.data.byteLength;
- currentFrame.pts = currentNal.pts;
- currentFrame.dts = currentNal.dts;
- } else {
- // Specifically flag key frames for ease of use later
- if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
- currentFrame.keyFrame = true;
- }
-
- currentFrame.duration = currentNal.dts - currentFrame.dts;
- currentFrame.byteLength += currentNal.data.byteLength;
- currentFrame.push(currentNal);
- }
- } // For the last frame, use the duration of the previous frame if we
- // have nothing better to go on
-
-
- if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
- currentFrame.duration = frames[frames.length - 1].duration;
- } // Push the final frame
- // TODO added for LHLS, make sure this is OK
-
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- return frames;
- }; // Convert an array of frames into an array of Gop with each Gop being composed
- // of the frames that make up that Gop
- // Also keep track of cummulative data about the Gop from the frames such as the
- // Gop duration, starting pts, etc.
-
-
- var groupFramesIntoGops = function groupFramesIntoGops(frames) {
- var i,
- currentFrame,
- currentGop = [],
- gops = []; // We must pre-set some of the values on the Gop since we
- // keep running totals of these values
-
- currentGop.byteLength = 0;
- currentGop.nalCount = 0;
- currentGop.duration = 0;
- currentGop.pts = frames[0].pts;
- currentGop.dts = frames[0].dts; // store some metadata about all the Gops
-
- gops.byteLength = 0;
- gops.nalCount = 0;
- gops.duration = 0;
- gops.pts = frames[0].pts;
- gops.dts = frames[0].dts;
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
-
- if (currentFrame.keyFrame) {
- // Since the very first frame is expected to be an keyframe
- // only push to the gops array when currentGop is not empty
- if (currentGop.length) {
- gops.push(currentGop);
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration;
- }
-
- currentGop = [currentFrame];
- currentGop.nalCount = currentFrame.length;
- currentGop.byteLength = currentFrame.byteLength;
- currentGop.pts = currentFrame.pts;
- currentGop.dts = currentFrame.dts;
- currentGop.duration = currentFrame.duration;
- } else {
- currentGop.duration += currentFrame.duration;
- currentGop.nalCount += currentFrame.length;
- currentGop.byteLength += currentFrame.byteLength;
- currentGop.push(currentFrame);
- }
- }
-
- if (gops.length && currentGop.duration <= 0) {
- currentGop.duration = gops[gops.length - 1].duration;
- }
-
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration; // push the final Gop
-
- gops.push(currentGop);
- return gops;
- };
- /*
- * Search for the first keyframe in the GOPs and throw away all frames
- * until that keyframe. Then extend the duration of the pulled keyframe
- * and pull the PTS and DTS of the keyframe so that it covers the time
- * range of the frames that were disposed.
- *
- * @param {Array} gops video GOPs
- * @returns {Array} modified video GOPs
- */
-
-
- var extendFirstKeyFrame = function extendFirstKeyFrame(gops) {
- var currentGop;
-
- if (!gops[0][0].keyFrame && gops.length > 1) {
- // Remove the first GOP
- currentGop = gops.shift();
- gops.byteLength -= currentGop.byteLength;
- gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
- // first gop to cover the time period of the
- // frames we just removed
-
- gops[0][0].dts = currentGop.dts;
- gops[0][0].pts = currentGop.pts;
- gops[0][0].duration += currentGop.duration;
- }
-
- return gops;
- };
- /**
- * Default sample object
- * see ISO/IEC 14496-12:2012, section 8.6.4.3
- */
-
-
- var createDefaultSample = function createDefaultSample() {
- return {
- size: 0,
- flags: {
- isLeading: 0,
- dependsOn: 1,
- isDependedOn: 0,
- hasRedundancy: 0,
- degradationPriority: 0,
- isNonSyncSample: 1
- }
- };
- };
- /*
- * Collates information from a video frame into an object for eventual
- * entry into an MP4 sample table.
- *
- * @param {Object} frame the video frame
- * @param {Number} dataOffset the byte offset to position the sample
- * @return {Object} object containing sample table info for a frame
- */
-
-
- var sampleForFrame = function sampleForFrame(frame, dataOffset) {
- var sample = createDefaultSample();
- sample.dataOffset = dataOffset;
- sample.compositionTimeOffset = frame.pts - frame.dts;
- sample.duration = frame.duration;
- sample.size = 4 * frame.length; // Space for nal unit size
-
- sample.size += frame.byteLength;
-
- if (frame.keyFrame) {
- sample.flags.dependsOn = 2;
- sample.flags.isNonSyncSample = 0;
- }
-
- return sample;
- }; // generate the track's sample table from an array of gops
-
-
- var generateSampleTable$1 = function generateSampleTable(gops, baseDataOffset) {
- var h,
- i,
- sample,
- currentGop,
- currentFrame,
- dataOffset = baseDataOffset || 0,
- samples = [];
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h];
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i];
- sample = sampleForFrame(currentFrame, dataOffset);
- dataOffset += sample.size;
- samples.push(sample);
- }
- }
-
- return samples;
- }; // generate the track's raw mdat data from an array of gops
-
-
- var concatenateNalData = function concatenateNalData(gops) {
- var h,
- i,
- j,
- currentGop,
- currentFrame,
- currentNal,
- dataOffset = 0,
- nalsByteLength = gops.byteLength,
- numberOfNals = gops.nalCount,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each Gop..
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h]; // For each Frame..
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i]; // For each NAL..
-
- for (j = 0; j < currentFrame.length; j++) {
- currentNal = currentFrame[j];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
- }
- }
-
- return data;
- }; // generate the track's sample table from a frame
-
-
- var generateSampleTableForFrame = function generateSampleTableForFrame(frame, baseDataOffset) {
- var sample,
- dataOffset = baseDataOffset || 0,
- samples = [];
- sample = sampleForFrame(frame, dataOffset);
- samples.push(sample);
- return samples;
- }; // generate the track's raw mdat data from a frame
-
-
- var concatenateNalDataForFrame = function concatenateNalDataForFrame(frame) {
- var i,
- currentNal,
- dataOffset = 0,
- nalsByteLength = frame.byteLength,
- numberOfNals = frame.length,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each NAL..
-
- for (i = 0; i < frame.length; i++) {
- currentNal = frame[i];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
-
- return data;
- };
-
- var frameUtils = {
- groupNalsIntoFrames: groupNalsIntoFrames,
- groupFramesIntoGops: groupFramesIntoGops,
- extendFirstKeyFrame: extendFirstKeyFrame,
- generateSampleTable: generateSampleTable$1,
- concatenateNalData: concatenateNalData,
- generateSampleTableForFrame: generateSampleTableForFrame,
- concatenateNalDataForFrame: concatenateNalDataForFrame
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var highPrefix = [33, 16, 5, 32, 164, 27];
- var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
-
- var zeroFill = function zeroFill(count) {
- var a = [];
-
- while (count--) {
- a.push(0);
- }
-
- return a;
- };
-
- var makeTable = function makeTable(metaTable) {
- return Object.keys(metaTable).reduce(function (obj, key) {
- obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
- return arr.concat(part);
- }, []));
- return obj;
- }, {});
- };
-
- var silence;
-
- var silence_1 = function silence_1() {
- if (!silence) {
- // Frames-of-silence to use for filling in missing AAC frames
- var coneOfSilence = {
- 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
- 88200: [highPrefix, [231], zeroFill(170), [56]],
- 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
- 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
- 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
- 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
- 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
- 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
- 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
- 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
- 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
- };
- silence = makeTable(coneOfSilence);
- }
-
- return silence;
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
-
- var ONE_SECOND_IN_TS$4 = 90000,
- // 90kHz clock
- secondsToVideoTs,
- secondsToAudioTs,
- videoTsToSeconds,
- audioTsToSeconds,
- audioTsToVideoTs,
- videoTsToAudioTs,
- metadataTsToSeconds;
-
- secondsToVideoTs = function secondsToVideoTs(seconds) {
- return seconds * ONE_SECOND_IN_TS$4;
- };
-
- secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
- return seconds * sampleRate;
- };
-
- videoTsToSeconds = function videoTsToSeconds(timestamp) {
- return timestamp / ONE_SECOND_IN_TS$4;
- };
-
- audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
- return timestamp / sampleRate;
- };
-
- audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
- return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
- };
-
- videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
- return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
- };
- /**
- * Adjust ID3 tag or caption timing information by the timeline pts values
- * (if keepOriginalTimestamps is false) and convert to seconds
- */
-
-
- metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
- return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
- };
-
- var clock = {
- ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
- secondsToVideoTs: secondsToVideoTs,
- secondsToAudioTs: secondsToAudioTs,
- videoTsToSeconds: videoTsToSeconds,
- audioTsToSeconds: audioTsToSeconds,
- audioTsToVideoTs: audioTsToVideoTs,
- videoTsToAudioTs: videoTsToAudioTs,
- metadataTsToSeconds: metadataTsToSeconds
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- /**
- * Sum the `byteLength` properties of the data in each AAC frame
- */
-
- var sumFrameByteLengths = function sumFrameByteLengths(array) {
- var i,
- currentObj,
- sum = 0; // sum the byteLength's all each nal unit in the frame
-
- for (i = 0; i < array.length; i++) {
- currentObj = array[i];
- sum += currentObj.data.byteLength;
- }
-
- return sum;
- }; // Possibly pad (prefix) the audio track with silence if appending this track
- // would lead to the introduction of a gap in the audio buffer
-
-
- var prefixWithSilence = function prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
- var baseMediaDecodeTimeTs,
- frameDuration = 0,
- audioGapDuration = 0,
- audioFillFrameCount = 0,
- audioFillDuration = 0,
- silentFrame,
- i,
- firstFrame;
-
- if (!frames.length) {
- return;
- }
-
- baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
-
- frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
-
- if (audioAppendStartTs && videoBaseMediaDecodeTime) {
- // insert the shortest possible amount (audio gap or audio to video gap)
- audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
-
- audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
- audioFillDuration = audioFillFrameCount * frameDuration;
- } // don't attempt to fill gaps smaller than a single frame or larger
- // than a half second
-
-
- if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
- return;
- }
-
- silentFrame = silence_1()[track.samplerate];
-
- if (!silentFrame) {
- // we don't have a silent frame pregenerated for the sample rate, so use a frame
- // from the content instead
- silentFrame = frames[0].data;
- }
-
- for (i = 0; i < audioFillFrameCount; i++) {
- firstFrame = frames[0];
- frames.splice(0, 0, {
- data: silentFrame,
- dts: firstFrame.dts - frameDuration,
- pts: firstFrame.pts - frameDuration
- });
- }
-
- track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
- return audioFillDuration;
- }; // If the audio segment extends before the earliest allowed dts
- // value, remove AAC frames until starts at or after the earliest
- // allowed DTS so that we don't end up with a negative baseMedia-
- // DecodeTime for the audio track
-
-
- var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts) {
- if (track.minSegmentDts >= earliestAllowedDts) {
- return adtsFrames;
- } // We will need to recalculate the earliest segment Dts
-
-
- track.minSegmentDts = Infinity;
- return adtsFrames.filter(function (currentFrame) {
- // If this is an allowed frame, keep it and record it's Dts
- if (currentFrame.dts >= earliestAllowedDts) {
- track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
- track.minSegmentPts = track.minSegmentDts;
- return true;
- } // Otherwise, discard it
-
-
- return false;
- });
- }; // generate the track's raw mdat data from an array of frames
-
-
- var generateSampleTable = function generateSampleTable(frames) {
- var i,
- currentFrame,
- samples = [];
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- samples.push({
- size: currentFrame.data.byteLength,
- duration: 1024 // For AAC audio, all samples contain 1024 samples
-
- });
- }
-
- return samples;
- }; // generate the track's sample table from an array of frames
-
-
- var concatenateFrameData = function concatenateFrameData(frames) {
- var i,
- currentFrame,
- dataOffset = 0,
- data = new Uint8Array(sumFrameByteLengths(frames));
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- data.set(currentFrame.data, dataOffset);
- dataOffset += currentFrame.data.byteLength;
- }
-
- return data;
- };
-
- var audioFrameUtils = {
- prefixWithSilence: prefixWithSilence,
- trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
- generateSampleTable: generateSampleTable,
- concatenateFrameData: concatenateFrameData
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ONE_SECOND_IN_TS$3 = clock.ONE_SECOND_IN_TS;
- /**
- * Store information about the start and end of the track and the
- * duration for each frame/sample we process in order to calculate
- * the baseMediaDecodeTime
- */
-
- var collectDtsInfo = function collectDtsInfo(track, data) {
- if (typeof data.pts === 'number') {
- if (track.timelineStartInfo.pts === undefined) {
- track.timelineStartInfo.pts = data.pts;
- }
-
- if (track.minSegmentPts === undefined) {
- track.minSegmentPts = data.pts;
- } else {
- track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
- }
-
- if (track.maxSegmentPts === undefined) {
- track.maxSegmentPts = data.pts;
- } else {
- track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
- }
- }
-
- if (typeof data.dts === 'number') {
- if (track.timelineStartInfo.dts === undefined) {
- track.timelineStartInfo.dts = data.dts;
- }
-
- if (track.minSegmentDts === undefined) {
- track.minSegmentDts = data.dts;
- } else {
- track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
- }
-
- if (track.maxSegmentDts === undefined) {
- track.maxSegmentDts = data.dts;
- } else {
- track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
- }
- }
- };
- /**
- * Clear values used to calculate the baseMediaDecodeTime between
- * tracks
- */
-
-
- var clearDtsInfo = function clearDtsInfo(track) {
- delete track.minSegmentDts;
- delete track.maxSegmentDts;
- delete track.minSegmentPts;
- delete track.maxSegmentPts;
- };
- /**
- * Calculate the track's baseMediaDecodeTime based on the earliest
- * DTS the transmuxer has ever seen and the minimum DTS for the
- * current track
- * @param track {object} track metadata configuration
- * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime(track, keepOriginalTimestamps) {
- var baseMediaDecodeTime,
- scale,
- minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
-
- if (!keepOriginalTimestamps) {
- minSegmentDts -= track.timelineStartInfo.dts;
- } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
- // we want the start of the first segment to be placed
-
-
- baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
-
- baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
-
- baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
-
- if (track.type === 'audio') {
- // Audio has a different clock equal to the sampling_rate so we need to
- // scale the PTS values into the clock rate of the track
- scale = track.samplerate / ONE_SECOND_IN_TS$3;
- baseMediaDecodeTime *= scale;
- baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
- }
-
- return baseMediaDecodeTime;
- };
-
- var trackDecodeInfo = {
- clearDtsInfo: clearDtsInfo,
- calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
- collectDtsInfo: collectDtsInfo
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Reads in-band caption information from a video elementary
- * stream. Captions must follow the CEA-708 standard for injection
- * into an MPEG-2 transport streams.
- * @see https://en.wikipedia.org/wiki/CEA-708
- * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
- */
- // payload type field to indicate how they are to be
- // interpreted. CEAS-708 caption content is always transmitted with
- // payload type 0x04.
-
- var USER_DATA_REGISTERED_ITU_T_T35 = 4,
- RBSP_TRAILING_BITS = 128;
- /**
- * Parse a supplemental enhancement information (SEI) NAL unit.
- * Stops parsing once a message of type ITU T T35 has been found.
- *
- * @param bytes {Uint8Array} the bytes of a SEI NAL unit
- * @return {object} the parsed SEI payload
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- */
-
- var parseSei = function parseSei(bytes) {
- var i = 0,
- result = {
- payloadType: -1,
- payloadSize: 0
- },
- payloadType = 0,
- payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
-
- while (i < bytes.byteLength) {
- // stop once we have hit the end of the sei_rbsp
- if (bytes[i] === RBSP_TRAILING_BITS) {
- break;
- } // Parse payload type
-
-
- while (bytes[i] === 0xFF) {
- payloadType += 255;
- i++;
- }
-
- payloadType += bytes[i++]; // Parse payload size
-
- while (bytes[i] === 0xFF) {
- payloadSize += 255;
- i++;
- }
-
- payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
- // there can only ever be one caption message in a frame's sei
-
- if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
- var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
-
- if (userIdentifier === 'GA94') {
- result.payloadType = payloadType;
- result.payloadSize = payloadSize;
- result.payload = bytes.subarray(i, i + payloadSize);
- break;
- } else {
- result.payload = void 0;
- }
- } // skip the payload and parse the next message
-
-
- i += payloadSize;
- payloadType = 0;
- payloadSize = 0;
- }
-
- return result;
- }; // see ANSI/SCTE 128-1 (2013), section 8.1
-
-
- var parseUserData = function parseUserData(sei) {
- // itu_t_t35_contry_code must be 181 (United States) for
- // captions
- if (sei.payload[0] !== 181) {
- return null;
- } // itu_t_t35_provider_code should be 49 (ATSC) for captions
-
-
- if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
- return null;
- } // the user_identifier should be "GA94" to indicate ATSC1 data
-
-
- if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
- return null;
- } // finally, user_data_type_code should be 0x03 for caption data
-
-
- if (sei.payload[7] !== 0x03) {
- return null;
- } // return the user_data_type_structure and strip the trailing
- // marker bits
-
-
- return sei.payload.subarray(8, sei.payload.length - 1);
- }; // see CEA-708-D, section 4.4
-
-
- var parseCaptionPackets = function parseCaptionPackets(pts, userData) {
- var results = [],
- i,
- count,
- offset,
- data; // if this is just filler, return immediately
-
- if (!(userData[0] & 0x40)) {
- return results;
- } // parse out the cc_data_1 and cc_data_2 fields
-
-
- count = userData[0] & 0x1f;
-
- for (i = 0; i < count; i++) {
- offset = i * 3;
- data = {
- type: userData[offset + 2] & 0x03,
- pts: pts
- }; // capture cc data when cc_valid is 1
-
- if (userData[offset + 2] & 0x04) {
- data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
- results.push(data);
- }
- }
-
- return results;
- };
-
- var discardEmulationPreventionBytes$1 = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- }; // exports
-
-
- var captionPacketParser = {
- parseSei: parseSei,
- parseUserData: parseUserData,
- parseCaptionPackets: parseCaptionPackets,
- discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
- USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
- }; // Link To Transport
- // -----------------
-
- var CaptionStream$1 = function CaptionStream(options) {
- options = options || {};
- CaptionStream.prototype.init.call(this); // parse708captions flag, default to true
-
- this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
- this.captionPackets_ = [];
- this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
- ];
-
- if (this.parse708captions_) {
- this.cc708Stream_ = new Cea708Stream(); // eslint-disable-line no-use-before-define
- }
-
- this.reset(); // forward data and done events from CCs to this CaptionStream
-
- this.ccStreams_.forEach(function (cc) {
- cc.on('data', this.trigger.bind(this, 'data'));
- cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
- cc.on('done', this.trigger.bind(this, 'done'));
- }, this);
-
- if (this.parse708captions_) {
- this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
- this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
- this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
- }
- };
-
- CaptionStream$1.prototype = new stream();
-
- CaptionStream$1.prototype.push = function (event) {
- var sei, userData, newCaptionPackets; // only examine SEI NALs
-
- if (event.nalUnitType !== 'sei_rbsp') {
- return;
- } // parse the sei
-
-
- sei = captionPacketParser.parseSei(event.escapedRBSP); // no payload data, skip
-
- if (!sei.payload) {
- return;
- } // ignore everything but user_data_registered_itu_t_t35
-
-
- if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
- return;
- } // parse out the user data payload
-
-
- userData = captionPacketParser.parseUserData(sei); // ignore unrecognized userData
-
- if (!userData) {
- return;
- } // Sometimes, the same segment # will be downloaded twice. To stop the
- // caption data from being processed twice, we track the latest dts we've
- // received and ignore everything with a dts before that. However, since
- // data for a specific dts can be split across packets on either side of
- // a segment boundary, we need to make sure we *don't* ignore the packets
- // from the *next* segment that have dts === this.latestDts_. By constantly
- // tracking the number of packets received with dts === this.latestDts_, we
- // know how many should be ignored once we start receiving duplicates.
-
-
- if (event.dts < this.latestDts_) {
- // We've started getting older data, so set the flag.
- this.ignoreNextEqualDts_ = true;
- return;
- } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
- this.numSameDts_--;
-
- if (!this.numSameDts_) {
- // We've received the last duplicate packet, time to start processing again
- this.ignoreNextEqualDts_ = false;
- }
-
- return;
- } // parse out CC data packets and save them for later
-
-
- newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
- this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
-
- if (this.latestDts_ !== event.dts) {
- this.numSameDts_ = 0;
- }
-
- this.numSameDts_++;
- this.latestDts_ = event.dts;
- };
-
- CaptionStream$1.prototype.flushCCStreams = function (flushType) {
- this.ccStreams_.forEach(function (cc) {
- return flushType === 'flush' ? cc.flush() : cc.partialFlush();
- }, this);
- };
-
- CaptionStream$1.prototype.flushStream = function (flushType) {
- // make sure we actually parsed captions before proceeding
- if (!this.captionPackets_.length) {
- this.flushCCStreams(flushType);
- return;
- } // In Chrome, the Array#sort function is not stable so add a
- // presortIndex that we can use to ensure we get a stable-sort
-
-
- this.captionPackets_.forEach(function (elem, idx) {
- elem.presortIndex = idx;
- }); // sort caption byte-pairs based on their PTS values
-
- this.captionPackets_.sort(function (a, b) {
- if (a.pts === b.pts) {
- return a.presortIndex - b.presortIndex;
- }
-
- return a.pts - b.pts;
- });
- this.captionPackets_.forEach(function (packet) {
- if (packet.type < 2) {
- // Dispatch packet to the right Cea608Stream
- this.dispatchCea608Packet(packet);
- } else {
- // Dispatch packet to the Cea708Stream
- this.dispatchCea708Packet(packet);
- }
- }, this);
- this.captionPackets_.length = 0;
- this.flushCCStreams(flushType);
- };
-
- CaptionStream$1.prototype.flush = function () {
- return this.flushStream('flush');
- }; // Only called if handling partial data
-
-
- CaptionStream$1.prototype.partialFlush = function () {
- return this.flushStream('partialFlush');
- };
-
- CaptionStream$1.prototype.reset = function () {
- this.latestDts_ = null;
- this.ignoreNextEqualDts_ = false;
- this.numSameDts_ = 0;
- this.activeCea608Channel_ = [null, null];
- this.ccStreams_.forEach(function (ccStream) {
- ccStream.reset();
- });
- }; // From the CEA-608 spec:
-
- /*
- * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
- * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
- * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
- * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
- * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
- * to switch to captioning or Text.
- */
- // With that in mind, we ignore any data between an XDS control code and a
- // subsequent closed-captioning control code.
-
-
- CaptionStream$1.prototype.dispatchCea608Packet = function (packet) {
- // NOTE: packet.type is the CEA608 field
- if (this.setsTextOrXDSActive(packet)) {
- this.activeCea608Channel_[packet.type] = null;
- } else if (this.setsChannel1Active(packet)) {
- this.activeCea608Channel_[packet.type] = 0;
- } else if (this.setsChannel2Active(packet)) {
- this.activeCea608Channel_[packet.type] = 1;
- }
-
- if (this.activeCea608Channel_[packet.type] === null) {
- // If we haven't received anything to set the active channel, or the
- // packets are Text/XDS data, discard the data; we don't want jumbled
- // captions
- return;
- }
-
- this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
- };
-
- CaptionStream$1.prototype.setsChannel1Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1000;
- };
-
- CaptionStream$1.prototype.setsChannel2Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1800;
- };
-
- CaptionStream$1.prototype.setsTextOrXDSActive = function (packet) {
- return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
- };
-
- CaptionStream$1.prototype.dispatchCea708Packet = function (packet) {
- if (this.parse708captions_) {
- this.cc708Stream_.push(packet);
- }
- }; // ----------------------
- // Session to Application
- // ----------------------
- // This hash maps special and extended character codes to their
- // proper Unicode equivalent. The first one-byte key is just a
- // non-standard character code. The two-byte keys that follow are
- // the extended CEA708 character codes, along with the preceding
- // 0x10 extended character byte to distinguish these codes from
- // non-extended character codes. Every CEA708 character code that
- // is not in this object maps directly to a standard unicode
- // character code.
- // The transparent space and non-breaking transparent space are
- // technically not fully supported since there is no code to
- // make them transparent, so they have normal non-transparent
- // stand-ins.
- // The special closed caption (CC) character isn't a standard
- // unicode character, so a fairly similar unicode character was
- // chosen in it's place.
-
-
- var CHARACTER_TRANSLATION_708 = {
- 0x7f: 0x266a,
- // ♪
- 0x1020: 0x20,
- // Transparent Space
- 0x1021: 0xa0,
- // Nob-breaking Transparent Space
- 0x1025: 0x2026,
- // …
- 0x102a: 0x0160,
- // Š
- 0x102c: 0x0152,
- // Œ
- 0x1030: 0x2588,
- // █
- 0x1031: 0x2018,
- // ‘
- 0x1032: 0x2019,
- // ’
- 0x1033: 0x201c,
- // “
- 0x1034: 0x201d,
- // ”
- 0x1035: 0x2022,
- // •
- 0x1039: 0x2122,
- // ™
- 0x103a: 0x0161,
- // š
- 0x103c: 0x0153,
- // œ
- 0x103d: 0x2120,
- // ℠
- 0x103f: 0x0178,
- // Ÿ
- 0x1076: 0x215b,
- // ⅛
- 0x1077: 0x215c,
- // ⅜
- 0x1078: 0x215d,
- // ⅝
- 0x1079: 0x215e,
- // ⅞
- 0x107a: 0x23d0,
- // ⏐
- 0x107b: 0x23a4,
- // ⎤
- 0x107c: 0x23a3,
- // ⎣
- 0x107d: 0x23af,
- // ⎯
- 0x107e: 0x23a6,
- // ⎦
- 0x107f: 0x23a1,
- // ⎡
- 0x10a0: 0x3138 // ㄸ (CC char)
-
- };
-
- var get708CharFromCode = function get708CharFromCode(code) {
- var newCode = CHARACTER_TRANSLATION_708[code] || code;
-
- if (code & 0x1000 && code === newCode) {
- // Invalid extended code
- return '';
- }
-
- return String.fromCharCode(newCode);
- };
-
- var within708TextBlock = function within708TextBlock(b) {
- return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
- };
-
- var Cea708Window = function Cea708Window(windowNum) {
- this.windowNum = windowNum;
- this.reset();
- };
-
- Cea708Window.prototype.reset = function () {
- this.clearText();
- this.pendingNewLine = false;
- this.winAttr = {};
- this.penAttr = {};
- this.penLoc = {};
- this.penColor = {}; // These default values are arbitrary,
- // defineWindow will usually override them
-
- this.visible = 0;
- this.rowLock = 0;
- this.columnLock = 0;
- this.priority = 0;
- this.relativePositioning = 0;
- this.anchorVertical = 0;
- this.anchorHorizontal = 0;
- this.anchorPoint = 0;
- this.rowCount = 1;
- this.virtualRowCount = this.rowCount + 1;
- this.columnCount = 41;
- this.windowStyle = 0;
- this.penStyle = 0;
- };
-
- Cea708Window.prototype.getText = function () {
- return this.rows.join('\n');
- };
-
- Cea708Window.prototype.clearText = function () {
- this.rows = [''];
- this.rowIdx = 0;
- };
-
- Cea708Window.prototype.newLine = function (pts) {
- if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
- this.beforeRowOverflow(pts);
- }
-
- if (this.rows.length > 0) {
- this.rows.push('');
- this.rowIdx++;
- } // Show all virtual rows since there's no visible scrolling
-
-
- while (this.rows.length > this.virtualRowCount) {
- this.rows.shift();
- this.rowIdx--;
- }
- };
-
- Cea708Window.prototype.isEmpty = function () {
- if (this.rows.length === 0) {
- return true;
- } else if (this.rows.length === 1) {
- return this.rows[0] === '';
- }
-
- return false;
- };
-
- Cea708Window.prototype.addText = function (text) {
- this.rows[this.rowIdx] += text;
- };
-
- Cea708Window.prototype.backspace = function () {
- if (!this.isEmpty()) {
- var row = this.rows[this.rowIdx];
- this.rows[this.rowIdx] = row.substr(0, row.length - 1);
- }
- };
-
- var Cea708Service = function Cea708Service(serviceNum) {
- this.serviceNum = serviceNum;
- this.text = '';
- this.currentWindow = new Cea708Window(-1);
- this.windows = [];
- };
- /**
- * Initialize service windows
- * Must be run before service use
- *
- * @param {Integer} pts PTS value
- * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
- */
-
-
- Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
- this.startPts = pts;
-
- for (var win = 0; win < 8; win++) {
- this.windows[win] = new Cea708Window(win);
-
- if (typeof beforeRowOverflow === 'function') {
- this.windows[win].beforeRowOverflow = beforeRowOverflow;
- }
- }
- };
- /**
- * Set current window of service to be affected by commands
- *
- * @param {Integer} windowNum Window number
- */
-
-
- Cea708Service.prototype.setCurrentWindow = function (windowNum) {
- this.currentWindow = this.windows[windowNum];
- };
-
- var Cea708Stream = function Cea708Stream() {
- Cea708Stream.prototype.init.call(this);
- var self = this;
- this.current708Packet = null;
- this.services = {};
-
- this.push = function (packet) {
- if (packet.type === 3) {
- // 708 packet start
- self.new708Packet();
- self.add708Bytes(packet);
- } else {
- if (self.current708Packet === null) {
- // This should only happen at the start of a file if there's no packet start.
- self.new708Packet();
- }
-
- self.add708Bytes(packet);
- }
- };
- };
-
- Cea708Stream.prototype = new stream();
- /**
- * Push current 708 packet, create new 708 packet.
- */
-
- Cea708Stream.prototype.new708Packet = function () {
- if (this.current708Packet !== null) {
- this.push708Packet();
- }
-
- this.current708Packet = {
- data: [],
- ptsVals: []
- };
- };
- /**
- * Add pts and both bytes from packet into current 708 packet.
- */
-
-
- Cea708Stream.prototype.add708Bytes = function (packet) {
- var data = packet.ccData;
- var byte0 = data >>> 8;
- var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
- // that service blocks will always line up with byte pairs.
-
- this.current708Packet.ptsVals.push(packet.pts);
- this.current708Packet.data.push(byte0);
- this.current708Packet.data.push(byte1);
- };
- /**
- * Parse completed 708 packet into service blocks and push each service block.
- */
-
-
- Cea708Stream.prototype.push708Packet = function () {
- var packet708 = this.current708Packet;
- var packetData = packet708.data;
- var serviceNum = null;
- var blockSize = null;
- var i = 0;
- var b = packetData[i++];
- packet708.seq = b >> 6;
- packet708.sizeCode = b & 0x3f; // 0b00111111;
-
- for (; i < packetData.length; i++) {
- b = packetData[i++];
- serviceNum = b >> 5;
- blockSize = b & 0x1f; // 0b00011111
-
- if (serviceNum === 7 && blockSize > 0) {
- // Extended service num
- b = packetData[i++];
- serviceNum = b;
- }
-
- this.pushServiceBlock(serviceNum, i, blockSize);
-
- if (blockSize > 0) {
- i += blockSize - 1;
- }
- }
- };
- /**
- * Parse service block, execute commands, read text.
- *
- * Note: While many of these commands serve important purposes,
- * many others just parse out the parameters or attributes, but
- * nothing is done with them because this is not a full and complete
- * implementation of the entire 708 spec.
- *
- * @param {Integer} serviceNum Service number
- * @param {Integer} start Start index of the 708 packet data
- * @param {Integer} size Block size
- */
-
-
- Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
- var b;
- var i = start;
- var packetData = this.current708Packet.data;
- var service = this.services[serviceNum];
-
- if (!service) {
- service = this.initService(serviceNum, i);
- }
-
- for (; i < start + size && i < packetData.length; i++) {
- b = packetData[i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service);
- } else if (b === 0x10) {
- i = this.extendedCommands(i, service);
- } else if (0x80 <= b && b <= 0x87) {
- i = this.setCurrentWindow(i, service);
- } else if (0x98 <= b && b <= 0x9f) {
- i = this.defineWindow(i, service);
- } else if (b === 0x88) {
- i = this.clearWindows(i, service);
- } else if (b === 0x8c) {
- i = this.deleteWindows(i, service);
- } else if (b === 0x89) {
- i = this.displayWindows(i, service);
- } else if (b === 0x8a) {
- i = this.hideWindows(i, service);
- } else if (b === 0x8b) {
- i = this.toggleWindows(i, service);
- } else if (b === 0x97) {
- i = this.setWindowAttributes(i, service);
- } else if (b === 0x90) {
- i = this.setPenAttributes(i, service);
- } else if (b === 0x91) {
- i = this.setPenColor(i, service);
- } else if (b === 0x92) {
- i = this.setPenLocation(i, service);
- } else if (b === 0x8f) {
- service = this.reset(i, service);
- } else if (b === 0x08) {
- // BS: Backspace
- service.currentWindow.backspace();
- } else if (b === 0x0c) {
- // FF: Form feed
- service.currentWindow.clearText();
- } else if (b === 0x0d) {
- // CR: Carriage return
- service.currentWindow.pendingNewLine = true;
- } else if (b === 0x0e) {
- // HCR: Horizontal carriage return
- service.currentWindow.clearText();
- } else if (b === 0x8d) {
- // DLY: Delay, nothing to do
- i++;
- } else ;
- }
- };
- /**
- * Execute an extended command
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.extendedCommands = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service, true);
- }
-
- return i;
- };
- /**
- * Get PTS value of a given byte index
- *
- * @param {Integer} byteIndex Index of the byte
- * @return {Integer} PTS
- */
-
-
- Cea708Stream.prototype.getPts = function (byteIndex) {
- // There's 1 pts value per 2 bytes
- return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
- };
- /**
- * Initializes a service
- *
- * @param {Integer} serviceNum Service number
- * @return {Service} Initialized service object
- */
-
-
- Cea708Stream.prototype.initService = function (serviceNum, i) {
- var self = this;
- this.services[serviceNum] = new Cea708Service(serviceNum);
- this.services[serviceNum].init(this.getPts(i), function (pts) {
- self.flushDisplayed(pts, self.services[serviceNum]);
- });
- return this.services[serviceNum];
- };
- /**
- * Execute text writing to current window
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.handleText = function (i, service, isExtended) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var extended = isExtended ? 0x1000 : 0x0000;
- var char = get708CharFromCode(extended | b);
- var win = service.currentWindow;
-
- if (win.pendingNewLine && !win.isEmpty()) {
- win.newLine(this.getPts(i));
- }
-
- win.pendingNewLine = false;
- win.addText(char);
- return i;
- };
- /**
- * Parse and execute the CW# command.
- *
- * Set the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setCurrentWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- return i;
- };
- /**
- * Parse and execute the DF# command.
- *
- * Define a window and set it as the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.defineWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- var win = service.currentWindow;
- b = packetData[++i];
- win.visible = (b & 0x20) >> 5; // v
-
- win.rowLock = (b & 0x10) >> 4; // rl
-
- win.columnLock = (b & 0x08) >> 3; // cl
-
- win.priority = b & 0x07; // p
-
- b = packetData[++i];
- win.relativePositioning = (b & 0x80) >> 7; // rp
-
- win.anchorVertical = b & 0x7f; // av
-
- b = packetData[++i];
- win.anchorHorizontal = b; // ah
-
- b = packetData[++i];
- win.anchorPoint = (b & 0xf0) >> 4; // ap
-
- win.rowCount = b & 0x0f; // rc
-
- b = packetData[++i];
- win.columnCount = b & 0x3f; // cc
-
- b = packetData[++i];
- win.windowStyle = (b & 0x38) >> 3; // ws
-
- win.penStyle = b & 0x07; // ps
- // The spec says there are (rowCount+1) "virtual rows"
-
- win.virtualRowCount = win.rowCount + 1;
- return i;
- };
- /**
- * Parse and execute the SWA command.
- *
- * Set attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setWindowAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var winAttr = service.currentWindow.winAttr;
- b = packetData[++i];
- winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
-
- winAttr.fillRed = (b & 0x30) >> 4; // fr
-
- winAttr.fillGreen = (b & 0x0c) >> 2; // fg
-
- winAttr.fillBlue = b & 0x03; // fb
-
- b = packetData[++i];
- winAttr.borderType = (b & 0xc0) >> 6; // bt
-
- winAttr.borderRed = (b & 0x30) >> 4; // br
-
- winAttr.borderGreen = (b & 0x0c) >> 2; // bg
-
- winAttr.borderBlue = b & 0x03; // bb
-
- b = packetData[++i];
- winAttr.borderType += (b & 0x80) >> 5; // bt
-
- winAttr.wordWrap = (b & 0x40) >> 6; // ww
-
- winAttr.printDirection = (b & 0x30) >> 4; // pd
-
- winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
-
- winAttr.justify = b & 0x03; // j
-
- b = packetData[++i];
- winAttr.effectSpeed = (b & 0xf0) >> 4; // es
-
- winAttr.effectDirection = (b & 0x0c) >> 2; // ed
-
- winAttr.displayEffect = b & 0x03; // de
-
- return i;
- };
- /**
- * Gather text from all displayed windows and push a caption to output.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.flushDisplayed = function (pts, service) {
- var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
- // display text in the correct order, but sample files so far have not shown any issue.
-
- for (var winId = 0; winId < 8; winId++) {
- if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
- displayedText.push(service.windows[winId].getText());
- }
- }
-
- service.endPts = pts;
- service.text = displayedText.join('\n\n');
- this.pushCaption(service);
- service.startPts = pts;
- };
- /**
- * Push a caption to output if the caption contains text.
- *
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.pushCaption = function (service) {
- if (service.text !== '') {
- this.trigger('data', {
- startPts: service.startPts,
- endPts: service.endPts,
- text: service.text,
- stream: 'cc708_' + service.serviceNum
- });
- service.text = '';
- service.startPts = service.endPts;
- }
- };
- /**
- * Parse and execute the DSW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.displayWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the HDW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.hideWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 0;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the TGW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.toggleWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible ^= 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the CLW command.
- *
- * Clear text of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.clearWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].clearText();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the DLW command.
- *
- * Re-initialize windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.deleteWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].reset();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the SPA command.
- *
- * Set pen attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penAttr = service.currentWindow.penAttr;
- b = packetData[++i];
- penAttr.textTag = (b & 0xf0) >> 4; // tt
-
- penAttr.offset = (b & 0x0c) >> 2; // o
-
- penAttr.penSize = b & 0x03; // s
-
- b = packetData[++i];
- penAttr.italics = (b & 0x80) >> 7; // i
-
- penAttr.underline = (b & 0x40) >> 6; // u
-
- penAttr.edgeType = (b & 0x38) >> 3; // et
-
- penAttr.fontStyle = b & 0x07; // fs
-
- return i;
- };
- /**
- * Parse and execute the SPC command.
- *
- * Set pen color of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenColor = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penColor = service.currentWindow.penColor;
- b = packetData[++i];
- penColor.fgOpacity = (b & 0xc0) >> 6; // fo
-
- penColor.fgRed = (b & 0x30) >> 4; // fr
-
- penColor.fgGreen = (b & 0x0c) >> 2; // fg
-
- penColor.fgBlue = b & 0x03; // fb
-
- b = packetData[++i];
- penColor.bgOpacity = (b & 0xc0) >> 6; // bo
-
- penColor.bgRed = (b & 0x30) >> 4; // br
-
- penColor.bgGreen = (b & 0x0c) >> 2; // bg
-
- penColor.bgBlue = b & 0x03; // bb
-
- b = packetData[++i];
- penColor.edgeRed = (b & 0x30) >> 4; // er
-
- penColor.edgeGreen = (b & 0x0c) >> 2; // eg
-
- penColor.edgeBlue = b & 0x03; // eb
-
- return i;
- };
- /**
- * Parse and execute the SPL command.
- *
- * Set pen location of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenLocation = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
-
- service.currentWindow.pendingNewLine = true;
- b = packetData[++i];
- penLoc.row = b & 0x0f; // r
-
- b = packetData[++i];
- penLoc.column = b & 0x3f; // c
-
- return i;
- };
- /**
- * Execute the RST command.
- *
- * Reset service to a clean slate. Re-initialize.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Service} Re-initialized service
- */
-
-
- Cea708Stream.prototype.reset = function (i, service) {
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
- return this.initService(service.serviceNum, i);
- }; // This hash maps non-ASCII, special, and extended character codes to their
- // proper Unicode equivalent. The first keys that are only a single byte
- // are the non-standard ASCII characters, which simply map the CEA608 byte
- // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
- // character codes, but have their MSB bitmasked with 0x03 so that a lookup
- // can be performed regardless of the field and data channel on which the
- // character code was received.
-
-
- var CHARACTER_TRANSLATION = {
- 0x2a: 0xe1,
- // á
- 0x5c: 0xe9,
- // é
- 0x5e: 0xed,
- // í
- 0x5f: 0xf3,
- // ó
- 0x60: 0xfa,
- // ú
- 0x7b: 0xe7,
- // ç
- 0x7c: 0xf7,
- // ÷
- 0x7d: 0xd1,
- // Ñ
- 0x7e: 0xf1,
- // ñ
- 0x7f: 0x2588,
- // █
- 0x0130: 0xae,
- // ®
- 0x0131: 0xb0,
- // °
- 0x0132: 0xbd,
- // ½
- 0x0133: 0xbf,
- // ¿
- 0x0134: 0x2122,
- // ™
- 0x0135: 0xa2,
- // ¢
- 0x0136: 0xa3,
- // £
- 0x0137: 0x266a,
- // ♪
- 0x0138: 0xe0,
- // à
- 0x0139: 0xa0,
- //
- 0x013a: 0xe8,
- // è
- 0x013b: 0xe2,
- // â
- 0x013c: 0xea,
- // ê
- 0x013d: 0xee,
- // î
- 0x013e: 0xf4,
- // ô
- 0x013f: 0xfb,
- // û
- 0x0220: 0xc1,
- // Á
- 0x0221: 0xc9,
- // É
- 0x0222: 0xd3,
- // Ó
- 0x0223: 0xda,
- // Ú
- 0x0224: 0xdc,
- // Ü
- 0x0225: 0xfc,
- // ü
- 0x0226: 0x2018,
- // ‘
- 0x0227: 0xa1,
- // ¡
- 0x0228: 0x2a,
- // *
- 0x0229: 0x27,
- // '
- 0x022a: 0x2014,
- // —
- 0x022b: 0xa9,
- // ©
- 0x022c: 0x2120,
- // ℠
- 0x022d: 0x2022,
- // •
- 0x022e: 0x201c,
- // “
- 0x022f: 0x201d,
- // ”
- 0x0230: 0xc0,
- // À
- 0x0231: 0xc2,
- // Â
- 0x0232: 0xc7,
- // Ç
- 0x0233: 0xc8,
- // È
- 0x0234: 0xca,
- // Ê
- 0x0235: 0xcb,
- // Ë
- 0x0236: 0xeb,
- // ë
- 0x0237: 0xce,
- // Î
- 0x0238: 0xcf,
- // Ï
- 0x0239: 0xef,
- // ï
- 0x023a: 0xd4,
- // Ô
- 0x023b: 0xd9,
- // Ù
- 0x023c: 0xf9,
- // ù
- 0x023d: 0xdb,
- // Û
- 0x023e: 0xab,
- // «
- 0x023f: 0xbb,
- // »
- 0x0320: 0xc3,
- // Ã
- 0x0321: 0xe3,
- // ã
- 0x0322: 0xcd,
- // Í
- 0x0323: 0xcc,
- // Ì
- 0x0324: 0xec,
- // ì
- 0x0325: 0xd2,
- // Ò
- 0x0326: 0xf2,
- // ò
- 0x0327: 0xd5,
- // Õ
- 0x0328: 0xf5,
- // õ
- 0x0329: 0x7b,
- // {
- 0x032a: 0x7d,
- // }
- 0x032b: 0x5c,
- // \
- 0x032c: 0x5e,
- // ^
- 0x032d: 0x5f,
- // _
- 0x032e: 0x7c,
- // |
- 0x032f: 0x7e,
- // ~
- 0x0330: 0xc4,
- // Ä
- 0x0331: 0xe4,
- // ä
- 0x0332: 0xd6,
- // Ö
- 0x0333: 0xf6,
- // ö
- 0x0334: 0xdf,
- // ß
- 0x0335: 0xa5,
- // ¥
- 0x0336: 0xa4,
- // ¤
- 0x0337: 0x2502,
- // │
- 0x0338: 0xc5,
- // Å
- 0x0339: 0xe5,
- // å
- 0x033a: 0xd8,
- // Ø
- 0x033b: 0xf8,
- // ø
- 0x033c: 0x250c,
- // ┌
- 0x033d: 0x2510,
- // ┐
- 0x033e: 0x2514,
- // └
- 0x033f: 0x2518 // ┘
-
- };
-
- var getCharFromCode = function getCharFromCode(code) {
- if (code === null) {
- return '';
- }
-
- code = CHARACTER_TRANSLATION[code] || code;
- return String.fromCharCode(code);
- }; // the index of the last row in a CEA-608 display buffer
-
-
- var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
- // getting it through bit logic.
-
- var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // CEA-608 captions are rendered onto a 34x15 matrix of character
- // cells. The "bottom" row is the last element in the outer array.
-
- var createDisplayBuffer = function createDisplayBuffer() {
- var result = [],
- i = BOTTOM_ROW + 1;
-
- while (i--) {
- result.push('');
- }
-
- return result;
- };
-
- var Cea608Stream = function Cea608Stream(field, dataChannel) {
- Cea608Stream.prototype.init.call(this);
- this.field_ = field || 0;
- this.dataChannel_ = dataChannel || 0;
- this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
- this.setConstants();
- this.reset();
-
- this.push = function (packet) {
- var data, swap, char0, char1, text; // remove the parity bits
-
- data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
-
- if (data === this.lastControlCode_) {
- this.lastControlCode_ = null;
- return;
- } // Store control codes
-
-
- if ((data & 0xf000) === 0x1000) {
- this.lastControlCode_ = data;
- } else if (data !== this.PADDING_) {
- this.lastControlCode_ = null;
- }
-
- char0 = data >>> 8;
- char1 = data & 0xff;
-
- if (data === this.PADDING_) {
- return;
- } else if (data === this.RESUME_CAPTION_LOADING_) {
- this.mode_ = 'popOn';
- } else if (data === this.END_OF_CAPTION_) {
- // If an EOC is received while in paint-on mode, the displayed caption
- // text should be swapped to non-displayed memory as if it was a pop-on
- // caption. Because of that, we should explicitly switch back to pop-on
- // mode
- this.mode_ = 'popOn';
- this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
-
- this.flushDisplayed(packet.pts); // flip memory
-
- swap = this.displayed_;
- this.displayed_ = this.nonDisplayed_;
- this.nonDisplayed_ = swap; // start measuring the time to display the caption
-
- this.startPts_ = packet.pts;
- } else if (data === this.ROLL_UP_2_ROWS_) {
- this.rollUpRows_ = 2;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_3_ROWS_) {
- this.rollUpRows_ = 3;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_4_ROWS_) {
- this.rollUpRows_ = 4;
- this.setRollUp(packet.pts);
- } else if (data === this.CARRIAGE_RETURN_) {
- this.clearFormatting(packet.pts);
- this.flushDisplayed(packet.pts);
- this.shiftRowsUp_();
- this.startPts_ = packet.pts;
- } else if (data === this.BACKSPACE_) {
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- }
- } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
- this.nonDisplayed_ = createDisplayBuffer();
- } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
- if (this.mode_ !== 'paintOn') {
- // NOTE: This should be removed when proper caption positioning is
- // implemented
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- }
-
- this.mode_ = 'paintOn';
- this.startPts_ = packet.pts; // Append special characters to caption text
- } else if (this.isSpecialCharacter(char0, char1)) {
- // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Append extended characters to caption text
- } else if (this.isExtCharacter(char0, char1)) {
- // Extended characters always follow their "non-extended" equivalents.
- // IE if a "è" is desired, you'll always receive "eè"; non-compliant
- // decoders are supposed to drop the "è", while compliant decoders
- // backspace the "e" and insert "è".
- // Delete the previous character
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- } // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
-
-
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Process mid-row codes
- } else if (this.isMidRowCode(char0, char1)) {
- // Attributes are not additive, so clear all formatting
- this.clearFormatting(packet.pts); // According to the standard, mid-row codes
- // should be replaced with spaces, so add one now
-
- this[this.mode_](packet.pts, ' ');
- this.column_++;
-
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
-
- if ((char1 & 0x1) === 0x1) {
- this.addFormatting(packet.pts, ['u']);
- } // Detect offset control codes and adjust cursor
-
- } else if (this.isOffsetControlCode(char0, char1)) {
- // Cursor position is set by indent PAC (see below) in 4-column
- // increments, with an additional offset code of 1-3 to reach any
- // of the 32 columns specified by CEA-608. So all we need to do
- // here is increment the column cursor by the given offset.
- this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
- } else if (this.isPAC(char0, char1)) {
- // There's no logic for PAC -> row mapping, so we have to just
- // find the row code in an array and use its index :(
- var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
-
- if (this.mode_ === 'rollUp') {
- // This implies that the base row is incorrectly set.
- // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
- // of roll-up rows set.
- if (row - this.rollUpRows_ + 1 < 0) {
- row = this.rollUpRows_ - 1;
- }
-
- this.setRollUp(packet.pts, row);
- }
-
- if (row !== this.row_) {
- // formatting is only persistent for current row
- this.clearFormatting(packet.pts);
- this.row_ = row;
- } // All PACs can apply underline, so detect and apply
- // (All odd-numbered second bytes set underline)
-
-
- if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
- this.addFormatting(packet.pts, ['u']);
- }
-
- if ((data & 0x10) === 0x10) {
- // We've got an indent level code. Each successive even number
- // increments the column cursor by 4, so we can get the desired
- // column position by bit-shifting to the right (to get n/2)
- // and multiplying by 4.
- this.column_ = ((data & 0xe) >> 1) * 4;
- }
-
- if (this.isColorPAC(char1)) {
- // it's a color code, though we only support white, which
- // can be either normal or italicized. white italics can be
- // either 0x4e or 0x6e depending on the row, so we just
- // bitwise-and with 0xe to see if italics should be turned on
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
- } // We have a normal character in char0, and possibly one in char1
-
- } else if (this.isNormalChar(char0)) {
- if (char1 === 0x00) {
- char1 = null;
- }
-
- text = getCharFromCode(char0);
- text += getCharFromCode(char1);
- this[this.mode_](packet.pts, text);
- this.column_ += text.length;
- } // finish data processing
-
- };
- };
-
- Cea608Stream.prototype = new stream(); // Trigger a cue point that captures the current state of the
- // display buffer
-
- Cea608Stream.prototype.flushDisplayed = function (pts) {
- var content = this.displayed_ // remove spaces from the start and end of the string
- .map(function (row) {
- try {
- return row.trim();
- } catch (e) {
- // Ordinarily, this shouldn't happen. However, caption
- // parsing errors should not throw exceptions and
- // break playback.
- // eslint-disable-next-line no-console
- console.error('Skipping malformed caption.');
- return '';
- }
- }) // combine all text rows to display in one cue
- .join('\n') // and remove blank rows from the start and end, but not the middle
- .replace(/^\n+|\n+$/g, '');
-
- if (content.length) {
- this.trigger('data', {
- startPts: this.startPts_,
- endPts: pts,
- text: content,
- stream: this.name_
- });
- }
- };
- /**
- * Zero out the data, used for startup and on seek
- */
-
-
- Cea608Stream.prototype.reset = function () {
- this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
- // actually display captions. If a caption is shifted to a row
- // with a lower index than this, it is cleared from the display
- // buffer
-
- this.topRow_ = 0;
- this.startPts_ = 0;
- this.displayed_ = createDisplayBuffer();
- this.nonDisplayed_ = createDisplayBuffer();
- this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
-
- this.column_ = 0;
- this.row_ = BOTTOM_ROW;
- this.rollUpRows_ = 2; // This variable holds currently-applied formatting
-
- this.formatting_ = [];
- };
- /**
- * Sets up control code and related constants for this instance
- */
-
-
- Cea608Stream.prototype.setConstants = function () {
- // The following attributes have these uses:
- // ext_ : char0 for mid-row codes, and the base for extended
- // chars (ext_+0, ext_+1, and ext_+2 are char0s for
- // extended codes)
- // control_: char0 for control codes, except byte-shifted to the
- // left so that we can do this.control_ | CONTROL_CODE
- // offset_: char0 for tab offset codes
- //
- // It's also worth noting that control codes, and _only_ control codes,
- // differ between field 1 and field2. Field 2 control codes are always
- // their field 1 value plus 1. That's why there's the "| field" on the
- // control value.
- if (this.dataChannel_ === 0) {
- this.BASE_ = 0x10;
- this.EXT_ = 0x11;
- this.CONTROL_ = (0x14 | this.field_) << 8;
- this.OFFSET_ = 0x17;
- } else if (this.dataChannel_ === 1) {
- this.BASE_ = 0x18;
- this.EXT_ = 0x19;
- this.CONTROL_ = (0x1c | this.field_) << 8;
- this.OFFSET_ = 0x1f;
- } // Constants for the LSByte command codes recognized by Cea608Stream. This
- // list is not exhaustive. For a more comprehensive listing and semantics see
- // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
- // Padding
-
-
- this.PADDING_ = 0x0000; // Pop-on Mode
-
- this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
- this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
-
- this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
- this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
- this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
- this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
-
- this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
-
- this.BACKSPACE_ = this.CONTROL_ | 0x21;
- this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
- this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
- };
- /**
- * Detects if the 2-byte packet data is a special character
- *
- * Special characters have a second byte in the range 0x30 to 0x3f,
- * with the first byte being 0x11 (for data channel 1) or 0x19 (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an special character
- */
-
-
- Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet data is an extended character
- *
- * Extended characters have a second byte in the range 0x20 to 0x3f,
- * with the first byte being 0x12 or 0x13 (for data channel 1) or
- * 0x1a or 0x1b (for data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an extended character
- */
-
-
- Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
- return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet is a mid-row code
- *
- * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
- * the first byte being 0x11 (for data channel 1) or 0x19 (for data
- * channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a mid-row code
- */
-
-
- Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
- };
- /**
- * Detects if the 2-byte packet is an offset control code
- *
- * Offset control codes have a second byte in the range 0x21 to 0x23,
- * with the first byte being 0x17 (for data channel 1) or 0x1f (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an offset control code
- */
-
-
- Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
- return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
- };
- /**
- * Detects if the 2-byte packet is a Preamble Address Code
- *
- * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
- * or 0x18 to 0x1f (for data channel 2), with the second byte in the
- * range 0x40 to 0x7f.
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a PAC
- */
-
-
- Cea608Stream.prototype.isPAC = function (char0, char1) {
- return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
- };
- /**
- * Detects if a packet's second byte is in the range of a PAC color code
- *
- * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
- * 0x60 to 0x6f.
- *
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the byte is a color PAC
- */
-
-
- Cea608Stream.prototype.isColorPAC = function (char1) {
- return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
- };
- /**
- * Detects if a single byte is in the range of a normal character
- *
- * Normal text bytes are in the range 0x20 to 0x7f.
- *
- * @param {Integer} char The byte
- * @return {Boolean} Whether the byte is a normal character
- */
-
-
- Cea608Stream.prototype.isNormalChar = function (char) {
- return char >= 0x20 && char <= 0x7f;
- };
- /**
- * Configures roll-up
- *
- * @param {Integer} pts Current PTS
- * @param {Integer} newBaseRow Used by PACs to slide the current window to
- * a new position
- */
-
-
- Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
- // Reset the base row to the bottom row when switching modes
- if (this.mode_ !== 'rollUp') {
- this.row_ = BOTTOM_ROW;
- this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
-
- this.flushDisplayed(pts);
- this.nonDisplayed_ = createDisplayBuffer();
- this.displayed_ = createDisplayBuffer();
- }
-
- if (newBaseRow !== undefined && newBaseRow !== this.row_) {
- // move currently displayed captions (up or down) to the new base row
- for (var i = 0; i < this.rollUpRows_; i++) {
- this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
- this.displayed_[this.row_ - i] = '';
- }
- }
-
- if (newBaseRow === undefined) {
- newBaseRow = this.row_;
- }
-
- this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
- }; // Adds the opening HTML tag for the passed character to the caption text,
- // and keeps track of it for later closing
-
-
- Cea608Stream.prototype.addFormatting = function (pts, format) {
- this.formatting_ = this.formatting_.concat(format);
- var text = format.reduce(function (text, format) {
- return text + '<' + format + '>';
- }, '');
- this[this.mode_](pts, text);
- }; // Adds HTML closing tags for current formatting to caption text and
- // clears remembered formatting
-
-
- Cea608Stream.prototype.clearFormatting = function (pts) {
- if (!this.formatting_.length) {
- return;
- }
-
- var text = this.formatting_.reverse().reduce(function (text, format) {
- return text + '' + format + '>';
- }, '');
- this.formatting_ = [];
- this[this.mode_](pts, text);
- }; // Mode Implementations
-
-
- Cea608Stream.prototype.popOn = function (pts, text) {
- var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
-
- baseRow += text;
- this.nonDisplayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.rollUp = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.shiftRowsUp_ = function () {
- var i; // clear out inactive rows
-
- for (i = 0; i < this.topRow_; i++) {
- this.displayed_[i] = '';
- }
-
- for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
- this.displayed_[i] = '';
- } // shift displayed rows up
-
-
- for (i = this.topRow_; i < this.row_; i++) {
- this.displayed_[i] = this.displayed_[i + 1];
- } // clear out the bottom row
-
-
- this.displayed_[this.row_] = '';
- };
-
- Cea608Stream.prototype.paintOn = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- }; // exports
-
-
- var captionStream = {
- CaptionStream: CaptionStream$1,
- Cea608Stream: Cea608Stream,
- Cea708Stream: Cea708Stream
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var streamTypes = {
- H264_STREAM_TYPE: 0x1B,
- ADTS_STREAM_TYPE: 0x0F,
- METADATA_STREAM_TYPE: 0x15
- };
- var MAX_TS = 8589934592;
- var RO_THRESH = 4294967296;
- var TYPE_SHARED = 'shared';
-
- var handleRollover$1 = function handleRollover(value, reference) {
- var direction = 1;
-
- if (value > reference) {
- // If the current timestamp value is greater than our reference timestamp and we detect a
- // timestamp rollover, this means the roll over is happening in the opposite direction.
- // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
- // point will be set to a small number, e.g. 1. The user then seeks backwards over the
- // rollover point. In loading this segment, the timestamp values will be very large,
- // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
- // the time stamp to be `value - 2^33`.
- direction = -1;
- } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
- // cause an incorrect adjustment.
-
-
- while (Math.abs(reference - value) > RO_THRESH) {
- value += direction * MAX_TS;
- }
-
- return value;
- };
-
- var TimestampRolloverStream$1 = function TimestampRolloverStream(type) {
- var lastDTS, referenceDTS;
- TimestampRolloverStream.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
- // video and audio. We could use `undefined` here, but having a string
- // makes debugging a little clearer.
-
- this.type_ = type || TYPE_SHARED;
-
- this.push = function (data) {
- // Any "shared" rollover streams will accept _all_ data. Otherwise,
- // streams will only accept data that matches their type.
- if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
- return;
- }
-
- if (referenceDTS === undefined) {
- referenceDTS = data.dts;
- }
-
- data.dts = handleRollover$1(data.dts, referenceDTS);
- data.pts = handleRollover$1(data.pts, referenceDTS);
- lastDTS = data.dts;
- this.trigger('data', data);
- };
-
- this.flush = function () {
- referenceDTS = lastDTS;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.discontinuity = function () {
- referenceDTS = void 0;
- lastDTS = void 0;
- };
-
- this.reset = function () {
- this.discontinuity();
- this.trigger('reset');
- };
- };
-
- TimestampRolloverStream$1.prototype = new stream();
- var timestampRolloverStream = {
- TimestampRolloverStream: TimestampRolloverStream$1,
- handleRollover: handleRollover$1
- };
-
- var percentEncode$1 = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- },
- // return the string representation of the specified byte range,
- // interpreted as UTf-8.
- parseUtf8 = function parseUtf8(bytes, start, end) {
- return decodeURIComponent(percentEncode$1(bytes, start, end));
- },
- // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
- parseIso88591$1 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
- },
- parseSyncSafeInteger$1 = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- },
- tagParsers = {
- TXXX: function TXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the text fields
- tag.description = parseUtf8(tag.data, 1, i); // do not include the null terminator in the tag value
-
- tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
- break;
- }
- }
-
- tag.data = tag.value;
- },
- WXXX: function WXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.description = parseUtf8(tag.data, 1, i);
- tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
- break;
- }
- }
- },
- PRIV: function PRIV(tag) {
- var i;
-
- for (i = 0; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.owner = parseIso88591$1(tag.data, 0, i);
- break;
- }
- }
-
- tag.privateData = tag.data.subarray(i + 1);
- tag.data = tag.privateData;
- }
- },
- _MetadataStream;
-
- _MetadataStream = function MetadataStream(options) {
- var settings = {
- debug: !!(options && options.debug),
- // the bytes of the program-level descriptor field in MP2T
- // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
- // program element descriptors"
- descriptor: options && options.descriptor
- },
- // the total size in bytes of the ID3 tag being parsed
- tagSize = 0,
- // tag data that is not complete enough to be parsed
- buffer = [],
- // the total number of bytes currently in the buffer
- bufferSize = 0,
- i;
-
- _MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
- // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
-
-
- this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
-
- if (settings.descriptor) {
- for (i = 0; i < settings.descriptor.length; i++) {
- this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
- }
- }
-
- this.push = function (chunk) {
- var tag, frameStart, frameSize, frame, i, frameHeader;
-
- if (chunk.type !== 'timed-metadata') {
- return;
- } // if data_alignment_indicator is set in the PES header,
- // we must have the start of a new ID3 tag. Assume anything
- // remaining in the buffer was malformed and throw it out
-
-
- if (chunk.dataAlignmentIndicator) {
- bufferSize = 0;
- buffer.length = 0;
- } // ignore events that don't look like ID3 data
-
-
- if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) {
- if (settings.debug) {
- // eslint-disable-next-line no-console
- console.log('Skipping unrecognized metadata packet');
- }
-
- return;
- } // add this chunk to the data we've collected so far
-
-
- buffer.push(chunk);
- bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
-
- if (buffer.length === 1) {
- // the frame size is transmitted as a 28-bit integer in the
- // last four bytes of the ID3 header.
- // The most significant bit of each byte is dropped and the
- // results concatenated to recover the actual value.
- tagSize = parseSyncSafeInteger$1(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
- // convenient for our comparisons to include it
-
- tagSize += 10;
- } // if the entire frame has not arrived, wait for more data
-
-
- if (bufferSize < tagSize) {
- return;
- } // collect the entire frame so it can be parsed
-
-
- tag = {
- data: new Uint8Array(tagSize),
- frames: [],
- pts: buffer[0].pts,
- dts: buffer[0].dts
- };
-
- for (i = 0; i < tagSize;) {
- tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
- i += buffer[0].data.byteLength;
- bufferSize -= buffer[0].data.byteLength;
- buffer.shift();
- } // find the start of the first frame and the end of the tag
-
-
- frameStart = 10;
-
- if (tag.data[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger$1(tag.data.subarray(10, 14)); // clip any padding off the end
-
- tagSize -= parseSyncSafeInteger$1(tag.data.subarray(16, 20));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger$1(tag.data.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- // eslint-disable-next-line no-console
- return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
- }
-
- frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
- frame = {
- id: frameHeader,
- data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
- };
- frame.key = frame.id;
-
- if (tagParsers[frame.id]) {
- tagParsers[frame.id](frame); // handle the special PRIV frame used to indicate the start
- // time for raw AAC data
-
- if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.data,
- size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
- // on the value of this frame
- // we couldn't have known the appropriate pts and dts before
- // parsing this ID3 tag so set those values now
-
- if (tag.pts === undefined && tag.dts === undefined) {
- tag.pts = frame.timeStamp;
- tag.dts = frame.timeStamp;
- }
-
- this.trigger('timestamp', frame);
- }
- }
-
- tag.frames.push(frame);
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < tagSize);
-
- this.trigger('data', tag);
- };
- };
-
- _MetadataStream.prototype = new stream();
- var metadataStream = _MetadataStream;
- var TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
-
- var _TransportPacketStream, _TransportParseStream, _ElementaryStream; // constants
-
-
- var MP2T_PACKET_LENGTH$1 = 188,
- // bytes
- SYNC_BYTE$1 = 0x47;
- /**
- * Splits an incoming stream of binary data into MPEG-2 Transport
- * Stream packets.
- */
-
- _TransportPacketStream = function TransportPacketStream() {
- var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
- bytesInBuffer = 0;
-
- _TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
-
- /**
- * Split a stream of data into M2TS packets
- **/
-
-
- this.push = function (bytes) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH$1,
- everything; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (bytesInBuffer) {
- everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
- everything.set(buffer.subarray(0, bytesInBuffer));
- everything.set(bytes, bytesInBuffer);
- bytesInBuffer = 0;
- } else {
- everything = bytes;
- } // While we have enough data for a packet
-
-
- while (endIndex < everything.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
- // We found a packet so emit it and jump one whole packet forward in
- // the stream
- this.trigger('data', everything.subarray(startIndex, endIndex));
- startIndex += MP2T_PACKET_LENGTH$1;
- endIndex += MP2T_PACKET_LENGTH$1;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // If there was some data left over at the end of the segment that couldn't
- // possibly be a whole packet, keep it because it might be the start of a packet
- // that continues in the next segment
-
-
- if (startIndex < everything.byteLength) {
- buffer.set(everything.subarray(startIndex), 0);
- bytesInBuffer = everything.byteLength - startIndex;
- }
- };
- /**
- * Passes identified M2TS packets to the TransportParseStream to be parsed
- **/
-
-
- this.flush = function () {
- // If the buffer contains a whole packet when we are being flushed, emit it
- // and empty the buffer. Otherwise hold onto the data because it may be
- // important for decoding the next segment
- if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
- this.trigger('data', buffer);
- bytesInBuffer = 0;
- }
-
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.reset = function () {
- bytesInBuffer = 0;
- this.trigger('reset');
- };
- };
-
- _TransportPacketStream.prototype = new stream();
- /**
- * Accepts an MP2T TransportPacketStream and emits data events with parsed
- * forms of the individual transport stream packets.
- */
-
- _TransportParseStream = function TransportParseStream() {
- var parsePsi, parsePat, parsePmt, self;
-
- _TransportParseStream.prototype.init.call(this);
-
- self = this;
- this.packetsWaitingForPmt = [];
- this.programMapTable = undefined;
-
- parsePsi = function parsePsi(payload, psi) {
- var offset = 0; // PSI packets may be split into multiple sections and those
- // sections may be split into multiple packets. If a PSI
- // section starts in this packet, the payload_unit_start_indicator
- // will be true and the first byte of the payload will indicate
- // the offset from the current position to the start of the
- // section.
-
- if (psi.payloadUnitStartIndicator) {
- offset += payload[offset] + 1;
- }
-
- if (psi.type === 'pat') {
- parsePat(payload.subarray(offset), psi);
- } else {
- parsePmt(payload.subarray(offset), psi);
- }
- };
-
- parsePat = function parsePat(payload, pat) {
- pat.section_number = payload[7]; // eslint-disable-line camelcase
-
- pat.last_section_number = payload[8]; // eslint-disable-line camelcase
- // skip the PSI header and parse the first PMT entry
-
- self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
- pat.pmtPid = self.pmtPid;
- };
- /**
- * Parse out the relevant fields of a Program Map Table (PMT).
- * @param payload {Uint8Array} the PMT-specific portion of an MP2T
- * packet. The first byte in this array should be the table_id
- * field.
- * @param pmt {object} the object that should be decorated with
- * fields parsed from the PMT.
- */
-
-
- parsePmt = function parsePmt(payload, pmt) {
- var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
- // take effect. We don't believe this should ever be the case
- // for HLS but we'll ignore "forward" PMT declarations if we see
- // them. Future PMT declarations have the current_next_indicator
- // set to zero.
-
- if (!(payload[5] & 0x01)) {
- return;
- } // overwrite any existing program map table
-
-
- self.programMapTable = {
- video: null,
- audio: null,
- 'timed-metadata': {}
- }; // the mapping table ends at the end of the current section
-
- sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
- tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
- // long the program info descriptors are
-
- programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
-
- offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- var streamType = payload[offset];
- var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
- // TODO: should this be done for metadata too? for now maintain behavior of
- // multiple metadata streams
-
- if (streamType === streamTypes.H264_STREAM_TYPE && self.programMapTable.video === null) {
- self.programMapTable.video = pid;
- } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
- self.programMapTable.audio = pid;
- } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
- // map pid to stream type for metadata streams
- self.programMapTable['timed-metadata'][pid] = streamType;
- } // move to the next table entry
- // skip past the elementary stream descriptors, if present
-
-
- offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
- } // record the map on the packet as well
-
-
- pmt.programMapTable = self.programMapTable;
- };
- /**
- * Deliver a new MP2T packet to the next stream in the pipeline.
- */
-
-
- this.push = function (packet) {
- var result = {},
- offset = 4;
- result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
-
- result.pid = packet[1] & 0x1f;
- result.pid <<= 8;
- result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
- // fifth byte of the TS packet header. The adaptation field is
- // used to add stuffing to PES packets that don't fill a complete
- // TS packet, and to specify some forms of timing and control data
- // that we do not currently use.
-
- if ((packet[3] & 0x30) >>> 4 > 0x01) {
- offset += packet[offset] + 1;
- } // parse the rest of the packet based on the type
-
-
- if (result.pid === 0) {
- result.type = 'pat';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result);
- } else if (result.pid === this.pmtPid) {
- result.type = 'pmt';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
-
- while (this.packetsWaitingForPmt.length) {
- this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
- }
- } else if (this.programMapTable === undefined) {
- // When we have not seen a PMT yet, defer further processing of
- // PES packets until one has been parsed
- this.packetsWaitingForPmt.push([packet, offset, result]);
- } else {
- this.processPes_(packet, offset, result);
- }
- };
-
- this.processPes_ = function (packet, offset, result) {
- // set the appropriate stream type
- if (result.pid === this.programMapTable.video) {
- result.streamType = streamTypes.H264_STREAM_TYPE;
- } else if (result.pid === this.programMapTable.audio) {
- result.streamType = streamTypes.ADTS_STREAM_TYPE;
- } else {
- // if not video or audio, it is timed-metadata or unknown
- // if unknown, streamType will be undefined
- result.streamType = this.programMapTable['timed-metadata'][result.pid];
- }
-
- result.type = 'pes';
- result.data = packet.subarray(offset);
- this.trigger('data', result);
- };
- };
-
- _TransportParseStream.prototype = new stream();
- _TransportParseStream.STREAM_TYPES = {
- h264: 0x1b,
- adts: 0x0f
- };
- /**
- * Reconsistutes program elementary stream (PES) packets from parsed
- * transport stream packets. That is, if you pipe an
- * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
- * events will be events which capture the bytes for individual PES
- * packets plus relevant metadata that has been extracted from the
- * container.
- */
-
- _ElementaryStream = function ElementaryStream() {
- var self = this,
- // PES packet fragments
- video = {
- data: [],
- size: 0
- },
- audio = {
- data: [],
- size: 0
- },
- timedMetadata = {
- data: [],
- size: 0
- },
- programMapTable,
- parsePes = function parsePes(payload, pes) {
- var ptsDtsFlags;
- var startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
-
- pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
- // that are frame data that is continuing from the previous fragment. This
- // is to check that the pes data is the start of a new pes payload
-
- if (startPrefix !== 1) {
- return;
- } // get the packet length, this will be 0 for video
-
-
- pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
-
- pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
- // and a DTS value. Determine what combination of values is
- // available to work with.
-
- ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
- // performs all bitwise operations on 32-bit integers but javascript
- // supports a much greater range (52-bits) of integer using standard
- // mathematical operations.
- // We construct a 31-bit value using bitwise operators over the 31
- // most significant bits and then multiply by 4 (equal to a left-shift
- // of 2) before we add the final 2 least significant bits of the
- // timestamp (equal to an OR.)
-
- if (ptsDtsFlags & 0xC0) {
- // the PTS and DTS are not written out directly. For information
- // on how they are encoded, see
- // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
- pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
- pes.pts *= 4; // Left shift by 2
-
- pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
-
- pes.dts = pes.pts;
-
- if (ptsDtsFlags & 0x40) {
- pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
- pes.dts *= 4; // Left shift by 2
-
- pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
- }
- } // the data section starts immediately after the PES header.
- // pes_header_data_length specifies the number of header bytes
- // that follow the last byte of the field.
-
-
- pes.data = payload.subarray(9 + payload[8]);
- },
-
- /**
- * Pass completely parsed PES packets to the next stream in the pipeline
- **/
- flushStream = function flushStream(stream, type, forceFlush) {
- var packetData = new Uint8Array(stream.size),
- event = {
- type: type
- },
- i = 0,
- offset = 0,
- packetFlushable = false,
- fragment; // do nothing if there is not enough buffered data for a complete
- // PES header
-
- if (!stream.data.length || stream.size < 9) {
- return;
- }
-
- event.trackId = stream.data[0].pid; // reassemble the packet
-
- for (i = 0; i < stream.data.length; i++) {
- fragment = stream.data[i];
- packetData.set(fragment.data, offset);
- offset += fragment.data.byteLength;
- } // parse assembled packet's PES header
-
-
- parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
- // check that there is enough stream data to fill the packet
-
- packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
-
- if (forceFlush || packetFlushable) {
- stream.size = 0;
- stream.data.length = 0;
- } // only emit packets that are complete. this is to avoid assembling
- // incomplete PES packets due to poor segmentation
-
-
- if (packetFlushable) {
- self.trigger('data', event);
- }
- };
-
- _ElementaryStream.prototype.init.call(this);
- /**
- * Identifies M2TS packet types and parses PES packets using metadata
- * parsed from the PMT
- **/
-
-
- this.push = function (data) {
- ({
- pat: function pat() {// we have to wait for the PMT to arrive as well before we
- // have any meaningful metadata
- },
- pes: function pes() {
- var stream, streamType;
-
- switch (data.streamType) {
- case streamTypes.H264_STREAM_TYPE:
- stream = video;
- streamType = 'video';
- break;
-
- case streamTypes.ADTS_STREAM_TYPE:
- stream = audio;
- streamType = 'audio';
- break;
-
- case streamTypes.METADATA_STREAM_TYPE:
- stream = timedMetadata;
- streamType = 'timed-metadata';
- break;
-
- default:
- // ignore unknown stream types
- return;
- } // if a new packet is starting, we can flush the completed
- // packet
-
-
- if (data.payloadUnitStartIndicator) {
- flushStream(stream, streamType, true);
- } // buffer this fragment until we are sure we've received the
- // complete payload
-
-
- stream.data.push(data);
- stream.size += data.data.byteLength;
- },
- pmt: function pmt() {
- var event = {
- type: 'metadata',
- tracks: []
- };
- programMapTable = data.programMapTable; // translate audio and video streams to tracks
-
- if (programMapTable.video !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.video,
- codec: 'avc',
- type: 'video'
- });
- }
-
- if (programMapTable.audio !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.audio,
- codec: 'adts',
- type: 'audio'
- });
- }
-
- self.trigger('data', event);
- }
- })[data.type]();
- };
-
- this.reset = function () {
- video.size = 0;
- video.data.length = 0;
- audio.size = 0;
- audio.data.length = 0;
- this.trigger('reset');
- };
- /**
- * Flush any remaining input. Video PES packets may be of variable
- * length. Normally, the start of a new video packet can trigger the
- * finalization of the previous packet. That is not possible if no
- * more video is forthcoming, however. In that case, some other
- * mechanism (like the end of the file) has to be employed. When it is
- * clear that no additional data is forthcoming, calling this method
- * will flush the buffered packets.
- */
-
-
- this.flushStreams_ = function () {
- // !!THIS ORDER IS IMPORTANT!!
- // video first then audio
- flushStream(video, 'video');
- flushStream(audio, 'audio');
- flushStream(timedMetadata, 'timed-metadata');
- };
-
- this.flush = function () {
- this.flushStreams_();
- this.trigger('done');
- };
- };
-
- _ElementaryStream.prototype = new stream();
- var m2ts = {
- PAT_PID: 0x0000,
- MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
- TransportPacketStream: _TransportPacketStream,
- TransportParseStream: _TransportParseStream,
- ElementaryStream: _ElementaryStream,
- TimestampRolloverStream: TimestampRolloverStream,
- CaptionStream: captionStream.CaptionStream,
- Cea608Stream: captionStream.Cea608Stream,
- Cea708Stream: captionStream.Cea708Stream,
- MetadataStream: metadataStream
- };
-
- for (var type in streamTypes) {
- if (streamTypes.hasOwnProperty(type)) {
- m2ts[type] = streamTypes[type];
- }
- }
-
- var m2ts_1 = m2ts;
- var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
-
- var _AdtsStream;
-
- var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
- /*
- * Accepts a ElementaryStream and emits data events with parsed
- * AAC Audio Frames of the individual packets. Input audio in ADTS
- * format is unpacked and re-emitted as AAC frames.
- *
- * @see http://wiki.multimedia.cx/index.php?title=ADTS
- * @see http://wiki.multimedia.cx/?title=Understanding_AAC
- */
-
- _AdtsStream = function AdtsStream(handlePartialSegments) {
- var buffer,
- frameNum = 0;
-
- _AdtsStream.prototype.init.call(this);
-
- this.push = function (packet) {
- var i = 0,
- frameLength,
- protectionSkipBytes,
- frameEnd,
- oldBuffer,
- sampleCount,
- adtsFrameDuration;
-
- if (!handlePartialSegments) {
- frameNum = 0;
- }
-
- if (packet.type !== 'audio') {
- // ignore non-audio data
- return;
- } // Prepend any data in the buffer to the input data so that we can parse
- // aac frames the cross a PES packet boundary
-
-
- if (buffer) {
- oldBuffer = buffer;
- buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
- buffer.set(oldBuffer);
- buffer.set(packet.data, oldBuffer.byteLength);
- } else {
- buffer = packet.data;
- } // unpack any ADTS frames which have been fully received
- // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
-
-
- while (i + 5 < buffer.length) {
- // Look for the start of an ADTS header..
- if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- } // The protection skip bit tells us if we have 2 bytes of CRC data at the
- // end of the ADTS header
-
-
- protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
- // end of the sync sequence
-
- frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
- sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
- adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2];
- frameEnd = i + frameLength; // If we don't have enough data to actually finish this ADTS frame, return
- // and wait for more data
-
- if (buffer.byteLength < frameEnd) {
- return;
- } // Otherwise, deliver the complete AAC frame
-
-
- this.trigger('data', {
- pts: packet.pts + frameNum * adtsFrameDuration,
- dts: packet.dts + frameNum * adtsFrameDuration,
- sampleCount: sampleCount,
- audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
- channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
- samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
- samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
- // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
- samplesize: 16,
- data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
- });
- frameNum++; // If the buffer is empty, clear it and return
-
- if (buffer.byteLength === frameEnd) {
- buffer = undefined;
- return;
- } // Remove the finished frame from the buffer and start the process again
-
-
- buffer = buffer.subarray(frameEnd);
- }
- };
-
- this.flush = function () {
- frameNum = 0;
- this.trigger('done');
- };
-
- this.reset = function () {
- buffer = void 0;
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- buffer = void 0;
- this.trigger('endedtimeline');
- };
- };
-
- _AdtsStream.prototype = new stream();
- var adts = _AdtsStream;
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ExpGolomb;
- /**
- * Parser for exponential Golomb codes, a variable-bitwidth number encoding
- * scheme used by h264.
- */
-
- ExpGolomb = function ExpGolomb(workingData) {
- var // the number of bytes left to examine in workingData
- workingBytesAvailable = workingData.byteLength,
- // the current word being examined
- workingWord = 0,
- // :uint
- // the number of bits left to examine in the current word
- workingBitsAvailable = 0; // :uint;
- // ():uint
-
- this.length = function () {
- return 8 * workingBytesAvailable;
- }; // ():uint
-
-
- this.bitsAvailable = function () {
- return 8 * workingBytesAvailable + workingBitsAvailable;
- }; // ():void
-
-
- this.loadWord = function () {
- var position = workingData.byteLength - workingBytesAvailable,
- workingBytes = new Uint8Array(4),
- availableBytes = Math.min(4, workingBytesAvailable);
-
- if (availableBytes === 0) {
- throw new Error('no bytes available');
- }
-
- workingBytes.set(workingData.subarray(position, position + availableBytes));
- workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
-
- workingBitsAvailable = availableBytes * 8;
- workingBytesAvailable -= availableBytes;
- }; // (count:int):void
-
-
- this.skipBits = function (count) {
- var skipBytes; // :int
-
- if (workingBitsAvailable > count) {
- workingWord <<= count;
- workingBitsAvailable -= count;
- } else {
- count -= workingBitsAvailable;
- skipBytes = Math.floor(count / 8);
- count -= skipBytes * 8;
- workingBytesAvailable -= skipBytes;
- this.loadWord();
- workingWord <<= count;
- workingBitsAvailable -= count;
- }
- }; // (size:int):uint
-
-
- this.readBits = function (size) {
- var bits = Math.min(workingBitsAvailable, size),
- // :uint
- valu = workingWord >>> 32 - bits; // :uint
- // if size > 31, handle error
-
- workingBitsAvailable -= bits;
-
- if (workingBitsAvailable > 0) {
- workingWord <<= bits;
- } else if (workingBytesAvailable > 0) {
- this.loadWord();
- }
-
- bits = size - bits;
-
- if (bits > 0) {
- return valu << bits | this.readBits(bits);
- }
-
- return valu;
- }; // ():uint
-
-
- this.skipLeadingZeros = function () {
- var leadingZeroCount; // :uint
-
- for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
- if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
- // the first bit of working word is 1
- workingWord <<= leadingZeroCount;
- workingBitsAvailable -= leadingZeroCount;
- return leadingZeroCount;
- }
- } // we exhausted workingWord and still have not found a 1
-
-
- this.loadWord();
- return leadingZeroCount + this.skipLeadingZeros();
- }; // ():void
-
-
- this.skipUnsignedExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():void
-
-
- this.skipExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():uint
-
-
- this.readUnsignedExpGolomb = function () {
- var clz = this.skipLeadingZeros(); // :uint
-
- return this.readBits(clz + 1) - 1;
- }; // ():int
-
-
- this.readExpGolomb = function () {
- var valu = this.readUnsignedExpGolomb(); // :int
-
- if (0x01 & valu) {
- // the number is odd if the low order bit is set
- return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
- }
-
- return -1 * (valu >>> 1); // divide by two then make it negative
- }; // Some convenience functions
- // :Boolean
-
-
- this.readBoolean = function () {
- return this.readBits(1) === 1;
- }; // ():int
-
-
- this.readUnsignedByte = function () {
- return this.readBits(8);
- };
-
- this.loadWord();
- };
-
- var expGolomb = ExpGolomb;
-
- var _H264Stream, _NalByteStream;
-
- var PROFILES_WITH_OPTIONAL_SPS_DATA;
- /**
- * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
- */
-
- _NalByteStream = function NalByteStream() {
- var syncPoint = 0,
- i,
- buffer;
-
- _NalByteStream.prototype.init.call(this);
- /*
- * Scans a byte stream and triggers a data event with the NAL units found.
- * @param {Object} data Event received from H264Stream
- * @param {Uint8Array} data.data The h264 byte stream to be scanned
- *
- * @see H264Stream.push
- */
-
-
- this.push = function (data) {
- var swapBuffer;
-
- if (!buffer) {
- buffer = data.data;
- } else {
- swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
- swapBuffer.set(buffer);
- swapBuffer.set(data.data, buffer.byteLength);
- buffer = swapBuffer;
- }
-
- var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
- // scan for NAL unit boundaries
- // a match looks like this:
- // 0 0 1 .. NAL .. 0 0 1
- // ^ sync point ^ i
- // or this:
- // 0 0 1 .. NAL .. 0 0 0
- // ^ sync point ^ i
- // advance the sync point to a NAL start, if necessary
-
- for (; syncPoint < len - 3; syncPoint++) {
- if (buffer[syncPoint + 2] === 1) {
- // the sync point is properly aligned
- i = syncPoint + 5;
- break;
- }
- }
-
- while (i < len) {
- // look at the current byte to determine if we've hit the end of
- // a NAL unit boundary
- switch (buffer[i]) {
- case 0:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0) {
- i += 2;
- break;
- } else if (buffer[i - 2] !== 0) {
- i++;
- break;
- } // deliver the NAL unit if it isn't empty
-
-
- if (syncPoint + 3 !== i - 2) {
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- } // drop trailing zeroes
-
-
- do {
- i++;
- } while (buffer[i] !== 1 && i < len);
-
- syncPoint = i - 2;
- i += 3;
- break;
-
- case 1:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
- i += 3;
- break;
- } // deliver the NAL unit
-
-
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- syncPoint = i - 2;
- i += 3;
- break;
-
- default:
- // the current byte isn't a one or zero, so it cannot be part
- // of a sync sequence
- i += 3;
- break;
- }
- } // filter out the NAL units that were delivered
-
-
- buffer = buffer.subarray(syncPoint);
- i -= syncPoint;
- syncPoint = 0;
- };
-
- this.reset = function () {
- buffer = null;
- syncPoint = 0;
- this.trigger('reset');
- };
-
- this.flush = function () {
- // deliver the last buffered NAL unit
- if (buffer && buffer.byteLength > 3) {
- this.trigger('data', buffer.subarray(syncPoint + 3));
- } // reset the stream state
-
-
- buffer = null;
- syncPoint = 0;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
- };
-
- _NalByteStream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the SPS
- // see Recommendation ITU-T H.264 (4/2013),
- // 7.3.2.1.1 Sequence parameter set data syntax
-
- PROFILES_WITH_OPTIONAL_SPS_DATA = {
- 100: true,
- 110: true,
- 122: true,
- 244: true,
- 44: true,
- 83: true,
- 86: true,
- 118: true,
- 128: true,
- 138: true,
- 139: true,
- 134: true
- };
- /**
- * Accepts input from a ElementaryStream and produces H.264 NAL unit data
- * events.
- */
-
- _H264Stream = function H264Stream() {
- var nalByteStream = new _NalByteStream(),
- self,
- trackId,
- currentPts,
- currentDts,
- discardEmulationPreventionBytes,
- readSequenceParameterSet,
- skipScalingList;
-
- _H264Stream.prototype.init.call(this);
-
- self = this;
- /*
- * Pushes a packet from a stream onto the NalByteStream
- *
- * @param {Object} packet - A packet received from a stream
- * @param {Uint8Array} packet.data - The raw bytes of the packet
- * @param {Number} packet.dts - Decode timestamp of the packet
- * @param {Number} packet.pts - Presentation timestamp of the packet
- * @param {Number} packet.trackId - The id of the h264 track this packet came from
- * @param {('video'|'audio')} packet.type - The type of packet
- *
- */
-
- this.push = function (packet) {
- if (packet.type !== 'video') {
- return;
- }
-
- trackId = packet.trackId;
- currentPts = packet.pts;
- currentDts = packet.dts;
- nalByteStream.push(packet);
- };
- /*
- * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
- * for the NALUs to the next stream component.
- * Also, preprocess caption and sequence parameter NALUs.
- *
- * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
- * @see NalByteStream.push
- */
-
-
- nalByteStream.on('data', function (data) {
- var event = {
- trackId: trackId,
- pts: currentPts,
- dts: currentDts,
- data: data
- };
-
- switch (data[0] & 0x1f) {
- case 0x05:
- event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
- break;
-
- case 0x06:
- event.nalUnitType = 'sei_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- break;
-
- case 0x07:
- event.nalUnitType = 'seq_parameter_set_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- event.config = readSequenceParameterSet(event.escapedRBSP);
- break;
-
- case 0x08:
- event.nalUnitType = 'pic_parameter_set_rbsp';
- break;
-
- case 0x09:
- event.nalUnitType = 'access_unit_delimiter_rbsp';
- break;
- } // This triggers data on the H264Stream
-
-
- self.trigger('data', event);
- });
- nalByteStream.on('done', function () {
- self.trigger('done');
- });
- nalByteStream.on('partialdone', function () {
- self.trigger('partialdone');
- });
- nalByteStream.on('reset', function () {
- self.trigger('reset');
- });
- nalByteStream.on('endedtimeline', function () {
- self.trigger('endedtimeline');
- });
-
- this.flush = function () {
- nalByteStream.flush();
- };
-
- this.partialFlush = function () {
- nalByteStream.partialFlush();
- };
-
- this.reset = function () {
- nalByteStream.reset();
- };
-
- this.endTimeline = function () {
- nalByteStream.endTimeline();
- };
- /**
- * Advance the ExpGolomb decoder past a scaling list. The scaling
- * list is optionally transmitted as part of a sequence parameter
- * set and is not relevant to transmuxing.
- * @param count {number} the number of entries in this scaling list
- * @param expGolombDecoder {object} an ExpGolomb pointed to the
- * start of a scaling list
- * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
- */
-
-
- skipScalingList = function skipScalingList(count, expGolombDecoder) {
- var lastScale = 8,
- nextScale = 8,
- j,
- deltaScale;
-
- for (j = 0; j < count; j++) {
- if (nextScale !== 0) {
- deltaScale = expGolombDecoder.readExpGolomb();
- nextScale = (lastScale + deltaScale + 256) % 256;
- }
-
- lastScale = nextScale === 0 ? lastScale : nextScale;
- }
- };
- /**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
-
- discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- };
- /**
- * Read a sequence parameter set and return some interesting video
- * properties. A sequence parameter set is the H264 metadata that
- * describes the properties of upcoming video frames.
- * @param data {Uint8Array} the bytes of a sequence parameter set
- * @return {object} an object with configuration parsed from the
- * sequence parameter set, including the dimensions of the
- * associated video frames.
- */
-
-
- readSequenceParameterSet = function readSequenceParameterSet(data) {
- var frameCropLeftOffset = 0,
- frameCropRightOffset = 0,
- frameCropTopOffset = 0,
- frameCropBottomOffset = 0,
- sarScale = 1,
- expGolombDecoder,
- profileIdc,
- levelIdc,
- profileCompatibility,
- chromaFormatIdc,
- picOrderCntType,
- numRefFramesInPicOrderCntCycle,
- picWidthInMbsMinus1,
- picHeightInMapUnitsMinus1,
- frameMbsOnlyFlag,
- scalingListCount,
- sarRatio,
- aspectRatioIdc,
- i;
- expGolombDecoder = new expGolomb(data);
- profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
-
- profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
-
- levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
-
- expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
- // some profiles have more optional data we don't need
-
- if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
- chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
-
- if (chromaFormatIdc === 3) {
- expGolombDecoder.skipBits(1); // separate_colour_plane_flag
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
-
- expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
-
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_matrix_present_flag
- scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
-
- for (i = 0; i < scalingListCount; i++) {
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_list_present_flag[ i ]
- if (i < 6) {
- skipScalingList(16, expGolombDecoder);
- } else {
- skipScalingList(64, expGolombDecoder);
- }
- }
- }
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
-
- picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
-
- if (picOrderCntType === 0) {
- expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
- } else if (picOrderCntType === 1) {
- expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
-
- expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
-
- expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
-
- numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
-
- for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
- expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
-
- expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
-
- picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- frameMbsOnlyFlag = expGolombDecoder.readBits(1);
-
- if (frameMbsOnlyFlag === 0) {
- expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
- }
-
- expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
-
- if (expGolombDecoder.readBoolean()) {
- // frame_cropping_flag
- frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
- }
-
- if (expGolombDecoder.readBoolean()) {
- // vui_parameters_present_flag
- if (expGolombDecoder.readBoolean()) {
- // aspect_ratio_info_present_flag
- aspectRatioIdc = expGolombDecoder.readUnsignedByte();
-
- switch (aspectRatioIdc) {
- case 1:
- sarRatio = [1, 1];
- break;
-
- case 2:
- sarRatio = [12, 11];
- break;
-
- case 3:
- sarRatio = [10, 11];
- break;
-
- case 4:
- sarRatio = [16, 11];
- break;
-
- case 5:
- sarRatio = [40, 33];
- break;
-
- case 6:
- sarRatio = [24, 11];
- break;
-
- case 7:
- sarRatio = [20, 11];
- break;
-
- case 8:
- sarRatio = [32, 11];
- break;
-
- case 9:
- sarRatio = [80, 33];
- break;
-
- case 10:
- sarRatio = [18, 11];
- break;
-
- case 11:
- sarRatio = [15, 11];
- break;
-
- case 12:
- sarRatio = [64, 33];
- break;
-
- case 13:
- sarRatio = [160, 99];
- break;
-
- case 14:
- sarRatio = [4, 3];
- break;
-
- case 15:
- sarRatio = [3, 2];
- break;
-
- case 16:
- sarRatio = [2, 1];
- break;
-
- case 255:
- {
- sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
- break;
- }
- }
-
- if (sarRatio) {
- sarScale = sarRatio[0] / sarRatio[1];
- }
- }
- }
-
- return {
- profileIdc: profileIdc,
- levelIdc: levelIdc,
- profileCompatibility: profileCompatibility,
- width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
- height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
- sarRatio: sarRatio
- };
- };
- };
-
- _H264Stream.prototype = new stream();
- var h264 = {
- H264Stream: _H264Stream,
- NalByteStream: _NalByteStream
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Utilities to detect basic properties and metadata about Aac data.
- */
-
- var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
-
- var parseId3TagSize = function parseId3TagSize(header, byteIndex) {
- var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
- flags = header[byteIndex + 5],
- footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
-
- returnSize = returnSize >= 0 ? returnSize : 0;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
- };
-
- var getId3Offset = function getId3Offset(data, offset) {
- if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
- return offset;
- }
-
- offset += parseId3TagSize(data, offset);
- return getId3Offset(data, offset);
- }; // TODO: use vhs-utils
-
-
- var isLikelyAacData$1 = function isLikelyAacData(data) {
- var offset = getId3Offset(data, 0);
- return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
- // is not mp3 data but aac data.
- (data[offset + 1] & 0x16) === 0x10;
- };
-
- var parseSyncSafeInteger = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- }; // return a percent-encoded representation of the specified byte range
- // @see http://en.wikipedia.org/wiki/Percent-encoding
-
-
- var percentEncode = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- }; // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
-
-
- var parseIso88591 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
- };
-
- var parseAdtsSize = function parseAdtsSize(header, byteIndex) {
- var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
- middle = header[byteIndex + 4] << 3,
- highTwo = header[byteIndex + 3] & 0x3 << 11;
- return highTwo | middle | lowThree;
- };
-
- var parseType$2 = function parseType(header, byteIndex) {
- if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
- return 'timed-metadata';
- } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
- return 'audio';
- }
-
- return null;
- };
-
- var parseSampleRate = function parseSampleRate(packet) {
- var i = 0;
-
- while (i + 5 < packet.length) {
- if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- }
-
- return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
- }
-
- return null;
- };
-
- var parseAacTimestamp = function parseAacTimestamp(packet) {
- var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
-
- frameStart = 10;
-
- if (packet[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- return null;
- }
-
- frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
-
- if (frameHeader === 'PRIV') {
- frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
-
- for (var i = 0; i < frame.byteLength; i++) {
- if (frame[i] === 0) {
- var owner = parseIso88591(frame, 0, i);
-
- if (owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.subarray(i + 1);
- var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- return size;
- }
-
- break;
- }
- }
- }
-
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < packet.byteLength);
-
- return null;
- };
-
- var utils = {
- isLikelyAacData: isLikelyAacData$1,
- parseId3TagSize: parseId3TagSize,
- parseAdtsSize: parseAdtsSize,
- parseType: parseType$2,
- parseSampleRate: parseSampleRate,
- parseAacTimestamp: parseAacTimestamp
- };
-
- var _AacStream;
- /**
- * Splits an incoming stream of binary data into ADTS and ID3 Frames.
- */
-
-
- _AacStream = function AacStream() {
- var everything = new Uint8Array(),
- timeStamp = 0;
-
- _AacStream.prototype.init.call(this);
-
- this.setTimestamp = function (timestamp) {
- timeStamp = timestamp;
- };
-
- this.push = function (bytes) {
- var frameSize = 0,
- byteIndex = 0,
- bytesLeft,
- chunk,
- packet,
- tempLength; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (everything.length) {
- tempLength = everything.length;
- everything = new Uint8Array(bytes.byteLength + tempLength);
- everything.set(everything.subarray(0, tempLength));
- everything.set(bytes, tempLength);
- } else {
- everything = bytes;
- }
-
- while (everything.length - byteIndex >= 3) {
- if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
- // Exit early because we don't have enough to parse
- // the ID3 tag header
- if (everything.length - byteIndex < 10) {
- break;
- } // check framesize
-
-
- frameSize = utils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
- // Add to byteIndex to support multiple ID3 tags in sequence
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- chunk = {
- type: 'timed-metadata',
- data: everything.subarray(byteIndex, byteIndex + frameSize)
- };
- this.trigger('data', chunk);
- byteIndex += frameSize;
- continue;
- } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
- // Exit early because we don't have enough to parse
- // the ADTS frame header
- if (everything.length - byteIndex < 7) {
- break;
- }
-
- frameSize = utils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- packet = {
- type: 'audio',
- data: everything.subarray(byteIndex, byteIndex + frameSize),
- pts: timeStamp,
- dts: timeStamp
- };
- this.trigger('data', packet);
- byteIndex += frameSize;
- continue;
- }
-
- byteIndex++;
- }
-
- bytesLeft = everything.length - byteIndex;
-
- if (bytesLeft > 0) {
- everything = everything.subarray(byteIndex);
- } else {
- everything = new Uint8Array();
- }
- };
-
- this.reset = function () {
- everything = new Uint8Array();
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- everything = new Uint8Array();
- this.trigger('endedtimeline');
- };
- };
-
- _AacStream.prototype = new stream();
- var aac = _AacStream; // constants
-
- var AUDIO_PROPERTIES = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
- var audioProperties = AUDIO_PROPERTIES;
- var VIDEO_PROPERTIES = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
- var videoProperties = VIDEO_PROPERTIES;
- var H264Stream = h264.H264Stream;
- var isLikelyAacData = utils.isLikelyAacData;
- var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS; // object types
-
- var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
- /**
- * Compare two arrays (even typed) for same-ness
- */
-
-
- var arrayEquals = function arrayEquals(a, b) {
- var i;
-
- if (a.length !== b.length) {
- return false;
- } // compare the value of each element in the array
-
-
- for (i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) {
- return false;
- }
- }
-
- return true;
- };
-
- var generateSegmentTimingInfo = function generateSegmentTimingInfo(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
- var ptsOffsetFromDts = startPts - startDts,
- decodeDuration = endDts - startDts,
- presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
- // however, the player time values will reflect a start from the baseMediaDecodeTime.
- // In order to provide relevant values for the player times, base timing info on the
- // baseMediaDecodeTime and the DTS and PTS durations of the segment.
-
- return {
- start: {
- dts: baseMediaDecodeTime,
- pts: baseMediaDecodeTime + ptsOffsetFromDts
- },
- end: {
- dts: baseMediaDecodeTime + decodeDuration,
- pts: baseMediaDecodeTime + presentationDuration
- },
- prependedContentDuration: prependedContentDuration,
- baseMediaDecodeTime: baseMediaDecodeTime
- };
- };
- /**
- * Constructs a single-track, ISO BMFF media segment from AAC data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- _AudioSegmentStream = function AudioSegmentStream(track, options) {
- var adtsFrames = [],
- sequenceNumber = 0,
- earliestAllowedDts = 0,
- audioAppendStartTs = 0,
- videoBaseMediaDecodeTime = Infinity;
- options = options || {};
-
- _AudioSegmentStream.prototype.init.call(this);
-
- this.push = function (data) {
- trackDecodeInfo.collectDtsInfo(track, data);
-
- if (track) {
- audioProperties.forEach(function (prop) {
- track[prop] = data[prop];
- });
- } // buffer audio data until end() is called
-
-
- adtsFrames.push(data);
- };
-
- this.setEarliestDts = function (earliestDts) {
- earliestAllowedDts = earliestDts;
- };
-
- this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- videoBaseMediaDecodeTime = baseMediaDecodeTime;
- };
-
- this.setAudioAppendStart = function (timestamp) {
- audioAppendStartTs = timestamp;
- };
-
- this.flush = function () {
- var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
-
- if (adtsFrames.length === 0) {
- this.trigger('done', 'AudioSegmentStream');
- return;
- }
-
- frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
-
- videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
- // samples (that is, adts frames) in the audio data
-
- track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
-
- mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
- adtsFrames = [];
- moof = mp4Generator.moof(sequenceNumber, [track]);
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- trackDecodeInfo.clearDtsInfo(track);
- frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
- // tests) on adding the timingInfo event. However, it seems unlikely that there's a
- // valid use-case where an init segment/data should be triggered without associated
- // frames. Leaving for now, but should be looked into.
-
- if (frames.length) {
- segmentDuration = frames.length * frameDuration;
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
- // frame info is in video clock cycles. Convert to match expectation of
- // listeners (that all timestamps will be based on video clock cycles).
- clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
- frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
- this.trigger('timingInfo', {
- start: frames[0].pts,
- end: frames[0].pts + segmentDuration
- });
- }
-
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.trigger('done', 'AudioSegmentStream');
- };
-
- this.reset = function () {
- trackDecodeInfo.clearDtsInfo(track);
- adtsFrames = [];
- this.trigger('reset');
- };
- };
-
- _AudioSegmentStream.prototype = new stream();
- /**
- * Constructs a single-track, ISO BMFF media segment from H264 data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
- * gopsToAlignWith list when attempting to align gop pts
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
- _VideoSegmentStream = function VideoSegmentStream(track, options) {
- var sequenceNumber = 0,
- nalUnits = [],
- gopsToAlignWith = [],
- config,
- pps;
- options = options || {};
-
- _VideoSegmentStream.prototype.init.call(this);
-
- delete track.minPTS;
- this.gopCache_ = [];
- /**
- * Constructs a ISO BMFF segment given H264 nalUnits
- * @param {Object} nalUnit A data event representing a nalUnit
- * @param {String} nalUnit.nalUnitType
- * @param {Object} nalUnit.config Properties for a mp4 track
- * @param {Uint8Array} nalUnit.data The nalUnit bytes
- * @see lib/codecs/h264.js
- **/
-
- this.push = function (nalUnit) {
- trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
-
- if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
- config = nalUnit.config;
- track.sps = [nalUnit.data];
- videoProperties.forEach(function (prop) {
- track[prop] = config[prop];
- }, this);
- }
-
- if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
- pps = nalUnit.data;
- track.pps = [nalUnit.data];
- } // buffer video until flush() is called
-
-
- nalUnits.push(nalUnit);
- };
- /**
- * Pass constructed ISO BMFF track and boxes on to the
- * next stream in the pipeline
- **/
-
-
- this.flush = function () {
- var frames,
- gopForFusion,
- gops,
- moof,
- mdat,
- boxes,
- prependedContentDuration = 0,
- firstGop,
- lastGop; // Throw away nalUnits at the start of the byte stream until
- // we find the first AUD
-
- while (nalUnits.length) {
- if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
- break;
- }
-
- nalUnits.shift();
- } // Return early if no video data has been observed
-
-
- if (nalUnits.length === 0) {
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Organize the raw nal-units into arrays that represent
- // higher-level constructs such as frames and gops
- // (group-of-pictures)
-
-
- frames = frameUtils.groupNalsIntoFrames(nalUnits);
- gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
- // a problem since MSE (on Chrome) requires a leading keyframe.
- //
- // We have two approaches to repairing this situation:
- // 1) GOP-FUSION:
- // This is where we keep track of the GOPS (group-of-pictures)
- // from previous fragments and attempt to find one that we can
- // prepend to the current fragment in order to create a valid
- // fragment.
- // 2) KEYFRAME-PULLING:
- // Here we search for the first keyframe in the fragment and
- // throw away all the frames between the start of the fragment
- // and that keyframe. We then extend the duration and pull the
- // PTS of the keyframe forward so that it covers the time range
- // of the frames that were disposed of.
- //
- // #1 is far prefereable over #2 which can cause "stuttering" but
- // requires more things to be just right.
-
- if (!gops[0][0].keyFrame) {
- // Search for a gop for fusion from our gopCache
- gopForFusion = this.getGopForFusion_(nalUnits[0], track);
-
- if (gopForFusion) {
- // in order to provide more accurate timing information about the segment, save
- // the number of seconds prepended to the original segment due to GOP fusion
- prependedContentDuration = gopForFusion.duration;
- gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
- // new gop at the beginning
-
- gops.byteLength += gopForFusion.byteLength;
- gops.nalCount += gopForFusion.nalCount;
- gops.pts = gopForFusion.pts;
- gops.dts = gopForFusion.dts;
- gops.duration += gopForFusion.duration;
- } else {
- // If we didn't find a candidate gop fall back to keyframe-pulling
- gops = frameUtils.extendFirstKeyFrame(gops);
- }
- } // Trim gops to align with gopsToAlignWith
-
-
- if (gopsToAlignWith.length) {
- var alignedGops;
-
- if (options.alignGopsAtEnd) {
- alignedGops = this.alignGopsAtEnd_(gops);
- } else {
- alignedGops = this.alignGopsAtStart_(gops);
- }
-
- if (!alignedGops) {
- // save all the nals in the last GOP into the gop cache
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
-
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
- // when recalculated before sending off to CoalesceStream
-
-
- trackDecodeInfo.clearDtsInfo(track);
- gops = alignedGops;
- }
-
- trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
- // samples (that is, frames) in the video data
-
- track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
-
- mdat = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
- this.trigger('processedGopsInfo', gops.map(function (gop) {
- return {
- pts: gop.pts,
- dts: gop.dts,
- byteLength: gop.byteLength
- };
- }));
- firstGop = gops[0];
- lastGop = gops[gops.length - 1];
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
- this.trigger('timingInfo', {
- start: gops[0].pts,
- end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
- }); // save all the nals in the last GOP into the gop cache
-
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = [];
- this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
- this.trigger('timelineStartInfo', track.timelineStartInfo);
- moof = mp4Generator.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
- // throwing away hundreds of media segment fragments
-
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.resetStream_(); // Continue with the flush process now
-
- this.trigger('done', 'VideoSegmentStream');
- };
-
- this.reset = function () {
- this.resetStream_();
- nalUnits = [];
- this.gopCache_.length = 0;
- gopsToAlignWith.length = 0;
- this.trigger('reset');
- };
-
- this.resetStream_ = function () {
- trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
- // for instance, when we are rendition switching
-
- config = undefined;
- pps = undefined;
- }; // Search for a candidate Gop for gop-fusion from the gop cache and
- // return it or return null if no good candidate was found
-
-
- this.getGopForFusion_ = function (nalUnit) {
- var halfSecond = 45000,
- // Half-a-second in a 90khz clock
- allowableOverlap = 10000,
- // About 3 frames @ 30fps
- nearestDistance = Infinity,
- dtsDistance,
- nearestGopObj,
- currentGop,
- currentGopObj,
- i; // Search for the GOP nearest to the beginning of this nal unit
-
- for (i = 0; i < this.gopCache_.length; i++) {
- currentGopObj = this.gopCache_[i];
- currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
-
- if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
- continue;
- } // Reject Gops that would require a negative baseMediaDecodeTime
-
-
- if (currentGop.dts < track.timelineStartInfo.dts) {
- continue;
- } // The distance between the end of the gop and the start of the nalUnit
-
-
- dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
- // a half-second of the nal unit
-
- if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
- // Always use the closest GOP we found if there is more than
- // one candidate
- if (!nearestGopObj || nearestDistance > dtsDistance) {
- nearestGopObj = currentGopObj;
- nearestDistance = dtsDistance;
- }
- }
- }
-
- if (nearestGopObj) {
- return nearestGopObj.gop;
- }
-
- return null;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the START of the list
-
-
- this.alignGopsAtStart_ = function (gops) {
- var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
- byteLength = gops.byteLength;
- nalCount = gops.nalCount;
- duration = gops.duration;
- alignIndex = gopIndex = 0;
-
- while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- break;
- }
-
- if (gop.pts > align.pts) {
- // this current gop starts after the current gop we want to align on, so increment
- // align index
- alignIndex++;
- continue;
- } // current gop starts before the current gop we want to align on. so increment gop
- // index
-
-
- gopIndex++;
- byteLength -= gop.byteLength;
- nalCount -= gop.nalCount;
- duration -= gop.duration;
- }
-
- if (gopIndex === 0) {
- // no gops to trim
- return gops;
- }
-
- if (gopIndex === gops.length) {
- // all gops trimmed, skip appending all gops
- return null;
- }
-
- alignedGops = gops.slice(gopIndex);
- alignedGops.byteLength = byteLength;
- alignedGops.duration = duration;
- alignedGops.nalCount = nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the END of the list
-
-
- this.alignGopsAtEnd_ = function (gops) {
- var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
- alignIndex = gopsToAlignWith.length - 1;
- gopIndex = gops.length - 1;
- alignEndIndex = null;
- matchFound = false;
-
- while (alignIndex >= 0 && gopIndex >= 0) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- matchFound = true;
- break;
- }
-
- if (align.pts > gop.pts) {
- alignIndex--;
- continue;
- }
-
- if (alignIndex === gopsToAlignWith.length - 1) {
- // gop.pts is greater than the last alignment candidate. If no match is found
- // by the end of this loop, we still want to append gops that come after this
- // point
- alignEndIndex = gopIndex;
- }
-
- gopIndex--;
- }
-
- if (!matchFound && alignEndIndex === null) {
- return null;
- }
-
- var trimIndex;
-
- if (matchFound) {
- trimIndex = gopIndex;
- } else {
- trimIndex = alignEndIndex;
- }
-
- if (trimIndex === 0) {
- return gops;
- }
-
- var alignedGops = gops.slice(trimIndex);
- var metadata = alignedGops.reduce(function (total, gop) {
- total.byteLength += gop.byteLength;
- total.duration += gop.duration;
- total.nalCount += gop.nalCount;
- return total;
- }, {
- byteLength: 0,
- duration: 0,
- nalCount: 0
- });
- alignedGops.byteLength = metadata.byteLength;
- alignedGops.duration = metadata.duration;
- alignedGops.nalCount = metadata.nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- };
-
- this.alignGopsWith = function (newGopsToAlignWith) {
- gopsToAlignWith = newGopsToAlignWith;
- };
- };
-
- _VideoSegmentStream.prototype = new stream();
- /**
- * A Stream that can combine multiple streams (ie. audio & video)
- * into a single output segment for MSE. Also supports audio-only
- * and video-only streams.
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at media timeline start.
- */
-
- _CoalesceStream = function CoalesceStream(options, metadataStream) {
- // Number of Tracks per output segment
- // If greater than 1, we combine multiple
- // tracks into a single segment
- this.numberOfTracks = 0;
- this.metadataStream = metadataStream;
- options = options || {};
-
- if (typeof options.remux !== 'undefined') {
- this.remuxTracks = !!options.remux;
- } else {
- this.remuxTracks = true;
- }
-
- if (typeof options.keepOriginalTimestamps === 'boolean') {
- this.keepOriginalTimestamps = options.keepOriginalTimestamps;
- } else {
- this.keepOriginalTimestamps = false;
- }
-
- this.pendingTracks = [];
- this.videoTrack = null;
- this.pendingBoxes = [];
- this.pendingCaptions = [];
- this.pendingMetadata = [];
- this.pendingBytes = 0;
- this.emittedTracks = 0;
-
- _CoalesceStream.prototype.init.call(this); // Take output from multiple
-
-
- this.push = function (output) {
- // buffer incoming captions until the associated video segment
- // finishes
- if (output.text) {
- return this.pendingCaptions.push(output);
- } // buffer incoming id3 tags until the final flush
-
-
- if (output.frames) {
- return this.pendingMetadata.push(output);
- } // Add this track to the list of pending tracks and store
- // important information required for the construction of
- // the final segment
-
-
- this.pendingTracks.push(output.track);
- this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
- // We unshift audio and push video because
- // as of Chrome 75 when switching from
- // one init segment to another if the video
- // mdat does not appear after the audio mdat
- // only audio will play for the duration of our transmux.
-
- if (output.track.type === 'video') {
- this.videoTrack = output.track;
- this.pendingBoxes.push(output.boxes);
- }
-
- if (output.track.type === 'audio') {
- this.audioTrack = output.track;
- this.pendingBoxes.unshift(output.boxes);
- }
- };
- };
-
- _CoalesceStream.prototype = new stream();
-
- _CoalesceStream.prototype.flush = function (flushSource) {
- var offset = 0,
- event = {
- captions: [],
- captionStreams: {},
- metadata: [],
- info: {}
- },
- caption,
- id3,
- initSegment,
- timelineStartPts = 0,
- i;
-
- if (this.pendingTracks.length < this.numberOfTracks) {
- if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
- // Return because we haven't received a flush from a data-generating
- // portion of the segment (meaning that we have only recieved meta-data
- // or captions.)
- return;
- } else if (this.remuxTracks) {
- // Return until we have enough tracks from the pipeline to remux (if we
- // are remuxing audio and video into a single MP4)
- return;
- } else if (this.pendingTracks.length === 0) {
- // In the case where we receive a flush without any data having been
- // received we consider it an emitted track for the purposes of coalescing
- // `done` events.
- // We do this for the case where there is an audio and video track in the
- // segment but no audio data. (seen in several playlists with alternate
- // audio tracks and no audio present in the main TS segments.)
- this.emittedTracks++;
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
-
- return;
- }
- }
-
- if (this.videoTrack) {
- timelineStartPts = this.videoTrack.timelineStartInfo.pts;
- videoProperties.forEach(function (prop) {
- event.info[prop] = this.videoTrack[prop];
- }, this);
- } else if (this.audioTrack) {
- timelineStartPts = this.audioTrack.timelineStartInfo.pts;
- audioProperties.forEach(function (prop) {
- event.info[prop] = this.audioTrack[prop];
- }, this);
- }
-
- if (this.videoTrack || this.audioTrack) {
- if (this.pendingTracks.length === 1) {
- event.type = this.pendingTracks[0].type;
- } else {
- event.type = 'combined';
- }
-
- this.emittedTracks += this.pendingTracks.length;
- initSegment = mp4Generator.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
-
- event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
- // and track definitions
-
- event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
-
- event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
-
- for (i = 0; i < this.pendingBoxes.length; i++) {
- event.data.set(this.pendingBoxes[i], offset);
- offset += this.pendingBoxes[i].byteLength;
- } // Translate caption PTS times into second offsets to match the
- // video timeline for the segment, and add track info
-
-
- for (i = 0; i < this.pendingCaptions.length; i++) {
- caption = this.pendingCaptions[i];
- caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
- caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
- event.captionStreams[caption.stream] = true;
- event.captions.push(caption);
- } // Translate ID3 frame PTS times into second offsets to match the
- // video timeline for the segment
-
-
- for (i = 0; i < this.pendingMetadata.length; i++) {
- id3 = this.pendingMetadata[i];
- id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
- event.metadata.push(id3);
- } // We add this to every single emitted segment even though we only need
- // it for the first
-
-
- event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
-
- this.pendingTracks.length = 0;
- this.videoTrack = null;
- this.pendingBoxes.length = 0;
- this.pendingCaptions.length = 0;
- this.pendingBytes = 0;
- this.pendingMetadata.length = 0; // Emit the built segment
- // We include captions and ID3 tags for backwards compatibility,
- // ideally we should send only video and audio in the data event
-
- this.trigger('data', event); // Emit each caption to the outside world
- // Ideally, this would happen immediately on parsing captions,
- // but we need to ensure that video data is sent back first
- // so that caption timing can be adjusted to match video timing
-
- for (i = 0; i < event.captions.length; i++) {
- caption = event.captions[i];
- this.trigger('caption', caption);
- } // Emit each id3 tag to the outside world
- // Ideally, this would happen immediately on parsing the tag,
- // but we need to ensure that video data is sent back first
- // so that ID3 frame timing can be adjusted to match video timing
-
-
- for (i = 0; i < event.metadata.length; i++) {
- id3 = event.metadata[i];
- this.trigger('id3Frame', id3);
- }
- } // Only emit `done` if all tracks have been flushed and emitted
-
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
- };
-
- _CoalesceStream.prototype.setRemux = function (val) {
- this.remuxTracks = val;
- };
- /**
- * A Stream that expects MP2T binary data as input and produces
- * corresponding media segments, suitable for use with Media Source
- * Extension (MSE) implementations that support the ISO BMFF byte
- * stream format, like Chrome.
- */
-
-
- _Transmuxer = function Transmuxer(options) {
- var self = this,
- hasFlushed = true,
- videoTrack,
- audioTrack;
-
- _Transmuxer.prototype.init.call(this);
-
- options = options || {};
- this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
- this.transmuxPipeline_ = {};
-
- this.setupAacPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'aac';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.aacStream = new aac();
- pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('audio');
- pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('timed-metadata');
- pipeline.adtsStream = new adts();
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.aacStream;
- pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
- pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
- pipeline.metadataStream.on('timestamp', function (frame) {
- pipeline.aacStream.setTimestamp(frame.timeStamp);
- });
- pipeline.aacStream.on('data', function (data) {
- if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
- return;
- }
-
- audioTrack = audioTrack || {
- timelineStartInfo: {
- baseMediaDecodeTime: self.baseMediaDecodeTime
- },
- codec: 'adts',
- type: 'audio'
- }; // hook up the audio segment stream to the first track with aac data
-
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- };
-
- this.setupTsPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'ts';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.packetStream = new m2ts_1.TransportPacketStream();
- pipeline.parseStream = new m2ts_1.TransportParseStream();
- pipeline.elementaryStream = new m2ts_1.ElementaryStream();
- pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
- pipeline.adtsStream = new adts();
- pipeline.h264Stream = new H264Stream();
- pipeline.captionStream = new m2ts_1.CaptionStream(options);
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
-
- pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
- // demux the streams
-
- pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
- pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
- pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
-
- pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
- pipeline.elementaryStream.on('data', function (data) {
- var i;
-
- if (data.type === 'metadata') {
- i = data.tracks.length; // scan the tracks listed in the metadata
-
- while (i--) {
- if (!videoTrack && data.tracks[i].type === 'video') {
- videoTrack = data.tracks[i];
- videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- } else if (!audioTrack && data.tracks[i].type === 'audio') {
- audioTrack = data.tracks[i];
- audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- }
- } // hook up the video segment stream to the first track with h264 data
-
-
- if (videoTrack && !pipeline.videoSegmentStream) {
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
- pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
- // When video emits timelineStartInfo data after a flush, we forward that
- // info to the AudioSegmentStream, if it exists, because video timeline
- // data takes precedence. Do not do this if keepOriginalTimestamps is set,
- // because this is a particularly subtle form of timestamp alteration.
- if (audioTrack && !options.keepOriginalTimestamps) {
- audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
- // very earliest DTS we have seen in video because Chrome will
- // interpret any video track with a baseMediaDecodeTime that is
- // non-zero as a gap.
-
- pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
- pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
- pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
- if (audioTrack) {
- pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
-
- pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
- }
-
- if (audioTrack && !pipeline.audioSegmentStream) {
- // hook up the audio segment stream to the first track with aac data
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
- pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
- } // emit pmt info
-
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
- pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
- id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
- self.trigger('id3Frame', id3Frame);
- });
- pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- }; // hook up the segment streams once track metadata is delivered
-
-
- this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- var pipeline = this.transmuxPipeline_;
-
- if (!options.keepOriginalTimestamps) {
- this.baseMediaDecodeTime = baseMediaDecodeTime;
- }
-
- if (audioTrack) {
- audioTrack.timelineStartInfo.dts = undefined;
- audioTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(audioTrack);
-
- if (pipeline.audioTimestampRolloverStream) {
- pipeline.audioTimestampRolloverStream.discontinuity();
- }
- }
-
- if (videoTrack) {
- if (pipeline.videoSegmentStream) {
- pipeline.videoSegmentStream.gopCache_ = [];
- }
-
- videoTrack.timelineStartInfo.dts = undefined;
- videoTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(videoTrack);
- pipeline.captionStream.reset();
- }
-
- if (pipeline.timestampRolloverStream) {
- pipeline.timestampRolloverStream.discontinuity();
- }
- };
-
- this.setAudioAppendStart = function (timestamp) {
- if (audioTrack) {
- this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
- }
- };
-
- this.setRemux = function (val) {
- var pipeline = this.transmuxPipeline_;
- options.remux = val;
-
- if (pipeline && pipeline.coalesceStream) {
- pipeline.coalesceStream.setRemux(val);
- }
- };
-
- this.alignGopsWith = function (gopsToAlignWith) {
- if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
- this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
- }
- }; // feed incoming data to the front of the parsing pipeline
-
-
- this.push = function (data) {
- if (hasFlushed) {
- var isAac = isLikelyAacData(data);
-
- if (isAac && this.transmuxPipeline_.type !== 'aac') {
- this.setupAacPipeline();
- } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
- this.setupTsPipeline();
- }
-
- hasFlushed = false;
- }
-
- this.transmuxPipeline_.headOfPipeline.push(data);
- }; // flush any buffered data
-
-
- this.flush = function () {
- hasFlushed = true; // Start at the top of the pipeline and flush all pending work
-
- this.transmuxPipeline_.headOfPipeline.flush();
- };
-
- this.endTimeline = function () {
- this.transmuxPipeline_.headOfPipeline.endTimeline();
- };
-
- this.reset = function () {
- if (this.transmuxPipeline_.headOfPipeline) {
- this.transmuxPipeline_.headOfPipeline.reset();
- }
- }; // Caption data has to be reset when seeking outside buffered range
-
-
- this.resetCaptions = function () {
- if (this.transmuxPipeline_.captionStream) {
- this.transmuxPipeline_.captionStream.reset();
- }
- };
- };
-
- _Transmuxer.prototype = new stream();
- var transmuxer = {
- Transmuxer: _Transmuxer,
- VideoSegmentStream: _VideoSegmentStream,
- AudioSegmentStream: _AudioSegmentStream,
- AUDIO_PROPERTIES: audioProperties,
- VIDEO_PROPERTIES: videoProperties,
- // exported for testing
- generateSegmentTimingInfo: generateSegmentTimingInfo
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var toUnsigned$3 = function toUnsigned(value) {
- return value >>> 0;
- };
-
- var toHexString$1 = function toHexString(value) {
- return ('00' + value.toString(16)).slice(-2);
- };
-
- var bin = {
- toUnsigned: toUnsigned$3,
- toHexString: toHexString$1
- };
-
- var parseType$1 = function parseType(buffer) {
- var result = '';
- result += String.fromCharCode(buffer[0]);
- result += String.fromCharCode(buffer[1]);
- result += String.fromCharCode(buffer[2]);
- result += String.fromCharCode(buffer[3]);
- return result;
- };
-
- var parseType_1 = parseType$1;
- var toUnsigned$2 = bin.toUnsigned;
-
- var findBox = function findBox(data, path) {
- var results = [],
- i,
- size,
- type,
- end,
- subresults;
-
- if (!path.length) {
- // short-circuit the search for empty paths
- return null;
- }
-
- for (i = 0; i < data.byteLength;) {
- size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
- type = parseType_1(data.subarray(i + 4, i + 8));
- end = size > 1 ? i + size : data.byteLength;
-
- if (type === path[0]) {
- if (path.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data.subarray(i + 8, end));
- } else {
- // recursively search for the next box along the path
- subresults = findBox(data.subarray(i + 8, end), path.slice(1));
-
- if (subresults.length) {
- results = results.concat(subresults);
- }
- }
- }
-
- i = end;
- } // we've finished searching all of data
-
-
- return results;
- };
-
- var findBox_1 = findBox;
- var toUnsigned$1 = bin.toUnsigned;
-
- var tfdt = function tfdt(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- baseMediaDecodeTime: toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7])
- };
-
- if (result.version === 1) {
- result.baseMediaDecodeTime *= Math.pow(2, 32);
- result.baseMediaDecodeTime += toUnsigned$1(data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11]);
- }
-
- return result;
- };
-
- var parseTfdt = tfdt;
-
- var parseSampleFlags = function parseSampleFlags(flags) {
- return {
- isLeading: (flags[0] & 0x0c) >>> 2,
- dependsOn: flags[0] & 0x03,
- isDependedOn: (flags[1] & 0xc0) >>> 6,
- hasRedundancy: (flags[1] & 0x30) >>> 4,
- paddingValue: (flags[1] & 0x0e) >>> 1,
- isNonSyncSample: flags[1] & 0x01,
- degradationPriority: flags[2] << 8 | flags[3]
- };
- };
-
- var parseSampleFlags_1 = parseSampleFlags;
-
- var trun = function trun(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- samples: []
- },
- view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- // Flag interpretation
- dataOffsetPresent = result.flags[2] & 0x01,
- // compare with 2nd byte of 0x1
- firstSampleFlagsPresent = result.flags[2] & 0x04,
- // compare with 2nd byte of 0x4
- sampleDurationPresent = result.flags[1] & 0x01,
- // compare with 2nd byte of 0x100
- sampleSizePresent = result.flags[1] & 0x02,
- // compare with 2nd byte of 0x200
- sampleFlagsPresent = result.flags[1] & 0x04,
- // compare with 2nd byte of 0x400
- sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
- // compare with 2nd byte of 0x800
- sampleCount = view.getUint32(4),
- offset = 8,
- sample;
-
- if (dataOffsetPresent) {
- // 32 bit signed integer
- result.dataOffset = view.getInt32(offset);
- offset += 4;
- } // Overrides the flags for the first sample only. The order of
- // optional values will be: duration, size, compositionTimeOffset
-
-
- if (firstSampleFlagsPresent && sampleCount) {
- sample = {
- flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
- };
- offset += 4;
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- sampleCount--;
- }
-
- while (sampleCount--) {
- sample = {};
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleFlagsPresent) {
- sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- }
-
- return result;
- };
-
- var parseTrun = trun;
-
- var tfhd = function tfhd(data) {
- var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- trackId: view.getUint32(4)
- },
- baseDataOffsetPresent = result.flags[2] & 0x01,
- sampleDescriptionIndexPresent = result.flags[2] & 0x02,
- defaultSampleDurationPresent = result.flags[2] & 0x08,
- defaultSampleSizePresent = result.flags[2] & 0x10,
- defaultSampleFlagsPresent = result.flags[2] & 0x20,
- durationIsEmpty = result.flags[0] & 0x010000,
- defaultBaseIsMoof = result.flags[0] & 0x020000,
- i;
- i = 8;
-
- if (baseDataOffsetPresent) {
- i += 4; // truncate top 4 bytes
- // FIXME: should we read the full 64 bits?
-
- result.baseDataOffset = view.getUint32(12);
- i += 4;
- }
-
- if (sampleDescriptionIndexPresent) {
- result.sampleDescriptionIndex = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleDurationPresent) {
- result.defaultSampleDuration = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleSizePresent) {
- result.defaultSampleSize = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleFlagsPresent) {
- result.defaultSampleFlags = view.getUint32(i);
- }
-
- if (durationIsEmpty) {
- result.durationIsEmpty = true;
- }
-
- if (!baseDataOffsetPresent && defaultBaseIsMoof) {
- result.baseDataOffsetIsMoof = true;
- }
-
- return result;
- };
-
- var parseTfhd = tfhd;
- var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
- var CaptionStream = captionStream.CaptionStream;
- /**
- * Maps an offset in the mdat to a sample based on the the size of the samples.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Number} offset - The offset into the mdat
- * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
- * @return {?Object} The matching sample, or null if no match was found.
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
- var mapToSample = function mapToSample(offset, samples) {
- var approximateOffset = offset;
-
- for (var i = 0; i < samples.length; i++) {
- var sample = samples[i];
-
- if (approximateOffset < sample.size) {
- return sample;
- }
-
- approximateOffset -= sample.size;
- }
-
- return null;
- };
- /**
- * Finds SEI nal units contained in a Media Data Box.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Uint8Array} avcStream - The bytes of the mdat
- * @param {Object[]} samples - The samples parsed out by `parseSamples`
- * @param {Number} trackId - The trackId of this video track
- * @return {Object[]} seiNals - the parsed SEI NALUs found.
- * The contents of the seiNal should match what is expected by
- * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
- *
- * @see ISO-BMFF-12/2015, Section 8.1.1
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- **/
-
-
- var findSeiNals = function findSeiNals(avcStream, samples, trackId) {
- var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
- result = [],
- seiNal,
- i,
- length,
- lastMatchedSample;
-
- for (i = 0; i + 4 < avcStream.length; i += length) {
- length = avcView.getUint32(i);
- i += 4; // Bail if this doesn't appear to be an H264 stream
-
- if (length <= 0) {
- continue;
- }
-
- switch (avcStream[i] & 0x1F) {
- case 0x06:
- var data = avcStream.subarray(i + 1, i + 1 + length);
- var matchingSample = mapToSample(i, samples);
- seiNal = {
- nalUnitType: 'sei_rbsp',
- size: length,
- data: data,
- escapedRBSP: discardEmulationPreventionBytes(data),
- trackId: trackId
- };
-
- if (matchingSample) {
- seiNal.pts = matchingSample.pts;
- seiNal.dts = matchingSample.dts;
- lastMatchedSample = matchingSample;
- } else if (lastMatchedSample) {
- // If a matching sample cannot be found, use the last
- // sample's values as they should be as close as possible
- seiNal.pts = lastMatchedSample.pts;
- seiNal.dts = lastMatchedSample.dts;
- } else {
- // eslint-disable-next-line no-console
- console.log("We've encountered a nal unit without data. See mux.js#233.");
- break;
- }
-
- result.push(seiNal);
- break;
- }
- }
-
- return result;
- };
- /**
- * Parses sample information out of Track Run Boxes and calculates
- * the absolute presentation and decode timestamps of each sample.
- *
- * @param {Array} truns - The Trun Run boxes to be parsed
- * @param {Number} baseMediaDecodeTime - base media decode time from tfdt
- @see ISO-BMFF-12/2015, Section 8.8.12
- * @param {Object} tfhd - The parsed Track Fragment Header
- * @see inspect.parseTfhd
- * @return {Object[]} the parsed samples
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
-
- var parseSamples = function parseSamples(truns, baseMediaDecodeTime, tfhd) {
- var currentDts = baseMediaDecodeTime;
- var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
- var defaultSampleSize = tfhd.defaultSampleSize || 0;
- var trackId = tfhd.trackId;
- var allSamples = [];
- truns.forEach(function (trun) {
- // Note: We currently do not parse the sample table as well
- // as the trun. It's possible some sources will require this.
- // moov > trak > mdia > minf > stbl
- var trackRun = parseTrun(trun);
- var samples = trackRun.samples;
- samples.forEach(function (sample) {
- if (sample.duration === undefined) {
- sample.duration = defaultSampleDuration;
- }
-
- if (sample.size === undefined) {
- sample.size = defaultSampleSize;
- }
-
- sample.trackId = trackId;
- sample.dts = currentDts;
-
- if (sample.compositionTimeOffset === undefined) {
- sample.compositionTimeOffset = 0;
- }
-
- sample.pts = currentDts + sample.compositionTimeOffset;
- currentDts += sample.duration;
- });
- allSamples = allSamples.concat(samples);
- });
- return allSamples;
- };
- /**
- * Parses out caption nals from an FMP4 segment's video tracks.
- *
- * @param {Uint8Array} segment - The bytes of a single segment
- * @param {Number} videoTrackId - The trackId of a video track in the segment
- * @return {Object.} A mapping of video trackId to
- * a list of seiNals found in that track
- **/
-
-
- var parseCaptionNals = function parseCaptionNals(segment, videoTrackId) {
- // To get the samples
- var trafs = findBox_1(segment, ['moof', 'traf']); // To get SEI NAL units
-
- var mdats = findBox_1(segment, ['mdat']);
- var captionNals = {};
- var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
-
- mdats.forEach(function (mdat, index) {
- var matchingTraf = trafs[index];
- mdatTrafPairs.push({
- mdat: mdat,
- traf: matchingTraf
- });
- });
- mdatTrafPairs.forEach(function (pair) {
- var mdat = pair.mdat;
- var traf = pair.traf;
- var tfhd = findBox_1(traf, ['tfhd']); // Exactly 1 tfhd per traf
-
- var headerInfo = parseTfhd(tfhd[0]);
- var trackId = headerInfo.trackId;
- var tfdt = findBox_1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
-
- var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
- var truns = findBox_1(traf, ['trun']);
- var samples;
- var seiNals; // Only parse video data for the chosen video track
-
- if (videoTrackId === trackId && truns.length > 0) {
- samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
- seiNals = findSeiNals(mdat, samples, trackId);
-
- if (!captionNals[trackId]) {
- captionNals[trackId] = [];
- }
-
- captionNals[trackId] = captionNals[trackId].concat(seiNals);
- }
- });
- return captionNals;
- };
- /**
- * Parses out inband captions from an MP4 container and returns
- * caption objects that can be used by WebVTT and the TextTrack API.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
- * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
- * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number} trackId - The id of the video track to parse
- * @param {Number} timescale - The timescale for the video track from the init segment
- *
- * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
- * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
- * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
- * @return {String} parsedCaptions[].text - The visible content of the caption
- **/
-
-
- var parseEmbeddedCaptions = function parseEmbeddedCaptions(segment, trackId, timescale) {
- var seiNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
-
- if (trackId === null) {
- return null;
- }
-
- seiNals = parseCaptionNals(segment, trackId);
- return {
- seiNals: seiNals[trackId],
- timescale: timescale
- };
- };
- /**
- * Converts SEI NALUs into captions that can be used by video.js
- **/
-
-
- var CaptionParser = function CaptionParser() {
- var isInitialized = false;
- var captionStream; // Stores segments seen before trackId and timescale are set
-
- var segmentCache; // Stores video track ID of the track being parsed
-
- var trackId; // Stores the timescale of the track being parsed
-
- var timescale; // Stores captions parsed so far
-
- var parsedCaptions; // Stores whether we are receiving partial data or not
-
- var parsingPartial;
- /**
- * A method to indicate whether a CaptionParser has been initalized
- * @returns {Boolean}
- **/
-
- this.isInitialized = function () {
- return isInitialized;
- };
- /**
- * Initializes the underlying CaptionStream, SEI NAL parsing
- * and management, and caption collection
- **/
-
-
- this.init = function (options) {
- captionStream = new CaptionStream();
- isInitialized = true;
- parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
-
- captionStream.on('data', function (event) {
- // Convert to seconds in the source's timescale
- event.startTime = event.startPts / timescale;
- event.endTime = event.endPts / timescale;
- parsedCaptions.captions.push(event);
- parsedCaptions.captionStreams[event.stream] = true;
- });
- };
- /**
- * Determines if a new video track will be selected
- * or if the timescale changed
- * @return {Boolean}
- **/
-
-
- this.isNewInit = function (videoTrackIds, timescales) {
- if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
- return false;
- }
-
- return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
- };
- /**
- * Parses out SEI captions and interacts with underlying
- * CaptionStream to return dispatched captions
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
- * @param {Object.} timescales - The timescales found in the init segment
- * @see parseEmbeddedCaptions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.parse = function (segment, videoTrackIds, timescales) {
- var parsedData;
-
- if (!this.isInitialized()) {
- return null; // This is not likely to be a video segment
- } else if (!videoTrackIds || !timescales) {
- return null;
- } else if (this.isNewInit(videoTrackIds, timescales)) {
- // Use the first video track only as there is no
- // mechanism to switch to other video tracks
- trackId = videoTrackIds[0];
- timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
- // data until we have one.
- // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
- } else if (trackId === null || !timescale) {
- segmentCache.push(segment);
- return null;
- } // Now that a timescale and trackId is set, parse cached segments
-
-
- while (segmentCache.length > 0) {
- var cachedSegment = segmentCache.shift();
- this.parse(cachedSegment, videoTrackIds, timescales);
- }
-
- parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
-
- if (parsedData === null || !parsedData.seiNals) {
- return null;
- }
-
- this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
-
- this.flushStream();
- return parsedCaptions;
- };
- /**
- * Pushes SEI NALUs onto CaptionStream
- * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
- * Assumes that `parseCaptionNals` has been called first
- * @see m2ts/caption-stream.js
- **/
-
-
- this.pushNals = function (nals) {
- if (!this.isInitialized() || !nals || nals.length === 0) {
- return null;
- }
-
- nals.forEach(function (nal) {
- captionStream.push(nal);
- });
- };
- /**
- * Flushes underlying CaptionStream to dispatch processed, displayable captions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.flushStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- if (!parsingPartial) {
- captionStream.flush();
- } else {
- captionStream.partialFlush();
- }
- };
- /**
- * Reset caption buckets for new data
- **/
-
-
- this.clearParsedCaptions = function () {
- parsedCaptions.captions = [];
- parsedCaptions.captionStreams = {};
- };
- /**
- * Resets underlying CaptionStream
- * @see m2ts/caption-stream.js
- **/
-
-
- this.resetCaptionStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- captionStream.reset();
- };
- /**
- * Convenience method to clear all captions flushed from the
- * CaptionStream and still being parsed
- * @see m2ts/caption-stream.js
- **/
-
-
- this.clearAllCaptions = function () {
- this.clearParsedCaptions();
- this.resetCaptionStream();
- };
- /**
- * Reset caption parser
- **/
-
-
- this.reset = function () {
- segmentCache = [];
- trackId = null;
- timescale = null;
-
- if (!parsedCaptions) {
- parsedCaptions = {
- captions: [],
- // CC1, CC2, CC3, CC4
- captionStreams: {}
- };
- } else {
- this.clearParsedCaptions();
- }
-
- this.resetCaptionStream();
- };
-
- this.reset();
- };
-
- var captionParser = CaptionParser;
- var toUnsigned = bin.toUnsigned;
- var toHexString = bin.toHexString;
- var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader;
- /**
- * Parses an MP4 initialization segment and extracts the timescale
- * values for any declared tracks. Timescale values indicate the
- * number of clock ticks per second to assume for time-based values
- * elsewhere in the MP4.
- *
- * To determine the start time of an MP4, you need two pieces of
- * information: the timescale unit and the earliest base media decode
- * time. Multiple timescales can be specified within an MP4 but the
- * base media decode time is always expressed in the timescale from
- * the media header box for the track:
- * ```
- * moov > trak > mdia > mdhd.timescale
- * ```
- * @param init {Uint8Array} the bytes of the init segment
- * @return {object} a hash of track ids to timescale values or null if
- * the init segment is malformed.
- */
-
- timescale = function timescale(init) {
- var result = {},
- traks = findBox_1(init, ['moov', 'trak']); // mdhd timescale
-
- return traks.reduce(function (result, trak) {
- var tkhd, version, index, id, mdhd;
- tkhd = findBox_1(trak, ['tkhd'])[0];
-
- if (!tkhd) {
- return null;
- }
-
- version = tkhd[0];
- index = version === 0 ? 12 : 20;
- id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
- mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
-
- if (!mdhd) {
- return null;
- }
-
- version = mdhd[0];
- index = version === 0 ? 12 : 20;
- result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
- return result;
- }, result);
- };
- /**
- * Determine the base media decode start time, in seconds, for an MP4
- * fragment. If multiple fragments are specified, the earliest time is
- * returned.
- *
- * The base media decode time can be parsed from track fragment
- * metadata:
- * ```
- * moof > traf > tfdt.baseMediaDecodeTime
- * ```
- * It requires the timescale value from the mdhd to interpret.
- *
- * @param timescale {object} a hash of track ids to timescale values.
- * @return {number} the earliest base media decode start time for the
- * fragment, in seconds
- */
-
-
- startTime = function startTime(timescale, fragment) {
- var trafs, baseTimes, result; // we need info from two childrend of each track fragment box
-
- trafs = findBox_1(fragment, ['moof', 'traf']); // determine the start times for each track
-
- baseTimes = [].concat.apply([], trafs.map(function (traf) {
- return findBox_1(traf, ['tfhd']).map(function (tfhd) {
- var id, scale, baseTime; // get the track id from the tfhd
-
- id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
-
- scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
-
- baseTime = findBox_1(traf, ['tfdt']).map(function (tfdt) {
- var version, result;
- version = tfdt[0];
- result = toUnsigned(tfdt[4] << 24 | tfdt[5] << 16 | tfdt[6] << 8 | tfdt[7]);
-
- if (version === 1) {
- result *= Math.pow(2, 32);
- result += toUnsigned(tfdt[8] << 24 | tfdt[9] << 16 | tfdt[10] << 8 | tfdt[11]);
- }
-
- return result;
- })[0];
- baseTime = typeof baseTime === 'number' && !isNaN(baseTime) ? baseTime : Infinity; // convert base time to seconds
-
- return baseTime / scale;
- });
- })); // return the minimum
-
- result = Math.min.apply(null, baseTimes);
- return isFinite(result) ? result : 0;
- };
- /**
- * Determine the composition start, in seconds, for an MP4
- * fragment.
- *
- * The composition start time of a fragment can be calculated using the base
- * media decode time, composition time offset, and timescale, as follows:
- *
- * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
- *
- * All of the aforementioned information is contained within a media fragment's
- * `traf` box, except for timescale info, which comes from the initialization
- * segment, so a track id (also contained within a `traf`) is also necessary to
- * associate it with a timescale
- *
- *
- * @param timescales {object} - a hash of track ids to timescale values.
- * @param fragment {Unit8Array} - the bytes of a media segment
- * @return {number} the composition start time for the fragment, in seconds
- **/
-
-
- compositionStartTime = function compositionStartTime(timescales, fragment) {
- var trafBoxes = findBox_1(fragment, ['moof', 'traf']);
- var baseMediaDecodeTime = 0;
- var compositionTimeOffset = 0;
- var trackId;
-
- if (trafBoxes && trafBoxes.length) {
- // The spec states that track run samples contained within a `traf` box are contiguous, but
- // it does not explicitly state whether the `traf` boxes themselves are contiguous.
- // We will assume that they are, so we only need the first to calculate start time.
- var tfhd = findBox_1(trafBoxes[0], ['tfhd'])[0];
- var trun = findBox_1(trafBoxes[0], ['trun'])[0];
- var tfdt = findBox_1(trafBoxes[0], ['tfdt'])[0];
-
- if (tfhd) {
- var parsedTfhd = parseTfhd(tfhd);
- trackId = parsedTfhd.trackId;
- }
-
- if (tfdt) {
- var parsedTfdt = parseTfdt(tfdt);
- baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
- }
-
- if (trun) {
- var parsedTrun = parseTrun(trun);
-
- if (parsedTrun.samples && parsedTrun.samples.length) {
- compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
- }
- }
- } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
- // specified.
-
-
- var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
-
- return (baseMediaDecodeTime + compositionTimeOffset) / timescale;
- };
- /**
- * Find the trackIds of the video tracks in this source.
- * Found by parsing the Handler Reference and Track Header Boxes:
- * moov > trak > mdia > hdlr
- * moov > trak > tkhd
- *
- * @param {Uint8Array} init - The bytes of the init segment for this source
- * @return {Number[]} A list of trackIds
- *
- * @see ISO-BMFF-12/2015, Section 8.4.3
- **/
-
-
- getVideoTrackIds = function getVideoTrackIds(init) {
- var traks = findBox_1(init, ['moov', 'trak']);
- var videoTrackIds = [];
- traks.forEach(function (trak) {
- var hdlrs = findBox_1(trak, ['mdia', 'hdlr']);
- var tkhds = findBox_1(trak, ['tkhd']);
- hdlrs.forEach(function (hdlr, index) {
- var handlerType = parseType_1(hdlr.subarray(8, 12));
- var tkhd = tkhds[index];
- var view;
- var version;
- var trackId;
-
- if (handlerType === 'vide') {
- view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- version = view.getUint8(0);
- trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
- videoTrackIds.push(trackId);
- }
- });
- });
- return videoTrackIds;
- };
-
- getTimescaleFromMediaHeader = function getTimescaleFromMediaHeader(mdhd) {
- // mdhd is a FullBox, meaning it will have its own version as the first byte
- var version = mdhd[0];
- var index = version === 0 ? 12 : 20;
- return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
- };
- /**
- * Get all the video, audio, and hint tracks from a non fragmented
- * mp4 segment
- */
-
-
- getTracks = function getTracks(init) {
- var traks = findBox_1(init, ['moov', 'trak']);
- var tracks = [];
- traks.forEach(function (trak) {
- var track = {};
- var tkhd = findBox_1(trak, ['tkhd'])[0];
- var view, tkhdVersion; // id
-
- if (tkhd) {
- view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- tkhdVersion = view.getUint8(0);
- track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
- }
-
- var hdlr = findBox_1(trak, ['mdia', 'hdlr'])[0]; // type
-
- if (hdlr) {
- var type = parseType_1(hdlr.subarray(8, 12));
-
- if (type === 'vide') {
- track.type = 'video';
- } else if (type === 'soun') {
- track.type = 'audio';
- } else {
- track.type = type;
- }
- } // codec
-
-
- var stsd = findBox_1(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
-
- if (stsd) {
- var sampleDescriptions = stsd.subarray(8); // gives the codec type string
-
- track.codec = parseType_1(sampleDescriptions.subarray(4, 8));
- var codecBox = findBox_1(sampleDescriptions, [track.codec])[0];
- var codecConfig, codecConfigType;
-
- if (codecBox) {
- // https://tools.ietf.org/html/rfc6381#section-3.3
- if (/^[a-z]vc[1-9]$/i.test(track.codec)) {
- // we don't need anything but the "config" parameter of the
- // avc1 codecBox
- codecConfig = codecBox.subarray(78);
- codecConfigType = parseType_1(codecConfig.subarray(4, 8));
-
- if (codecConfigType === 'avcC' && codecConfig.length > 11) {
- track.codec += '.'; // left padded with zeroes for single digit hex
- // profile idc
-
- track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
-
- track.codec += toHexString(codecConfig[10]); // level idc
-
- track.codec += toHexString(codecConfig[11]);
- } else {
- // TODO: show a warning that we couldn't parse the codec
- // and are using the default
- track.codec = 'avc1.4d400d';
- }
- } else if (/^mp4[a,v]$/i.test(track.codec)) {
- // we do not need anything but the streamDescriptor of the mp4a codecBox
- codecConfig = codecBox.subarray(28);
- codecConfigType = parseType_1(codecConfig.subarray(4, 8));
-
- if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
- track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
-
- track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
- } else {
- // TODO: show a warning that we couldn't parse the codec
- // and are using the default
- track.codec = 'mp4a.40.2';
- }
- } else {
- // flac, opus, etc
- track.codec = track.codec.toLowerCase();
- }
- }
- }
-
- var mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
-
- if (mdhd) {
- track.timescale = getTimescaleFromMediaHeader(mdhd);
- }
-
- tracks.push(track);
- });
- return tracks;
- };
-
- var probe$2 = {
- // export mp4 inspector's findBox and parseType for backwards compatibility
- findBox: findBox_1,
- parseType: parseType_1,
- timescale: timescale,
- startTime: startTime,
- compositionStartTime: compositionStartTime,
- videoTrackIds: getVideoTrackIds,
- tracks: getTracks,
- getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
- };
-
- var parsePid = function parsePid(packet) {
- var pid = packet[1] & 0x1f;
- pid <<= 8;
- pid |= packet[2];
- return pid;
- };
-
- var parsePayloadUnitStartIndicator = function parsePayloadUnitStartIndicator(packet) {
- return !!(packet[1] & 0x40);
- };
-
- var parseAdaptionField = function parseAdaptionField(packet) {
- var offset = 0; // if an adaption field is present, its length is specified by the
- // fifth byte of the TS packet header. The adaptation field is
- // used to add stuffing to PES packets that don't fill a complete
- // TS packet, and to specify some forms of timing and control data
- // that we do not currently use.
-
- if ((packet[3] & 0x30) >>> 4 > 0x01) {
- offset += packet[4] + 1;
- }
-
- return offset;
- };
-
- var parseType = function parseType(packet, pmtPid) {
- var pid = parsePid(packet);
-
- if (pid === 0) {
- return 'pat';
- } else if (pid === pmtPid) {
- return 'pmt';
- } else if (pmtPid) {
- return 'pes';
- }
-
- return null;
- };
-
- var parsePat = function parsePat(packet) {
- var pusi = parsePayloadUnitStartIndicator(packet);
- var offset = 4 + parseAdaptionField(packet);
-
- if (pusi) {
- offset += packet[offset] + 1;
- }
-
- return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
- };
-
- var parsePmt = function parsePmt(packet) {
- var programMapTable = {};
- var pusi = parsePayloadUnitStartIndicator(packet);
- var payloadOffset = 4 + parseAdaptionField(packet);
-
- if (pusi) {
- payloadOffset += packet[payloadOffset] + 1;
- } // PMTs can be sent ahead of the time when they should actually
- // take effect. We don't believe this should ever be the case
- // for HLS but we'll ignore "forward" PMT declarations if we see
- // them. Future PMT declarations have the current_next_indicator
- // set to zero.
-
-
- if (!(packet[payloadOffset + 5] & 0x01)) {
- return;
- }
-
- var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
-
- sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
- tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
- // long the program info descriptors are
-
- programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
-
- var offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
-
- programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
- // skip past the elementary stream descriptors, if present
-
- offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
- }
-
- return programMapTable;
- };
-
- var parsePesType = function parsePesType(packet, programMapTable) {
- var pid = parsePid(packet);
- var type = programMapTable[pid];
-
- switch (type) {
- case streamTypes.H264_STREAM_TYPE:
- return 'video';
-
- case streamTypes.ADTS_STREAM_TYPE:
- return 'audio';
-
- case streamTypes.METADATA_STREAM_TYPE:
- return 'timed-metadata';
-
- default:
- return null;
- }
- };
-
- var parsePesTime = function parsePesTime(packet) {
- var pusi = parsePayloadUnitStartIndicator(packet);
-
- if (!pusi) {
- return null;
- }
-
- var offset = 4 + parseAdaptionField(packet);
-
- if (offset >= packet.byteLength) {
- // From the H 222.0 MPEG-TS spec
- // "For transport stream packets carrying PES packets, stuffing is needed when there
- // is insufficient PES packet data to completely fill the transport stream packet
- // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
- // the sum of the lengths of the data elements in it, so that the payload bytes
- // remaining after the adaptation field exactly accommodates the available PES packet
- // data."
- //
- // If the offset is >= the length of the packet, then the packet contains no data
- // and instead is just adaption field stuffing bytes
- return null;
- }
-
- var pes = null;
- var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
- // and a DTS value. Determine what combination of values is
- // available to work with.
-
- ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
- // performs all bitwise operations on 32-bit integers but javascript
- // supports a much greater range (52-bits) of integer using standard
- // mathematical operations.
- // We construct a 31-bit value using bitwise operators over the 31
- // most significant bits and then multiply by 4 (equal to a left-shift
- // of 2) before we add the final 2 least significant bits of the
- // timestamp (equal to an OR.)
-
- if (ptsDtsFlags & 0xC0) {
- pes = {}; // the PTS and DTS are not written out directly. For information
- // on how they are encoded, see
- // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
-
- pes.pts = (packet[offset + 9] & 0x0E) << 27 | (packet[offset + 10] & 0xFF) << 20 | (packet[offset + 11] & 0xFE) << 12 | (packet[offset + 12] & 0xFF) << 5 | (packet[offset + 13] & 0xFE) >>> 3;
- pes.pts *= 4; // Left shift by 2
-
- pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
-
- pes.dts = pes.pts;
-
- if (ptsDtsFlags & 0x40) {
- pes.dts = (packet[offset + 14] & 0x0E) << 27 | (packet[offset + 15] & 0xFF) << 20 | (packet[offset + 16] & 0xFE) << 12 | (packet[offset + 17] & 0xFF) << 5 | (packet[offset + 18] & 0xFE) >>> 3;
- pes.dts *= 4; // Left shift by 2
-
- pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
- }
- }
-
- return pes;
- };
-
- var parseNalUnitType = function parseNalUnitType(type) {
- switch (type) {
- case 0x05:
- return 'slice_layer_without_partitioning_rbsp_idr';
-
- case 0x06:
- return 'sei_rbsp';
-
- case 0x07:
- return 'seq_parameter_set_rbsp';
-
- case 0x08:
- return 'pic_parameter_set_rbsp';
-
- case 0x09:
- return 'access_unit_delimiter_rbsp';
-
- default:
- return null;
- }
- };
-
- var videoPacketContainsKeyFrame = function videoPacketContainsKeyFrame(packet) {
- var offset = 4 + parseAdaptionField(packet);
- var frameBuffer = packet.subarray(offset);
- var frameI = 0;
- var frameSyncPoint = 0;
- var foundKeyFrame = false;
- var nalType; // advance the sync point to a NAL start, if necessary
-
- for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
- if (frameBuffer[frameSyncPoint + 2] === 1) {
- // the sync point is properly aligned
- frameI = frameSyncPoint + 5;
- break;
- }
- }
-
- while (frameI < frameBuffer.byteLength) {
- // look at the current byte to determine if we've hit the end of
- // a NAL unit boundary
- switch (frameBuffer[frameI]) {
- case 0:
- // skip past non-sync sequences
- if (frameBuffer[frameI - 1] !== 0) {
- frameI += 2;
- break;
- } else if (frameBuffer[frameI - 2] !== 0) {
- frameI++;
- break;
- }
-
- if (frameSyncPoint + 3 !== frameI - 2) {
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
- } // drop trailing zeroes
-
-
- do {
- frameI++;
- } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
-
- frameSyncPoint = frameI - 2;
- frameI += 3;
- break;
-
- case 1:
- // skip past non-sync sequences
- if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
- frameI += 3;
- break;
- }
-
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
-
- frameSyncPoint = frameI - 2;
- frameI += 3;
- break;
-
- default:
- // the current byte isn't a one or zero, so it cannot be part
- // of a sync sequence
- frameI += 3;
- break;
- }
- }
-
- frameBuffer = frameBuffer.subarray(frameSyncPoint);
- frameI -= frameSyncPoint;
- frameSyncPoint = 0; // parse the final nal
-
- if (frameBuffer && frameBuffer.byteLength > 3) {
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
- }
-
- return foundKeyFrame;
- };
-
- var probe$1 = {
- parseType: parseType,
- parsePat: parsePat,
- parsePmt: parsePmt,
- parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
- parsePesType: parsePesType,
- parsePesTime: parsePesTime,
- videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
- };
- var handleRollover = timestampRolloverStream.handleRollover;
- var probe = {};
- probe.ts = probe$1;
- probe.aac = utils;
- var ONE_SECOND_IN_TS = clock.ONE_SECOND_IN_TS;
- var MP2T_PACKET_LENGTH = 188,
- // bytes
- SYNC_BYTE = 0x47;
- /**
- * walks through segment data looking for pat and pmt packets to parse out
- * program map table information
- */
-
- var parsePsi_ = function parsePsi_(bytes, pmt) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type;
-
- while (endIndex < bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pat':
- pmt.pid = probe.ts.parsePat(packet);
- break;
-
- case 'pmt':
- var table = probe.ts.parsePmt(packet);
- pmt.table = pmt.table || {};
- Object.keys(table).forEach(function (key) {
- pmt.table[key] = table[key];
- });
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- }
- };
- /**
- * walks through the segment data from the start and end to get timing information
- * for the first and last audio pes packets
- */
-
-
- var parseAudioPes_ = function parseAudioPes_(bytes, pmt, result) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type,
- pesType,
- pusi,
- parsed;
- var endLoop = false; // Start walking from start of segment to get first audio packet
-
- while (endIndex <= bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'audio' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'audio';
- result.audio.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // Start walking from end of segment to get last audio packet
-
-
- endIndex = bytes.byteLength;
- startIndex = endIndex - MP2T_PACKET_LENGTH;
- endLoop = false;
-
- while (startIndex >= 0) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'audio' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'audio';
- result.audio.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex -= MP2T_PACKET_LENGTH;
- endIndex -= MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex--;
- endIndex--;
- }
- };
- /**
- * walks through the segment data from the start and end to get timing information
- * for the first and last video pes packets as well as timing information for the first
- * key frame.
- */
-
-
- var parseVideoPes_ = function parseVideoPes_(bytes, pmt, result) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type,
- pesType,
- pusi,
- parsed,
- frame,
- i,
- pes;
- var endLoop = false;
- var currentFrame = {
- data: [],
- size: 0
- }; // Start walking from start of segment to get first video packet
-
- while (endIndex < bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'video') {
- if (pusi && !endLoop) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'video';
- result.video.push(parsed);
- endLoop = true;
- }
- }
-
- if (!result.firstKeyFrame) {
- if (pusi) {
- if (currentFrame.size !== 0) {
- frame = new Uint8Array(currentFrame.size);
- i = 0;
-
- while (currentFrame.data.length) {
- pes = currentFrame.data.shift();
- frame.set(pes, i);
- i += pes.byteLength;
- }
-
- if (probe.ts.videoPacketContainsKeyFrame(frame)) {
- var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
- // the keyframe seems to work fine with HLS playback
- // and definitely preferable to a crash with TypeError...
-
- if (firstKeyFrame) {
- result.firstKeyFrame = firstKeyFrame;
- result.firstKeyFrame.type = 'video';
- } else {
- // eslint-disable-next-line
- console.warn('Failed to extract PTS/DTS from PES at first keyframe. ' + 'This could be an unusual TS segment, or else mux.js did not ' + 'parse your TS segment correctly. If you know your TS ' + 'segments do contain PTS/DTS on keyframes please file a bug ' + 'report! You can try ffprobe to double check for yourself.');
- }
- }
-
- currentFrame.size = 0;
- }
- }
-
- currentFrame.data.push(packet);
- currentFrame.size += packet.byteLength;
- }
- }
-
- break;
- }
-
- if (endLoop && result.firstKeyFrame) {
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // Start walking from end of segment to get last video packet
-
-
- endIndex = bytes.byteLength;
- startIndex = endIndex - MP2T_PACKET_LENGTH;
- endLoop = false;
-
- while (startIndex >= 0) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'video' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'video';
- result.video.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex -= MP2T_PACKET_LENGTH;
- endIndex -= MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex--;
- endIndex--;
- }
- };
- /**
- * Adjusts the timestamp information for the segment to account for
- * rollover and convert to seconds based on pes packet timescale (90khz clock)
- */
-
-
- var adjustTimestamp_ = function adjustTimestamp_(segmentInfo, baseTimestamp) {
- if (segmentInfo.audio && segmentInfo.audio.length) {
- var audioBaseTimestamp = baseTimestamp;
-
- if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
- audioBaseTimestamp = segmentInfo.audio[0].dts;
- }
-
- segmentInfo.audio.forEach(function (info) {
- info.dts = handleRollover(info.dts, audioBaseTimestamp);
- info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
-
- info.dtsTime = info.dts / ONE_SECOND_IN_TS;
- info.ptsTime = info.pts / ONE_SECOND_IN_TS;
- });
- }
-
- if (segmentInfo.video && segmentInfo.video.length) {
- var videoBaseTimestamp = baseTimestamp;
-
- if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
- videoBaseTimestamp = segmentInfo.video[0].dts;
- }
-
- segmentInfo.video.forEach(function (info) {
- info.dts = handleRollover(info.dts, videoBaseTimestamp);
- info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
-
- info.dtsTime = info.dts / ONE_SECOND_IN_TS;
- info.ptsTime = info.pts / ONE_SECOND_IN_TS;
- });
-
- if (segmentInfo.firstKeyFrame) {
- var frame = segmentInfo.firstKeyFrame;
- frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
- frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
-
- frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
- frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
- }
- }
- };
- /**
- * inspects the aac data stream for start and end time information
- */
-
-
- var inspectAac_ = function inspectAac_(bytes) {
- var endLoop = false,
- audioCount = 0,
- sampleRate = null,
- timestamp = null,
- frameSize = 0,
- byteIndex = 0,
- packet;
-
- while (bytes.length - byteIndex >= 3) {
- var type = probe.aac.parseType(bytes, byteIndex);
-
- switch (type) {
- case 'timed-metadata':
- // Exit early because we don't have enough to parse
- // the ID3 tag header
- if (bytes.length - byteIndex < 10) {
- endLoop = true;
- break;
- }
-
- frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (frameSize > bytes.length) {
- endLoop = true;
- break;
- }
-
- if (timestamp === null) {
- packet = bytes.subarray(byteIndex, byteIndex + frameSize);
- timestamp = probe.aac.parseAacTimestamp(packet);
- }
-
- byteIndex += frameSize;
- break;
-
- case 'audio':
- // Exit early because we don't have enough to parse
- // the ADTS frame header
- if (bytes.length - byteIndex < 7) {
- endLoop = true;
- break;
- }
-
- frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (frameSize > bytes.length) {
- endLoop = true;
- break;
- }
-
- if (sampleRate === null) {
- packet = bytes.subarray(byteIndex, byteIndex + frameSize);
- sampleRate = probe.aac.parseSampleRate(packet);
- }
-
- audioCount++;
- byteIndex += frameSize;
- break;
-
- default:
- byteIndex++;
- break;
- }
-
- if (endLoop) {
- return null;
- }
- }
-
- if (sampleRate === null || timestamp === null) {
- return null;
- }
-
- var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
- var result = {
- audio: [{
- type: 'audio',
- dts: timestamp,
- pts: timestamp
- }, {
- type: 'audio',
- dts: timestamp + audioCount * 1024 * audioTimescale,
- pts: timestamp + audioCount * 1024 * audioTimescale
- }]
- };
- return result;
- };
- /**
- * inspects the transport stream segment data for start and end time information
- * of the audio and video tracks (when present) as well as the first key frame's
- * start time.
- */
-
-
- var inspectTs_ = function inspectTs_(bytes) {
- var pmt = {
- pid: null,
- table: null
- };
- var result = {};
- parsePsi_(bytes, pmt);
-
- for (var pid in pmt.table) {
- if (pmt.table.hasOwnProperty(pid)) {
- var type = pmt.table[pid];
-
- switch (type) {
- case streamTypes.H264_STREAM_TYPE:
- result.video = [];
- parseVideoPes_(bytes, pmt, result);
-
- if (result.video.length === 0) {
- delete result.video;
- }
-
- break;
-
- case streamTypes.ADTS_STREAM_TYPE:
- result.audio = [];
- parseAudioPes_(bytes, pmt, result);
-
- if (result.audio.length === 0) {
- delete result.audio;
- }
-
- break;
- }
- }
- }
-
- return result;
- };
- /**
- * Inspects segment byte data and returns an object with start and end timing information
- *
- * @param {Uint8Array} bytes The segment byte data
- * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
- * timestamps for rollover. This value must be in 90khz clock.
- * @return {Object} Object containing start and end frame timing info of segment.
- */
-
-
- var inspect = function inspect(bytes, baseTimestamp) {
- var isAacData = probe.aac.isLikelyAacData(bytes);
- var result;
-
- if (isAacData) {
- result = inspectAac_(bytes);
- } else {
- result = inspectTs_(bytes);
- }
-
- if (!result || !result.audio && !result.video) {
- return null;
- }
-
- adjustTimestamp_(result, baseTimestamp);
- return result;
- };
-
- var tsInspector = {
- inspect: inspect,
- parseAudioPes_: parseAudioPes_
- };
- /* global self */
-
- /**
- * Re-emits transmuxer events by converting them into messages to the
- * world outside the worker.
- *
- * @param {Object} transmuxer the transmuxer to wire events on
- * @private
- */
-
- var wireTransmuxerEvents = function wireTransmuxerEvents(self, transmuxer) {
- transmuxer.on('data', function (segment) {
- // transfer ownership of the underlying ArrayBuffer
- // instead of doing a copy to save memory
- // ArrayBuffers are transferable but generic TypedArrays are not
- // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
- var initArray = segment.initSegment;
- segment.initSegment = {
- data: initArray.buffer,
- byteOffset: initArray.byteOffset,
- byteLength: initArray.byteLength
- };
- var typedArray = segment.data;
- segment.data = typedArray.buffer;
- self.postMessage({
- action: 'data',
- segment: segment,
- byteOffset: typedArray.byteOffset,
- byteLength: typedArray.byteLength
- }, [segment.data]);
- });
- transmuxer.on('done', function (data) {
- self.postMessage({
- action: 'done'
- });
- });
- transmuxer.on('gopInfo', function (gopInfo) {
- self.postMessage({
- action: 'gopInfo',
- gopInfo: gopInfo
- });
- });
- transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
- var videoSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- videoSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'videoSegmentTimingInfo',
- videoSegmentTimingInfo: videoSegmentTimingInfo
- });
- });
- transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
- // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
- var audioSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- audioSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'audioSegmentTimingInfo',
- audioSegmentTimingInfo: audioSegmentTimingInfo
- });
- });
- transmuxer.on('id3Frame', function (id3Frame) {
- self.postMessage({
- action: 'id3Frame',
- id3Frame: id3Frame
- });
- });
- transmuxer.on('caption', function (caption) {
- self.postMessage({
- action: 'caption',
- caption: caption
- });
- });
- transmuxer.on('trackinfo', function (trackInfo) {
- self.postMessage({
- action: 'trackinfo',
- trackInfo: trackInfo
- });
- });
- transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
- // convert to video TS since we prioritize video time over audio
- self.postMessage({
- action: 'audioTimingInfo',
- audioTimingInfo: {
- start: clock.videoTsToSeconds(audioTimingInfo.start),
- end: clock.videoTsToSeconds(audioTimingInfo.end)
- }
- });
- });
- transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
- self.postMessage({
- action: 'videoTimingInfo',
- videoTimingInfo: {
- start: clock.videoTsToSeconds(videoTimingInfo.start),
- end: clock.videoTsToSeconds(videoTimingInfo.end)
- }
- });
- });
- };
- /**
- * All incoming messages route through this hash. If no function exists
- * to handle an incoming message, then we ignore the message.
- *
- * @class MessageHandlers
- * @param {Object} options the options to initialize with
- */
-
-
- var MessageHandlers = /*#__PURE__*/function () {
- function MessageHandlers(self, options) {
- this.options = options || {};
- this.self = self;
- this.init();
- }
- /**
- * initialize our web worker and wire all the events.
- */
-
-
- var _proto = MessageHandlers.prototype;
-
- _proto.init = function init() {
- if (this.transmuxer) {
- this.transmuxer.dispose();
- }
-
- this.transmuxer = new transmuxer.Transmuxer(this.options);
- wireTransmuxerEvents(this.self, this.transmuxer);
- };
-
- _proto.pushMp4Captions = function pushMp4Captions(data) {
- if (!this.captionParser) {
- this.captionParser = new captionParser();
- this.captionParser.init();
- }
-
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- var parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
- this.self.postMessage({
- action: 'mp4Captions',
- captions: parsed && parsed.captions || [],
- data: segment.buffer
- }, [segment.buffer]);
- };
-
- _proto.probeMp4StartTime = function probeMp4StartTime(_ref) {
- var timescales = _ref.timescales,
- data = _ref.data;
- var startTime = probe$2.startTime(timescales, data);
- this.self.postMessage({
- action: 'probeMp4StartTime',
- startTime: startTime,
- data: data
- }, [data.buffer]);
- };
-
- _proto.probeMp4Tracks = function probeMp4Tracks(_ref2) {
- var data = _ref2.data;
- var tracks = probe$2.tracks(data);
- this.self.postMessage({
- action: 'probeMp4Tracks',
- tracks: tracks,
- data: data
- }, [data.buffer]);
- }
- /**
- * Probe an mpeg2-ts segment to determine the start time of the segment in it's
- * internal "media time," as well as whether it contains video and/or audio.
- *
- * @private
- * @param {Uint8Array} bytes - segment bytes
- * @param {number} baseStartTime
- * Relative reference timestamp used when adjusting frame timestamps for rollover.
- * This value should be in seconds, as it's converted to a 90khz clock within the
- * function body.
- * @return {Object} The start time of the current segment in "media time" as well as
- * whether it contains video and/or audio
- */
- ;
-
- _proto.probeTs = function probeTs(_ref3) {
- var data = _ref3.data,
- baseStartTime = _ref3.baseStartTime;
- var tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock.ONE_SECOND_IN_TS : void 0;
- var timeInfo = tsInspector.inspect(data, tsStartTime);
- var result = null;
-
- if (timeInfo) {
- result = {
- // each type's time info comes back as an array of 2 times, start and end
- hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
- hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
- };
-
- if (result.hasVideo) {
- result.videoStart = timeInfo.video[0].ptsTime;
- }
-
- if (result.hasAudio) {
- result.audioStart = timeInfo.audio[0].ptsTime;
- }
- }
-
- this.self.postMessage({
- action: 'probeTs',
- result: result,
- data: data
- }, [data.buffer]);
- };
-
- _proto.clearAllMp4Captions = function clearAllMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearAllCaptions();
- }
- };
-
- _proto.clearParsedMp4Captions = function clearParsedMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearParsedCaptions();
- }
- }
- /**
- * Adds data (a ts segment) to the start of the transmuxer pipeline for
- * processing.
- *
- * @param {ArrayBuffer} data data to push into the muxer
- */
- ;
-
- _proto.push = function push(data) {
- // Cast array buffer to correct type for transmuxer
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- this.transmuxer.push(segment);
- }
- /**
- * Recreate the transmuxer so that the next segment added via `push`
- * start with a fresh transmuxer.
- */
- ;
-
- _proto.reset = function reset() {
- this.transmuxer.reset();
- }
- /**
- * Set the value that will be used as the `baseMediaDecodeTime` time for the
- * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
- * set relative to the first based on the PTS values.
- *
- * @param {Object} data used to set the timestamp offset in the muxer
- */
- ;
-
- _proto.setTimestampOffset = function setTimestampOffset(data) {
- var timestampOffset = data.timestampOffset || 0;
- this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset)));
- };
-
- _proto.setAudioAppendStart = function setAudioAppendStart(data) {
- this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));
- };
-
- _proto.setRemux = function setRemux(data) {
- this.transmuxer.setRemux(data.remux);
- }
- /**
- * Forces the pipeline to finish processing the last segment and emit it's
- * results.
- *
- * @param {Object} data event data, not really used
- */
- ;
-
- _proto.flush = function flush(data) {
- this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
-
- self.postMessage({
- action: 'done',
- type: 'transmuxed'
- });
- };
-
- _proto.endTimeline = function endTimeline() {
- this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
- // timelines
-
- self.postMessage({
- action: 'endedtimeline',
- type: 'transmuxed'
- });
- };
-
- _proto.alignGopsWith = function alignGopsWith(data) {
- this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
- };
-
- return MessageHandlers;
- }();
- /**
- * Our web worker interface so that things can talk to mux.js
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- *
- * @param {Object} self the scope for the web worker
- */
-
-
- self.onmessage = function (event) {
- if (event.data.action === 'init' && event.data.options) {
- this.messageHandlers = new MessageHandlers(self, event.data.options);
- return;
- }
-
- if (!this.messageHandlers) {
- this.messageHandlers = new MessageHandlers(self);
- }
-
- if (event.data && event.data.action && event.data.action !== 'init') {
- if (this.messageHandlers[event.data.action]) {
- this.messageHandlers[event.data.action](event.data);
- }
- }
- };
- });
- var TransmuxWorker = factory(workerCode$1);
- /* rollup-plugin-worker-factory end for worker!/Users/gkatsevman/p/http-streaming-release/src/transmuxer-worker.js */
-
- var handleData_ = function handleData_(event, transmuxedData, callback) {
- var _event$data$segment = event.data.segment,
- type = _event$data$segment.type,
- initSegment = _event$data$segment.initSegment,
- captions = _event$data$segment.captions,
- captionStreams = _event$data$segment.captionStreams,
- metadata = _event$data$segment.metadata,
- videoFrameDtsTime = _event$data$segment.videoFrameDtsTime,
- videoFramePtsTime = _event$data$segment.videoFramePtsTime;
- transmuxedData.buffer.push({
- captions: captions,
- captionStreams: captionStreams,
- metadata: metadata
- });
- var boxes = event.data.segment.boxes || {
- data: event.data.segment.data
- };
- var result = {
- type: type,
- // cast ArrayBuffer to TypedArray
- data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
- initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
- };
-
- if (typeof videoFrameDtsTime !== 'undefined') {
- result.videoFrameDtsTime = videoFrameDtsTime;
- }
-
- if (typeof videoFramePtsTime !== 'undefined') {
- result.videoFramePtsTime = videoFramePtsTime;
- }
-
- callback(result);
- };
- var handleDone_ = function handleDone_(_ref) {
- var transmuxedData = _ref.transmuxedData,
- callback = _ref.callback;
- // Previously we only returned data on data events,
- // not on done events. Clear out the buffer to keep that consistent.
- transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
- // have received
-
- callback(transmuxedData);
- };
- var handleGopInfo_ = function handleGopInfo_(event, transmuxedData) {
- transmuxedData.gopInfo = event.data.gopInfo;
- };
- var processTransmux = function processTransmux(options) {
- var transmuxer = options.transmuxer,
- bytes = options.bytes,
- audioAppendStart = options.audioAppendStart,
- gopsToAlignWith = options.gopsToAlignWith,
- remux = options.remux,
- onData = options.onData,
- onTrackInfo = options.onTrackInfo,
- onAudioTimingInfo = options.onAudioTimingInfo,
- onVideoTimingInfo = options.onVideoTimingInfo,
- onVideoSegmentTimingInfo = options.onVideoSegmentTimingInfo,
- onAudioSegmentTimingInfo = options.onAudioSegmentTimingInfo,
- onId3 = options.onId3,
- onCaptions = options.onCaptions,
- onDone = options.onDone,
- onEndedTimeline = options.onEndedTimeline,
- isEndOfTimeline = options.isEndOfTimeline;
- var transmuxedData = {
- buffer: []
- };
- var waitForEndedTimelineEvent = isEndOfTimeline;
-
- var handleMessage = function handleMessage(event) {
- if (transmuxer.currentTransmux !== options) {
- // disposed
- return;
- }
-
- if (event.data.action === 'data') {
- handleData_(event, transmuxedData, onData);
- }
-
- if (event.data.action === 'trackinfo') {
- onTrackInfo(event.data.trackInfo);
- }
-
- if (event.data.action === 'gopInfo') {
- handleGopInfo_(event, transmuxedData);
- }
-
- if (event.data.action === 'audioTimingInfo') {
- onAudioTimingInfo(event.data.audioTimingInfo);
- }
-
- if (event.data.action === 'videoTimingInfo') {
- onVideoTimingInfo(event.data.videoTimingInfo);
- }
-
- if (event.data.action === 'videoSegmentTimingInfo') {
- onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
- }
-
- if (event.data.action === 'audioSegmentTimingInfo') {
- onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
- }
-
- if (event.data.action === 'id3Frame') {
- onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
- }
-
- if (event.data.action === 'caption') {
- onCaptions(event.data.caption);
- }
-
- if (event.data.action === 'endedtimeline') {
- waitForEndedTimelineEvent = false;
- onEndedTimeline();
- } // wait for the transmuxed event since we may have audio and video
-
-
- if (event.data.type !== 'transmuxed') {
- return;
- } // If the "endedtimeline" event has not yet fired, and this segment represents the end
- // of a timeline, that means there may still be data events before the segment
- // processing can be considerred complete. In that case, the final event should be
- // an "endedtimeline" event with the type "transmuxed."
-
-
- if (waitForEndedTimelineEvent) {
- return;
- }
-
- transmuxer.onmessage = null;
- handleDone_({
- transmuxedData: transmuxedData,
- callback: onDone
- });
- /* eslint-disable no-use-before-define */
-
- dequeue(transmuxer);
- /* eslint-enable */
- };
-
- transmuxer.onmessage = handleMessage;
-
- if (audioAppendStart) {
- transmuxer.postMessage({
- action: 'setAudioAppendStart',
- appendStart: audioAppendStart
- });
- } // allow empty arrays to be passed to clear out GOPs
-
-
- if (Array.isArray(gopsToAlignWith)) {
- transmuxer.postMessage({
- action: 'alignGopsWith',
- gopsToAlignWith: gopsToAlignWith
- });
- }
-
- if (typeof remux !== 'undefined') {
- transmuxer.postMessage({
- action: 'setRemux',
- remux: remux
- });
- }
-
- if (bytes.byteLength) {
- var buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
- var byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
- transmuxer.postMessage({
- action: 'push',
- // Send the typed-array of data as an ArrayBuffer so that
- // it can be sent as a "Transferable" and avoid the costly
- // memory copy
- data: buffer,
- // To recreate the original typed-array, we need information
- // about what portion of the ArrayBuffer it was a view into
- byteOffset: byteOffset,
- byteLength: bytes.byteLength
- }, [buffer]);
- }
-
- if (isEndOfTimeline) {
- transmuxer.postMessage({
- action: 'endTimeline'
- });
- } // even if we didn't push any bytes, we have to make sure we flush in case we reached
- // the end of the segment
-
-
- transmuxer.postMessage({
- action: 'flush'
- });
- };
- var dequeue = function dequeue(transmuxer) {
- transmuxer.currentTransmux = null;
-
- if (transmuxer.transmuxQueue.length) {
- transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
-
- if (typeof transmuxer.currentTransmux === 'function') {
- transmuxer.currentTransmux();
- } else {
- processTransmux(transmuxer.currentTransmux);
- }
- }
- };
- var processAction = function processAction(transmuxer, action) {
- transmuxer.postMessage({
- action: action
- });
- dequeue(transmuxer);
- };
- var enqueueAction = function enqueueAction(action, transmuxer) {
- if (!transmuxer.currentTransmux) {
- transmuxer.currentTransmux = action;
- processAction(transmuxer, action);
- return;
- }
-
- transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
- };
- var reset = function reset(transmuxer) {
- enqueueAction('reset', transmuxer);
- };
- var endTimeline = function endTimeline(transmuxer) {
- enqueueAction('endTimeline', transmuxer);
- };
- var transmux = function transmux(options) {
- if (!options.transmuxer.currentTransmux) {
- options.transmuxer.currentTransmux = options;
- processTransmux(options);
- return;
- }
-
- options.transmuxer.transmuxQueue.push(options);
- };
- var createTransmuxer = function createTransmuxer(options) {
- var transmuxer = new TransmuxWorker();
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue = [];
- var term = transmuxer.terminate;
-
- transmuxer.terminate = function () {
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue.length = 0;
- return term.call(transmuxer);
- };
-
- transmuxer.postMessage({
- action: 'init',
- options: options
- });
- return transmuxer;
- };
- var segmentTransmuxer = {
- reset: reset,
- endTimeline: endTimeline,
- transmux: transmux,
- createTransmuxer: createTransmuxer
- };
-
- var workerCallback = function workerCallback(options) {
- var transmuxer = options.transmuxer;
- var endAction = options.endAction || options.action;
- var callback = options.callback;
-
- var message = _extends_1({}, options, {
- endAction: null,
- transmuxer: null,
- callback: null
- });
-
- var listenForEndEvent = function listenForEndEvent(event) {
- if (event.data.action !== endAction) {
- return;
- }
-
- transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
-
- if (event.data.data) {
- event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
-
- if (options.data) {
- options.data = event.data.data;
- }
- }
-
- callback(event.data);
- };
-
- transmuxer.addEventListener('message', listenForEndEvent);
-
- if (options.data) {
- var isArrayBuffer = options.data instanceof ArrayBuffer;
- message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
- message.byteLength = options.data.byteLength;
- var transfers = [isArrayBuffer ? options.data : options.data.buffer];
- transmuxer.postMessage(message, transfers);
- } else {
- transmuxer.postMessage(message);
- }
- };
-
- var REQUEST_ERRORS = {
- FAILURE: 2,
- TIMEOUT: -101,
- ABORTED: -102
- };
- /**
- * Abort all requests
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- */
-
- var abortAll = function abortAll(activeXhrs) {
- activeXhrs.forEach(function (xhr) {
- xhr.abort();
- });
- };
- /**
- * Gather important bandwidth stats once a request has completed
- *
- * @param {Object} request - the XHR request from which to gather stats
- */
-
-
- var getRequestStats = function getRequestStats(request) {
- return {
- bandwidth: request.bandwidth,
- bytesReceived: request.bytesReceived || 0,
- roundTripTime: request.roundTripTime || 0
- };
- };
- /**
- * If possible gather bandwidth stats as a request is in
- * progress
- *
- * @param {Event} progressEvent - an event object from an XHR's progress event
- */
-
-
- var getProgressStats = function getProgressStats(progressEvent) {
- var request = progressEvent.target;
- var roundTripTime = Date.now() - request.requestTime;
- var stats = {
- bandwidth: Infinity,
- bytesReceived: 0,
- roundTripTime: roundTripTime || 0
- };
- stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
- // because we should only use bandwidth stats on progress to determine when
- // abort a request early due to insufficient bandwidth
-
- stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
- return stats;
- };
- /**
- * Handle all error conditions in one place and return an object
- * with all the information
- *
- * @param {Error|null} error - if non-null signals an error occured with the XHR
- * @param {Object} request - the XHR request that possibly generated the error
- */
-
-
- var handleErrors = function handleErrors(error, request) {
- if (request.timedout) {
- return {
- status: request.status,
- message: 'HLS request timed-out at URL: ' + request.uri,
- code: REQUEST_ERRORS.TIMEOUT,
- xhr: request
- };
- }
-
- if (request.aborted) {
- return {
- status: request.status,
- message: 'HLS request aborted at URL: ' + request.uri,
- code: REQUEST_ERRORS.ABORTED,
- xhr: request
- };
- }
-
- if (error) {
- return {
- status: request.status,
- message: 'HLS request errored at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
- return {
- status: request.status,
- message: 'Empty HLS response at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- return null;
- };
- /**
- * Handle responses for key data and convert the key data to the correct format
- * for the decryption step later
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Array} objects - objects to add the key bytes to.
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
- var handleKeyResponse = function handleKeyResponse(segment, objects, finishProcessingFn) {
- return function (error, request) {
- var response = request.response;
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- if (response.byteLength !== 16) {
- return finishProcessingFn({
- status: request.status,
- message: 'Invalid HLS key at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- }, segment);
- }
-
- var view = new DataView(response);
- var bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
-
- for (var i = 0; i < objects.length; i++) {
- objects[i].bytes = bytes;
- }
-
- return finishProcessingFn(null, segment);
- };
- };
-
- var parseInitSegment = function parseInitSegment(segment, _callback) {
- var type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
- // only know how to parse mp4 init segments at the moment
-
- if (type !== 'mp4') {
- var uri = segment.map.resolvedUri || segment.map.uri;
- return _callback({
- internal: true,
- message: "Found unsupported " + (type || 'unknown') + " container for initialization segment at URL: " + uri,
- code: REQUEST_ERRORS.FAILURE
- });
- }
-
- workerCallback({
- action: 'probeMp4Tracks',
- data: segment.map.bytes,
- transmuxer: segment.transmuxer,
- callback: function callback(_ref) {
- var tracks = _ref.tracks,
- data = _ref.data;
- // transfer bytes back to us
- segment.map.bytes = data;
- tracks.forEach(function (track) {
- segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
-
- if (segment.map.tracks[track.type]) {
- return;
- }
-
- segment.map.tracks[track.type] = track;
-
- if (typeof track.id === 'number' && track.timescale) {
- segment.map.timescales = segment.map.timescales || {};
- segment.map.timescales[track.id] = track.timescale;
- }
- });
- return _callback(null);
- }
- });
- };
- /**
- * Handle init-segment responses
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
- var handleInitSegmentResponse = function handleInitSegmentResponse(_ref2) {
- var segment = _ref2.segment,
- finishProcessingFn = _ref2.finishProcessingFn;
- return function (error, request) {
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- var bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
- // until the key request is done to decrypt.
-
- if (segment.map.key) {
- segment.map.encryptedBytes = bytes;
- return finishProcessingFn(null, segment);
- }
-
- segment.map.bytes = bytes;
- parseInitSegment(segment, function (parseError) {
- if (parseError) {
- parseError.xhr = request;
- parseError.status = request.status;
- return finishProcessingFn(parseError, segment);
- }
-
- finishProcessingFn(null, segment);
- });
- };
- };
- /**
- * Response handler for segment-requests being sure to set the correct
- * property depending on whether the segment is encryped or not
- * Also records and keeps track of stats that are used for ABR purposes
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
- var handleSegmentResponse = function handleSegmentResponse(_ref3) {
- var segment = _ref3.segment,
- finishProcessingFn = _ref3.finishProcessingFn,
- responseType = _ref3.responseType;
- return function (error, request) {
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- var newBytes = // although responseText "should" exist, this guard serves to prevent an error being
- // thrown for two primary cases:
- // 1. the mime type override stops working, or is not implemented for a specific
- // browser
- // 2. when using mock XHR libraries like sinon that do not allow the override behavior
- responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
- segment.stats = getRequestStats(request);
-
- if (segment.key) {
- segment.encryptedBytes = new Uint8Array(newBytes);
- } else {
- segment.bytes = new Uint8Array(newBytes);
- }
-
- return finishProcessingFn(null, segment);
- };
- };
-
- var transmuxAndNotify = function transmuxAndNotify(_ref4) {
- var segment = _ref4.segment,
- bytes = _ref4.bytes,
- trackInfoFn = _ref4.trackInfoFn,
- timingInfoFn = _ref4.timingInfoFn,
- videoSegmentTimingInfoFn = _ref4.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref4.audioSegmentTimingInfoFn,
- id3Fn = _ref4.id3Fn,
- captionsFn = _ref4.captionsFn,
- isEndOfTimeline = _ref4.isEndOfTimeline,
- endedTimelineFn = _ref4.endedTimelineFn,
- dataFn = _ref4.dataFn,
- doneFn = _ref4.doneFn;
- var fmp4Tracks = segment.map && segment.map.tracks || {};
- var isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
- // One reason for this is that in the case of full segments, we want to trust start
- // times from the probe, rather than the transmuxer.
-
- var audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
- var audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
- var videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
- var videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
-
- var finish = function finish() {
- return transmux({
- bytes: bytes,
- transmuxer: segment.transmuxer,
- audioAppendStart: segment.audioAppendStart,
- gopsToAlignWith: segment.gopsToAlignWith,
- remux: isMuxed,
- onData: function onData(result) {
- result.type = result.type === 'combined' ? 'video' : result.type;
- dataFn(segment, result);
- },
- onTrackInfo: function onTrackInfo(trackInfo) {
- if (trackInfoFn) {
- if (isMuxed) {
- trackInfo.isMuxed = true;
- }
-
- trackInfoFn(segment, trackInfo);
- }
- },
- onAudioTimingInfo: function onAudioTimingInfo(audioTimingInfo) {
- // we only want the first start value we encounter
- if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
- audioStartFn(audioTimingInfo.start);
- audioStartFn = null;
- } // we want to continually update the end time
-
-
- if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
- audioEndFn(audioTimingInfo.end);
- }
- },
- onVideoTimingInfo: function onVideoTimingInfo(videoTimingInfo) {
- // we only want the first start value we encounter
- if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
- videoStartFn(videoTimingInfo.start);
- videoStartFn = null;
- } // we want to continually update the end time
-
-
- if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
- videoEndFn(videoTimingInfo.end);
- }
- },
- onVideoSegmentTimingInfo: function onVideoSegmentTimingInfo(videoSegmentTimingInfo) {
- videoSegmentTimingInfoFn(videoSegmentTimingInfo);
- },
- onAudioSegmentTimingInfo: function onAudioSegmentTimingInfo(audioSegmentTimingInfo) {
- audioSegmentTimingInfoFn(audioSegmentTimingInfo);
- },
- onId3: function onId3(id3Frames, dispatchType) {
- id3Fn(segment, id3Frames, dispatchType);
- },
- onCaptions: function onCaptions(captions) {
- captionsFn(segment, [captions]);
- },
- isEndOfTimeline: isEndOfTimeline,
- onEndedTimeline: function onEndedTimeline() {
- endedTimelineFn();
- },
- onDone: function onDone(result) {
- if (!doneFn) {
- return;
- }
-
- result.type = result.type === 'combined' ? 'video' : result.type;
- doneFn(null, segment, result);
- }
- });
- }; // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
- // Meaning cached frame data may corrupt our notion of where this segment
- // really starts. To get around this, probe for the info needed.
-
-
- workerCallback({
- action: 'probeTs',
- transmuxer: segment.transmuxer,
- data: bytes,
- baseStartTime: segment.baseStartTime,
- callback: function callback(data) {
- segment.bytes = bytes = data.data;
- var probeResult = data.result;
-
- if (probeResult) {
- trackInfoFn(segment, {
- hasAudio: probeResult.hasAudio,
- hasVideo: probeResult.hasVideo,
- isMuxed: isMuxed
- });
- trackInfoFn = null;
-
- if (probeResult.hasAudio && !isMuxed) {
- audioStartFn(probeResult.audioStart);
- }
-
- if (probeResult.hasVideo) {
- videoStartFn(probeResult.videoStart);
- }
-
- audioStartFn = null;
- videoStartFn = null;
- }
-
- finish();
- }
- });
- };
-
- var handleSegmentBytes = function handleSegmentBytes(_ref5) {
- var segment = _ref5.segment,
- bytes = _ref5.bytes,
- trackInfoFn = _ref5.trackInfoFn,
- timingInfoFn = _ref5.timingInfoFn,
- videoSegmentTimingInfoFn = _ref5.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref5.audioSegmentTimingInfoFn,
- id3Fn = _ref5.id3Fn,
- captionsFn = _ref5.captionsFn,
- isEndOfTimeline = _ref5.isEndOfTimeline,
- endedTimelineFn = _ref5.endedTimelineFn,
- dataFn = _ref5.dataFn,
- doneFn = _ref5.doneFn;
- var bytesAsUint8Array = new Uint8Array(bytes); // TODO:
- // We should have a handler that fetches the number of bytes required
- // to check if something is fmp4. This will allow us to save bandwidth
- // because we can only blacklist a playlist and abort requests
- // by codec after trackinfo triggers.
-
- if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
- segment.isFmp4 = true;
- var tracks = segment.map.tracks;
- var trackInfo = {
- isFmp4: true,
- hasVideo: !!tracks.video,
- hasAudio: !!tracks.audio
- }; // if we have a audio track, with a codec that is not set to
- // encrypted audio
-
- if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
- trackInfo.audioCodec = tracks.audio.codec;
- } // if we have a video track, with a codec that is not set to
- // encrypted video
-
-
- if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
- trackInfo.videoCodec = tracks.video.codec;
- }
-
- if (tracks.video && tracks.audio) {
- trackInfo.isMuxed = true;
- } // since we don't support appending fmp4 data on progress, we know we have the full
- // segment here
-
-
- trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
- // time. The end time can be roughly calculated by the receiver using the duration.
- //
- // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
- // that is the true start of the segment (where the playback engine should begin
- // decoding).
-
- var finishLoading = function finishLoading(captions) {
- // if the track still has audio at this point it is only possible
- // for it to be audio only. See `tracks.video && tracks.audio` if statement
- // above.
- // we make sure to use segment.bytes here as that
- dataFn(segment, {
- data: bytesAsUint8Array,
- type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
- });
-
- if (captions && captions.length) {
- captionsFn(segment, captions);
- }
-
- doneFn(null, segment, {});
- };
-
- workerCallback({
- action: 'probeMp4StartTime',
- timescales: segment.map.timescales,
- data: bytesAsUint8Array,
- transmuxer: segment.transmuxer,
- callback: function callback(_ref6) {
- var data = _ref6.data,
- startTime = _ref6.startTime;
- // transfer bytes back to us
- bytes = data.buffer;
- segment.bytes = bytesAsUint8Array = data;
-
- if (trackInfo.hasAudio && !trackInfo.isMuxed) {
- timingInfoFn(segment, 'audio', 'start', startTime);
- }
-
- if (trackInfo.hasVideo) {
- timingInfoFn(segment, 'video', 'start', startTime);
- } // Run through the CaptionParser in case there are captions.
- // Initialize CaptionParser if it hasn't been yet
-
-
- if (!tracks.video || !data.byteLength || !segment.transmuxer) {
- finishLoading();
- return;
- }
-
- workerCallback({
- action: 'pushMp4Captions',
- endAction: 'mp4Captions',
- transmuxer: segment.transmuxer,
- data: bytesAsUint8Array,
- timescales: segment.map.timescales,
- trackIds: [tracks.video.id],
- callback: function callback(message) {
- // transfer bytes back to us
- bytes = message.data.buffer;
- segment.bytes = bytesAsUint8Array = message.data;
- finishLoading(message.captions);
- }
- });
- }
- });
- return;
- } // VTT or other segments that don't need processing
-
-
- if (!segment.transmuxer) {
- doneFn(null, segment, {});
- return;
- }
-
- if (typeof segment.container === 'undefined') {
- segment.container = detectContainerForBytes(bytesAsUint8Array);
- }
-
- if (segment.container !== 'ts' && segment.container !== 'aac') {
- trackInfoFn(segment, {
- hasAudio: false,
- hasVideo: false
- });
- doneFn(null, segment, {});
- return;
- } // ts or aac
-
-
- transmuxAndNotify({
- segment: segment,
- bytes: bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- };
-
- var decrypt = function decrypt(_ref7, callback) {
- var id = _ref7.id,
- key = _ref7.key,
- encryptedBytes = _ref7.encryptedBytes,
- decryptionWorker = _ref7.decryptionWorker;
-
- var decryptionHandler = function decryptionHandler(event) {
- if (event.data.source === id) {
- decryptionWorker.removeEventListener('message', decryptionHandler);
- var decrypted = event.data.decrypted;
- callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
- }
- };
-
- decryptionWorker.addEventListener('message', decryptionHandler);
- var keyBytes;
-
- if (key.bytes.slice) {
- keyBytes = key.bytes.slice();
- } else {
- keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
- } // incrementally decrypt the bytes
-
-
- decryptionWorker.postMessage(createTransferableMessage({
- source: id,
- encrypted: encryptedBytes,
- key: keyBytes,
- iv: key.iv
- }), [encryptedBytes.buffer, keyBytes.buffer]);
- };
- /**
- * Decrypt the segment via the decryption web worker
- *
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after decryption has completed
- */
-
-
- var decryptSegment = function decryptSegment(_ref8) {
- var decryptionWorker = _ref8.decryptionWorker,
- segment = _ref8.segment,
- trackInfoFn = _ref8.trackInfoFn,
- timingInfoFn = _ref8.timingInfoFn,
- videoSegmentTimingInfoFn = _ref8.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref8.audioSegmentTimingInfoFn,
- id3Fn = _ref8.id3Fn,
- captionsFn = _ref8.captionsFn,
- isEndOfTimeline = _ref8.isEndOfTimeline,
- endedTimelineFn = _ref8.endedTimelineFn,
- dataFn = _ref8.dataFn,
- doneFn = _ref8.doneFn;
- decrypt({
- id: segment.requestId,
- key: segment.key,
- encryptedBytes: segment.encryptedBytes,
- decryptionWorker: decryptionWorker
- }, function (decryptedBytes) {
- segment.bytes = decryptedBytes;
- handleSegmentBytes({
- segment: segment,
- bytes: segment.bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- });
- };
- /**
- * This function waits for all XHRs to finish (with either success or failure)
- * before continueing processing via it's callback. The function gathers errors
- * from each request into a single errors array so that the error status for
- * each request can be examined later.
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after all resources have been
- * downloaded and any decryption completed
- */
-
-
- var waitForCompletion = function waitForCompletion(_ref9) {
- var activeXhrs = _ref9.activeXhrs,
- decryptionWorker = _ref9.decryptionWorker,
- trackInfoFn = _ref9.trackInfoFn,
- timingInfoFn = _ref9.timingInfoFn,
- videoSegmentTimingInfoFn = _ref9.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref9.audioSegmentTimingInfoFn,
- id3Fn = _ref9.id3Fn,
- captionsFn = _ref9.captionsFn,
- isEndOfTimeline = _ref9.isEndOfTimeline,
- endedTimelineFn = _ref9.endedTimelineFn,
- dataFn = _ref9.dataFn,
- doneFn = _ref9.doneFn;
- var count = 0;
- var didError = false;
- return function (error, segment) {
- if (didError) {
- return;
- }
-
- if (error) {
- didError = true; // If there are errors, we have to abort any outstanding requests
-
- abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
- // handle the aborted events from those requests, there are some cases where we may
- // never get an aborted event. For instance, if the network connection is lost and
- // there were two requests, the first may have triggered an error immediately, while
- // the second request remains unsent. In that case, the aborted algorithm will not
- // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
- //
- // We also can't rely on the ready state of the XHR, since the request that
- // triggered the connection error may also show as a ready state of 0 (unsent).
- // Therefore, we have to finish this group of requests immediately after the first
- // seen error.
-
- return doneFn(error, segment);
- }
-
- count += 1;
-
- if (count === activeXhrs.length) {
- var segmentFinish = function segmentFinish() {
- if (segment.encryptedBytes) {
- return decryptSegment({
- decryptionWorker: decryptionWorker,
- segment: segment,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- } // Otherwise, everything is ready just continue
-
-
- handleSegmentBytes({
- segment: segment,
- bytes: segment.bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- }; // Keep track of when *all* of the requests have completed
-
-
- segment.endOfAllRequests = Date.now();
-
- if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
- return decrypt({
- decryptionWorker: decryptionWorker,
- // add -init to the "id" to differentiate between segment
- // and init segment decryption, just in case they happen
- // at the same time at some point in the future.
- id: segment.requestId + '-init',
- encryptedBytes: segment.map.encryptedBytes,
- key: segment.map.key
- }, function (decryptedBytes) {
- segment.map.bytes = decryptedBytes;
- parseInitSegment(segment, function (parseError) {
- if (parseError) {
- abortAll(activeXhrs);
- return doneFn(parseError, segment);
- }
-
- segmentFinish();
- });
- });
- }
-
- segmentFinish();
- }
- };
- };
- /**
- * Calls the abort callback if any request within the batch was aborted. Will only call
- * the callback once per batch of requests, even if multiple were aborted.
- *
- * @param {Object} loadendState - state to check to see if the abort function was called
- * @param {Function} abortFn - callback to call for abort
- */
-
-
- var handleLoadEnd = function handleLoadEnd(_ref10) {
- var loadendState = _ref10.loadendState,
- abortFn = _ref10.abortFn;
- return function (event) {
- var request = event.target;
-
- if (request.aborted && abortFn && !loadendState.calledAbortFn) {
- abortFn();
- loadendState.calledAbortFn = true;
- }
- };
- };
- /**
- * Simple progress event callback handler that gathers some stats before
- * executing a provided callback with the `segment` object
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} progressFn - a callback that is executed each time a progress event
- * is received
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Event} event - the progress event object from XMLHttpRequest
- */
-
-
- var handleProgress = function handleProgress(_ref11) {
- var segment = _ref11.segment,
- progressFn = _ref11.progressFn;
- _ref11.trackInfoFn;
- _ref11.timingInfoFn;
- _ref11.videoSegmentTimingInfoFn;
- _ref11.audioSegmentTimingInfoFn;
- _ref11.id3Fn;
- _ref11.captionsFn;
- _ref11.isEndOfTimeline;
- _ref11.endedTimelineFn;
- _ref11.dataFn;
- return function (event) {
- var request = event.target;
-
- if (request.aborted) {
- return;
- }
-
- segment.stats = videojs__default['default'].mergeOptions(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
-
- if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
- segment.stats.firstBytesReceivedAt = Date.now();
- }
-
- return progressFn(event, segment);
- };
- };
- /**
- * Load all resources and does any processing necessary for a media-segment
- *
- * Features:
- * decrypts the media-segment if it has a key uri and an iv
- * aborts *all* requests if *any* one request fails
- *
- * The segment object, at minimum, has the following format:
- * {
- * resolvedUri: String,
- * [transmuxer]: Object,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [key]: {
- * resolvedUri: String
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * iv: {
- * bytes: Uint32Array
- * }
- * },
- * [map]: {
- * resolvedUri: String,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [bytes]: Uint8Array
- * }
- * }
- * ...where [name] denotes optional properties
- *
- * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
- * @param {Object} xhrOptions - the base options to provide to all xhr requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
- * decryption routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} abortFn - a callback called (only once) if any piece of a request was
- * aborted
- * @param {Function} progressFn - a callback that receives progress events from the main
- * segment's xhr request
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that receives data from the main segment's xhr
- * request, transmuxed if needed
- * @param {Function} doneFn - a callback that is executed only once all requests have
- * succeeded or failed
- * @return {Function} a function that, when invoked, immediately aborts all
- * outstanding requests
- */
-
-
- var mediaSegmentRequest = function mediaSegmentRequest(_ref12) {
- var xhr = _ref12.xhr,
- xhrOptions = _ref12.xhrOptions,
- decryptionWorker = _ref12.decryptionWorker,
- segment = _ref12.segment,
- abortFn = _ref12.abortFn,
- progressFn = _ref12.progressFn,
- trackInfoFn = _ref12.trackInfoFn,
- timingInfoFn = _ref12.timingInfoFn,
- videoSegmentTimingInfoFn = _ref12.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref12.audioSegmentTimingInfoFn,
- id3Fn = _ref12.id3Fn,
- captionsFn = _ref12.captionsFn,
- isEndOfTimeline = _ref12.isEndOfTimeline,
- endedTimelineFn = _ref12.endedTimelineFn,
- dataFn = _ref12.dataFn,
- doneFn = _ref12.doneFn;
- var activeXhrs = [];
- var finishProcessingFn = waitForCompletion({
- activeXhrs: activeXhrs,
- decryptionWorker: decryptionWorker,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- }); // optionally, request the decryption key
-
- if (segment.key && !segment.key.bytes) {
- var objects = [segment.key];
-
- if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
- objects.push(segment.map.key);
- }
-
- var keyRequestOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- var keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
- var keyXhr = xhr(keyRequestOptions, keyRequestCallback);
- activeXhrs.push(keyXhr);
- } // optionally, request the associated media init segment
-
-
- if (segment.map && !segment.map.bytes) {
- var differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
-
- if (differentMapKey) {
- var mapKeyRequestOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.map.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- var mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
- var mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
- activeXhrs.push(mapKeyXhr);
- }
-
- var initSegmentOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.map.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment.map)
- });
- var initSegmentRequestCallback = handleInitSegmentResponse({
- segment: segment,
- finishProcessingFn: finishProcessingFn
- });
- var initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
- activeXhrs.push(initSegmentXhr);
- }
-
- var segmentRequestOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment)
- });
- var segmentRequestCallback = handleSegmentResponse({
- segment: segment,
- finishProcessingFn: finishProcessingFn,
- responseType: segmentRequestOptions.responseType
- });
- var segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
- segmentXhr.addEventListener('progress', handleProgress({
- segment: segment,
- progressFn: progressFn,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn
- }));
- activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
- // multiple times, provide a shared state object
-
- var loadendState = {};
- activeXhrs.forEach(function (activeXhr) {
- activeXhr.addEventListener('loadend', handleLoadEnd({
- loadendState: loadendState,
- abortFn: abortFn
- }));
- });
- return function () {
- return abortAll(activeXhrs);
- };
- };
-
- /**
- * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
- * codec strings, or translating codec strings into objects that can be examined.
- */
- var logFn$1 = logger('CodecUtils');
- /**
- * Returns a set of codec strings parsed from the playlist or the default
- * codec strings if no codecs were specified in the playlist
- *
- * @param {Playlist} media the current media playlist
- * @return {Object} an object with the video and audio codecs
- */
-
- var getCodecs = function getCodecs(media) {
- // if the codecs were explicitly specified, use them instead of the
- // defaults
- var mediaAttributes = media.attributes || {};
-
- if (mediaAttributes.CODECS) {
- return parseCodecs(mediaAttributes.CODECS);
- }
- };
-
- var isMaat = function isMaat(master, media) {
- var mediaAttributes = media.attributes || {};
- return master && master.mediaGroups && master.mediaGroups.AUDIO && mediaAttributes.AUDIO && master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
- };
- var isMuxed = function isMuxed(master, media) {
- if (!isMaat(master, media)) {
- return true;
- }
-
- var mediaAttributes = media.attributes || {};
- var audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
-
- for (var groupId in audioGroup) {
- // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
- // or there are listed playlists (the case for DASH, as the manifest will have already
- // provided all of the details necessary to generate the audio playlist, as opposed to
- // HLS' externally requested playlists), then the content is demuxed.
- if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
- return true;
- }
- }
-
- return false;
- };
- var unwrapCodecList = function unwrapCodecList(codecList) {
- var codecs = {};
- codecList.forEach(function (_ref) {
- var mediaType = _ref.mediaType,
- type = _ref.type,
- details = _ref.details;
- codecs[mediaType] = codecs[mediaType] || [];
- codecs[mediaType].push(translateLegacyCodec("" + type + details));
- });
- Object.keys(codecs).forEach(function (mediaType) {
- if (codecs[mediaType].length > 1) {
- logFn$1("multiple " + mediaType + " codecs found as attributes: " + codecs[mediaType].join(', ') + ". Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.");
- codecs[mediaType] = null;
- return;
- }
-
- codecs[mediaType] = codecs[mediaType][0];
- });
- return codecs;
- };
- var codecCount = function codecCount(codecObj) {
- var count = 0;
-
- if (codecObj.audio) {
- count++;
- }
-
- if (codecObj.video) {
- count++;
- }
-
- return count;
- };
- /**
- * Calculates the codec strings for a working configuration of
- * SourceBuffers to play variant streams in a master playlist. If
- * there is no possible working configuration, an empty object will be
- * returned.
- *
- * @param master {Object} the m3u8 object for the master playlist
- * @param media {Object} the m3u8 object for the variant playlist
- * @return {Object} the codec strings.
- *
- * @private
- */
-
- var codecsForPlaylist = function codecsForPlaylist(master, media) {
- var mediaAttributes = media.attributes || {};
- var codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
- // Put another way, there is no way to have a video-only multiple-audio HLS!
-
- if (isMaat(master, media) && !codecInfo.audio) {
- if (!isMuxed(master, media)) {
- // It is possible for codecs to be specified on the audio media group playlist but
- // not on the rendition playlist. This is mostly the case for DASH, where audio and
- // video are always separate (and separately specified).
- var defaultCodecs = unwrapCodecList(codecsFromDefault(master, mediaAttributes.AUDIO) || []);
-
- if (defaultCodecs.audio) {
- codecInfo.audio = defaultCodecs.audio;
- }
- }
- }
-
- return codecInfo;
- };
-
- var logFn = logger('PlaylistSelector');
-
- var representationToString = function representationToString(representation) {
- if (!representation || !representation.playlist) {
- return;
- }
-
- var playlist = representation.playlist;
- return JSON.stringify({
- id: playlist.id,
- bandwidth: representation.bandwidth,
- width: representation.width,
- height: representation.height,
- codecs: playlist.attributes && playlist.attributes.CODECS || ''
- });
- }; // Utilities
-
- /**
- * Returns the CSS value for the specified property on an element
- * using `getComputedStyle`. Firefox has a long-standing issue where
- * getComputedStyle() may return null when running in an iframe with
- * `display: none`.
- *
- * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
- * @param {HTMLElement} el the htmlelement to work on
- * @param {string} the proprety to get the style for
- */
-
-
- var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
- if (!el) {
- return '';
- }
-
- var result = window__default['default'].getComputedStyle(el);
-
- if (!result) {
- return '';
- }
-
- return result[property];
- };
- /**
- * Resuable stable sort function
- *
- * @param {Playlists} array
- * @param {Function} sortFn Different comparators
- * @function stableSort
- */
-
-
- var stableSort = function stableSort(array, sortFn) {
- var newArray = array.slice();
- array.sort(function (left, right) {
- var cmp = sortFn(left, right);
-
- if (cmp === 0) {
- return newArray.indexOf(left) - newArray.indexOf(right);
- }
-
- return cmp;
- });
- };
- /**
- * A comparator function to sort two playlist object by bandwidth.
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the bandwidth attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the bandwidth of right is greater than left and
- * exactly zero if the two are equal.
- */
-
-
- var comparePlaylistBandwidth = function comparePlaylistBandwidth(left, right) {
- var leftBandwidth;
- var rightBandwidth;
-
- if (left.attributes.BANDWIDTH) {
- leftBandwidth = left.attributes.BANDWIDTH;
- }
-
- leftBandwidth = leftBandwidth || window__default['default'].Number.MAX_VALUE;
-
- if (right.attributes.BANDWIDTH) {
- rightBandwidth = right.attributes.BANDWIDTH;
- }
-
- rightBandwidth = rightBandwidth || window__default['default'].Number.MAX_VALUE;
- return leftBandwidth - rightBandwidth;
- };
- /**
- * A comparator function to sort two playlist object by resolution (width).
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the resolution.width attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the resolution.width of right is greater than left and
- * exactly zero if the two are equal.
- */
-
- var comparePlaylistResolution = function comparePlaylistResolution(left, right) {
- var leftWidth;
- var rightWidth;
-
- if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
- leftWidth = left.attributes.RESOLUTION.width;
- }
-
- leftWidth = leftWidth || window__default['default'].Number.MAX_VALUE;
-
- if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
- rightWidth = right.attributes.RESOLUTION.width;
- }
-
- rightWidth = rightWidth || window__default['default'].Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
- // have the same media dimensions/ resolution
-
- if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
- return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
- }
-
- return leftWidth - rightWidth;
- };
- /**
- * Chooses the appropriate media playlist based on bandwidth and player size
- *
- * @param {Object} master
- * Object representation of the master manifest
- * @param {number} playerBandwidth
- * Current calculated bandwidth of the player
- * @param {number} playerWidth
- * Current width of the player element (should account for the device pixel ratio)
- * @param {number} playerHeight
- * Current height of the player element (should account for the device pixel ratio)
- * @param {boolean} limitRenditionByPlayerDimensions
- * True if the player width and height should be used during the selection, false otherwise
- * @param {Object} masterPlaylistController
- * the current masterPlaylistController object
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-
- var simpleSelector = function simpleSelector(master, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, masterPlaylistController) {
- // If we end up getting called before `master` is available, exit early
- if (!master) {
- return;
- }
-
- var options = {
- bandwidth: playerBandwidth,
- width: playerWidth,
- height: playerHeight,
- limitRenditionByPlayerDimensions: limitRenditionByPlayerDimensions
- };
- var playlists = master.playlists; // if playlist is audio only, select between currently active audio group playlists.
-
- if (Playlist.isAudioOnly(master)) {
- playlists = masterPlaylistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
- // at the buttom of this function for debugging.
-
- options.audioOnly = true;
- } // convert the playlists to an intermediary representation to make comparisons easier
-
-
- var sortedPlaylistReps = playlists.map(function (playlist) {
- var bandwidth;
- var width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
- var height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
- bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
- bandwidth = bandwidth || window__default['default'].Number.MAX_VALUE;
- return {
- bandwidth: bandwidth,
- width: width,
- height: height,
- playlist: playlist
- };
- });
- stableSort(sortedPlaylistReps, function (left, right) {
- return left.bandwidth - right.bandwidth;
- }); // filter out any playlists that have been excluded due to
- // incompatible configurations
-
- sortedPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return !Playlist.isIncompatible(rep.playlist);
- }); // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
-
- var enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return Playlist.isEnabled(rep.playlist);
- });
-
- if (!enabledPlaylistReps.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return !Playlist.isDisabled(rep.playlist);
- });
- } // filter out any variant that has greater effective bitrate
- // than the current estimated bandwidth
-
-
- var bandwidthPlaylistReps = enabledPlaylistReps.filter(function (rep) {
- return rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth;
- });
- var highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
- // and then taking the very first element
-
- var bandwidthBestRep = bandwidthPlaylistReps.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0]; // if we're not going to limit renditions by player size, make an early decision.
-
- if (limitRenditionByPlayerDimensions === false) {
- var _chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
-
- if (_chosenRep && _chosenRep.playlist) {
- var type = 'sortedPlaylistReps';
-
- if (bandwidthBestRep) {
- type = 'bandwidthBestRep';
- }
-
- if (enabledPlaylistReps[0]) {
- type = 'enabledPlaylistReps';
- }
-
- logFn("choosing " + representationToString(_chosenRep) + " using " + type + " with options", options);
- return _chosenRep.playlist;
- }
-
- logFn('could not choose a playlist with options', options);
- return null;
- } // filter out playlists without resolution information
-
-
- var haveResolution = bandwidthPlaylistReps.filter(function (rep) {
- return rep.width && rep.height;
- }); // sort variants by resolution
-
- stableSort(haveResolution, function (left, right) {
- return left.width - right.width;
- }); // if we have the exact resolution as the player use it
-
- var resolutionBestRepList = haveResolution.filter(function (rep) {
- return rep.width === playerWidth && rep.height === playerHeight;
- });
- highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
-
- var resolutionBestRep = resolutionBestRepList.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0];
- var resolutionPlusOneList;
- var resolutionPlusOneSmallest;
- var resolutionPlusOneRep; // find the smallest variant that is larger than the player
- // if there is no match of exact resolution
-
- if (!resolutionBestRep) {
- resolutionPlusOneList = haveResolution.filter(function (rep) {
- return rep.width > playerWidth || rep.height > playerHeight;
- }); // find all the variants have the same smallest resolution
-
- resolutionPlusOneSmallest = resolutionPlusOneList.filter(function (rep) {
- return rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height;
- }); // ensure that we also pick the highest bandwidth variant that
- // is just-larger-than the video player
-
- highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
- resolutionPlusOneRep = resolutionPlusOneSmallest.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0];
- } // fallback chain of variants
-
-
- var chosenRep = resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
-
- if (chosenRep && chosenRep.playlist) {
- var _type = 'sortedPlaylistReps';
-
- if (resolutionPlusOneRep) {
- _type = 'resolutionPlusOneRep';
- } else if (resolutionBestRep) {
- _type = 'resolutionBestRep';
- } else if (bandwidthBestRep) {
- _type = 'bandwidthBestRep';
- } else if (enabledPlaylistReps[0]) {
- _type = 'enabledPlaylistReps';
- }
-
- logFn("choosing " + representationToString(chosenRep) + " using " + _type + " with options", options);
- return chosenRep.playlist;
- }
-
- logFn('could not choose a playlist with options', options);
- return null;
- };
-
- /**
- * Chooses the appropriate media playlist based on the most recent
- * bandwidth estimate and the player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-
- var lastBandwidthSelector = function lastBandwidthSelector() {
- var pixelRatio = this.useDevicePixelRatio ? window__default['default'].devicePixelRatio || 1 : 1;
- return simpleSelector(this.playlists.master, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
- };
- /**
- * Chooses the appropriate media playlist based on an
- * exponential-weighted moving average of the bandwidth after
- * filtering for player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @param {number} decay - a number between 0 and 1. Higher values of
- * this parameter will cause previous bandwidth estimates to lose
- * significance more quickly.
- * @return {Function} a function which can be invoked to create a new
- * playlist selector function.
- * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
- */
-
- var movingAverageBandwidthSelector = function movingAverageBandwidthSelector(decay) {
- var average = -1;
- var lastSystemBandwidth = -1;
-
- if (decay < 0 || decay > 1) {
- throw new Error('Moving average bandwidth decay must be between 0 and 1.');
- }
-
- return function () {
- var pixelRatio = this.useDevicePixelRatio ? window__default['default'].devicePixelRatio || 1 : 1;
-
- if (average < 0) {
- average = this.systemBandwidth;
- lastSystemBandwidth = this.systemBandwidth;
- } // stop the average value from decaying for every 250ms
- // when the systemBandwidth is constant
- // and
- // stop average from setting to a very low value when the
- // systemBandwidth becomes 0 in case of chunk cancellation
-
-
- if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
- average = decay * this.systemBandwidth + (1 - decay) * average;
- lastSystemBandwidth = this.systemBandwidth;
- }
-
- return simpleSelector(this.playlists.master, average, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
- };
- };
- /**
- * Chooses the appropriate media playlist based on the potential to rebuffer
- *
- * @param {Object} settings
- * Object of information required to use this selector
- * @param {Object} settings.master
- * Object representation of the master manifest
- * @param {number} settings.currentTime
- * The current time of the player
- * @param {number} settings.bandwidth
- * Current measured bandwidth
- * @param {number} settings.duration
- * Duration of the media
- * @param {number} settings.segmentDuration
- * Segment duration to be used in round trip time calculations
- * @param {number} settings.timeUntilRebuffer
- * Time left in seconds until the player has to rebuffer
- * @param {number} settings.currentTimeline
- * The current timeline segments are being loaded from
- * @param {SyncController} settings.syncController
- * SyncController for determining if we have a sync point for a given playlist
- * @return {Object|null}
- * {Object} return.playlist
- * The highest bandwidth playlist with the least amount of rebuffering
- * {Number} return.rebufferingImpact
- * The amount of time in seconds switching to this playlist will rebuffer. A
- * negative value means that switching will cause zero rebuffering.
- */
-
- var minRebufferMaxBandwidthSelector = function minRebufferMaxBandwidthSelector(settings) {
- var master = settings.master,
- currentTime = settings.currentTime,
- bandwidth = settings.bandwidth,
- duration = settings.duration,
- segmentDuration = settings.segmentDuration,
- timeUntilRebuffer = settings.timeUntilRebuffer,
- currentTimeline = settings.currentTimeline,
- syncController = settings.syncController; // filter out any playlists that have been excluded due to
- // incompatible configurations
-
- var compatiblePlaylists = master.playlists.filter(function (playlist) {
- return !Playlist.isIncompatible(playlist);
- }); // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
-
- var enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
-
- if (!enabledPlaylists.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylists = compatiblePlaylists.filter(function (playlist) {
- return !Playlist.isDisabled(playlist);
- });
- }
-
- var bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
- var rebufferingEstimates = bandwidthPlaylists.map(function (playlist) {
- var syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
- // sync request first. This will double the request time
-
- var numRequests = syncPoint ? 1 : 2;
- var requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
- var rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
- return {
- playlist: playlist,
- rebufferingImpact: rebufferingImpact
- };
- });
- var noRebufferingPlaylists = rebufferingEstimates.filter(function (estimate) {
- return estimate.rebufferingImpact <= 0;
- }); // Sort by bandwidth DESC
-
- stableSort(noRebufferingPlaylists, function (a, b) {
- return comparePlaylistBandwidth(b.playlist, a.playlist);
- });
-
- if (noRebufferingPlaylists.length) {
- return noRebufferingPlaylists[0];
- }
-
- stableSort(rebufferingEstimates, function (a, b) {
- return a.rebufferingImpact - b.rebufferingImpact;
- });
- return rebufferingEstimates[0] || null;
- };
- /**
- * Chooses the appropriate media playlist, which in this case is the lowest bitrate
- * one with video. If no renditions with video exist, return the lowest audio rendition.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Object|null}
- * {Object} return.playlist
- * The lowest bitrate playlist that contains a video codec. If no such rendition
- * exists pick the lowest audio rendition.
- */
-
- var lowestBitrateCompatibleVariantSelector = function lowestBitrateCompatibleVariantSelector() {
- var _this = this;
-
- // filter out any playlists that have been excluded due to
- // incompatible configurations or playback errors
- var playlists = this.playlists.master.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
-
- stableSort(playlists, function (a, b) {
- return comparePlaylistBandwidth(a, b);
- }); // Parse and assume that playlists with no video codec have no video
- // (this is not necessarily true, although it is generally true).
- //
- // If an entire manifest has no valid videos everything will get filtered
- // out.
-
- var playlistsWithVideo = playlists.filter(function (playlist) {
- return !!codecsForPlaylist(_this.playlists.master, playlist).video;
- });
- return playlistsWithVideo[0] || null;
- };
-
- /**
- * Combine all segments into a single Uint8Array
- *
- * @param {Object} segmentObj
- * @return {Uint8Array} concatenated bytes
- * @private
- */
- var concatSegments = function concatSegments(segmentObj) {
- var offset = 0;
- var tempBuffer;
-
- if (segmentObj.bytes) {
- tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
-
- segmentObj.segments.forEach(function (segment) {
- tempBuffer.set(segment, offset);
- offset += segment.byteLength;
- });
- }
-
- return tempBuffer;
- };
-
- /**
- * @file text-tracks.js
- */
- /**
- * Create captions text tracks on video.js if they do not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {Object} tech the video.js tech
- * @param {Object} captionStream the caption stream to create
- * @private
- */
-
- var createCaptionsTrackIfNotExists = function createCaptionsTrackIfNotExists(inbandTextTracks, tech, captionStream) {
- if (!inbandTextTracks[captionStream]) {
- tech.trigger({
- type: 'usage',
- name: 'vhs-608'
- });
- tech.trigger({
- type: 'usage',
- name: 'hls-608'
- });
- var instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
-
- if (/^cc708_/.test(captionStream)) {
- instreamId = 'SERVICE' + captionStream.split('_')[1];
- }
-
- var track = tech.textTracks().getTrackById(instreamId);
-
- if (track) {
- // Resuse an existing track with a CC# id because this was
- // very likely created by videojs-contrib-hls from information
- // in the m3u8 for us to use
- inbandTextTracks[captionStream] = track;
- } else {
- // This section gets called when we have caption services that aren't specified in the manifest.
- // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
- var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
- var label = captionStream;
- var language = captionStream;
- var def = false;
- var captionService = captionServices[instreamId];
-
- if (captionService) {
- label = captionService.label;
- language = captionService.language;
- def = captionService.default;
- } // Otherwise, create a track with the default `CC#` label and
- // without a language
-
-
- inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
- kind: 'captions',
- id: instreamId,
- // TODO: investigate why this doesn't seem to turn the caption on by default
- default: def,
- label: label,
- language: language
- }, false).track;
- }
- }
- };
- /**
- * Add caption text track data to a source handler given an array of captions
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {Array} captionArray an array of caption data
- * @private
- */
-
- var addCaptionData = function addCaptionData(_ref) {
- var inbandTextTracks = _ref.inbandTextTracks,
- captionArray = _ref.captionArray,
- timestampOffset = _ref.timestampOffset;
-
- if (!captionArray) {
- return;
- }
-
- var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
- captionArray.forEach(function (caption) {
- var track = caption.stream;
- inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
- });
- };
- /**
- * Define properties on a cue for backwards compatability,
- * but warn the user that the way that they are using it
- * is depricated and will be removed at a later date.
- *
- * @param {Cue} cue the cue to add the properties on
- * @private
- */
-
- var deprecateOldCue = function deprecateOldCue(cue) {
- Object.defineProperties(cue.frame, {
- id: {
- get: function get() {
- videojs__default['default'].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
- return cue.value.key;
- }
- },
- value: {
- get: function get() {
- videojs__default['default'].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- },
- privateData: {
- get: function get() {
- videojs__default['default'].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- }
- });
- };
- /**
- * Add metadata text track data to a source handler given an array of metadata
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {Array} metadataArray an array of meta data
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {number} videoDuration the duration of the video
- * @private
- */
-
-
- var addMetadata = function addMetadata(_ref2) {
- var inbandTextTracks = _ref2.inbandTextTracks,
- metadataArray = _ref2.metadataArray,
- timestampOffset = _ref2.timestampOffset,
- videoDuration = _ref2.videoDuration;
-
- if (!metadataArray) {
- return;
- }
-
- var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
- var metadataTrack = inbandTextTracks.metadataTrack_;
-
- if (!metadataTrack) {
- return;
- }
-
- metadataArray.forEach(function (metadata) {
- var time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
- // ignore this bit of metadata.
- // This likely occurs when you have an non-timed ID3 tag like TIT2,
- // which is the "Title/Songname/Content description" frame
-
- if (typeof time !== 'number' || window__default['default'].isNaN(time) || time < 0 || !(time < Infinity)) {
- return;
- }
-
- metadata.frames.forEach(function (frame) {
- var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
- cue.frame = frame;
- cue.value = frame;
- deprecateOldCue(cue);
- metadataTrack.addCue(cue);
- });
- });
-
- if (!metadataTrack.cues || !metadataTrack.cues.length) {
- return;
- } // Updating the metadeta cues so that
- // the endTime of each cue is the startTime of the next cue
- // the endTime of last cue is the duration of the video
-
-
- var cues = metadataTrack.cues;
- var cuesArray = []; // Create a copy of the TextTrackCueList...
- // ...disregarding cues with a falsey value
-
- for (var i = 0; i < cues.length; i++) {
- if (cues[i]) {
- cuesArray.push(cues[i]);
- }
- } // Group cues by their startTime value
-
-
- var cuesGroupedByStartTime = cuesArray.reduce(function (obj, cue) {
- var timeSlot = obj[cue.startTime] || [];
- timeSlot.push(cue);
- obj[cue.startTime] = timeSlot;
- return obj;
- }, {}); // Sort startTimes by ascending order
-
- var sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort(function (a, b) {
- return Number(a) - Number(b);
- }); // Map each cue group's endTime to the next group's startTime
-
- sortedStartTimes.forEach(function (startTime, idx) {
- var cueGroup = cuesGroupedByStartTime[startTime];
- var nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
-
- cueGroup.forEach(function (cue) {
- cue.endTime = nextTime;
- });
- });
- };
- /**
- * Create metadata text track on video.js if it does not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {string} dispatchType the inband metadata track dispatch type
- * @param {Object} tech the video.js tech
- * @private
- */
-
- var createMetadataTrackIfNotExists = function createMetadataTrackIfNotExists(inbandTextTracks, dispatchType, tech) {
- if (inbandTextTracks.metadataTrack_) {
- return;
- }
-
- inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'Timed Metadata'
- }, false).track;
- inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
- };
- /**
- * Remove cues from a track on video.js.
- *
- * @param {Double} start start of where we should remove the cue
- * @param {Double} end end of where the we should remove the cue
- * @param {Object} track the text track to remove the cues from
- * @private
- */
-
- var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
- var i;
- var cue;
-
- if (!track) {
- return;
- }
-
- if (!track.cues) {
- return;
- }
-
- i = track.cues.length;
-
- while (i--) {
- cue = track.cues[i]; // Remove any cue within the provided start and end time
-
- if (cue.startTime >= start && cue.endTime <= end) {
- track.removeCue(cue);
- }
- }
- };
- /**
- * Remove duplicate cues from a track on video.js (a cue is considered a
- * duplicate if it has the same time interval and text as another)
- *
- * @param {Object} track the text track to remove the duplicate cues from
- * @private
- */
-
- var removeDuplicateCuesFromTrack = function removeDuplicateCuesFromTrack(track) {
- var cues = track.cues;
-
- if (!cues) {
- return;
- }
-
- for (var i = 0; i < cues.length; i++) {
- var duplicates = [];
- var occurrences = 0;
-
- for (var j = 0; j < cues.length; j++) {
- if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
- occurrences++;
-
- if (occurrences > 1) {
- duplicates.push(cues[j]);
- }
- }
- }
-
- if (duplicates.length) {
- duplicates.forEach(function (dupe) {
- return track.removeCue(dupe);
- });
- }
- }
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- var ONE_SECOND_IN_TS = 90000,
- // 90kHz clock
- secondsToVideoTs,
- secondsToAudioTs,
- videoTsToSeconds,
- audioTsToSeconds,
- audioTsToVideoTs,
- videoTsToAudioTs,
- metadataTsToSeconds;
-
- secondsToVideoTs = function secondsToVideoTs(seconds) {
- return seconds * ONE_SECOND_IN_TS;
- };
-
- secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
- return seconds * sampleRate;
- };
-
- videoTsToSeconds = function videoTsToSeconds(timestamp) {
- return timestamp / ONE_SECOND_IN_TS;
- };
-
- audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
- return timestamp / sampleRate;
- };
-
- audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
- return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
- };
-
- videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
- return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
- };
- /**
- * Adjust ID3 tag or caption timing information by the timeline pts values
- * (if keepOriginalTimestamps is false) and convert to seconds
- */
-
-
- metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
- return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
- };
-
- var clock = {
- ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
- secondsToVideoTs: secondsToVideoTs,
- secondsToAudioTs: secondsToAudioTs,
- videoTsToSeconds: videoTsToSeconds,
- audioTsToSeconds: audioTsToSeconds,
- audioTsToVideoTs: audioTsToVideoTs,
- videoTsToAudioTs: videoTsToAudioTs,
- metadataTsToSeconds: metadataTsToSeconds
- };
-
- /**
- * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
- * front of current time.
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {number} currentTime
- * The current time
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- * @return {Array}
- * List of gops considered safe to append over
- */
-
- var gopsSafeToAlignWith = function gopsSafeToAlignWith(buffer, currentTime, mapping) {
- if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
- return [];
- } // pts value for current time + 3 seconds to give a bit more wiggle room
-
-
- var currentTimePts = Math.ceil((currentTime - mapping + 3) * clock.ONE_SECOND_IN_TS);
- var i;
-
- for (i = 0; i < buffer.length; i++) {
- if (buffer[i].pts > currentTimePts) {
- break;
- }
- }
-
- return buffer.slice(i);
- };
- /**
- * Appends gop information (timing and byteLength) received by the transmuxer for the
- * gops appended in the last call to appendBuffer
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Array} gops
- * List of new gop information
- * @param {boolean} replace
- * If true, replace the buffer with the new gop information. If false, append the
- * new gop information to the buffer in the right location of time.
- * @return {Array}
- * Updated list of gop information
- */
-
- var updateGopBuffer = function updateGopBuffer(buffer, gops, replace) {
- if (!gops.length) {
- return buffer;
- }
-
- if (replace) {
- // If we are in safe append mode, then completely overwrite the gop buffer
- // with the most recent appeneded data. This will make sure that when appending
- // future segments, we only try to align with gops that are both ahead of current
- // time and in the last segment appended.
- return gops.slice();
- }
-
- var start = gops[0].pts;
- var i = 0;
-
- for (i; i < buffer.length; i++) {
- if (buffer[i].pts >= start) {
- break;
- }
- }
-
- return buffer.slice(0, i).concat(gops);
- };
- /**
- * Removes gop information in buffer that overlaps with provided start and end
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Double} start
- * position to start the remove at
- * @param {Double} end
- * position to end the remove at
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- */
-
- var removeGopBuffer = function removeGopBuffer(buffer, start, end, mapping) {
- var startPts = Math.ceil((start - mapping) * clock.ONE_SECOND_IN_TS);
- var endPts = Math.ceil((end - mapping) * clock.ONE_SECOND_IN_TS);
- var updatedBuffer = buffer.slice();
- var i = buffer.length;
-
- while (i--) {
- if (buffer[i].pts <= endPts) {
- break;
- }
- }
-
- if (i === -1) {
- // no removal because end of remove range is before start of buffer
- return updatedBuffer;
- }
-
- var j = i + 1;
-
- while (j--) {
- if (buffer[j].pts <= startPts) {
- break;
- }
- } // clamp remove range start to 0 index
-
-
- j = Math.max(j, 0);
- updatedBuffer.splice(j, i - j + 1);
- return updatedBuffer;
- };
-
- var shallowEqual = function shallowEqual(a, b) {
- // if both are undefined
- // or one or the other is undefined
- // they are not equal
- if (!a && !b || !a && b || a && !b) {
- return false;
- } // they are the same object and thus, equal
-
-
- if (a === b) {
- return true;
- } // sort keys so we can make sure they have
- // all the same keys later.
-
-
- var akeys = Object.keys(a).sort();
- var bkeys = Object.keys(b).sort(); // different number of keys, not equal
-
- if (akeys.length !== bkeys.length) {
- return false;
- }
-
- for (var i = 0; i < akeys.length; i++) {
- var key = akeys[i]; // different sorted keys, not equal
-
- if (key !== bkeys[i]) {
- return false;
- } // different values, not equal
-
-
- if (a[key] !== b[key]) {
- return false;
- }
- }
-
- return true;
- };
-
- // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
- var QUOTA_EXCEEDED_ERR = 22;
-
- /**
- * The segment loader has no recourse except to fetch a segment in the
- * current playlist and use the internal timestamps in that segment to
- * generate a syncPoint. This function returns a good candidate index
- * for that process.
- *
- * @param {Array} segments - the segments array from a playlist.
- * @return {number} An index of a segment from the playlist to load
- */
-
- var getSyncSegmentCandidate = function getSyncSegmentCandidate(currentTimeline, segments, targetTime) {
- segments = segments || [];
- var timelineSegments = [];
- var time = 0;
-
- for (var i = 0; i < segments.length; i++) {
- var segment = segments[i];
-
- if (currentTimeline === segment.timeline) {
- timelineSegments.push(i);
- time += segment.duration;
-
- if (time > targetTime) {
- return i;
- }
- }
- }
-
- if (timelineSegments.length === 0) {
- return 0;
- } // default to the last timeline segment
-
-
- return timelineSegments[timelineSegments.length - 1];
- }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
- // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
- // as a start to prevent any potential issues with removing content too close to the
- // playhead.
-
- var MIN_BACK_BUFFER = 1; // in ms
-
- var CHECK_BUFFER_DELAY = 500;
-
- var finite = function finite(num) {
- return typeof num === 'number' && isFinite(num);
- }; // With most content hovering around 30fps, if a segment has a duration less than a half
- // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
- // not accurately reflect the rest of the content.
-
-
- var MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
- var illegalMediaSwitch = function illegalMediaSwitch(loaderType, startingMedia, trackInfo) {
- // Although these checks should most likely cover non 'main' types, for now it narrows
- // the scope of our checks.
- if (loaderType !== 'main' || !startingMedia || !trackInfo) {
- return null;
- }
-
- if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
- return 'Neither audio nor video found in segment.';
- }
-
- if (startingMedia.hasVideo && !trackInfo.hasVideo) {
- return 'Only audio found in segment when we expected video.' + ' We can\'t switch to audio only from a stream that had video.' + ' To get rid of this message, please add codec information to the manifest.';
- }
-
- if (!startingMedia.hasVideo && trackInfo.hasVideo) {
- return 'Video found in segment when we expected only audio.' + ' We can\'t switch to a stream with video from an audio only stream.' + ' To get rid of this message, please add codec information to the manifest.';
- }
-
- return null;
- };
- /**
- * Calculates a time value that is safe to remove from the back buffer without interrupting
- * playback.
- *
- * @param {TimeRange} seekable
- * The current seekable range
- * @param {number} currentTime
- * The current time of the player
- * @param {number} targetDuration
- * The target duration of the current playlist
- * @return {number}
- * Time that is safe to remove from the back buffer without interrupting playback
- */
-
- var safeBackBufferTrimTime = function safeBackBufferTrimTime(seekable, currentTime, targetDuration) {
- // 30 seconds before the playhead provides a safe default for trimming.
- //
- // Choosing a reasonable default is particularly important for high bitrate content and
- // VOD videos/live streams with large windows, as the buffer may end up overfilled and
- // throw an APPEND_BUFFER_ERR.
- var trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
-
- if (seekable.length) {
- // Some live playlists may have a shorter window of content than the full allowed back
- // buffer. For these playlists, don't save content that's no longer within the window.
- trimTime = Math.max(trimTime, seekable.start(0));
- } // Don't remove within target duration of the current time to avoid the possibility of
- // removing the GOP currently being played, as removing it can cause playback stalls.
-
-
- var maxTrimTime = currentTime - targetDuration;
- return Math.min(maxTrimTime, trimTime);
- };
-
- var segmentInfoString = function segmentInfoString(segmentInfo) {
- var startOfSegment = segmentInfo.startOfSegment,
- duration = segmentInfo.duration,
- segment = segmentInfo.segment,
- part = segmentInfo.part,
- _segmentInfo$playlist = segmentInfo.playlist,
- seq = _segmentInfo$playlist.mediaSequence,
- id = _segmentInfo$playlist.id,
- _segmentInfo$playlist2 = _segmentInfo$playlist.segments,
- segments = _segmentInfo$playlist2 === void 0 ? [] : _segmentInfo$playlist2,
- index = segmentInfo.mediaIndex,
- partIndex = segmentInfo.partIndex,
- timeline = segmentInfo.timeline;
- var segmentLen = segments.length - 1;
- var selection = 'mediaIndex/partIndex increment';
-
- if (segmentInfo.getMediaInfoForTime) {
- selection = "getMediaInfoForTime (" + segmentInfo.getMediaInfoForTime + ")";
- } else if (segmentInfo.isSyncRequest) {
- selection = 'getSyncSegmentCandidate (isSyncRequest)';
- }
-
- var hasPartIndex = typeof partIndex === 'number';
- var name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
- var zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
- preloadSegment: segment
- }) - 1 : 0;
- return name + " [" + (seq + index) + "/" + (seq + segmentLen) + "]" + (hasPartIndex ? " part [" + partIndex + "/" + zeroBasedPartCount + "]" : '') + (" segment start/end [" + segment.start + " => " + segment.end + "]") + (hasPartIndex ? " part start/end [" + part.start + " => " + part.end + "]" : '') + (" startOfSegment [" + startOfSegment + "]") + (" duration [" + duration + "]") + (" timeline [" + timeline + "]") + (" selected by [" + selection + "]") + (" playlist [" + id + "]");
- };
-
- var timingInfoPropertyForMedia = function timingInfoPropertyForMedia(mediaType) {
- return mediaType + "TimingInfo";
- };
- /**
- * Returns the timestamp offset to use for the segment.
- *
- * @param {number} segmentTimeline
- * The timeline of the segment
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} startOfSegment
- * The estimated segment start
- * @param {TimeRange[]} buffered
- * The loader's buffer
- * @param {boolean} overrideCheck
- * If true, no checks are made to see if the timestamp offset value should be set,
- * but sets it directly to a value.
- *
- * @return {number|null}
- * Either a number representing a new timestamp offset, or null if the segment is
- * part of the same timeline
- */
-
-
- var timestampOffsetForSegment = function timestampOffsetForSegment(_ref) {
- var segmentTimeline = _ref.segmentTimeline,
- currentTimeline = _ref.currentTimeline,
- startOfSegment = _ref.startOfSegment,
- buffered = _ref.buffered,
- overrideCheck = _ref.overrideCheck;
-
- // Check to see if we are crossing a discontinuity to see if we need to set the
- // timestamp offset on the transmuxer and source buffer.
- //
- // Previously, we changed the timestampOffset if the start of this segment was less than
- // the currently set timestampOffset, but this isn't desirable as it can produce bad
- // behavior, especially around long running live streams.
- if (!overrideCheck && segmentTimeline === currentTimeline) {
- return null;
- } // When changing renditions, it's possible to request a segment on an older timeline. For
- // instance, given two renditions with the following:
- //
- // #EXTINF:10
- // segment1
- // #EXT-X-DISCONTINUITY
- // #EXTINF:10
- // segment2
- // #EXTINF:10
- // segment3
- //
- // And the current player state:
- //
- // current time: 8
- // buffer: 0 => 20
- //
- // The next segment on the current rendition would be segment3, filling the buffer from
- // 20s onwards. However, if a rendition switch happens after segment2 was requested,
- // then the next segment to be requested will be segment1 from the new rendition in
- // order to fill time 8 and onwards. Using the buffered end would result in repeated
- // content (since it would position segment1 of the new rendition starting at 20s). This
- // case can be identified when the new segment's timeline is a prior value. Instead of
- // using the buffered end, the startOfSegment can be used, which, hopefully, will be
- // more accurate to the actual start time of the segment.
-
-
- if (segmentTimeline < currentTimeline) {
- return startOfSegment;
- } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
- // value uses the end of the last segment if it is available. While this value
- // should often be correct, it's better to rely on the buffered end, as the new
- // content post discontinuity should line up with the buffered end as if it were
- // time 0 for the new content.
-
-
- return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
- };
- /**
- * Returns whether or not the loader should wait for a timeline change from the timeline
- * change controller before processing the segment.
- *
- * Primary timing in VHS goes by video. This is different from most media players, as
- * audio is more often used as the primary timing source. For the foreseeable future, VHS
- * will continue to use video as the primary timing source, due to the current logic and
- * expectations built around it.
-
- * Since the timing follows video, in order to maintain sync, the video loader is
- * responsible for setting both audio and video source buffer timestamp offsets.
- *
- * Setting different values for audio and video source buffers could lead to
- * desyncing. The following examples demonstrate some of the situations where this
- * distinction is important. Note that all of these cases involve demuxed content. When
- * content is muxed, the audio and video are packaged together, therefore syncing
- * separate media playlists is not an issue.
- *
- * CASE 1: Audio prepares to load a new timeline before video:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the audio loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the video loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the audio loader goes ahead and loads and appends the 6th segment before the video
- * loader crosses the discontinuity, then when appended, the 6th audio segment will use
- * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
- * the audio loader must provide the audioAppendStart value to trim the content in the
- * transmuxer, and that value relies on the audio timestamp offset. Since the audio
- * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
- * segment until that value is provided.
- *
- * CASE 2: Video prepares to load a new timeline before audio:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the video loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the audio loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the video loader goes ahead and loads and appends the 6th segment, then once the
- * segment is loaded and processed, both the video and audio timestamp offsets will be
- * set, since video is used as the primary timing source. This is to ensure content lines
- * up appropriately, as any modifications to the video timing are reflected by audio when
- * the video loader sets the audio and video timestamp offsets to the same value. However,
- * setting the timestamp offset for audio before audio has had a chance to change
- * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
- * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
- *
- * CASE 3: When seeking, audio prepares to load a new timeline before video
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, both audio and video loaders are loading segments from timeline
- * 0, but imagine that the seek originated from timeline 1.
- *
- * When seeking to a new timeline, the timestamp offset will be set based on the expected
- * segment start of the loaded video segment. In order to maintain sync, the audio loader
- * must wait for the video loader to load its segment and update both the audio and video
- * timestamp offsets before it may load and append its own segment. This is the case
- * whether the seek results in a mismatched segment request (e.g., the audio loader
- * chooses to load segment 3 and the video loader chooses to load segment 4) or the
- * loaders choose to load the same segment index from each playlist, as the segments may
- * not be aligned perfectly, even for matching segment indexes.
- *
- * @param {Object} timelinechangeController
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} segmentTimeline
- * The timeline of the segment being loaded
- * @param {('main'|'audio')} loaderType
- * The loader type
- * @param {boolean} audioDisabled
- * Whether the audio is disabled for the loader. This should only be true when the
- * loader may have muxed audio in its segment, but should not append it, e.g., for
- * the main loader when an alternate audio playlist is active.
- *
- * @return {boolean}
- * Whether the loader should wait for a timeline change from the timeline change
- * controller before processing the segment
- */
-
- var shouldWaitForTimelineChange = function shouldWaitForTimelineChange(_ref2) {
- var timelineChangeController = _ref2.timelineChangeController,
- currentTimeline = _ref2.currentTimeline,
- segmentTimeline = _ref2.segmentTimeline,
- loaderType = _ref2.loaderType,
- audioDisabled = _ref2.audioDisabled;
-
- if (currentTimeline === segmentTimeline) {
- return false;
- }
-
- if (loaderType === 'audio') {
- var lastMainTimelineChange = timelineChangeController.lastTimelineChange({
- type: 'main'
- }); // Audio loader should wait if:
- //
- // * main hasn't had a timeline change yet (thus has not loaded its first segment)
- // * main hasn't yet changed to the timeline audio is looking to load
-
- return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
- } // The main loader only needs to wait for timeline changes if there's demuxed audio.
- // Otherwise, there's nothing to wait for, since audio would be muxed into the main
- // loader's segments (or the content is audio/video only and handled by the main
- // loader).
-
-
- if (loaderType === 'main' && audioDisabled) {
- var pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
- type: 'audio'
- }); // Main loader should wait for the audio loader if audio is not pending a timeline
- // change to the current timeline.
- //
- // Since the main loader is responsible for setting the timestamp offset for both
- // audio and video, the main loader must wait for audio to be about to change to its
- // timeline before setting the offset, otherwise, if audio is behind in loading,
- // segments from the previous timeline would be adjusted by the new timestamp offset.
- //
- // This requirement means that video will not cross a timeline until the audio is
- // about to cross to it, so that way audio and video will always cross the timeline
- // together.
- //
- // In addition to normal timeline changes, these rules also apply to the start of a
- // stream (going from a non-existent timeline, -1, to timeline 0). It's important
- // that these rules apply to the first timeline change because if they did not, it's
- // possible that the main loader will cross two timelines before the audio loader has
- // crossed one. Logic may be implemented to handle the startup as a special case, but
- // it's easier to simply treat all timeline changes the same.
-
- if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
- return false;
- }
-
- return true;
- }
-
- return false;
- };
- var mediaDuration = function mediaDuration(audioTimingInfo, videoTimingInfo) {
- var audioDuration = audioTimingInfo && typeof audioTimingInfo.start === 'number' && typeof audioTimingInfo.end === 'number' ? audioTimingInfo.end - audioTimingInfo.start : 0;
- var videoDuration = videoTimingInfo && typeof videoTimingInfo.start === 'number' && typeof videoTimingInfo.end === 'number' ? videoTimingInfo.end - videoTimingInfo.start : 0;
- return Math.max(audioDuration, videoDuration);
- };
- var segmentTooLong = function segmentTooLong(_ref3) {
- var segmentDuration = _ref3.segmentDuration,
- maxDuration = _ref3.maxDuration;
-
- // 0 duration segments are most likely due to metadata only segments or a lack of
- // information.
- if (!segmentDuration) {
- return false;
- } // For HLS:
- //
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
- // The EXTINF duration of each Media Segment in the Playlist
- // file, when rounded to the nearest integer, MUST be less than or equal
- // to the target duration; longer segments can trigger playback stalls
- // or other errors.
- //
- // For DASH, the mpd-parser uses the largest reported segment duration as the target
- // duration. Although that reported duration is occasionally approximate (i.e., not
- // exact), a strict check may report that a segment is too long more often in DASH.
-
-
- return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
- };
- var getTroublesomeSegmentDurationMessage = function getTroublesomeSegmentDurationMessage(segmentInfo, sourceType) {
- // Right now we aren't following DASH's timing model exactly, so only perform
- // this check for HLS content.
- if (sourceType !== 'hls') {
- return null;
- }
-
- var segmentDuration = mediaDuration(segmentInfo.audioTimingInfo, segmentInfo.videoTimingInfo); // Don't report if we lack information.
- //
- // If the segment has a duration of 0 it is either a lack of information or a
- // metadata only segment and shouldn't be reported here.
-
- if (!segmentDuration) {
- return null;
- }
-
- var targetDuration = segmentInfo.playlist.targetDuration;
- var isSegmentWayTooLong = segmentTooLong({
- segmentDuration: segmentDuration,
- maxDuration: targetDuration * 2
- });
- var isSegmentSlightlyTooLong = segmentTooLong({
- segmentDuration: segmentDuration,
- maxDuration: targetDuration
- });
- var segmentTooLongMessage = "Segment with index " + segmentInfo.mediaIndex + " " + ("from playlist " + segmentInfo.playlist.id + " ") + ("has a duration of " + segmentDuration + " ") + ("when the reported duration is " + segmentInfo.duration + " ") + ("and the target duration is " + targetDuration + ". ") + 'For HLS content, a duration in excess of the target duration may result in ' + 'playback issues. See the HLS specification section on EXT-X-TARGETDURATION for ' + 'more details: ' + 'https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1';
-
- if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
- return {
- severity: isSegmentWayTooLong ? 'warn' : 'info',
- message: segmentTooLongMessage
- };
- }
-
- return null;
- };
- /**
- * An object that manages segment loading and appending.
- *
- * @class SegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-
- var SegmentLoader = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(SegmentLoader, _videojs$EventTarget);
-
- function SegmentLoader(settings, options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this; // check pre-conditions
-
- if (!settings) {
- throw new TypeError('Initialization settings are required');
- }
-
- if (typeof settings.currentTime !== 'function') {
- throw new TypeError('No currentTime getter specified');
- }
-
- if (!settings.mediaSource) {
- throw new TypeError('No MediaSource specified');
- } // public properties
-
-
- _this.bandwidth = settings.bandwidth;
- _this.throughput = {
- rate: 0,
- count: 0
- };
- _this.roundTrip = NaN;
-
- _this.resetStats_();
-
- _this.mediaIndex = null;
- _this.partIndex = null; // private settings
-
- _this.hasPlayed_ = settings.hasPlayed;
- _this.currentTime_ = settings.currentTime;
- _this.seekable_ = settings.seekable;
- _this.seeking_ = settings.seeking;
- _this.duration_ = settings.duration;
- _this.mediaSource_ = settings.mediaSource;
- _this.vhs_ = settings.vhs;
- _this.loaderType_ = settings.loaderType;
- _this.currentMediaInfo_ = void 0;
- _this.startingMediaInfo_ = void 0;
- _this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
- _this.goalBufferLength_ = settings.goalBufferLength;
- _this.sourceType_ = settings.sourceType;
- _this.sourceUpdater_ = settings.sourceUpdater;
- _this.inbandTextTracks_ = settings.inbandTextTracks;
- _this.state_ = 'INIT';
- _this.timelineChangeController_ = settings.timelineChangeController;
- _this.shouldSaveSegmentTimingInfo_ = true;
- _this.parse708captions_ = settings.parse708captions; // private instance variables
-
- _this.checkBufferTimeout_ = null;
- _this.error_ = void 0;
- _this.currentTimeline_ = -1;
- _this.pendingSegment_ = null;
- _this.xhrOptions_ = null;
- _this.pendingSegments_ = [];
- _this.audioDisabled_ = false;
- _this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
-
- _this.gopBuffer_ = [];
- _this.timeMapping_ = 0;
- _this.safeAppend_ = videojs__default['default'].browser.IE_VERSION >= 11;
- _this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- _this.playlistOfLastInitSegment_ = {
- audio: null,
- video: null
- };
- _this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
- // information yet to start the loading process (e.g., if the audio loader wants to
- // load a segment from the next timeline but the main loader hasn't yet crossed that
- // timeline), then the load call will be added to the queue until it is ready to be
- // processed.
-
- _this.loadQueue_ = [];
- _this.metadataQueue_ = {
- id3: [],
- caption: []
- };
- _this.waitingOnRemove_ = false;
- _this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
-
- _this.activeInitSegmentId_ = null;
- _this.initSegments_ = {}; // HLSe playback
-
- _this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
- _this.keyCache_ = {};
- _this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
- // between a time in the display time and a segment index within
- // a playlist
-
- _this.syncController_ = settings.syncController;
- _this.syncPoint_ = {
- segmentIndex: 0,
- time: 0
- };
- _this.transmuxer_ = _this.createTransmuxer_();
-
- _this.triggerSyncInfoUpdate_ = function () {
- return _this.trigger('syncinfoupdate');
- };
-
- _this.syncController_.on('syncinfoupdate', _this.triggerSyncInfoUpdate_);
-
- _this.mediaSource_.addEventListener('sourceopen', function () {
- if (!_this.isEndOfStream_()) {
- _this.ended_ = false;
- }
- }); // ...for determining the fetch location
-
-
- _this.fetchAtBuffer_ = false;
- _this.logger_ = logger("SegmentLoader[" + _this.loaderType_ + "]");
- Object.defineProperty(assertThisInitialized(_this), 'state', {
- get: function get() {
- return this.state_;
- },
- set: function set(newState) {
- if (newState !== this.state_) {
- this.logger_(this.state_ + " -> " + newState);
- this.state_ = newState;
- this.trigger('statechange');
- }
- }
- });
-
- _this.sourceUpdater_.on('ready', function () {
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- }); // Only the main loader needs to listen for pending timeline changes, as the main
- // loader should wait for audio to be ready to change its timeline so that both main
- // and audio timelines change together. For more details, see the
- // shouldWaitForTimelineChange function.
-
-
- if (_this.loaderType_ === 'main') {
- _this.timelineChangeController_.on('pendingtimelinechange', function () {
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- });
- } // The main loader only listens on pending timeline changes, but the audio loader,
- // since its loads follow main, needs to listen on timeline changes. For more details,
- // see the shouldWaitForTimelineChange function.
-
-
- if (_this.loaderType_ === 'audio') {
- _this.timelineChangeController_.on('timelinechange', function () {
- if (_this.hasEnoughInfoToLoad_()) {
- _this.processLoadQueue_();
- }
-
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- });
- }
-
- return _this;
- }
-
- var _proto = SegmentLoader.prototype;
-
- _proto.createTransmuxer_ = function createTransmuxer_() {
- return segmentTransmuxer.createTransmuxer({
- remux: false,
- alignGopsAtEnd: this.safeAppend_,
- keepOriginalTimestamps: true,
- parse708captions: this.parse708captions_
- });
- }
- /**
- * reset all of our media stats
- *
- * @private
- */
- ;
-
- _proto.resetStats_ = function resetStats_() {
- this.mediaBytesTransferred = 0;
- this.mediaRequests = 0;
- this.mediaRequestsAborted = 0;
- this.mediaRequestsTimedout = 0;
- this.mediaRequestsErrored = 0;
- this.mediaTransferDuration = 0;
- this.mediaSecondsLoaded = 0;
- this.mediaAppends = 0;
- }
- /**
- * dispose of the SegmentLoader and reset to the default state
- */
- ;
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.state = 'DISPOSED';
- this.pause();
- this.abort_();
-
- if (this.transmuxer_) {
- this.transmuxer_.terminate();
- }
-
- this.resetStats_();
-
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- }
-
- if (this.syncController_ && this.triggerSyncInfoUpdate_) {
- this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
- }
-
- this.off();
- };
-
- _proto.setAudio = function setAudio(enable) {
- this.audioDisabled_ = !enable;
-
- if (enable) {
- this.appendInitSegment_.audio = true;
- } else {
- // remove current track audio if it gets disabled
- this.sourceUpdater_.removeAudio(0, this.duration_());
- }
- }
- /**
- * abort anything that is currently doing on with the SegmentLoader
- * and reset to a default state
- */
- ;
-
- _proto.abort = function abort() {
- if (this.state !== 'WAITING') {
- if (this.pendingSegment_) {
- this.pendingSegment_ = null;
- }
-
- return;
- }
-
- this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
- // since we are no longer "waiting" on any requests. XHR callback is not always run
- // when the request is aborted. This will prevent the loader from being stuck in the
- // WAITING state indefinitely.
-
- this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
- // next segment
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
- /**
- * abort all pending xhr requests and null any pending segements
- *
- * @private
- */
- ;
-
- _proto.abort_ = function abort_() {
- if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
- this.pendingSegment_.abortRequests();
- } // clear out the segment being processed
-
-
- this.pendingSegment_ = null;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
- this.waitingOnRemove_ = false;
- window__default['default'].clearTimeout(this.quotaExceededErrorRetryTimeout_);
- this.quotaExceededErrorRetryTimeout_ = null;
- };
-
- _proto.checkForAbort_ = function checkForAbort_(requestId) {
- // If the state is APPENDING, then aborts will not modify the state, meaning the first
- // callback that happens should reset the state to READY so that loading can continue.
- if (this.state === 'APPENDING' && !this.pendingSegment_) {
- this.state = 'READY';
- return true;
- }
-
- if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
- return true;
- }
-
- return false;
- }
- /**
- * set an error on the segment loader and null out any pending segements
- *
- * @param {Error} error the error to set on the SegmentLoader
- * @return {Error} the error that was set or that is currently set
- */
- ;
-
- _proto.error = function error(_error) {
- if (typeof _error !== 'undefined') {
- this.logger_('error occurred:', _error);
- this.error_ = _error;
- }
-
- this.pendingSegment_ = null;
- return this.error_;
- };
-
- _proto.endOfStream = function endOfStream() {
- this.ended_ = true;
-
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
-
- this.gopBuffer_.length = 0;
- this.pause();
- this.trigger('ended');
- }
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- ;
-
- _proto.buffered_ = function buffered_() {
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- return videojs__default['default'].createTimeRanges();
- }
-
- if (this.loaderType_ === 'main') {
- var _this$startingMediaIn = this.startingMediaInfo_,
- hasAudio = _this$startingMediaIn.hasAudio,
- hasVideo = _this$startingMediaIn.hasVideo,
- isMuxed = _this$startingMediaIn.isMuxed;
-
- if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
- return this.sourceUpdater_.buffered();
- }
-
- if (hasVideo) {
- return this.sourceUpdater_.videoBuffered();
- }
- } // One case that can be ignored for now is audio only with alt audio,
- // as we don't yet have proper support for that.
-
-
- return this.sourceUpdater_.audioBuffered();
- }
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- ;
-
- _proto.initSegmentForMap = function initSegmentForMap(map, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!map) {
- return null;
- }
-
- var id = initSegmentId(map);
- var storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: map.bytes,
- tracks: map.tracks,
- timescales: map.timescales
- };
- }
-
- return storedMap || map;
- }
- /**
- * Gets and sets key for the provided key
- *
- * @param {Object} key
- * The key object representing the key to get or set
- * @param {boolean=} set
- * If true, the key for the provided key should be saved
- * @return {Object}
- * Key object for desired key
- */
- ;
-
- _proto.segmentKey = function segmentKey(key, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!key) {
- return null;
- }
-
- var id = segmentKeyId(key);
- var storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
-
- if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
- this.keyCache_[id] = storedKey = {
- resolvedUri: key.resolvedUri,
- bytes: key.bytes
- };
- }
-
- var result = {
- resolvedUri: (storedKey || key).resolvedUri
- };
-
- if (storedKey) {
- result.bytes = storedKey.bytes;
- }
-
- return result;
- }
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- ;
-
- _proto.couldBeginLoading_ = function couldBeginLoading_() {
- return this.playlist_ && !this.paused();
- }
- /**
- * load a playlist and start to fill the buffer
- */
- ;
-
- _proto.load = function load() {
- // un-pause
- this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
- // specified
-
- if (!this.playlist_) {
- return;
- } // if all the configuration is ready, initialize and begin loading
-
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- } // if we're in the middle of processing a segment already, don't
- // kick off an additional segment request
-
-
- if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
- return;
- }
-
- this.state = 'READY';
- }
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- ;
-
- _proto.init_ = function init_() {
- this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
- // audio data from the muxed content should be removed
-
- this.resetEverything();
- return this.monitorBuffer_();
- }
- /**
- * set a playlist on the segment loader
- *
- * @param {PlaylistLoader} media the playlist to set on the segment loader
- */
- ;
-
- _proto.playlist = function playlist(newPlaylist, options) {
- if (options === void 0) {
- options = {};
- }
-
- if (!newPlaylist) {
- return;
- }
-
- var oldPlaylist = this.playlist_;
- var segmentInfo = this.pendingSegment_;
- this.playlist_ = newPlaylist;
- this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
- // is always our zero-time so force a sync update each time the playlist
- // is refreshed from the server
- //
- // Use the INIT state to determine if playback has started, as the playlist sync info
- // should be fixed once requests begin (as sync points are generated based on sync
- // info), but not before then.
-
- if (this.state === 'INIT') {
- newPlaylist.syncInfo = {
- mediaSequence: newPlaylist.mediaSequence,
- time: 0
- }; // Setting the date time mapping means mapping the program date time (if available)
- // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
- // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
- // be updated as the playlist is refreshed before the loader starts loading, the
- // program date time mapping needs to be updated as well.
- //
- // This mapping is only done for the main loader because a program date time should
- // map equivalently between playlists.
-
- if (this.loaderType_ === 'main') {
- this.syncController_.setDateTimeMappingForStart(newPlaylist);
- }
- }
-
- var oldId = null;
-
- if (oldPlaylist) {
- if (oldPlaylist.id) {
- oldId = oldPlaylist.id;
- } else if (oldPlaylist.uri) {
- oldId = oldPlaylist.uri;
- }
- }
-
- this.logger_("playlist update [" + oldId + " => " + (newPlaylist.id || newPlaylist.uri) + "]"); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
- // in LIVE, we always want to update with new playlists (including refreshes)
-
- this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
- // buffering now
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- }
-
- if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
- if (this.mediaIndex !== null) {
- // we must "resync" the segment loader when we switch renditions and
- // the segment loader is already synced to the previous rendition
- this.resyncLoader();
- }
-
- this.currentMediaInfo_ = void 0;
- this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
-
- return;
- } // we reloaded the same playlist so we are in a live scenario
- // and we will likely need to adjust the mediaIndex
-
-
- var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
- this.logger_("live window shift [" + mediaSequenceDiff + "]"); // update the mediaIndex on the SegmentLoader
- // this is important because we can abort a request and this value must be
- // equal to the last appended mediaIndex
-
- if (this.mediaIndex !== null) {
- this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
- // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
- // new playlist was incremented by 1.
-
- if (this.mediaIndex < 0) {
- this.mediaIndex = null;
- this.partIndex = null;
- } else {
- var segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
- // unless parts fell off of the playlist for this segment.
- // In that case we need to reset partIndex and resync
-
- if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
- var mediaIndex = this.mediaIndex;
- this.logger_("currently processing part (index " + this.partIndex + ") no longer exists.");
- this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
- // as the part was dropped from our current playlists segment.
- // The mediaIndex will still be valid so keep that around.
-
- this.mediaIndex = mediaIndex;
- }
- }
- } // update the mediaIndex on the SegmentInfo object
- // this is important because we will update this.mediaIndex with this value
- // in `handleAppendsDone_` after the segment has been successfully appended
-
-
- if (segmentInfo) {
- segmentInfo.mediaIndex -= mediaSequenceDiff;
-
- if (segmentInfo.mediaIndex < 0) {
- segmentInfo.mediaIndex = null;
- segmentInfo.partIndex = null;
- } else {
- // we need to update the referenced segment so that timing information is
- // saved for the new playlist's segment, however, if the segment fell off the
- // playlist, we can leave the old reference and just lose the timing info
- if (segmentInfo.mediaIndex >= 0) {
- segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
- }
-
- if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
- segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
- }
- }
- }
-
- this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
- }
- /**
- * Prevent the loader from fetching additional segments. If there
- * is a segment request outstanding, it will finish processing
- * before the loader halts. A segment loader can be unpaused by
- * calling load().
- */
- ;
-
- _proto.pause = function pause() {
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- this.checkBufferTimeout_ = null;
- }
- }
- /**
- * Returns whether the segment loader is fetching additional
- * segments when given the opportunity. This property can be
- * modified through calls to pause() and load().
- */
- ;
-
- _proto.paused = function paused() {
- return this.checkBufferTimeout_ === null;
- }
- /**
- * Delete all the buffered data and reset the SegmentLoader
- *
- * @param {Function} [done] an optional callback to be executed when the remove
- * operation is complete
- */
- ;
-
- _proto.resetEverything = function resetEverything(done) {
- this.ended_ = false;
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
- // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
- // we then clamp the value to duration if necessary.
-
- this.remove(0, Infinity, done); // clears fmp4 captions
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
- /**
- * Force the SegmentLoader to resync and start loading around the currentTime instead
- * of starting at the end of the buffer
- *
- * Useful for fast quality changes
- */
- ;
-
- _proto.resetLoader = function resetLoader() {
- this.fetchAtBuffer_ = false;
- this.resyncLoader();
- }
- /**
- * Force the SegmentLoader to restart synchronization and make a conservative guess
- * before returning to the simple walk-forward method
- */
- ;
-
- _proto.resyncLoader = function resyncLoader() {
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
-
- this.mediaIndex = null;
- this.partIndex = null;
- this.syncPoint_ = null;
- this.isPendingTimestampOffset_ = false;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.abort();
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- }
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- * @param {Function} [done] - an optional callback to be executed when the remove
- * @param {boolean} force - force all remove operations to happen
- * operation is complete
- */
- ;
-
- _proto.remove = function remove(start, end, done, force) {
- if (done === void 0) {
- done = function done() {};
- }
-
- if (force === void 0) {
- force = false;
- }
-
- // clamp end to duration if we need to remove everything.
- // This is due to a browser bug that causes issues if we remove to Infinity.
- // videojs/videojs-contrib-hls#1225
- if (end === Infinity) {
- end = this.duration_();
- } // skip removes that would throw an error
- // commonly happens during a rendition switch at the start of a video
- // from start 0 to end 0
-
-
- if (end <= start) {
- this.logger_('skipping remove because end ${end} is <= start ${start}');
- return;
- }
-
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
-
- return;
- } // set it to one to complete this function's removes
-
-
- var removesRemaining = 1;
-
- var removeFinished = function removeFinished() {
- removesRemaining--;
-
- if (removesRemaining === 0) {
- done();
- }
- };
-
- if (force || !this.audioDisabled_) {
- removesRemaining++;
- this.sourceUpdater_.removeAudio(start, end, removeFinished);
- } // While it would be better to only remove video if the main loader has video, this
- // should be safe with audio only as removeVideo will call back even if there's no
- // video buffer.
- //
- // In theory we can check to see if there's video before calling the remove, but in
- // the event that we're switching between renditions and from video to audio only
- // (when we add support for that), we may need to clear the video contents despite
- // what the new media will contain.
-
-
- if (force || this.loaderType_ === 'main') {
- this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
- removesRemaining++;
- this.sourceUpdater_.removeVideo(start, end, removeFinished);
- } // remove any captions and ID3 tags
-
-
- for (var track in this.inbandTextTracks_) {
- removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
-
- removeFinished();
- }
- /**
- * (re-)schedule monitorBufferTick_ to run as soon as possible
- *
- * @private
- */
- ;
-
- _proto.monitorBuffer_ = function monitorBuffer_() {
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window__default['default'].setTimeout(this.monitorBufferTick_.bind(this), 1);
- }
- /**
- * As long as the SegmentLoader is in the READY state, periodically
- * invoke fillBuffer_().
- *
- * @private
- */
- ;
-
- _proto.monitorBufferTick_ = function monitorBufferTick_() {
- if (this.state === 'READY') {
- this.fillBuffer_();
- }
-
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window__default['default'].setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
- }
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- ;
-
- _proto.fillBuffer_ = function fillBuffer_() {
- // TODO since the source buffer maintains a queue, and we shouldn't call this function
- // except when we're ready for the next segment, this check can most likely be removed
- if (this.sourceUpdater_.updating()) {
- return;
- } // see if we need to begin loading immediately
-
-
- var segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- this.isPendingTimestampOffset_ = false;
- this.timelineChangeController_.pendingTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
-
- this.loadSegment_(segmentInfo);
- }
- /**
- * Determines if we should call endOfStream on the media source based
- * on the state of the buffer or if appened segment was the final
- * segment in the playlist.
- *
- * @param {number} [mediaIndex] the media index of segment we last appended
- * @param {Object} [playlist] a media playlist object
- * @return {boolean} do we need to call endOfStream on the MediaSource
- */
- ;
-
- _proto.isEndOfStream_ = function isEndOfStream_(mediaIndex, playlist, partIndex) {
- if (mediaIndex === void 0) {
- mediaIndex = this.mediaIndex;
- }
-
- if (playlist === void 0) {
- playlist = this.playlist_;
- }
-
- if (partIndex === void 0) {
- partIndex = this.partIndex;
- }
-
- if (!playlist || !this.mediaSource_) {
- return false;
- }
-
- var segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
-
- var appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
-
- var appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endOfStream
- // so that MediaSources can trigger the `ended` event when it runs out of
- // buffered data instead of waiting for me
-
- return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
- }
- /**
- * Determines what request should be made given current segment loader state.
- *
- * @return {Object} a request object that describes the segment/part to load
- */
- ;
-
- _proto.chooseNextRequest_ = function chooseNextRequest_() {
- var bufferedEnd = lastBufferedEnd(this.buffered_()) || 0;
- var bufferedTime = Math.max(0, bufferedEnd - this.currentTime_());
- var preloaded = !this.hasPlayed_() && bufferedTime >= 1;
- var haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
- var segments = this.playlist_.segments; // return no segment if:
- // 1. we don't have segments
- // 2. The video has not yet played and we already downloaded a segment
- // 3. we already have enough buffered time
-
- if (!segments.length || preloaded || haveEnoughBuffer) {
- return null;
- }
-
- this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
- var next = {
- partIndex: null,
- mediaIndex: null,
- startOfSegment: null,
- playlist: this.playlist_,
- isSyncRequest: Boolean(!this.syncPoint_)
- };
-
- if (next.isSyncRequest) {
- next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
- } else if (this.mediaIndex !== null) {
- var segment = segments[this.mediaIndex];
- var partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
- next.startOfSegment = segment.end ? segment.end : bufferedEnd;
-
- if (segment.parts && segment.parts[partIndex + 1]) {
- next.mediaIndex = this.mediaIndex;
- next.partIndex = partIndex + 1;
- } else {
- next.mediaIndex = this.mediaIndex + 1;
- }
- } else {
- // Find the segment containing the end of the buffer or current time.
- var _Playlist$getMediaInf = Playlist.getMediaInfoForTime({
- playlist: this.playlist_,
- currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
- startingPartIndex: this.syncPoint_.partIndex,
- startingSegmentIndex: this.syncPoint_.segmentIndex,
- startTime: this.syncPoint_.time
- }),
- segmentIndex = _Playlist$getMediaInf.segmentIndex,
- startTime = _Playlist$getMediaInf.startTime,
- _partIndex = _Playlist$getMediaInf.partIndex;
-
- next.getMediaInfoForTime = this.fetchAtBuffer_ ? 'bufferedEnd' : 'currentTime';
- next.mediaIndex = segmentIndex;
- next.startOfSegment = startTime;
- next.partIndex = _partIndex;
- }
-
- var nextSegment = segments[next.mediaIndex];
- var nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
- // the next partIndex is invalid do not choose a next segment.
-
- if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
- return null;
- } // if the next segment has parts, and we don't have a partIndex.
- // Set partIndex to 0
-
-
- if (typeof next.partIndex !== 'number' && nextSegment.parts) {
- next.partIndex = 0;
- }
-
- var ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
- // 1. this is the last segment in the playlist
- // 2. end of stream has been called on the media source already
- // 3. the player is not seeking
-
- if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
- return null;
- }
-
- return this.generateSegmentInfo_(next);
- };
-
- _proto.generateSegmentInfo_ = function generateSegmentInfo_(options) {
- var playlist = options.playlist,
- mediaIndex = options.mediaIndex,
- startOfSegment = options.startOfSegment,
- isSyncRequest = options.isSyncRequest,
- partIndex = options.partIndex,
- forceTimestampOffset = options.forceTimestampOffset,
- getMediaInfoForTime = options.getMediaInfoForTime;
- var segment = playlist.segments[mediaIndex];
- var part = typeof partIndex === 'number' && segment.parts[partIndex];
- var segmentInfo = {
- requestId: 'segment-loader-' + Math.random(),
- // resolve the segment URL relative to the playlist
- uri: part && part.resolvedUri || segment.resolvedUri,
- // the segment's mediaIndex at the time it was requested
- mediaIndex: mediaIndex,
- partIndex: part ? partIndex : null,
- // whether or not to update the SegmentLoader's state with this
- // segment's mediaIndex
- isSyncRequest: isSyncRequest,
- startOfSegment: startOfSegment,
- // the segment's playlist
- playlist: playlist,
- // unencrypted bytes of the segment
- bytes: null,
- // when a key is defined for this segment, the encrypted bytes
- encryptedBytes: null,
- // The target timestampOffset for this segment when we append it
- // to the source buffer
- timestampOffset: null,
- // The timeline that the segment is in
- timeline: segment.timeline,
- // The expected duration of the segment in seconds
- duration: part && part.duration || segment.duration,
- // retain the segment in case the playlist updates while doing an async process
- segment: segment,
- part: part,
- byteLength: 0,
- transmuxer: this.transmuxer_,
- // type of getMediaInfoForTime that was used to get this segment
- getMediaInfoForTime: getMediaInfoForTime
- };
- var overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
- segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
- segmentTimeline: segment.timeline,
- currentTimeline: this.currentTimeline_,
- startOfSegment: startOfSegment,
- buffered: this.buffered_(),
- overrideCheck: overrideCheck
- });
- var audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
-
- if (typeof audioBufferedEnd === 'number') {
- // since the transmuxer is using the actual timing values, but the buffer is
- // adjusted by the timestamp offset, we must adjust the value here
- segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
- }
-
- if (this.sourceUpdater_.videoBuffered().length) {
- segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
- // adjusted by the timestmap offset, we must adjust the value here
- this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
- }
-
- return segmentInfo;
- } // get the timestampoffset for a segment,
- // added so that vtt segment loader can override and prevent
- // adding timestamp offsets.
- ;
-
- _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_(options) {
- return timestampOffsetForSegment(options);
- }
- /**
- * Determines if the network has enough bandwidth to complete the current segment
- * request in a timely manner. If not, the request will be aborted early and bandwidth
- * updated to trigger a playlist switch.
- *
- * @param {Object} stats
- * Object containing stats about the request timing and size
- * @private
- */
- ;
-
- _proto.earlyAbortWhenNeeded_ = function earlyAbortWhenNeeded_(stats) {
- if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
- // TODO: Replace using timeout with a boolean indicating whether this playlist is
- // the lowestEnabledRendition.
- !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
- !this.playlist_.attributes.BANDWIDTH) {
- return;
- } // Wait at least 1 second since the first byte of data has been received before
- // using the calculated bandwidth from the progress event to allow the bitrate
- // to stabilize
-
-
- if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
- return;
- }
-
- var currentTime = this.currentTime_();
- var measuredBandwidth = stats.bandwidth;
- var segmentDuration = this.pendingSegment_.duration;
- var requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
- // if we are only left with less than 1 second when the request completes.
- // A negative timeUntilRebuffering indicates we are already rebuffering
-
- var timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
- // is larger than the estimated time until the player runs out of forward buffer
-
- if (requestTimeRemaining <= timeUntilRebuffer$1) {
- return;
- }
-
- var switchCandidate = minRebufferMaxBandwidthSelector({
- master: this.vhs_.playlists.master,
- currentTime: currentTime,
- bandwidth: measuredBandwidth,
- duration: this.duration_(),
- segmentDuration: segmentDuration,
- timeUntilRebuffer: timeUntilRebuffer$1,
- currentTimeline: this.currentTimeline_,
- syncController: this.syncController_
- });
-
- if (!switchCandidate) {
- return;
- }
-
- var rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
- var timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
- var minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
- // potential round trip time of the new request so that we are not too aggressive
- // with switching to a playlist that might save us a fraction of a second.
-
- if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
- minimumTimeSaving = 1;
- }
-
- if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
- return;
- } // set the bandwidth to that of the desired playlist being sure to scale by
- // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
- // don't trigger a bandwidthupdate as the bandwidth is artifial
-
-
- this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
- this.trigger('earlyabort');
- };
-
- _proto.handleAbort_ = function handleAbort_(segmentInfo) {
- this.logger_("Aborting " + segmentInfoString(segmentInfo));
- this.mediaRequestsAborted += 1;
- }
- /**
- * XHR `progress` event handler
- *
- * @param {Event}
- * The XHR `progress` event
- * @param {Object} simpleSegment
- * A simplified segment object copy
- * @private
- */
- ;
-
- _proto.handleProgress_ = function handleProgress_(event, simpleSegment) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- this.trigger('progress');
- };
-
- _proto.handleTrackInfo_ = function handleTrackInfo_(simpleSegment, trackInfo) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- if (this.checkForIllegalMediaSwitch(trackInfo)) {
- return;
- }
-
- trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
- // Guard against cases where we're not getting track info at all until we are
- // certain that all streams will provide it.
-
- if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.startingMediaInfo_ = trackInfo;
- this.currentMediaInfo_ = trackInfo;
- this.logger_('trackinfo update', trackInfo);
- this.trigger('trackinfo');
- } // trackinfo may cause an abort if the trackinfo
- // causes a codec change to an unsupported codec.
-
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // set trackinfo on the pending segment so that
- // it can append.
-
-
- this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
-
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- };
-
- _proto.handleTimingInfo_ = function handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- var segmentInfo = this.pendingSegment_;
- var timingInfoProperty = timingInfoPropertyForMedia(mediaType);
- segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
- segmentInfo[timingInfoProperty][timeType] = time;
- this.logger_("timinginfo: " + mediaType + " - " + timeType + " - " + time); // check if any calls were waiting on the timing info
-
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- };
-
- _proto.handleCaptions_ = function handleCaptions_(simpleSegment, captionData) {
- var _this2 = this;
-
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // This could only happen with fmp4 segments, but
- // should still not happen in general
-
-
- if (captionData.length === 0) {
- this.logger_('SegmentLoader received no captions from a caption event');
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
- // can be adjusted by the timestamp offset
-
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
- return;
- }
-
- var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
- var captionTracks = {}; // get total start/end and captions for each track/stream
-
- captionData.forEach(function (caption) {
- // caption.stream is actually a track name...
- // set to the existing values in tracks or default values
- captionTracks[caption.stream] = captionTracks[caption.stream] || {
- // Infinity, as any other value will be less than this
- startTime: Infinity,
- captions: [],
- // 0 as an other value will be more than this
- endTime: 0
- };
- var captionTrack = captionTracks[caption.stream];
- captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
- captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
- captionTrack.captions.push(caption);
- });
- Object.keys(captionTracks).forEach(function (trackName) {
- var _captionTracks$trackN = captionTracks[trackName],
- startTime = _captionTracks$trackN.startTime,
- endTime = _captionTracks$trackN.endTime,
- captions = _captionTracks$trackN.captions;
- var inbandTextTracks = _this2.inbandTextTracks_;
-
- _this2.logger_("adding cues from " + startTime + " -> " + endTime + " for " + trackName);
-
- createCaptionsTrackIfNotExists(inbandTextTracks, _this2.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
- // We do this because a rendition change that also changes the timescale for captions
- // will result in captions being re-parsed for certain segments. If we add them again
- // without clearing we will have two of the same captions visible.
-
- removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
- addCaptionData({
- captionArray: captions,
- inbandTextTracks: inbandTextTracks,
- timestampOffset: timestampOffset
- });
- }); // Reset stored captions since we added parsed
- // captions to a text track at this point
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- };
-
- _proto.handleId3_ = function handleId3_(simpleSegment, id3Frames, dispatchType) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
-
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
- return;
- }
-
- var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
- // audio/video source with a metadata track, and an alt audio with a metadata track.
- // However, this probably won't happen, and if it does it can be handled then.
-
- createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
- addMetadata({
- inbandTextTracks: this.inbandTextTracks_,
- metadataArray: id3Frames,
- timestampOffset: timestampOffset,
- videoDuration: this.duration_()
- });
- };
-
- _proto.processMetadataQueue_ = function processMetadataQueue_() {
- this.metadataQueue_.id3.forEach(function (fn) {
- return fn();
- });
- this.metadataQueue_.caption.forEach(function (fn) {
- return fn();
- });
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- };
-
- _proto.processCallQueue_ = function processCallQueue_() {
- var callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
-
- this.callQueue_ = [];
- callQueue.forEach(function (fun) {
- return fun();
- });
- };
-
- _proto.processLoadQueue_ = function processLoadQueue_() {
- var loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
-
- this.loadQueue_ = [];
- loadQueue.forEach(function (fun) {
- return fun();
- });
- }
- /**
- * Determines whether the loader has enough info to load the next segment.
- *
- * @return {boolean}
- * Whether or not the loader has enough info to load the next segment
- */
- ;
-
- _proto.hasEnoughInfoToLoad_ = function hasEnoughInfoToLoad_() {
- // Since primary timing goes by video, only the audio loader potentially needs to wait
- // to load.
- if (this.loaderType_ !== 'audio') {
- return true;
- }
-
- var segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
- // enough info to load.
-
- if (!segmentInfo) {
- return false;
- } // The first segment can and should be loaded immediately so that source buffers are
- // created together (before appending). Source buffer creation uses the presence of
- // audio and video data to determine whether to create audio/video source buffers, and
- // uses processed (transmuxed or parsed) media to determine the types required.
-
-
- if (!this.currentMediaInfo_) {
- return true;
- }
-
- if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
- // can be requested and downloaded and only wait before it is transmuxed or parsed.
- // But in practice, there are a few reasons why it is better to wait until a loader
- // is ready to append that segment before requesting and downloading:
- //
- // 1. Because audio and main loaders cross discontinuities together, if this loader
- // is waiting for the other to catch up, then instead of requesting another
- // segment and using up more bandwidth, by not yet loading, more bandwidth is
- // allotted to the loader currently behind.
- // 2. media-segment-request doesn't have to have logic to consider whether a segment
- // is ready to be processed or not, isolating the queueing behavior to the loader.
- // 3. The audio loader bases some of its segment properties on timing information
- // provided by the main loader, meaning that, if the logic for waiting on
- // processing was in media-segment-request, then it would also need to know how
- // to re-generate the segment information after the main loader caught up.
- shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })) {
- return false;
- }
-
- return true;
- };
-
- _proto.hasEnoughInfoToAppend_ = function hasEnoughInfoToAppend_() {
- if (!this.sourceUpdater_.ready()) {
- return false;
- } // If content needs to be removed or the loader is waiting on an append reattempt,
- // then no additional content should be appended until the prior append is resolved.
-
-
- if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
- return false;
- }
-
- var segmentInfo = this.pendingSegment_; // no segment to append any data for or
- // we do not have information on this specific
- // segment yet
-
- if (!segmentInfo || !segmentInfo.trackInfo) {
- return false;
- }
-
- var _this$currentMediaInf = this.currentMediaInfo_,
- hasAudio = _this$currentMediaInf.hasAudio,
- hasVideo = _this$currentMediaInf.hasVideo,
- isMuxed = _this$currentMediaInf.isMuxed;
-
- if (hasVideo && !segmentInfo.videoTimingInfo) {
- return false;
- } // muxed content only relies on video timing information for now.
-
-
- if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
- return false;
- }
-
- if (shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })) {
- return false;
- }
-
- return true;
- };
-
- _proto.handleData_ = function handleData_(simpleSegment, result) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // If there's anything in the call queue, then this data came later and should be
- // executed after the calls currently queued.
-
-
- if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
- this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
-
- this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
-
- this.updateMediaSecondsLoaded_(segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
- // logic may change behavior depending on the state, and changing state too early may
- // inflate our estimates of bandwidth. In the future this should be re-examined to
- // note more granular states.
- // don't process and append data if the mediaSource is closed
-
- if (this.mediaSource_.readyState === 'closed') {
- return;
- } // if this request included an initialization segment, save that data
- // to the initSegment cache
-
-
- if (simpleSegment.map) {
- simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
-
- segmentInfo.segment.map = simpleSegment.map;
- } // if this request included a segment key, save that data in the cache
-
-
- if (simpleSegment.key) {
- this.segmentKey(simpleSegment.key, true);
- }
-
- segmentInfo.isFmp4 = simpleSegment.isFmp4;
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
-
- if (segmentInfo.isFmp4) {
- this.trigger('fmp4');
- segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
- } else {
- var useVideoTimingInfo = this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- var firstVideoFrameTimeForData;
-
- if (useVideoTimingInfo) {
- firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
- } // Segment loader knows more about segment timing than the transmuxer (in certain
- // aspects), so make any changes required for a more accurate start time.
- // Don't set the end time yet, as the segment may not be finished processing.
-
-
- segmentInfo.timingInfo.start = this.trueSegmentStart_({
- currentStart: segmentInfo.timingInfo.start,
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex,
- currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
- useVideoTimingInfo: useVideoTimingInfo,
- firstVideoFrameTimeForData: firstVideoFrameTimeForData,
- videoTimingInfo: segmentInfo.videoTimingInfo,
- audioTimingInfo: segmentInfo.audioTimingInfo
- });
- } // Init segments for audio and video only need to be appended in certain cases. Now
- // that data is about to be appended, we can check the final cases to determine
- // whether we should append an init segment.
-
-
- this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
- // as we use the start of the segment to offset the best guess (playlist provided)
- // timestamp offset.
-
- this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
- // be appended or not.
-
- if (segmentInfo.isSyncRequest) {
- // first save/update our timing info for this segment.
- // this is what allows us to choose an accurate segment
- // and the main reason we make a sync request.
- this.updateTimingInfoEnd_(segmentInfo);
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo: segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
- var next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
- // after taking into account its timing info, do not append it.
-
- if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
- this.logger_('sync segment was incorrect, not appending');
- return;
- } // otherwise append it like any other segment as our guess was correct.
-
-
- this.logger_('sync segment was correct, appending');
- } // Save some state so that in the future anything waiting on first append (and/or
- // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
- // we need some notion of whether the timestamp offset or other relevant information
- // has had a chance to be set.
-
-
- segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
-
- this.processMetadataQueue_();
- this.appendData_(segmentInfo, result);
- };
-
- _proto.updateAppendInitSegmentStatus = function updateAppendInitSegmentStatus(segmentInfo, type) {
- // alt audio doesn't manage timestamp offset
- if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' && // in the case that we're handling partial data, we don't want to append an init
- // segment for each chunk
- !segmentInfo.changedTimestampOffset) {
- // if the timestamp offset changed, the timeline may have changed, so we have to re-
- // append init segments
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- }
-
- if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
- // make sure we append init segment on playlist changes, in case the media config
- // changed
- this.appendInitSegment_[type] = true;
- }
- };
-
- _proto.getInitSegmentAndUpdateState_ = function getInitSegmentAndUpdateState_(_ref4) {
- var type = _ref4.type,
- initSegment = _ref4.initSegment,
- map = _ref4.map,
- playlist = _ref4.playlist;
-
- // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
- // (Section 3) required to parse the applicable Media Segments. It applies to every
- // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
- // or until the end of the playlist."
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
- if (map) {
- var id = initSegmentId(map);
-
- if (this.activeInitSegmentId_ === id) {
- // don't need to re-append the init segment if the ID matches
- return null;
- } // a map-specified init segment takes priority over any transmuxed (or otherwise
- // obtained) init segment
- //
- // this also caches the init segment for later use
-
-
- initSegment = this.initSegmentForMap(map, true).bytes;
- this.activeInitSegmentId_ = id;
- } // We used to always prepend init segments for video, however, that shouldn't be
- // necessary. Instead, we should only append on changes, similar to what we've always
- // done for audio. This is more important (though may not be that important) for
- // frame-by-frame appending for LHLS, simply because of the increased quantity of
- // appends.
-
-
- if (initSegment && this.appendInitSegment_[type]) {
- // Make sure we track the playlist that we last used for the init segment, so that
- // we can re-append the init segment in the event that we get data from a new
- // playlist. Discontinuities and track changes are handled in other sections.
- this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
-
- this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
- // we are appending the muxer init segment
-
- this.activeInitSegmentId_ = null;
- return initSegment;
- }
-
- return null;
- };
-
- _proto.handleQuotaExceededError_ = function handleQuotaExceededError_(_ref5, error) {
- var _this3 = this;
-
- var segmentInfo = _ref5.segmentInfo,
- type = _ref5.type,
- bytes = _ref5.bytes;
- var audioBuffered = this.sourceUpdater_.audioBuffered();
- var videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
- // should be cleared out during the buffer removals. However, log in case it helps
- // debug.
-
- if (audioBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
- }
-
- if (videoBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
- }
-
- var audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
- var audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
- var videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
- var videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
-
- if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
- // Can't remove enough buffer to make room for new segment (or the browser doesn't
- // allow for appends of segments this size). In the future, it may be possible to
- // split up the segment and append in pieces, but for now, error out this playlist
- // in an attempt to switch to a more manageable rendition.
- this.logger_('On QUOTA_EXCEEDED_ERR, single segment too large to append to ' + 'buffer, triggering an error. ' + ("Appended byte length: " + bytes.byteLength + ", ") + ("audio buffer: " + timeRangesToArray(audioBuffered).join(', ') + ", ") + ("video buffer: " + timeRangesToArray(videoBuffered).join(', ') + ", "));
- this.error({
- message: 'Quota exceeded error with append of a single segment of content',
- excludeUntil: Infinity
- });
- this.trigger('error');
- return;
- } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
- // that the segment-loader should block on future events until this one is handled, so
- // that it doesn't keep moving onto further segments. Adding the call to the call
- // queue will prevent further appends until waitingOnRemove_ and
- // quotaExceededErrorRetryTimeout_ are cleared.
- //
- // Note that this will only block the current loader. In the case of demuxed content,
- // the other load may keep filling as fast as possible. In practice, this should be
- // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
- // source buffer, or video fills without enough room for audio to append (and without
- // the availability of clearing out seconds of back buffer to make room for audio).
- // But it might still be good to handle this case in the future as a TODO.
-
-
- this.waitingOnRemove_ = true;
- this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }));
- var currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
- // before retrying.
-
- var timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
- this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to " + timeToRemoveUntil);
- this.remove(0, timeToRemoveUntil, function () {
- _this3.logger_("On QUOTA_EXCEEDED_ERR, retrying append in " + MIN_BACK_BUFFER + "s");
-
- _this3.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
- // attempts (since we can't clear less than the minimum)
-
- _this3.quotaExceededErrorRetryTimeout_ = window__default['default'].setTimeout(function () {
- _this3.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
-
- _this3.quotaExceededErrorRetryTimeout_ = null;
-
- _this3.processCallQueue_();
- }, MIN_BACK_BUFFER * 1000);
- }, true);
- };
-
- _proto.handleAppendError_ = function handleAppendError_(_ref6, error) {
- var segmentInfo = _ref6.segmentInfo,
- type = _ref6.type,
- bytes = _ref6.bytes;
-
- // if there's no error, nothing to do
- if (!error) {
- return;
- }
-
- if (error.code === QUOTA_EXCEEDED_ERR) {
- this.handleQuotaExceededError_({
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }); // A quota exceeded error should be recoverable with a future re-append, so no need
- // to trigger an append error.
-
- return;
- }
-
- this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
- this.error(type + " append of " + bytes.length + "b failed for segment " + ("#" + segmentInfo.mediaIndex + " in playlist " + segmentInfo.playlist.id)); // If an append errors, we often can't recover.
- // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
- //
- // Trigger a special error so that it can be handled separately from normal,
- // recoverable errors.
-
- this.trigger('appenderror');
- };
-
- _proto.appendToSourceBuffer_ = function appendToSourceBuffer_(_ref7) {
- var segmentInfo = _ref7.segmentInfo,
- type = _ref7.type,
- initSegment = _ref7.initSegment,
- data = _ref7.data,
- bytes = _ref7.bytes;
-
- // If this is a re-append, bytes were already created and don't need to be recreated
- if (!bytes) {
- var segments = [data];
- var byteLength = data.byteLength;
-
- if (initSegment) {
- // if the media initialization segment is changing, append it before the content
- // segment
- segments.unshift(initSegment);
- byteLength += initSegment.byteLength;
- } // Technically we should be OK appending the init segment separately, however, we
- // haven't yet tested that, and prepending is how we have always done things.
-
-
- bytes = concatSegments({
- bytes: byteLength,
- segments: segments
- });
- }
-
- this.sourceUpdater_.appendBuffer({
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }, this.handleAppendError_.bind(this, {
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }));
- };
-
- _proto.handleSegmentTimingInfo_ = function handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
- if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
- return;
- }
-
- var segment = this.pendingSegment_.segment;
- var timingInfoProperty = type + "TimingInfo";
-
- if (!segment[timingInfoProperty]) {
- segment[timingInfoProperty] = {};
- }
-
- segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
- segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
- segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
- segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
- segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
-
- segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
- };
-
- _proto.appendData_ = function appendData_(segmentInfo, result) {
- var type = result.type,
- data = result.data;
-
- if (!data || !data.byteLength) {
- return;
- }
-
- if (type === 'audio' && this.audioDisabled_) {
- return;
- }
-
- var initSegment = this.getInitSegmentAndUpdateState_({
- type: type,
- initSegment: result.initSegment,
- playlist: segmentInfo.playlist,
- map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
- });
- this.appendToSourceBuffer_({
- segmentInfo: segmentInfo,
- type: type,
- initSegment: initSegment,
- data: data
- });
- }
- /**
- * load a specific segment from a request into the buffer
- *
- * @private
- */
- ;
-
- _proto.loadSegment_ = function loadSegment_(segmentInfo) {
- var _this4 = this;
-
- this.state = 'WAITING';
- this.pendingSegment_ = segmentInfo;
- this.trimBackBuffer_(segmentInfo);
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
-
- if (!this.hasEnoughInfoToLoad_()) {
- this.loadQueue_.push(function () {
- // regenerate the audioAppendStart, timestampOffset, etc as they
- // may have changed since this function was added to the queue.
- var options = _extends_1({}, segmentInfo, {
- forceTimestampOffset: true
- });
-
- _extends_1(segmentInfo, _this4.generateSegmentInfo_(options));
-
- _this4.isPendingTimestampOffset_ = false;
-
- _this4.updateTransmuxerAndRequestSegment_(segmentInfo);
- });
- return;
- }
-
- this.updateTransmuxerAndRequestSegment_(segmentInfo);
- };
-
- _proto.updateTransmuxerAndRequestSegment_ = function updateTransmuxerAndRequestSegment_(segmentInfo) {
- var _this5 = this;
-
- // We'll update the source buffer's timestamp offset once we have transmuxed data, but
- // the transmuxer still needs to be updated before then.
- //
- // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
- // offset must be passed to the transmuxer for stream correcting adjustments.
- if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
- this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
-
- segmentInfo.gopsToAlignWith = [];
- this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
-
- this.transmuxer_.postMessage({
- action: 'reset'
- });
- this.transmuxer_.postMessage({
- action: 'setTimestampOffset',
- timestampOffset: segmentInfo.timestampOffset
- });
- }
-
- var simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
- var isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
- var isWalkingForward = this.mediaIndex !== null;
- var isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
- // the first timeline
- segmentInfo.timeline > 0;
- var isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
- this.logger_("Requesting " + segmentInfoString(segmentInfo)); // If there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),
- // then this init segment has never been seen before and should be appended.
- //
- // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
- // both to true and leave the decision of whether to append the init segment to append time.
-
- if (simpleSegment.map && !simpleSegment.map.bytes) {
- this.logger_('going to request init segment.');
- this.appendInitSegment_ = {
- video: true,
- audio: true
- };
- }
-
- segmentInfo.abortRequests = mediaSegmentRequest({
- xhr: this.vhs_.xhr,
- xhrOptions: this.xhrOptions_,
- decryptionWorker: this.decrypter_,
- segment: simpleSegment,
- abortFn: this.handleAbort_.bind(this, segmentInfo),
- progressFn: this.handleProgress_.bind(this),
- trackInfoFn: this.handleTrackInfo_.bind(this),
- timingInfoFn: this.handleTimingInfo_.bind(this),
- videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
- audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
- captionsFn: this.handleCaptions_.bind(this),
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: function endedTimelineFn() {
- _this5.logger_('received endedtimeline callback');
- },
- id3Fn: this.handleId3_.bind(this),
- dataFn: this.handleData_.bind(this),
- doneFn: this.segmentRequestFinished_.bind(this)
- });
- }
- /**
- * trim the back buffer so that we don't have too much data
- * in the source buffer
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- */
- ;
-
- _proto.trimBackBuffer_ = function trimBackBuffer_(segmentInfo) {
- var removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
- // buffer and a very conservative "garbage collector"
- // We manually clear out the old buffer to ensure
- // we don't trigger the QuotaExceeded error
- // on the source buffer during subsequent appends
-
- if (removeToTime > 0) {
- this.remove(0, removeToTime);
- }
- }
- /**
- * created a simplified copy of the segment object with just the
- * information necessary to perform the XHR and decryption
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- * @return {Object} a simplified segment object copy
- */
- ;
-
- _proto.createSimplifiedSegmentObj_ = function createSimplifiedSegmentObj_(segmentInfo) {
- var segment = segmentInfo.segment;
- var part = segmentInfo.part;
- var simpleSegment = {
- resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
- byterange: part ? part.byterange : segment.byterange,
- requestId: segmentInfo.requestId,
- transmuxer: segmentInfo.transmuxer,
- audioAppendStart: segmentInfo.audioAppendStart,
- gopsToAlignWith: segmentInfo.gopsToAlignWith,
- part: segmentInfo.part
- };
- var previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
-
- if (previousSegment && previousSegment.timeline === segment.timeline) {
- // The baseStartTime of a segment is used to handle rollover when probing the TS
- // segment to retrieve timing information. Since the probe only looks at the media's
- // times (e.g., PTS and DTS values of the segment), and doesn't consider the
- // player's time (e.g., player.currentTime()), baseStartTime should reflect the
- // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
- // seconds of media time, so should be used here. The previous segment is used since
- // the end of the previous segment should represent the beginning of the current
- // segment, so long as they are on the same timeline.
- if (previousSegment.videoTimingInfo) {
- simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
- } else if (previousSegment.audioTimingInfo) {
- simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
- }
- }
-
- if (segment.key) {
- // if the media sequence is greater than 2^32, the IV will be incorrect
- // assuming 10s segments, that would be about 1300 years
- var iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
- simpleSegment.key = this.segmentKey(segment.key);
- simpleSegment.key.iv = iv;
- }
-
- if (segment.map) {
- simpleSegment.map = this.initSegmentForMap(segment.map);
- }
-
- return simpleSegment;
- };
-
- _proto.saveTransferStats_ = function saveTransferStats_(stats) {
- // every request counts as a media request even if it has been aborted
- // or canceled due to a timeout
- this.mediaRequests += 1;
-
- if (stats) {
- this.mediaBytesTransferred += stats.bytesReceived;
- this.mediaTransferDuration += stats.roundTripTime;
- }
- };
-
- _proto.saveBandwidthRelatedStats_ = function saveBandwidthRelatedStats_(duration, stats) {
- // byteLength will be used for throughput, and should be based on bytes receieved,
- // which we only know at the end of the request and should reflect total bytes
- // downloaded rather than just bytes processed from components of the segment
- this.pendingSegment_.byteLength = stats.bytesReceived;
-
- if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_("Ignoring segment's bandwidth because its duration of " + duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
- return;
- }
-
- this.bandwidth = stats.bandwidth;
- this.roundTrip = stats.roundTripTime;
- };
-
- _proto.handleTimeout_ = function handleTimeout_() {
- // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functinality between segment loaders
- this.mediaRequestsTimedout += 1;
- this.bandwidth = 1;
- this.roundTrip = NaN;
- this.trigger('bandwidthupdate');
- }
- /**
- * Handle the callback from the segmentRequest function and set the
- * associated SegmentLoader state and errors if necessary
- *
- * @private
- */
- ;
-
- _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
- // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
- // check the call queue directly since this function doesn't need to deal with any
- // data, and can continue even if the source buffers are not set up and we didn't get
- // any data from the segment
- if (this.callQueue_.length) {
- this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
-
- if (!this.pendingSegment_) {
- return;
- } // the request was aborted and the SegmentLoader has already started
- // another request. this can happen when the timeout for an aborted
- // request triggers due to a limitation in the XHR library
- // do not count this as any sort of request or we risk double-counting
-
-
- if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
- return;
- } // an error occurred from the active pendingSegment_ so reset everything
-
-
- if (error) {
- this.pendingSegment_ = null;
- this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
-
- if (error.code === REQUEST_ERRORS.ABORTED) {
- return;
- }
-
- this.pause(); // the error is really just that at least one of the requests timed-out
- // set the bandwidth to a very low value and trigger an ABR switch to
- // take emergency action
-
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- return;
- } // if control-flow has arrived here, then the error is real
- // emit an error event to blacklist the current playlist
-
-
- this.mediaRequestsErrored += 1;
- this.error(error);
- this.trigger('error');
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
- // generated for ABR purposes
-
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
- segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
-
- if (result.gopInfo) {
- this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
- } // Although we may have already started appending on progress, we shouldn't switch the
- // state away from loading until we are officially done loading the segment data.
-
-
- this.state = 'APPENDING'; // used for testing
-
- this.trigger('appending');
- this.waitForAppendsToComplete_(segmentInfo);
- };
-
- _proto.setTimeMapping_ = function setTimeMapping_(timeline) {
- var timelineMapping = this.syncController_.mappingForTimeline(timeline);
-
- if (timelineMapping !== null) {
- this.timeMapping_ = timelineMapping;
- }
- };
-
- _proto.updateMediaSecondsLoaded_ = function updateMediaSecondsLoaded_(segment) {
- if (typeof segment.start === 'number' && typeof segment.end === 'number') {
- this.mediaSecondsLoaded += segment.end - segment.start;
- } else {
- this.mediaSecondsLoaded += segment.duration;
- }
- };
-
- _proto.shouldUpdateTransmuxerTimestampOffset_ = function shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
- if (timestampOffset === null) {
- return false;
- } // note that we're potentially using the same timestamp offset for both video and
- // audio
-
-
- if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- return true;
- }
-
- if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- return true;
- }
-
- return false;
- };
-
- _proto.trueSegmentStart_ = function trueSegmentStart_(_ref8) {
- var currentStart = _ref8.currentStart,
- playlist = _ref8.playlist,
- mediaIndex = _ref8.mediaIndex,
- firstVideoFrameTimeForData = _ref8.firstVideoFrameTimeForData,
- currentVideoTimestampOffset = _ref8.currentVideoTimestampOffset,
- useVideoTimingInfo = _ref8.useVideoTimingInfo,
- videoTimingInfo = _ref8.videoTimingInfo,
- audioTimingInfo = _ref8.audioTimingInfo;
-
- if (typeof currentStart !== 'undefined') {
- // if start was set once, keep using it
- return currentStart;
- }
-
- if (!useVideoTimingInfo) {
- return audioTimingInfo.start;
- }
-
- var previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
- // within that segment. Since the transmuxer maintains a cache of incomplete data
- // from and/or the last frame seen, the start time may reflect a frame that starts
- // in the previous segment. Check for that case and ensure the start time is
- // accurate for the segment.
-
- if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
- return firstVideoFrameTimeForData;
- }
-
- return videoTimingInfo.start;
- };
-
- _proto.waitForAppendsToComplete_ = function waitForAppendsToComplete_(segmentInfo) {
- if (!this.currentMediaInfo_) {
- this.error({
- message: 'No starting media returned, likely due to an unsupported media format.',
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return;
- } // Although transmuxing is done, appends may not yet be finished. Throw a marker
- // on each queue this loader is responsible for to ensure that the appends are
- // complete.
-
-
- var _this$currentMediaInf2 = this.currentMediaInfo_,
- hasAudio = _this$currentMediaInf2.hasAudio,
- hasVideo = _this$currentMediaInf2.hasVideo,
- isMuxed = _this$currentMediaInf2.isMuxed;
- var waitForVideo = this.loaderType_ === 'main' && hasVideo;
- var waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
- segmentInfo.waitingOnAppends = 0; // segments with no data
-
- if (!segmentInfo.hasAppendedData_) {
- if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
- // When there's no audio or video data in the segment, there's no audio or video
- // timing information.
- //
- // If there's no audio or video timing information, then the timestamp offset
- // can't be adjusted to the appropriate value for the transmuxer and source
- // buffers.
- //
- // Therefore, the next segment should be used to set the timestamp offset.
- this.isPendingTimestampOffset_ = true;
- } // override settings for metadata only segments
-
-
- segmentInfo.timingInfo = {
- start: 0
- };
- segmentInfo.waitingOnAppends++;
-
- if (!this.isPendingTimestampOffset_) {
- // update the timestampoffset
- this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
- // no video/audio data.
-
- this.processMetadataQueue_();
- } // append is "done" instantly with no data.
-
-
- this.checkAppendsDone_(segmentInfo);
- return;
- } // Since source updater could call back synchronously, do the increments first.
-
-
- if (waitForVideo) {
- segmentInfo.waitingOnAppends++;
- }
-
- if (waitForAudio) {
- segmentInfo.waitingOnAppends++;
- }
-
- if (waitForVideo) {
- this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
-
- if (waitForAudio) {
- this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
- };
-
- _proto.checkAppendsDone_ = function checkAppendsDone_(segmentInfo) {
- if (this.checkForAbort_(segmentInfo.requestId)) {
- return;
- }
-
- segmentInfo.waitingOnAppends--;
-
- if (segmentInfo.waitingOnAppends === 0) {
- this.handleAppendsDone_();
- }
- };
-
- _proto.checkForIllegalMediaSwitch = function checkForIllegalMediaSwitch(trackInfo) {
- var illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.currentMediaInfo_, trackInfo);
-
- if (illegalMediaSwitchError) {
- this.error({
- message: illegalMediaSwitchError,
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return true;
- }
-
- return false;
- };
-
- _proto.updateSourceBufferTimestampOffset_ = function updateSourceBufferTimestampOffset_(segmentInfo) {
- if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
- // priority, timing-wise, so we must wait
- typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
- segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
- this.loaderType_ !== 'main') {
- return;
- }
-
- var didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
- // the timing info here comes from video. In the event that the audio is longer than
- // the video, this will trim the start of the audio.
- // This also trims any offset from 0 at the beginning of the media
-
- segmentInfo.timestampOffset -= segmentInfo.timingInfo.start; // In the event that there are part segment downloads, each will try to update the
- // timestamp offset. Retaining this bit of state prevents us from updating in the
- // future (within the same segment), however, there may be a better way to handle it.
-
- segmentInfo.changedTimestampOffset = true;
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (didChange) {
- this.trigger('timestampoffset');
- }
- };
-
- _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_(segmentInfo) {
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
- var useVideoTimingInfo = this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- var prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
-
- if (!prioritizedTimingInfo) {
- return;
- }
-
- segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
- // current example is the case of fmp4), so use the rough duration to calculate an
- // end time.
- prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
- }
- /**
- * callback to run when appendBuffer is finished. detects if we are
- * in a good state to do things with the data we got, or if we need
- * to wait for more
- *
- * @private
- */
- ;
-
- _proto.handleAppendsDone_ = function handleAppendsDone_() {
- // appendsdone can cause an abort
- if (this.pendingSegment_) {
- this.trigger('appendsdone');
- }
-
- if (!this.pendingSegment_) {
- this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
- // all appending cases?
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
-
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
- // best to wait until all appends are done so we're sure that the primary media is
- // finished (and we have its end time).
-
- this.updateTimingInfoEnd_(segmentInfo);
-
- if (this.shouldSaveSegmentTimingInfo_) {
- // Timeline mappings should only be saved for the main loader. This is for multiple
- // reasons:
- //
- // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
- // and the main loader try to save the timeline mapping, whichever comes later
- // will overwrite the first. In theory this is OK, as the mappings should be the
- // same, however, it breaks for (2)
- // 2) In the event of a live stream, the initial live point will make for a somewhat
- // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
- // the mapping will be off for one of the streams, dependent on which one was
- // first saved (see (1)).
- // 3) Primary timing goes by video in VHS, so the mapping should be video.
- //
- // Since the audio loader will wait for the main loader to load the first segment,
- // the main loader will save the first timeline mapping, and ensure that there won't
- // be a case where audio loads two segments without saving a mapping (thus leading
- // to missing segment timing info).
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo: segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
- }
-
- var segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
-
- if (segmentDurationMessage) {
- if (segmentDurationMessage.severity === 'warn') {
- videojs__default['default'].log.warn(segmentDurationMessage.message);
- } else {
- this.logger_(segmentDurationMessage.message);
- }
- }
-
- this.recordThroughput_(segmentInfo);
- this.pendingSegment_ = null;
- this.state = 'READY';
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate'); // if the sync request was not appended
- // then it was not the correct segment.
- // throw it away and use the data it gave us
- // to get the correct one.
-
- if (!segmentInfo.hasAppendedData_) {
- this.logger_("Throwing away un-appended sync request " + segmentInfoString(segmentInfo));
- return;
- }
- }
-
- this.logger_("Appended " + segmentInfoString(segmentInfo));
- this.addSegmentMetadataCue_(segmentInfo);
- this.fetchAtBuffer_ = true;
-
- if (this.currentTimeline_ !== segmentInfo.timeline) {
- this.timelineChangeController_.lastTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- }); // If audio is not disabled, the main segment loader is responsible for updating
- // the audio timeline as well. If the content is video only, this won't have any
- // impact.
-
- if (this.loaderType_ === 'main' && !this.audioDisabled_) {
- this.timelineChangeController_.lastTimelineChange({
- type: 'audio',
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
- }
-
- this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
- // the following conditional otherwise it may consider this a bad "guess"
- // and attempt to resync when the post-update seekable window and live
- // point would mean that this was the perfect segment to fetch
-
- this.trigger('syncinfoupdate');
- var segment = segmentInfo.segment; // If we previously appended a segment that ends more than 3 targetDurations before
- // the currentTime_ that means that our conservative guess was too conservative.
- // In that case, reset the loader state so that we try to use any information gained
- // from the previous request to create a new, more accurate, sync-point.
-
- if (segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3) {
- this.resetEverything();
- return;
- }
-
- var isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
- // and conservatively guess
-
- if (isWalkingForward) {
- this.trigger('bandwidthupdate');
- }
-
- this.trigger('progress');
- this.mediaIndex = segmentInfo.mediaIndex;
- this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
- // buffer, end the stream. this ensures the "ended" event will
- // fire if playback reaches that point.
-
- if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
- this.endOfStream();
- } // used for testing
-
-
- this.trigger('appended');
-
- if (segmentInfo.hasAppendedData_) {
- this.mediaAppends++;
- }
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
- /**
- * Records the current throughput of the decrypt, transmux, and append
- * portion of the semgment pipeline. `throughput.rate` is a the cumulative
- * moving average of the throughput. `throughput.count` is the number of
- * data points in the average.
- *
- * @private
- * @param {Object} segmentInfo the object returned by loadSegment
- */
- ;
-
- _proto.recordThroughput_ = function recordThroughput_(segmentInfo) {
- if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_("Ignoring segment's throughput because its duration of " + segmentInfo.duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
- return;
- }
-
- var rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
- // by zero in the case where the throughput is ridiculously high
-
- var segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
-
- var segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
- // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
-
- this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
- }
- /**
- * Adds a cue to the segment-metadata track with some metadata information about the
- * segment
- *
- * @private
- * @param {Object} segmentInfo
- * the object returned by loadSegment
- * @method addSegmentMetadataCue_
- */
- ;
-
- _proto.addSegmentMetadataCue_ = function addSegmentMetadataCue_(segmentInfo) {
- if (!this.segmentMetadataTrack_) {
- return;
- }
-
- var segment = segmentInfo.segment;
- var start = segment.start;
- var end = segment.end; // Do not try adding the cue if the start and end times are invalid.
-
- if (!finite(start) || !finite(end)) {
- return;
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
- var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
- var value = {
- custom: segment.custom,
- dateTimeObject: segment.dateTimeObject,
- dateTimeString: segment.dateTimeString,
- bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
- resolution: segmentInfo.playlist.attributes.RESOLUTION,
- codecs: segmentInfo.playlist.attributes.CODECS,
- byteLength: segmentInfo.byteLength,
- uri: segmentInfo.uri,
- timeline: segmentInfo.timeline,
- playlist: segmentInfo.playlist.id,
- start: start,
- end: end
- };
- var data = JSON.stringify(value);
- var cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
- // the differences of WebKitDataCue in safari and VTTCue in other browsers
-
- cue.value = value;
- this.segmentMetadataTrack_.addCue(cue);
- };
-
- return SegmentLoader;
- }(videojs__default['default'].EventTarget);
-
- function noop() {}
-
- var toTitleCase = function toTitleCase(string) {
- if (typeof string !== 'string') {
- return string;
- }
-
- return string.replace(/./, function (w) {
- return w.toUpperCase();
- });
- };
-
- var bufferTypes = ['video', 'audio'];
-
- var _updating = function updating(type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
- };
-
- var nextQueueIndexOfType = function nextQueueIndexOfType(type, queue) {
- for (var i = 0; i < queue.length; i++) {
- var queueEntry = queue[i];
-
- if (queueEntry.type === 'mediaSource') {
- // If the next entry is a media source entry (uses multiple source buffers), block
- // processing to allow it to go through first.
- return null;
- }
-
- if (queueEntry.type === type) {
- return i;
- }
- }
-
- return null;
- };
-
- var shiftQueue = function shiftQueue(type, sourceUpdater) {
- if (sourceUpdater.queue.length === 0) {
- return;
- }
-
- var queueIndex = 0;
- var queueEntry = sourceUpdater.queue[queueIndex];
-
- if (queueEntry.type === 'mediaSource') {
- if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
- sourceUpdater.queue.shift();
- queueEntry.action(sourceUpdater);
-
- if (queueEntry.doneFn) {
- queueEntry.doneFn();
- } // Only specific source buffer actions must wait for async updateend events. Media
- // Source actions process synchronously. Therefore, both audio and video source
- // buffers are now clear to process the next queue entries.
-
-
- shiftQueue('audio', sourceUpdater);
- shiftQueue('video', sourceUpdater);
- } // Media Source actions require both source buffers, so if the media source action
- // couldn't process yet (because one or both source buffers are busy), block other
- // queue actions until both are available and the media source action can process.
-
-
- return;
- }
-
- if (type === 'mediaSource') {
- // If the queue was shifted by a media source action (this happens when pushing a
- // media source action onto the queue), then it wasn't from an updateend event from an
- // audio or video source buffer, so there's no change from previous state, and no
- // processing should be done.
- return;
- } // Media source queue entries don't need to consider whether the source updater is
- // started (i.e., source buffers are created) as they don't need the source buffers, but
- // source buffer queue entries do.
-
-
- if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || _updating(type, sourceUpdater)) {
- return;
- }
-
- if (queueEntry.type !== type) {
- queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
-
- if (queueIndex === null) {
- // Either there's no queue entry that uses this source buffer type in the queue, or
- // there's a media source queue entry before the next entry of this type, in which
- // case wait for that action to process first.
- return;
- }
-
- queueEntry = sourceUpdater.queue[queueIndex];
- }
-
- sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
- //
- // The queue pending operation must be set before the action is performed in the event
- // that the action results in a synchronous event that is acted upon. For instance, if
- // an exception is thrown that can be handled, it's possible that new actions will be
- // appended to an empty queue and immediately executed, but would not have the correct
- // pending information if this property was set after the action was performed.
-
- sourceUpdater.queuePending[type] = queueEntry;
- queueEntry.action(type, sourceUpdater);
-
- if (!queueEntry.doneFn) {
- // synchronous operation, process next entry
- sourceUpdater.queuePending[type] = null;
- shiftQueue(type, sourceUpdater);
- return;
- }
- };
-
- var cleanupBuffer = function cleanupBuffer(type, sourceUpdater) {
- var buffer = sourceUpdater[type + "Buffer"];
- var titleType = toTitleCase(type);
-
- if (!buffer) {
- return;
- }
-
- buffer.removeEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
- buffer.removeEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
- sourceUpdater.codecs[type] = null;
- sourceUpdater[type + "Buffer"] = null;
- };
-
- var inSourceBuffers = function inSourceBuffers(mediaSource, sourceBuffer) {
- return mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
- };
-
- var actions = {
- appendBuffer: function appendBuffer(bytes, segmentInfo, onError) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Appending segment " + segmentInfo.mediaIndex + "'s " + bytes.length + " bytes to " + type + "Buffer");
-
- try {
- sourceBuffer.appendBuffer(bytes);
- } catch (e) {
- sourceUpdater.logger_("Error with code " + e.code + " " + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + ("when appending segment " + segmentInfo.mediaIndex + " to " + type + "Buffer"));
- sourceUpdater.queuePending[type] = null;
- onError(e);
- }
- };
- },
- remove: function remove(start, end) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Removing " + start + " to " + end + " from " + type + "Buffer");
-
- try {
- sourceBuffer.remove(start, end);
- } catch (e) {
- sourceUpdater.logger_("Remove " + start + " to " + end + " from " + type + "Buffer failed");
- }
- };
- },
- timestampOffset: function timestampOffset(offset) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Setting " + type + "timestampOffset to " + offset);
- sourceBuffer.timestampOffset = offset;
- };
- },
- callback: function callback(_callback) {
- return function (type, sourceUpdater) {
- _callback();
- };
- },
- endOfStream: function endOfStream(error) {
- return function (sourceUpdater) {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
-
- sourceUpdater.logger_("Calling mediaSource endOfStream(" + (error || '') + ")");
-
- try {
- sourceUpdater.mediaSource.endOfStream(error);
- } catch (e) {
- videojs__default['default'].log.warn('Failed to call media source endOfStream', e);
- }
- };
- },
- duration: function duration(_duration) {
- return function (sourceUpdater) {
- sourceUpdater.logger_("Setting mediaSource duration to " + _duration);
-
- try {
- sourceUpdater.mediaSource.duration = _duration;
- } catch (e) {
- videojs__default['default'].log.warn('Failed to set media source duration', e);
- }
- };
- },
- abort: function abort() {
- return function (type, sourceUpdater) {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
-
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("calling abort on " + type + "Buffer");
-
- try {
- sourceBuffer.abort();
- } catch (e) {
- videojs__default['default'].log.warn("Failed to abort on " + type + "Buffer", e);
- }
- };
- },
- addSourceBuffer: function addSourceBuffer(type, codec) {
- return function (sourceUpdater) {
- var titleType = toTitleCase(type);
- var mime = getMimeForCodec(codec);
- sourceUpdater.logger_("Adding " + type + "Buffer with codec " + codec + " to mediaSource");
- var sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
- sourceBuffer.addEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
- sourceBuffer.addEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
- sourceUpdater.codecs[type] = codec;
- sourceUpdater[type + "Buffer"] = sourceBuffer;
- };
- },
- removeSourceBuffer: function removeSourceBuffer(type) {
- return function (sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Removing " + type + "Buffer with codec " + sourceUpdater.codecs[type] + " from mediaSource");
-
- try {
- sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
- } catch (e) {
- videojs__default['default'].log.warn("Failed to removeSourceBuffer " + type + "Buffer", e);
- }
- };
- },
- changeType: function changeType(codec) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- var mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- } // do not update codec if we don't need to.
-
-
- if (sourceUpdater.codecs[type] === codec) {
- return;
- }
-
- sourceUpdater.logger_("changing " + type + "Buffer codec from " + sourceUpdater.codecs[type] + " to " + codec);
- sourceBuffer.changeType(mime);
- sourceUpdater.codecs[type] = codec;
- };
- }
- };
-
- var pushQueue = function pushQueue(_ref) {
- var type = _ref.type,
- sourceUpdater = _ref.sourceUpdater,
- action = _ref.action,
- doneFn = _ref.doneFn,
- name = _ref.name;
- sourceUpdater.queue.push({
- type: type,
- action: action,
- doneFn: doneFn,
- name: name
- });
- shiftQueue(type, sourceUpdater);
- };
-
- var onUpdateend = function onUpdateend(type, sourceUpdater) {
- return function (e) {
- // Although there should, in theory, be a pending action for any updateend receieved,
- // there are some actions that may trigger updateend events without set definitions in
- // the w3c spec. For instance, setting the duration on the media source may trigger
- // updateend events on source buffers. This does not appear to be in the spec. As such,
- // if we encounter an updateend without a corresponding pending action from our queue
- // for that source buffer type, process the next action.
- if (sourceUpdater.queuePending[type]) {
- var doneFn = sourceUpdater.queuePending[type].doneFn;
- sourceUpdater.queuePending[type] = null;
-
- if (doneFn) {
- // if there's an error, report it
- doneFn(sourceUpdater[type + "Error_"]);
- }
- }
-
- shiftQueue(type, sourceUpdater);
- };
- };
- /**
- * A queue of callbacks to be serialized and applied when a
- * MediaSource and its associated SourceBuffers are not in the
- * updating state. It is used by the segment loader to update the
- * underlying SourceBuffers when new data is loaded, for instance.
- *
- * @class SourceUpdater
- * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
- * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
- */
-
-
- var SourceUpdater = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(SourceUpdater, _videojs$EventTarget);
-
- function SourceUpdater(mediaSource) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- _this.mediaSource = mediaSource;
-
- _this.sourceopenListener_ = function () {
- return shiftQueue('mediaSource', assertThisInitialized(_this));
- };
-
- _this.mediaSource.addEventListener('sourceopen', _this.sourceopenListener_);
-
- _this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
-
- _this.audioTimestampOffset_ = 0;
- _this.videoTimestampOffset_ = 0;
- _this.queue = [];
- _this.queuePending = {
- audio: null,
- video: null
- };
- _this.delayedAudioAppendQueue_ = [];
- _this.videoAppendQueued_ = false;
- _this.codecs = {};
- _this.onVideoUpdateEnd_ = onUpdateend('video', assertThisInitialized(_this));
- _this.onAudioUpdateEnd_ = onUpdateend('audio', assertThisInitialized(_this));
-
- _this.onVideoError_ = function (e) {
- // used for debugging
- _this.videoError_ = e;
- };
-
- _this.onAudioError_ = function (e) {
- // used for debugging
- _this.audioError_ = e;
- };
-
- _this.createdSourceBuffers_ = false;
- _this.initializedEme_ = false;
- _this.triggeredReady_ = false;
- return _this;
- }
-
- var _proto = SourceUpdater.prototype;
-
- _proto.initializedEme = function initializedEme() {
- this.initializedEme_ = true;
- this.triggerReady();
- };
-
- _proto.hasCreatedSourceBuffers = function hasCreatedSourceBuffers() {
- // if false, likely waiting on one of the segment loaders to get enough data to create
- // source buffers
- return this.createdSourceBuffers_;
- };
-
- _proto.hasInitializedAnyEme = function hasInitializedAnyEme() {
- return this.initializedEme_;
- };
-
- _proto.ready = function ready() {
- return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
- };
-
- _proto.createSourceBuffers = function createSourceBuffers(codecs) {
- if (this.hasCreatedSourceBuffers()) {
- // already created them before
- return;
- } // the intial addOrChangeSourceBuffers will always be
- // two add buffers.
-
-
- this.addOrChangeSourceBuffers(codecs);
- this.createdSourceBuffers_ = true;
- this.trigger('createdsourcebuffers');
- this.triggerReady();
- };
-
- _proto.triggerReady = function triggerReady() {
- // only allow ready to be triggered once, this prevents the case
- // where:
- // 1. we trigger createdsourcebuffers
- // 2. ie 11 synchronously initializates eme
- // 3. the synchronous initialization causes us to trigger ready
- // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
- if (this.ready() && !this.triggeredReady_) {
- this.triggeredReady_ = true;
- this.trigger('ready');
- }
- }
- /**
- * Add a type of source buffer to the media source.
- *
- * @param {string} type
- * The type of source buffer to add.
- *
- * @param {string} codec
- * The codec to add the source buffer with.
- */
- ;
-
- _proto.addSourceBuffer = function addSourceBuffer(type, codec) {
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.addSourceBuffer(type, codec),
- name: 'addSourceBuffer'
- });
- }
- /**
- * call abort on a source buffer.
- *
- * @param {string} type
- * The type of source buffer to call abort on.
- */
- ;
-
- _proto.abort = function abort(type) {
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.abort(type),
- name: 'abort'
- });
- }
- /**
- * Call removeSourceBuffer and remove a specific type
- * of source buffer on the mediaSource.
- *
- * @param {string} type
- * The type of source buffer to remove.
- */
- ;
-
- _proto.removeSourceBuffer = function removeSourceBuffer(type) {
- if (!this.canRemoveSourceBuffer()) {
- videojs__default['default'].log.error('removeSourceBuffer is not supported!');
- return;
- }
-
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.removeSourceBuffer(type),
- name: 'removeSourceBuffer'
- });
- }
- /**
- * Whether or not the removeSourceBuffer function is supported
- * on the mediaSource.
- *
- * @return {boolean}
- * if removeSourceBuffer can be called.
- */
- ;
-
- _proto.canRemoveSourceBuffer = function canRemoveSourceBuffer() {
- // IE reports that it supports removeSourceBuffer, but often throws
- // errors when attempting to use the function. So we report that it
- // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
- // throws errors, so we report that it does not support this as well.
- return !videojs__default['default'].browser.IE_VERSION && !videojs__default['default'].browser.IS_FIREFOX && window__default['default'].MediaSource && window__default['default'].MediaSource.prototype && typeof window__default['default'].MediaSource.prototype.removeSourceBuffer === 'function';
- }
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- ;
-
- SourceUpdater.canChangeType = function canChangeType() {
- return window__default['default'].SourceBuffer && window__default['default'].SourceBuffer.prototype && typeof window__default['default'].SourceBuffer.prototype.changeType === 'function';
- }
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- ;
-
- _proto.canChangeType = function canChangeType() {
- return this.constructor.canChangeType();
- }
- /**
- * Call the changeType function on a source buffer, given the code and type.
- *
- * @param {string} type
- * The type of source buffer to call changeType on.
- *
- * @param {string} codec
- * The codec string to change type with on the source buffer.
- */
- ;
-
- _proto.changeType = function changeType(type, codec) {
- if (!this.canChangeType()) {
- videojs__default['default'].log.error('changeType is not supported!');
- return;
- }
-
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.changeType(codec),
- name: 'changeType'
- });
- }
- /**
- * Add source buffers with a codec or, if they are already created,
- * call changeType on source buffers using changeType.
- *
- * @param {Object} codecs
- * Codecs to switch to
- */
- ;
-
- _proto.addOrChangeSourceBuffers = function addOrChangeSourceBuffers(codecs) {
- var _this2 = this;
-
- if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
- throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
- }
-
- Object.keys(codecs).forEach(function (type) {
- var codec = codecs[type];
-
- if (!_this2.hasCreatedSourceBuffers()) {
- return _this2.addSourceBuffer(type, codec);
- }
-
- if (_this2.canChangeType()) {
- _this2.changeType(type, codec);
- }
- });
- }
- /**
- * Queue an update to append an ArrayBuffer.
- *
- * @param {MediaObject} object containing audioBytes and/or videoBytes
- * @param {Function} done the function to call when done
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
- */
- ;
-
- _proto.appendBuffer = function appendBuffer(options, doneFn) {
- var _this3 = this;
-
- var segmentInfo = options.segmentInfo,
- type = options.type,
- bytes = options.bytes;
- this.processedAppend_ = true;
-
- if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
- this.delayedAudioAppendQueue_.push([options, doneFn]);
- this.logger_("delayed audio append of " + bytes.length + " until video append");
- return;
- } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
- // not be fired. This means that the queue will be blocked until the next action
- // taken by the segment-loader. Provide a mechanism for segment-loader to handle
- // these errors by calling the doneFn with the specific error.
-
-
- var onError = doneFn;
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.appendBuffer(bytes, segmentInfo || {
- mediaIndex: -1
- }, onError),
- doneFn: doneFn,
- name: 'appendBuffer'
- });
-
- if (type === 'video') {
- this.videoAppendQueued_ = true;
-
- if (!this.delayedAudioAppendQueue_.length) {
- return;
- }
-
- var queue = this.delayedAudioAppendQueue_.slice();
- this.logger_("queuing delayed audio " + queue.length + " appendBuffers");
- this.delayedAudioAppendQueue_.length = 0;
- queue.forEach(function (que) {
- _this3.appendBuffer.apply(_this3, que);
- });
- }
- }
- /**
- * Get the audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The audio buffer's buffered time range
- */
- ;
-
- _proto.audioBuffered = function audioBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
- return videojs__default['default'].createTimeRange();
- }
-
- return this.audioBuffer.buffered ? this.audioBuffer.buffered : videojs__default['default'].createTimeRange();
- }
- /**
- * Get the video buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The video buffer's buffered time range
- */
- ;
-
- _proto.videoBuffered = function videoBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
- return videojs__default['default'].createTimeRange();
- }
-
- return this.videoBuffer.buffered ? this.videoBuffer.buffered : videojs__default['default'].createTimeRange();
- }
- /**
- * Get a combined video/audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * the combined time range
- */
- ;
-
- _proto.buffered = function buffered() {
- var video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
- var audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
-
- if (audio && !video) {
- return this.audioBuffered();
- }
-
- if (video && !audio) {
- return this.videoBuffered();
- }
-
- return bufferIntersection(this.audioBuffered(), this.videoBuffered());
- }
- /**
- * Add a callback to the queue that will set duration on the mediaSource.
- *
- * @param {number} duration
- * The duration to set
- *
- * @param {Function} [doneFn]
- * function to run after duration has been set.
- */
- ;
-
- _proto.setDuration = function setDuration(duration, doneFn) {
- if (doneFn === void 0) {
- doneFn = noop;
- }
-
- // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.duration(duration),
- name: 'duration',
- doneFn: doneFn
- });
- }
- /**
- * Add a mediaSource endOfStream call to the queue
- *
- * @param {Error} [error]
- * Call endOfStream with an error
- *
- * @param {Function} [doneFn]
- * A function that should be called when the
- * endOfStream call has finished.
- */
- ;
-
- _proto.endOfStream = function endOfStream(error, doneFn) {
- if (error === void 0) {
- error = null;
- }
-
- if (doneFn === void 0) {
- doneFn = noop;
- }
-
- if (typeof error !== 'string') {
- error = undefined;
- } // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
-
-
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.endOfStream(error),
- name: 'endOfStream',
- doneFn: doneFn
- });
- }
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- ;
-
- _proto.removeAudio = function removeAudio(start, end, done) {
- if (done === void 0) {
- done = noop;
- }
-
- if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- ;
-
- _proto.removeVideo = function removeVideo(start, end, done) {
- if (done === void 0) {
- done = noop;
- }
-
- if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
- /**
- * Whether the underlying sourceBuffer is updating or not
- *
- * @return {boolean} the updating status of the SourceBuffer
- */
- ;
-
- _proto.updating = function updating() {
- // the audio/video source buffer is updating
- if (_updating('audio', this) || _updating('video', this)) {
- return true;
- }
-
- return false;
- }
- /**
- * Set/get the timestampoffset on the audio SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- ;
-
- _proto.audioTimestampOffset = function audioTimestampOffset(offset) {
- if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
- this.audioTimestampOffset_ !== offset) {
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.audioTimestampOffset_ = offset;
- }
-
- return this.audioTimestampOffset_;
- }
- /**
- * Set/get the timestampoffset on the video SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- ;
-
- _proto.videoTimestampOffset = function videoTimestampOffset(offset) {
- if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
- this.videoTimestampOffset !== offset) {
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.videoTimestampOffset_ = offset;
- }
-
- return this.videoTimestampOffset_;
- }
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the audio queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- ;
-
- _proto.audioQueueCallback = function audioQueueCallback(callback) {
- if (!this.audioBuffer) {
- return;
- }
-
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the video queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- ;
-
- _proto.videoQueueCallback = function videoQueueCallback(callback) {
- if (!this.videoBuffer) {
- return;
- }
-
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
- /**
- * dispose of the source updater and the underlying sourceBuffer
- */
- ;
-
- _proto.dispose = function dispose() {
- var _this4 = this;
-
- this.trigger('dispose');
- bufferTypes.forEach(function (type) {
- _this4.abort(type);
-
- if (_this4.canRemoveSourceBuffer()) {
- _this4.removeSourceBuffer(type);
- } else {
- _this4[type + "QueueCallback"](function () {
- return cleanupBuffer(type, _this4);
- });
- }
- });
- this.videoAppendQueued_ = false;
- this.delayedAudioAppendQueue_.length = 0;
-
- if (this.sourceopenListener_) {
- this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
- }
-
- this.off();
- };
-
- return SourceUpdater;
- }(videojs__default['default'].EventTarget);
-
- var uint8ToUtf8 = function uint8ToUtf8(uintArray) {
- return decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
- };
-
- var VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(function (char) {
- return char.charCodeAt(0);
- }));
- /**
- * An object that manages segment loading and appending.
- *
- * @class VTTSegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-
- var VTTSegmentLoader = /*#__PURE__*/function (_SegmentLoader) {
- inheritsLoose(VTTSegmentLoader, _SegmentLoader);
-
- function VTTSegmentLoader(settings, options) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _SegmentLoader.call(this, settings, options) || this; // SegmentLoader requires a MediaSource be specified or it will throw an error;
- // however, VTTSegmentLoader has no need of a media source, so delete the reference
-
- _this.mediaSource_ = null;
- _this.subtitlesTrack_ = null;
- _this.loaderType_ = 'subtitle';
- _this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
- // the sync controller leads to improper behavior.
-
- _this.shouldSaveSegmentTimingInfo_ = false;
- return _this;
- }
-
- var _proto = VTTSegmentLoader.prototype;
-
- _proto.createTransmuxer_ = function createTransmuxer_() {
- // don't need to transmux any subtitles
- return null;
- }
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- ;
-
- _proto.buffered_ = function buffered_() {
- if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
- return videojs__default['default'].createTimeRanges();
- }
-
- var cues = this.subtitlesTrack_.cues;
- var start = cues[0].startTime;
- var end = cues[cues.length - 1].startTime;
- return videojs__default['default'].createTimeRanges([[start, end]]);
- }
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- ;
-
- _proto.initSegmentForMap = function initSegmentForMap(map, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!map) {
- return null;
- }
-
- var id = initSegmentId(map);
- var storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- // append WebVTT line terminators to the media initialization segment if it exists
- // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
- // requires two or more WebVTT line terminators between the WebVTT header and the
- // rest of the file
- var combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
- var combinedSegment = new Uint8Array(combinedByteLength);
- combinedSegment.set(map.bytes);
- combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: combinedSegment
- };
- }
-
- return storedMap || map;
- }
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- ;
-
- _proto.couldBeginLoading_ = function couldBeginLoading_() {
- return this.playlist_ && this.subtitlesTrack_ && !this.paused();
- }
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- ;
-
- _proto.init_ = function init_() {
- this.state = 'READY';
- this.resetEverything();
- return this.monitorBuffer_();
- }
- /**
- * Set a subtitle track on the segment loader to add subtitles to
- *
- * @param {TextTrack=} track
- * The text track to add loaded subtitles to
- * @return {TextTrack}
- * Returns the subtitles track
- */
- ;
-
- _proto.track = function track(_track) {
- if (typeof _track === 'undefined') {
- return this.subtitlesTrack_;
- }
-
- this.subtitlesTrack_ = _track; // if we were unpaused but waiting for a sourceUpdater, start
- // buffering now
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- this.init_();
- }
-
- return this.subtitlesTrack_;
- }
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- */
- ;
-
- _proto.remove = function remove(start, end) {
- removeCuesFromTrack(start, end, this.subtitlesTrack_);
- }
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- ;
-
- _proto.fillBuffer_ = function fillBuffer_() {
- var _this2 = this;
-
- // see if we need to begin loading immediately
- var segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
- // We don't have the timestamp offset that we need to sync subtitles.
- // Rerun on a timestamp offset or user interaction.
- var checkTimestampOffset = function checkTimestampOffset() {
- _this2.state = 'READY';
-
- if (!_this2.paused()) {
- // if not paused, queue a buffer check as soon as possible
- _this2.monitorBuffer_();
- }
- };
-
- this.syncController_.one('timestampoffset', checkTimestampOffset);
- this.state = 'WAITING_ON_TIMELINE';
- return;
- }
-
- this.loadSegment_(segmentInfo);
- } // never set a timestamp offset for vtt segments.
- ;
-
- _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_() {
- return null;
- };
-
- _proto.chooseNextRequest_ = function chooseNextRequest_() {
- return this.skipEmptySegments_(_SegmentLoader.prototype.chooseNextRequest_.call(this));
- }
- /**
- * Prevents the segment loader from requesting segments we know contain no subtitles
- * by walking forward until we find the next segment that we don't know whether it is
- * empty or not.
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @return {Object}
- * a segment info object that describes the current segment
- */
- ;
-
- _proto.skipEmptySegments_ = function skipEmptySegments_(segmentInfo) {
- while (segmentInfo && segmentInfo.segment.empty) {
- // stop at the last possible segmentInfo
- if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
- segmentInfo = null;
- break;
- }
-
- segmentInfo = this.generateSegmentInfo_({
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex + 1,
- startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
- isSyncRequest: segmentInfo.isSyncRequest
- });
- }
-
- return segmentInfo;
- };
-
- _proto.stopForError = function stopForError(error) {
- this.error(error);
- this.state = 'READY';
- this.pause();
- this.trigger('error');
- }
- /**
- * append a decrypted segement to the SourceBuffer through a SourceUpdater
- *
- * @private
- */
- ;
-
- _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
- var _this3 = this;
-
- if (!this.subtitlesTrack_) {
- this.state = 'READY';
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats); // the request was aborted
-
- if (!this.pendingSegment_) {
- this.state = 'READY';
- this.mediaRequestsAborted += 1;
- return;
- }
-
- if (error) {
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- }
-
- if (error.code === REQUEST_ERRORS.ABORTED) {
- this.mediaRequestsAborted += 1;
- } else {
- this.mediaRequestsErrored += 1;
- }
-
- this.stopForError(error);
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functionality between segment loaders
-
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
- this.state = 'APPENDING'; // used for tests
-
- this.trigger('appending');
- var segment = segmentInfo.segment;
-
- if (segment.map) {
- segment.map.bytes = simpleSegment.map.bytes;
- }
-
- segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, wait till it finished loading
-
- if (typeof window__default['default'].WebVTT !== 'function' && this.subtitlesTrack_ && this.subtitlesTrack_.tech_) {
- var loadHandler;
-
- var errorHandler = function errorHandler() {
- _this3.subtitlesTrack_.tech_.off('vttjsloaded', loadHandler);
-
- _this3.stopForError({
- message: 'Error loading vtt.js'
- });
-
- return;
- };
-
- loadHandler = function loadHandler() {
- _this3.subtitlesTrack_.tech_.off('vttjserror', errorHandler);
-
- _this3.segmentRequestFinished_(error, simpleSegment, result);
- };
-
- this.state = 'WAITING_ON_VTTJS';
- this.subtitlesTrack_.tech_.one('vttjsloaded', loadHandler);
- this.subtitlesTrack_.tech_.one('vttjserror', errorHandler);
- return;
- }
-
- segment.requested = true;
-
- try {
- this.parseVTTCues_(segmentInfo);
- } catch (e) {
- this.stopForError({
- message: e.message
- });
- return;
- }
-
- this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
-
- if (segmentInfo.cues.length) {
- segmentInfo.timingInfo = {
- start: segmentInfo.cues[0].startTime,
- end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
- };
- } else {
- segmentInfo.timingInfo = {
- start: segmentInfo.startOfSegment,
- end: segmentInfo.startOfSegment + segmentInfo.duration
- };
- }
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate');
- this.pendingSegment_ = null;
- this.state = 'READY';
- return;
- }
-
- segmentInfo.byteLength = segmentInfo.bytes.byteLength;
- this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
- // the subtitle track
-
- segmentInfo.cues.forEach(function (cue) {
- _this3.subtitlesTrack_.addCue(_this3.featuresNativeTextTracks_ ? new window__default['default'].VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
- }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
- // cues to have identical time-intervals, but if the text is also identical
- // we can safely assume it is a duplicate that can be removed (ex. when a cue
- // "overlaps" VTT segments)
-
- removeDuplicateCuesFromTrack(this.subtitlesTrack_);
- this.handleAppendsDone_();
- };
-
- _proto.handleData_ = function handleData_() {// noop as we shouldn't be getting video/audio data captions
- // that we do not support here.
- };
-
- _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_() {// noop
- }
- /**
- * Uses the WebVTT parser to parse the segment response
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @private
- */
- ;
-
- _proto.parseVTTCues_ = function parseVTTCues_(segmentInfo) {
- var decoder;
- var decodeBytesToString = false;
-
- if (typeof window__default['default'].TextDecoder === 'function') {
- decoder = new window__default['default'].TextDecoder('utf8');
- } else {
- decoder = window__default['default'].WebVTT.StringDecoder();
- decodeBytesToString = true;
- }
-
- var parser = new window__default['default'].WebVTT.Parser(window__default['default'], window__default['default'].vttjs, decoder);
- segmentInfo.cues = [];
- segmentInfo.timestampmap = {
- MPEGTS: 0,
- LOCAL: 0
- };
- parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
-
- parser.ontimestampmap = function (map) {
- segmentInfo.timestampmap = map;
- };
-
- parser.onparsingerror = function (error) {
- videojs__default['default'].log.warn('Error encountered when parsing cues: ' + error.message);
- };
-
- if (segmentInfo.segment.map) {
- var mapData = segmentInfo.segment.map.bytes;
-
- if (decodeBytesToString) {
- mapData = uint8ToUtf8(mapData);
- }
-
- parser.parse(mapData);
- }
-
- var segmentData = segmentInfo.bytes;
-
- if (decodeBytesToString) {
- segmentData = uint8ToUtf8(segmentData);
- }
-
- parser.parse(segmentData);
- parser.flush();
- }
- /**
- * Updates the start and end times of any cues parsed by the WebVTT parser using
- * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
- * from the SyncController
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @param {Object} mappingObj
- * object containing a mapping from TS to media time
- * @param {Object} playlist
- * the playlist object containing the segment
- * @private
- */
- ;
-
- _proto.updateTimeMapping_ = function updateTimeMapping_(segmentInfo, mappingObj, playlist) {
- var segment = segmentInfo.segment;
-
- if (!mappingObj) {
- // If the sync controller does not have a mapping of TS to Media Time for the
- // timeline, then we don't have enough information to update the cue
- // start/end times
- return;
- }
-
- if (!segmentInfo.cues.length) {
- // If there are no cues, we also do not have enough information to figure out
- // segment timing. Mark that the segment contains no cues so we don't re-request
- // an empty segment.
- segment.empty = true;
- return;
- }
-
- var timestampmap = segmentInfo.timestampmap;
- var diff = timestampmap.MPEGTS / clock.ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
- segmentInfo.cues.forEach(function (cue) {
- // First convert cue time to TS time using the timestamp-map provided within the vtt
- cue.startTime += diff;
- cue.endTime += diff;
- });
-
- if (!playlist.syncInfo) {
- var firstStart = segmentInfo.cues[0].startTime;
- var lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
- playlist.syncInfo = {
- mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
- time: Math.min(firstStart, lastStart - segment.duration)
- };
- }
- };
-
- return VTTSegmentLoader;
- }(SegmentLoader);
-
- /**
- * @file ad-cue-tags.js
- */
- /**
- * Searches for an ad cue that overlaps with the given mediaTime
- *
- * @param {Object} track
- * the track to find the cue for
- *
- * @param {number} mediaTime
- * the time to find the cue at
- *
- * @return {Object|null}
- * the found cue or null
- */
-
- var findAdCue = function findAdCue(track, mediaTime) {
- var cues = track.cues;
-
- for (var i = 0; i < cues.length; i++) {
- var cue = cues[i];
-
- if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
- return cue;
- }
- }
-
- return null;
- };
- var updateAdCues = function updateAdCues(media, track, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- if (!media.segments) {
- return;
- }
-
- var mediaTime = offset;
- var cue;
-
- for (var i = 0; i < media.segments.length; i++) {
- var segment = media.segments[i];
-
- if (!cue) {
- // Since the cues will span for at least the segment duration, adding a fudge
- // factor of half segment duration will prevent duplicate cues from being
- // created when timing info is not exact (e.g. cue start time initialized
- // at 10.006677, but next call mediaTime is 10.003332 )
- cue = findAdCue(track, mediaTime + segment.duration / 2);
- }
-
- if (cue) {
- if ('cueIn' in segment) {
- // Found a CUE-IN so end the cue
- cue.endTime = mediaTime;
- cue.adEndTime = mediaTime;
- mediaTime += segment.duration;
- cue = null;
- continue;
- }
-
- if (mediaTime < cue.endTime) {
- // Already processed this mediaTime for this cue
- mediaTime += segment.duration;
- continue;
- } // otherwise extend cue until a CUE-IN is found
-
-
- cue.endTime += segment.duration;
- } else {
- if ('cueOut' in segment) {
- cue = new window__default['default'].VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
- cue.adStartTime = mediaTime; // Assumes tag format to be
- // #EXT-X-CUE-OUT:30
-
- cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
- track.addCue(cue);
- }
-
- if ('cueOutCont' in segment) {
- // Entered into the middle of an ad cue
- // Assumes tag formate to be
- // #EXT-X-CUE-OUT-CONT:10/30
- var _segment$cueOutCont$s = segment.cueOutCont.split('/').map(parseFloat),
- adOffset = _segment$cueOutCont$s[0],
- adTotal = _segment$cueOutCont$s[1];
-
- cue = new window__default['default'].VTTCue(mediaTime, mediaTime + segment.duration, '');
- cue.adStartTime = mediaTime - adOffset;
- cue.adEndTime = cue.adStartTime + adTotal;
- track.addCue(cue);
- }
- }
-
- mediaTime += segment.duration;
- }
- };
-
- var syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
- // the equivalence display-time 0 === segment-index 0
- {
- name: 'VOD',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (duration !== Infinity) {
- var syncPoint = {
- time: 0,
- segmentIndex: 0,
- partIndex: null
- };
- return syncPoint;
- }
-
- return null;
- }
- }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
- {
- name: 'ProgramDateTime',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
- return null;
- }
-
- var syncPoint = null;
- var lastDistance = null;
- var partsAndSegments = getPartsAndSegments(playlist);
- currentTime = currentTime || 0;
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
- var partAndSegment = partsAndSegments[index];
- var segment = partAndSegment.segment;
- var datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
-
- if (!datetimeMapping) {
- continue;
- }
-
- if (segment.dateTimeObject) {
- var segmentTime = segment.dateTimeObject.getTime() / 1000;
- var start = segmentTime + datetimeMapping; // take part duration into account.
-
- if (segment.parts && typeof partAndSegment.partIndex === 'number') {
- for (var z = 0; z < partAndSegment.partIndex; z++) {
- start += segment.parts[z].duration;
- }
- }
-
- var distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
- break;
- }
-
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
- }
-
- return syncPoint;
- }
- }, // Stategy "Segment": We have a known time mapping for a timeline and a
- // segment in the current timeline with timing data
- {
- name: 'Segment',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- var syncPoint = null;
- var lastDistance = null;
- currentTime = currentTime || 0;
- var partsAndSegments = getPartsAndSegments(playlist);
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
- var partAndSegment = partsAndSegments[index];
- var segment = partAndSegment.segment;
- var start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
-
- if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
- var distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
- }
- }
-
- return syncPoint;
- }
- }, // Stategy "Discontinuity": We have a discontinuity with a known
- // display-time
- {
- name: 'Discontinuity',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- var syncPoint = null;
- currentTime = currentTime || 0;
-
- if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- var lastDistance = null;
-
- for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
- var segmentIndex = playlist.discontinuityStarts[i];
- var discontinuity = playlist.discontinuitySequence + i + 1;
- var discontinuitySync = syncController.discontinuities[discontinuity];
-
- if (discontinuitySync) {
- var distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: discontinuitySync.time,
- segmentIndex: segmentIndex,
- partIndex: null
- };
- }
- }
- }
- }
-
- return syncPoint;
- }
- }, // Stategy "Playlist": We have a playlist with a known mapping of
- // segment index to display time
- {
- name: 'Playlist',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (playlist.syncInfo) {
- var syncPoint = {
- time: playlist.syncInfo.time,
- segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
- partIndex: null
- };
- return syncPoint;
- }
-
- return null;
- }
- }];
-
- var SyncController = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(SyncController, _videojs$EventTarget);
-
- function SyncController(options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this; // ...for synching across variants
-
- _this.timelines = [];
- _this.discontinuities = [];
- _this.timelineToDatetimeMappings = {};
- _this.logger_ = logger('SyncController');
- return _this;
- }
- /**
- * Find a sync-point for the playlist specified
- *
- * A sync-point is defined as a known mapping from display-time to
- * a segment-index in the current playlist.
- *
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinite if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Object}
- * A sync-point object
- */
-
-
- var _proto = SyncController.prototype;
-
- _proto.getSyncPoint = function getSyncPoint(playlist, duration, currentTimeline, currentTime) {
- var syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
-
- if (!syncPoints.length) {
- // Signal that we need to attempt to get a sync-point manually
- // by fetching a segment in the playlist and constructing
- // a sync-point from that information
- return null;
- } // Now find the sync-point that is closest to the currentTime because
- // that should result in the most accurate guess about which segment
- // to fetch
-
-
- return this.selectSyncPoint_(syncPoints, {
- key: 'time',
- value: currentTime
- });
- }
- /**
- * Calculate the amount of time that has expired off the playlist during playback
- *
- * @param {Playlist} playlist
- * Playlist object to calculate expired from
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playling a live source)
- * @return {number|null}
- * The amount of time that has expired off the playlist during playback. Null
- * if no sync-points for the playlist can be found.
- */
- ;
-
- _proto.getExpiredTime = function getExpiredTime(playlist, duration) {
- if (!playlist || !playlist.segments) {
- return null;
- }
-
- var syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
-
- if (!syncPoints.length) {
- return null;
- }
-
- var syncPoint = this.selectSyncPoint_(syncPoints, {
- key: 'segmentIndex',
- value: 0
- }); // If the sync-point is beyond the start of the playlist, we want to subtract the
- // duration from index 0 to syncPoint.segmentIndex instead of adding.
-
- if (syncPoint.segmentIndex > 0) {
- syncPoint.time *= -1;
- }
-
- return Math.abs(syncPoint.time + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: syncPoint.segmentIndex,
- endIndex: 0
- }));
- }
- /**
- * Runs each sync-point strategy and returns a list of sync-points returned by the
- * strategies
- *
- * @private
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Array}
- * A list of sync-point objects
- */
- ;
-
- _proto.runStrategies_ = function runStrategies_(playlist, duration, currentTimeline, currentTime) {
- var syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
-
- for (var i = 0; i < syncPointStrategies.length; i++) {
- var strategy = syncPointStrategies[i];
- var syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
-
- if (syncPoint) {
- syncPoint.strategy = strategy.name;
- syncPoints.push({
- strategy: strategy.name,
- syncPoint: syncPoint
- });
- }
- }
-
- return syncPoints;
- }
- /**
- * Selects the sync-point nearest the specified target
- *
- * @private
- * @param {Array} syncPoints
- * List of sync-points to select from
- * @param {Object} target
- * Object specifying the property and value we are targeting
- * @param {string} target.key
- * Specifies the property to target. Must be either 'time' or 'segmentIndex'
- * @param {number} target.value
- * The value to target for the specified key.
- * @return {Object}
- * The sync-point nearest the target
- */
- ;
-
- _proto.selectSyncPoint_ = function selectSyncPoint_(syncPoints, target) {
- var bestSyncPoint = syncPoints[0].syncPoint;
- var bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
- var bestStrategy = syncPoints[0].strategy;
-
- for (var i = 1; i < syncPoints.length; i++) {
- var newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
-
- if (newDistance < bestDistance) {
- bestDistance = newDistance;
- bestSyncPoint = syncPoints[i].syncPoint;
- bestStrategy = syncPoints[i].strategy;
- }
- }
-
- this.logger_("syncPoint for [" + target.key + ": " + target.value + "] chosen with strategy" + (" [" + bestStrategy + "]: [time:" + bestSyncPoint.time + ",") + (" segmentIndex:" + bestSyncPoint.segmentIndex) + (typeof bestSyncPoint.partIndex === 'number' ? ",partIndex:" + bestSyncPoint.partIndex : '') + ']');
- return bestSyncPoint;
- }
- /**
- * Save any meta-data present on the segments when segments leave
- * the live window to the playlist to allow for synchronization at the
- * playlist level later.
- *
- * @param {Playlist} oldPlaylist - The previous active playlist
- * @param {Playlist} newPlaylist - The updated and most current playlist
- */
- ;
-
- _proto.saveExpiredSegmentInfo = function saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
- var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // When a segment expires from the playlist and it has a start time
- // save that information as a possible sync-point reference in future
-
- for (var i = mediaSequenceDiff - 1; i >= 0; i--) {
- var lastRemovedSegment = oldPlaylist.segments[i];
-
- if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
- newPlaylist.syncInfo = {
- mediaSequence: oldPlaylist.mediaSequence + i,
- time: lastRemovedSegment.start
- };
- this.logger_("playlist refresh sync: [time:" + newPlaylist.syncInfo.time + "," + (" mediaSequence: " + newPlaylist.syncInfo.mediaSequence + "]"));
- this.trigger('syncinfoupdate');
- break;
- }
- }
- }
- /**
- * Save the mapping from playlist's ProgramDateTime to display. This should only happen
- * before segments start to load.
- *
- * @param {Playlist} playlist - The currently active playlist
- */
- ;
-
- _proto.setDateTimeMappingForStart = function setDateTimeMappingForStart(playlist) {
- // It's possible for the playlist to be updated before playback starts, meaning time
- // zero is not yet set. If, during these playlist refreshes, a discontinuity is
- // crossed, then the old time zero mapping (for the prior timeline) would be retained
- // unless the mappings are cleared.
- this.timelineToDatetimeMappings = {};
-
- if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
- var firstSegment = playlist.segments[0];
- var playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
- this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
- }
- }
- /**
- * Calculates and saves timeline mappings, playlist sync info, and segment timing values
- * based on the latest timing information.
- *
- * @param {Object} options
- * Options object
- * @param {SegmentInfo} options.segmentInfo
- * The current active request information
- * @param {boolean} options.shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved for timeline mapping and program date time mappings.
- */
- ;
-
- _proto.saveSegmentTimingInfo = function saveSegmentTimingInfo(_ref) {
- var segmentInfo = _ref.segmentInfo,
- shouldSaveTimelineMapping = _ref.shouldSaveTimelineMapping;
- var didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
- var segment = segmentInfo.segment;
-
- if (didCalculateSegmentTimeMapping) {
- this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
- // now with segment timing information
-
- if (!segmentInfo.playlist.syncInfo) {
- segmentInfo.playlist.syncInfo = {
- mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
- time: segment.start
- };
- }
- }
-
- var dateTime = segment.dateTimeObject;
-
- if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
- this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
- }
- };
-
- _proto.timestampOffsetForTimeline = function timestampOffsetForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
-
- return this.timelines[timeline].time;
- };
-
- _proto.mappingForTimeline = function mappingForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
-
- return this.timelines[timeline].mapping;
- }
- /**
- * Use the "media time" for a segment to generate a mapping to "display time" and
- * save that display time to the segment.
- *
- * @private
- * @param {SegmentInfo} segmentInfo
- * The current active request information
- * @param {Object} timingInfo
- * The start and end time of the current segment in "media time"
- * @param {boolean} shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved in timelines.
- * @return {boolean}
- * Returns false if segment time mapping could not be calculated
- */
- ;
-
- _proto.calculateSegmentTimeMapping_ = function calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
- // TODO: remove side effects
- var segment = segmentInfo.segment;
- var part = segmentInfo.part;
- var mappingObj = this.timelines[segmentInfo.timeline];
- var start;
- var end;
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- mappingObj = {
- time: segmentInfo.startOfSegment,
- mapping: segmentInfo.startOfSegment - timingInfo.start
- };
-
- if (shouldSaveTimelineMapping) {
- this.timelines[segmentInfo.timeline] = mappingObj;
- this.trigger('timestampoffset');
- this.logger_("time mapping for timeline " + segmentInfo.timeline + ": " + ("[time: " + mappingObj.time + "] [mapping: " + mappingObj.mapping + "]"));
- }
-
- start = segmentInfo.startOfSegment;
- end = timingInfo.end + mappingObj.mapping;
- } else if (mappingObj) {
- start = timingInfo.start + mappingObj.mapping;
- end = timingInfo.end + mappingObj.mapping;
- } else {
- return false;
- }
-
- if (part) {
- part.start = start;
- part.end = end;
- } // If we don't have a segment start yet or the start value we got
- // is less than our current segment.start value, save a new start value.
- // We have to do this because parts will have segment timing info saved
- // multiple times and we want segment start to be the earliest part start
- // value for that segment.
-
-
- if (!segment.start || start < segment.start) {
- segment.start = start;
- }
-
- segment.end = end;
- return true;
- }
- /**
- * Each time we have discontinuity in the playlist, attempt to calculate the location
- * in display of the start of the discontinuity and save that. We also save an accuracy
- * value so that we save values with the most accuracy (closest to 0.)
- *
- * @private
- * @param {SegmentInfo} segmentInfo - The current active request information
- */
- ;
-
- _proto.saveDiscontinuitySyncInfo_ = function saveDiscontinuitySyncInfo_(segmentInfo) {
- var playlist = segmentInfo.playlist;
- var segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
- // the start of the range and it's accuracy is 0 (greater accuracy values
- // mean more approximation)
-
- if (segment.discontinuity) {
- this.discontinuities[segment.timeline] = {
- time: segment.start,
- accuracy: 0
- };
- } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- // Search for future discontinuities that we can provide better timing
- // information for and save that information for sync purposes
- for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
- var segmentIndex = playlist.discontinuityStarts[i];
- var discontinuity = playlist.discontinuitySequence + i + 1;
- var mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
- var accuracy = Math.abs(mediaIndexDiff);
-
- if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
- var time = void 0;
-
- if (mediaIndexDiff < 0) {
- time = segment.start - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex,
- endIndex: segmentIndex
- });
- } else {
- time = segment.end + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex + 1,
- endIndex: segmentIndex
- });
- }
-
- this.discontinuities[discontinuity] = {
- time: time,
- accuracy: accuracy
- };
- }
- }
- }
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.off();
- };
-
- return SyncController;
- }(videojs__default['default'].EventTarget);
-
- /**
- * The TimelineChangeController acts as a source for segment loaders to listen for and
- * keep track of latest and pending timeline changes. This is useful to ensure proper
- * sync, as each loader may need to make a consideration for what timeline the other
- * loader is on before making changes which could impact the other loader's media.
- *
- * @class TimelineChangeController
- * @extends videojs.EventTarget
- */
-
- var TimelineChangeController = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(TimelineChangeController, _videojs$EventTarget);
-
- function TimelineChangeController() {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- _this.pendingTimelineChanges_ = {};
- _this.lastTimelineChanges_ = {};
- return _this;
- }
-
- var _proto = TimelineChangeController.prototype;
-
- _proto.clearPendingTimelineChange = function clearPendingTimelineChange(type) {
- this.pendingTimelineChanges_[type] = null;
- this.trigger('pendingtimelinechange');
- };
-
- _proto.pendingTimelineChange = function pendingTimelineChange(_ref) {
- var type = _ref.type,
- from = _ref.from,
- to = _ref.to;
-
- if (typeof from === 'number' && typeof to === 'number') {
- this.pendingTimelineChanges_[type] = {
- type: type,
- from: from,
- to: to
- };
- this.trigger('pendingtimelinechange');
- }
-
- return this.pendingTimelineChanges_[type];
- };
-
- _proto.lastTimelineChange = function lastTimelineChange(_ref2) {
- var type = _ref2.type,
- from = _ref2.from,
- to = _ref2.to;
-
- if (typeof from === 'number' && typeof to === 'number') {
- this.lastTimelineChanges_[type] = {
- type: type,
- from: from,
- to: to
- };
- delete this.pendingTimelineChanges_[type];
- this.trigger('timelinechange');
- }
-
- return this.lastTimelineChanges_[type];
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.pendingTimelineChanges_ = {};
- this.lastTimelineChanges_ = {};
- this.off();
- };
-
- return TimelineChangeController;
- }(videojs__default['default'].EventTarget);
-
- /* rollup-plugin-worker-factory start for worker!/Users/gkatsevman/p/http-streaming-release/src/decrypter-worker.js */
- var workerCode = transform(function (self) {
-
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function require(path, base) {
- return commonjsRequire(path, base === undefined || base === null ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
-
- function commonjsRequire() {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
-
- var createClass = createCommonjsModule(function (module) {
- 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);
- }
- }
-
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
-
- module.exports = _createClass;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- var setPrototypeOf = createCommonjsModule(function (module) {
- function _setPrototypeOf(o, p) {
- module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _setPrototypeOf(o, p);
- }
-
- module.exports = _setPrototypeOf;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- var inheritsLoose = createCommonjsModule(function (module) {
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- setPrototypeOf(subClass, superClass);
- }
-
- module.exports = _inheritsLoose;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- /**
- * @file stream.js
- */
-
- /**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
-
- var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
- }();
- /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
-
- /**
- * Returns the subarray of a Uint8Array without PKCS#7 padding.
- *
- * @param padded {Uint8Array} unencrypted bytes that have been padded
- * @return {Uint8Array} the unpadded bytes
- * @see http://tools.ietf.org/html/rfc5652
- */
-
-
- function unpad(padded) {
- return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
- }
- /*! @name aes-decrypter @version 3.1.2 @license Apache-2.0 */
-
- /**
- * @file aes.js
- *
- * This file contains an adaptation of the AES decryption algorithm
- * from the Standford Javascript Cryptography Library. That work is
- * covered by the following copyright and permissions notice:
- *
- * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. 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 AUTHORS ``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 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.
- *
- * The views and conclusions contained in the software and documentation
- * are those of the authors and should not be interpreted as representing
- * official policies, either expressed or implied, of the authors.
- */
-
- /**
- * Expand the S-box tables.
- *
- * @private
- */
-
-
- var precompute = function precompute() {
- var tables = [[[], [], [], [], []], [[], [], [], [], []]];
- var encTable = tables[0];
- var decTable = tables[1];
- var sbox = encTable[4];
- var sboxInv = decTable[4];
- var i;
- var x;
- var xInv;
- var d = [];
- var th = [];
- var x2;
- var x4;
- var x8;
- var s;
- var tEnc;
- var tDec; // Compute double and third tables
-
- for (i = 0; i < 256; i++) {
- th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
- }
-
- for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
- // Compute sbox
- s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
- s = s >> 8 ^ s & 255 ^ 99;
- sbox[x] = s;
- sboxInv[s] = x; // Compute MixColumns
-
- x8 = d[x4 = d[x2 = d[x]]];
- tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- tEnc = d[s] * 0x101 ^ s * 0x1010100;
-
- for (i = 0; i < 4; i++) {
- encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
- decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
- }
- } // Compactify. Considerable speedup on Firefox.
-
-
- for (i = 0; i < 5; i++) {
- encTable[i] = encTable[i].slice(0);
- decTable[i] = decTable[i].slice(0);
- }
-
- return tables;
- };
-
- var aesTables = null;
- /**
- * Schedule out an AES key for both encryption and decryption. This
- * is a low-level class. Use a cipher mode to do bulk encryption.
- *
- * @class AES
- * @param key {Array} The key as an array of 4, 6 or 8 words.
- */
-
- var AES = /*#__PURE__*/function () {
- function AES(key) {
- /**
- * The expanded S-box and inverse S-box tables. These will be computed
- * on the client so that we don't have to send them down the wire.
- *
- * There are two tables, _tables[0] is for encryption and
- * _tables[1] is for decryption.
- *
- * The first 4 sub-tables are the expanded S-box with MixColumns. The
- * last (_tables[01][4]) is the S-box itself.
- *
- * @private
- */
- // if we have yet to precompute the S-box tables
- // do so now
- if (!aesTables) {
- aesTables = precompute();
- } // then make a copy of that object for use
-
-
- this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
- var i;
- var j;
- var tmp;
- var sbox = this._tables[0][4];
- var decTable = this._tables[1];
- var keyLen = key.length;
- var rcon = 1;
-
- if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
- throw new Error('Invalid aes key size');
- }
-
- var encKey = key.slice(0);
- var decKey = [];
- this._key = [encKey, decKey]; // schedule encryption keys
-
- for (i = keyLen; i < 4 * keyLen + 28; i++) {
- tmp = encKey[i - 1]; // apply sbox
-
- if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
- tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
-
- if (i % keyLen === 0) {
- tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
- rcon = rcon << 1 ^ (rcon >> 7) * 283;
- }
- }
-
- encKey[i] = encKey[i - keyLen] ^ tmp;
- } // schedule decryption keys
-
-
- for (j = 0; i; j++, i--) {
- tmp = encKey[j & 3 ? i : i - 4];
-
- if (i <= 4 || j < 4) {
- decKey[j] = tmp;
- } else {
- decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
- }
- }
- }
- /**
- * Decrypt 16 bytes, specified as four 32-bit words.
- *
- * @param {number} encrypted0 the first word to decrypt
- * @param {number} encrypted1 the second word to decrypt
- * @param {number} encrypted2 the third word to decrypt
- * @param {number} encrypted3 the fourth word to decrypt
- * @param {Int32Array} out the array to write the decrypted words
- * into
- * @param {number} offset the offset into the output array to start
- * writing results
- * @return {Array} The plaintext.
- */
-
-
- var _proto = AES.prototype;
-
- _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
- var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
-
- var a = encrypted0 ^ key[0];
- var b = encrypted3 ^ key[1];
- var c = encrypted2 ^ key[2];
- var d = encrypted1 ^ key[3];
- var a2;
- var b2;
- var c2; // key.length === 2 ?
-
- var nInnerRounds = key.length / 4 - 2;
- var i;
- var kIndex = 4;
- var table = this._tables[1]; // load up the tables
-
- var table0 = table[0];
- var table1 = table[1];
- var table2 = table[2];
- var table3 = table[3];
- var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
-
- for (i = 0; i < nInnerRounds; i++) {
- a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
- b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
- c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
- d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
- kIndex += 4;
- a = a2;
- b = b2;
- c = c2;
- } // Last round.
-
-
- for (i = 0; i < 4; i++) {
- out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
- a2 = a;
- a = b;
- b = c;
- c = d;
- d = a2;
- }
- };
-
- return AES;
- }();
- /**
- * A wrapper around the Stream class to use setTimeout
- * and run stream "jobs" Asynchronously
- *
- * @class AsyncStream
- * @extends Stream
- */
-
-
- var AsyncStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(AsyncStream, _Stream);
-
- function AsyncStream() {
- var _this;
-
- _this = _Stream.call(this, Stream) || this;
- _this.jobs = [];
- _this.delay = 1;
- _this.timeout_ = null;
- return _this;
- }
- /**
- * process an async job
- *
- * @private
- */
-
-
- var _proto = AsyncStream.prototype;
-
- _proto.processJob_ = function processJob_() {
- this.jobs.shift()();
-
- if (this.jobs.length) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- } else {
- this.timeout_ = null;
- }
- }
- /**
- * push a job into the stream
- *
- * @param {Function} job the job to push into the stream
- */
- ;
-
- _proto.push = function push(job) {
- this.jobs.push(job);
-
- if (!this.timeout_) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- }
- };
-
- return AsyncStream;
- }(Stream);
- /**
- * Convert network-order (big-endian) bytes into their little-endian
- * representation.
- */
-
-
- var ntoh = function ntoh(word) {
- return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
- };
- /**
- * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * use for the first round of CBC.
- * @return {Uint8Array} the decrypted bytes
- *
- * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
- * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
- * @see https://tools.ietf.org/html/rfc2315
- */
-
-
- var decrypt = function decrypt(encrypted, key, initVector) {
- // word-level access to the encrypted bytes
- var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
- var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
-
- var decrypted = new Uint8Array(encrypted.byteLength);
- var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
- // decrypted data
-
- var init0;
- var init1;
- var init2;
- var init3;
- var encrypted0;
- var encrypted1;
- var encrypted2;
- var encrypted3; // iteration variable
-
- var wordIx; // pull out the words of the IV to ensure we don't modify the
- // passed-in reference and easier access
-
- init0 = initVector[0];
- init1 = initVector[1];
- init2 = initVector[2];
- init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
- // to each decrypted block
-
- for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
- // convert big-endian (network order) words into little-endian
- // (javascript order)
- encrypted0 = ntoh(encrypted32[wordIx]);
- encrypted1 = ntoh(encrypted32[wordIx + 1]);
- encrypted2 = ntoh(encrypted32[wordIx + 2]);
- encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
-
- decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
- // plaintext
-
- decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
- decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
- decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
- decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
-
- init0 = encrypted0;
- init1 = encrypted1;
- init2 = encrypted2;
- init3 = encrypted3;
- }
-
- return decrypted;
- };
- /**
- * The `Decrypter` class that manages decryption of AES
- * data through `AsyncStream` objects and the `decrypt`
- * function
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * @param {Function} done the function to run when done
- * @class Decrypter
- */
-
-
- var Decrypter = /*#__PURE__*/function () {
- function Decrypter(encrypted, key, initVector, done) {
- var step = Decrypter.STEP;
- var encrypted32 = new Int32Array(encrypted.buffer);
- var decrypted = new Uint8Array(encrypted.byteLength);
- var i = 0;
- this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
-
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
-
- for (i = step; i < encrypted32.length; i += step) {
- initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
- } // invoke the done() callback when everything is finished
-
-
- this.asyncStream_.push(function () {
- // remove pkcs#7 padding from the decrypted bytes
- done(null, unpad(decrypted));
- });
- }
- /**
- * a getter for step the maximum number of bytes to process at one time
- *
- * @return {number} the value of step 32000
- */
-
-
- var _proto = Decrypter.prototype;
- /**
- * @private
- */
-
- _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
- return function () {
- var bytes = decrypt(encrypted, key, initVector);
- decrypted.set(bytes, encrypted.byteOffset);
- };
- };
-
- createClass(Decrypter, null, [{
- key: "STEP",
- get: function get() {
- // 4 * 8000;
- return 32000;
- }
- }]);
- return Decrypter;
- }();
- /**
- * @file bin-utils.js
- */
-
- /**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-
-
- var createTransferableMessage = function createTransferableMessage(message) {
- var transferable = {};
- Object.keys(message).forEach(function (key) {
- var value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
- return transferable;
- };
- /* global self */
-
- /**
- * Our web worker interface so that things can talk to aes-decrypter
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- */
-
-
- self.onmessage = function (event) {
- var data = event.data;
- var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
- var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
- var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
- /* eslint-disable no-new, handle-callback-err */
-
- new Decrypter(encrypted, key, iv, function (err, bytes) {
- self.postMessage(createTransferableMessage({
- source: data.source,
- decrypted: bytes
- }), [bytes.buffer]);
- });
- /* eslint-enable */
- };
- });
- var Decrypter = factory(workerCode);
- /* rollup-plugin-worker-factory end for worker!/Users/gkatsevman/p/http-streaming-release/src/decrypter-worker.js */
-
- /**
- * Convert the properties of an HLS track into an audioTrackKind.
- *
- * @private
- */
-
- var audioTrackKind_ = function audioTrackKind_(properties) {
- var kind = properties.default ? 'main' : 'alternative';
-
- if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
- kind = 'main-desc';
- }
-
- return kind;
- };
- /**
- * Pause provided segment loader and playlist loader if active
- *
- * @param {SegmentLoader} segmentLoader
- * SegmentLoader to pause
- * @param {Object} mediaType
- * Active media type
- * @function stopLoaders
- */
-
-
- var stopLoaders = function stopLoaders(segmentLoader, mediaType) {
- segmentLoader.abort();
- segmentLoader.pause();
-
- if (mediaType && mediaType.activePlaylistLoader) {
- mediaType.activePlaylistLoader.pause();
- mediaType.activePlaylistLoader = null;
- }
- };
- /**
- * Start loading provided segment loader and playlist loader
- *
- * @param {PlaylistLoader} playlistLoader
- * PlaylistLoader to start loading
- * @param {Object} mediaType
- * Active media type
- * @function startLoaders
- */
-
- var startLoaders = function startLoaders(playlistLoader, mediaType) {
- // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
- // playlist loader
- mediaType.activePlaylistLoader = playlistLoader;
- playlistLoader.load();
- };
- /**
- * Returns a function to be called when the media group changes. It performs a
- * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
- * change of group is merely a rendition switch of the same content at another encoding,
- * rather than a change of content, such as switching audio from English to Spanish.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a non-destructive resync of SegmentLoader when the active media
- * group changes.
- * @function onGroupChanged
- */
-
- var onGroupChanged = function onGroupChanged(type, settings) {
- return function () {
- var _settings$segmentLoad = settings.segmentLoaders,
- segmentLoader = _settings$segmentLoad[type],
- mainSegmentLoader = _settings$segmentLoad.main,
- mediaType = settings.mediaTypes[type];
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.getActiveGroup();
- var previousActiveLoader = mediaType.activePlaylistLoader;
- var lastGroup = mediaType.lastGroup_; // the group did not change do nothing
-
- if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup || activeGroup.isMasterPlaylist) {
- // there is no group active or active group is a main playlist and won't change
- return;
- }
-
- if (!activeGroup.playlistLoader) {
- if (previousActiveLoader) {
- // The previous group had a playlist loader but the new active group does not
- // this means we are switching from demuxed to muxed audio. In this case we want to
- // do a destructive reset of the main segment loader and not restart the audio
- // loaders.
- mainSegmentLoader.resetEverything();
- }
-
- return;
- } // Non-destructive resync
-
-
- segmentLoader.resyncLoader();
- startLoaders(activeGroup.playlistLoader, mediaType);
- };
- };
- var onGroupChanging = function onGroupChanging(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- mediaType.lastGroup_ = null;
- segmentLoader.abort();
- segmentLoader.pause();
- };
- };
- /**
- * Returns a function to be called when the media track changes. It performs a
- * destructive reset of the SegmentLoader to ensure we start loading as close to
- * currentTime as possible.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a destructive reset of SegmentLoader when the active media
- * track changes.
- * @function onTrackChanged
- */
-
- var onTrackChanged = function onTrackChanged(type, settings) {
- return function () {
- var masterPlaylistLoader = settings.masterPlaylistLoader,
- _settings$segmentLoad2 = settings.segmentLoaders,
- segmentLoader = _settings$segmentLoad2[type],
- mainSegmentLoader = _settings$segmentLoad2.main,
- mediaType = settings.mediaTypes[type];
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.getActiveGroup();
- var previousActiveLoader = mediaType.activePlaylistLoader;
- var lastTrack = mediaType.lastTrack_; // track did not change, do nothing
-
- if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup) {
- // there is no group active so we do not want to restart loaders
- return;
- }
-
- if (activeGroup.isMasterPlaylist) {
- // track did not change, do nothing
- if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
- return;
- }
-
- var mpc = settings.vhs.masterPlaylistController_;
- var newPlaylist = mpc.selectPlaylist(); // media will not change do nothing
-
- if (mpc.media() === newPlaylist) {
- return;
- }
-
- mediaType.logger_("track change. Switching master audio from " + lastTrack.id + " to " + activeTrack.id);
- masterPlaylistLoader.pause();
- mainSegmentLoader.resetEverything();
- mpc.fastQualityChange_(newPlaylist);
- return;
- }
-
- if (type === 'AUDIO') {
- if (!activeGroup.playlistLoader) {
- // when switching from demuxed audio/video to muxed audio/video (noted by no
- // playlist loader for the audio group), we want to do a destructive reset of the
- // main segment loader and not restart the audio loaders
- mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
- // it should be stopped
-
- mainSegmentLoader.resetEverything();
- return;
- } // although the segment loader is an audio segment loader, call the setAudio
- // function to ensure it is prepared to re-append the init segment (or handle other
- // config changes)
-
-
- segmentLoader.setAudio(true);
- mainSegmentLoader.setAudio(false);
- }
-
- if (previousActiveLoader === activeGroup.playlistLoader) {
- // Nothing has actually changed. This can happen because track change events can fire
- // multiple times for a "single" change. One for enabling the new active track, and
- // one for disabling the track that was active
- startLoaders(activeGroup.playlistLoader, mediaType);
- return;
- }
-
- if (segmentLoader.track) {
- // For WebVTT, set the new text track in the segmentloader
- segmentLoader.track(activeTrack);
- } // destructive reset
-
-
- segmentLoader.resetEverything();
- startLoaders(activeGroup.playlistLoader, mediaType);
- };
- };
- var onError = {
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning (or error if the playlist is blacklisted) to
- * console and switches back to default audio track.
- * @function onError.AUDIO
- */
- AUDIO: function AUDIO(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type],
- blacklistCurrentPlaylist = settings.blacklistCurrentPlaylist;
- stopLoaders(segmentLoader, mediaType); // switch back to default audio track
-
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.activeGroup();
- var id = (activeGroup.filter(function (group) {
- return group.default;
- })[0] || activeGroup[0]).id;
- var defaultTrack = mediaType.tracks[id];
-
- if (activeTrack === defaultTrack) {
- // Default track encountered an error. All we can do now is blacklist the current
- // rendition and hope another will switch audio groups
- blacklistCurrentPlaylist({
- message: 'Problem encountered loading the default audio track.'
- });
- return;
- }
-
- videojs__default['default'].log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
-
- for (var trackId in mediaType.tracks) {
- mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
- }
-
- mediaType.onTrackChanged();
- };
- },
-
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning to console and disables the active subtitle track
- * @function onError.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- videojs__default['default'].log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
- stopLoaders(segmentLoader, mediaType);
- var track = mediaType.activeTrack();
-
- if (track) {
- track.mode = 'disabled';
- }
-
- mediaType.onTrackChanged();
- };
- }
- };
- var setupListeners = {
- /**
- * Setup event listeners for audio playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.AUDIO
- */
- AUDIO: function AUDIO(type, playlistLoader, settings) {
- if (!playlistLoader) {
- // no playlist loader means audio will be muxed with the video
- return;
- }
-
- var tech = settings.tech,
- requestOptions = settings.requestOptions,
- segmentLoader = settings.segmentLoaders[type];
- playlistLoader.on('loadedmetadata', function () {
- var media = playlistLoader.media();
- segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
-
- if (!tech.paused() || media.endList && tech.preload() !== 'none') {
- segmentLoader.load();
- }
- });
- playlistLoader.on('loadedplaylist', function () {
- segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
-
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
- playlistLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup event listeners for subtitle playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, playlistLoader, settings) {
- var tech = settings.tech,
- requestOptions = settings.requestOptions,
- segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- playlistLoader.on('loadedmetadata', function () {
- var media = playlistLoader.media();
- segmentLoader.playlist(media, requestOptions);
- segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
-
- if (!tech.paused() || media.endList && tech.preload() !== 'none') {
- segmentLoader.load();
- }
- });
- playlistLoader.on('loadedplaylist', function () {
- segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
-
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
- playlistLoader.on('error', onError[type](type, settings));
- }
- };
- var initialize = {
- /**
- * Setup PlaylistLoaders and AudioTracks for the audio groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.AUDIO
- */
- 'AUDIO': function AUDIO(type, settings) {
- var vhs = settings.vhs,
- sourceType = settings.sourceType,
- segmentLoader = settings.segmentLoaders[type],
- requestOptions = settings.requestOptions,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$ = settings.mediaTypes[type],
- groups = _settings$mediaTypes$.groups,
- tracks = _settings$mediaTypes$.tracks,
- logger_ = _settings$mediaTypes$.logger_,
- masterPlaylistLoader = settings.masterPlaylistLoader;
- var audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master); // force a default if we have none
-
- if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
- mediaGroups[type] = {
- main: {
- default: {
- default: true
- }
- }
- };
- }
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- var properties = mediaGroups[type][groupId][variantLabel];
- var playlistLoader = void 0;
-
- if (audioOnlyMaster) {
- logger_("AUDIO group '" + groupId + "' label '" + variantLabel + "' is a master playlist");
- properties.isMasterPlaylist = true;
- playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
- // use the resolved media playlist object
- } else if (sourceType === 'vhs-json' && properties.playlists) {
- playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
- } else if (properties.resolvedUri) {
- playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
- // should we even have properties.playlists in this check.
- } else if (properties.playlists && sourceType === 'dash') {
- playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
- } else {
- // no resolvedUri means the audio is muxed with the video when using this
- // audio track
- playlistLoader = null;
- }
-
- properties = videojs__default['default'].mergeOptions({
- id: variantLabel,
- playlistLoader: playlistLoader
- }, properties);
- setupListeners[type](type, properties.playlistLoader, settings);
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = new videojs__default['default'].AudioTrack({
- id: variantLabel,
- kind: audioTrackKind_(properties),
- enabled: false,
- language: properties.language,
- default: properties.default,
- label: variantLabel
- });
- tracks[variantLabel] = track;
- }
- }
- } // setup single error event handler for the segment loader
-
-
- segmentLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup PlaylistLoaders and TextTracks for the subtitle groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.SUBTITLES
- */
- 'SUBTITLES': function SUBTITLES(type, settings) {
- var tech = settings.tech,
- vhs = settings.vhs,
- sourceType = settings.sourceType,
- segmentLoader = settings.segmentLoaders[type],
- requestOptions = settings.requestOptions,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$2 = settings.mediaTypes[type],
- groups = _settings$mediaTypes$2.groups,
- tracks = _settings$mediaTypes$2.tracks,
- masterPlaylistLoader = settings.masterPlaylistLoader;
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- if (mediaGroups[type][groupId][variantLabel].forced) {
- // Subtitle playlists with the forced attribute are not selectable in Safari.
- // According to Apple's HLS Authoring Specification:
- // If content has forced subtitles and regular subtitles in a given language,
- // the regular subtitles track in that language MUST contain both the forced
- // subtitles and the regular subtitles for that language.
- // Because of this requirement and that Safari does not add forced subtitles,
- // forced subtitles are skipped here to maintain consistent experience across
- // all platforms
- continue;
- }
-
- var properties = mediaGroups[type][groupId][variantLabel];
- var playlistLoader = void 0;
-
- if (sourceType === 'hls') {
- playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
- } else if (sourceType === 'dash') {
- var playlists = properties.playlists.filter(function (p) {
- return p.excludeUntil !== Infinity;
- });
-
- if (!playlists.length) {
- return;
- }
-
- playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
- } else if (sourceType === 'vhs-json') {
- playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
- // as provided, otherwise use the resolved URI to load the playlist
- properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
- }
-
- properties = videojs__default['default'].mergeOptions({
- id: variantLabel,
- playlistLoader: playlistLoader
- }, properties);
- setupListeners[type](type, properties.playlistLoader, settings);
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = tech.addRemoteTextTrack({
- id: variantLabel,
- kind: 'subtitles',
- default: properties.default && properties.autoselect,
- language: properties.language,
- label: variantLabel
- }, false).track;
- tracks[variantLabel] = track;
- }
- }
- } // setup single error event handler for the segment loader
-
-
- segmentLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup TextTracks for the closed-caption groups
- *
- * @param {String} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize['CLOSED-CAPTIONS']
- */
- 'CLOSED-CAPTIONS': function CLOSEDCAPTIONS(type, settings) {
- var tech = settings.tech,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$3 = settings.mediaTypes[type],
- groups = _settings$mediaTypes$3.groups,
- tracks = _settings$mediaTypes$3.tracks;
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- var properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
-
- if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
- continue;
- }
-
- var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
- var newProps = {
- label: variantLabel,
- language: properties.language,
- instreamId: properties.instreamId,
- default: properties.default && properties.autoselect
- };
-
- if (captionServices[newProps.instreamId]) {
- newProps = videojs__default['default'].mergeOptions(newProps, captionServices[newProps.instreamId]);
- }
-
- if (newProps.default === undefined) {
- delete newProps.default;
- } // No PlaylistLoader is required for Closed-Captions because the captions are
- // embedded within the video stream
-
-
- groups[groupId].push(videojs__default['default'].mergeOptions({
- id: variantLabel
- }, properties));
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = tech.addRemoteTextTrack({
- id: newProps.instreamId,
- kind: 'captions',
- default: newProps.default,
- language: newProps.language,
- label: newProps.label
- }, false).track;
- tracks[variantLabel] = track;
- }
- }
- }
- }
- };
-
- var groupMatch = function groupMatch(list, media) {
- for (var i = 0; i < list.length; i++) {
- if (playlistMatch(media, list[i])) {
- return true;
- }
-
- if (list[i].playlists && groupMatch(list[i].playlists, media)) {
- return true;
- }
- }
-
- return false;
- };
- /**
- * Returns a function used to get the active group of the provided type
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media group for the provided type. Takes an
- * optional parameter {TextTrack} track. If no track is provided, a list of all
- * variants in the group, otherwise the variant corresponding to the provided
- * track is returned.
- * @function activeGroup
- */
-
-
- var activeGroup = function activeGroup(type, settings) {
- return function (track) {
- var masterPlaylistLoader = settings.masterPlaylistLoader,
- groups = settings.mediaTypes[type].groups;
- var media = masterPlaylistLoader.media();
-
- if (!media) {
- return null;
- }
-
- var variants = null; // set to variants to main media active group
-
- if (media.attributes[type]) {
- variants = groups[media.attributes[type]];
- }
-
- var groupKeys = Object.keys(groups);
-
- if (!variants) {
- // find the masterPlaylistLoader media
- // that is in a media group if we are dealing
- // with audio only
- if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.master)) {
- for (var i = 0; i < groupKeys.length; i++) {
- var groupPropertyList = groups[groupKeys[i]];
-
- if (groupMatch(groupPropertyList, media)) {
- variants = groupPropertyList;
- break;
- }
- } // use the main group if it exists
-
- } else if (groups.main) {
- variants = groups.main; // only one group, use that one
- } else if (groupKeys.length === 1) {
- variants = groups[groupKeys[0]];
- }
- }
-
- if (typeof track === 'undefined') {
- return variants;
- }
-
- if (track === null || !variants) {
- // An active track was specified so a corresponding group is expected. track === null
- // means no track is currently active so there is no corresponding group
- return null;
- }
-
- return variants.filter(function (props) {
- return props.id === track.id;
- })[0] || null;
- };
- };
- var activeTrack = {
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.AUDIO
- */
- AUDIO: function AUDIO(type, settings) {
- return function () {
- var tracks = settings.mediaTypes[type].tracks;
-
- for (var id in tracks) {
- if (tracks[id].enabled) {
- return tracks[id];
- }
- }
-
- return null;
- };
- },
-
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, settings) {
- return function () {
- var tracks = settings.mediaTypes[type].tracks;
-
- for (var id in tracks) {
- if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
- return tracks[id];
- }
- }
-
- return null;
- };
- }
- };
- var getActiveGroup = function getActiveGroup(type, _ref) {
- var mediaTypes = _ref.mediaTypes;
- return function () {
- var activeTrack_ = mediaTypes[type].activeTrack();
-
- if (!activeTrack_) {
- return null;
- }
-
- return mediaTypes[type].activeGroup(activeTrack_);
- };
- };
- /**
- * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
- * Closed-Captions) specified in the master manifest.
- *
- * @param {Object} settings
- * Object containing required information for setting up the media groups
- * @param {Tech} settings.tech
- * The tech of the player
- * @param {Object} settings.requestOptions
- * XHR request options used by the segment loaders
- * @param {PlaylistLoader} settings.masterPlaylistLoader
- * PlaylistLoader for the master source
- * @param {VhsHandler} settings.vhs
- * VHS SourceHandler
- * @param {Object} settings.master
- * The parsed master manifest
- * @param {Object} settings.mediaTypes
- * Object to store the loaders, tracks, and utility methods for each media type
- * @param {Function} settings.blacklistCurrentPlaylist
- * Blacklists the current rendition and forces a rendition switch.
- * @function setupMediaGroups
- */
-
- var setupMediaGroups = function setupMediaGroups(settings) {
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
- initialize[type](type, settings);
- });
- var mediaTypes = settings.mediaTypes,
- masterPlaylistLoader = settings.masterPlaylistLoader,
- tech = settings.tech,
- vhs = settings.vhs,
- _settings$segmentLoad3 = settings.segmentLoaders,
- audioSegmentLoader = _settings$segmentLoad3['AUDIO'],
- mainSegmentLoader = _settings$segmentLoad3.main; // setup active group and track getters and change event handlers
-
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- mediaTypes[type].activeGroup = activeGroup(type, settings);
- mediaTypes[type].activeTrack = activeTrack[type](type, settings);
- mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
- mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
- mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
- mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
- }); // DO NOT enable the default subtitle or caption track.
- // DO enable the default audio track
-
- var audioGroup = mediaTypes.AUDIO.activeGroup();
-
- if (audioGroup) {
- var groupId = (audioGroup.filter(function (group) {
- return group.default;
- })[0] || audioGroup[0]).id;
- mediaTypes.AUDIO.tracks[groupId].enabled = true;
- mediaTypes.AUDIO.onGroupChanged();
- mediaTypes.AUDIO.onTrackChanged();
- var activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
- // track is changed, but needs to be handled here since the track may not be considered
- // changed on the first call to onTrackChanged
-
- if (!activeAudioGroup.playlistLoader) {
- // either audio is muxed with video or the stream is audio only
- mainSegmentLoader.setAudio(true);
- } else {
- // audio is demuxed
- mainSegmentLoader.setAudio(false);
- audioSegmentLoader.setAudio(true);
- }
- }
-
- masterPlaylistLoader.on('mediachange', function () {
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- return mediaTypes[type].onGroupChanged();
- });
- });
- masterPlaylistLoader.on('mediachanging', function () {
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- return mediaTypes[type].onGroupChanging();
- });
- }); // custom audio track change event handler for usage event
-
- var onAudioTrackChanged = function onAudioTrackChanged() {
- mediaTypes.AUDIO.onTrackChanged();
- tech.trigger({
- type: 'usage',
- name: 'vhs-audio-change'
- });
- tech.trigger({
- type: 'usage',
- name: 'hls-audio-change'
- });
- };
-
- tech.audioTracks().addEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
- vhs.on('dispose', function () {
- tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
- }); // clear existing audio tracks and add the ones we just created
-
- tech.clearTracks('audio');
-
- for (var id in mediaTypes.AUDIO.tracks) {
- tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
- }
- };
- /**
- * Creates skeleton object used to store the loaders, tracks, and utility methods for each
- * media type
- *
- * @return {Object}
- * Object to store the loaders, tracks, and utility methods for each media type
- * @function createMediaTypes
- */
-
- var createMediaTypes = function createMediaTypes() {
- var mediaTypes = {};
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
- mediaTypes[type] = {
- groups: {},
- tracks: {},
- activePlaylistLoader: null,
- activeGroup: noop,
- activeTrack: noop,
- getActiveGroup: noop,
- onGroupChanged: noop,
- onTrackChanged: noop,
- lastTrack_: null,
- logger_: logger("MediaGroups[" + type + "]")
- };
- });
- return mediaTypes;
- };
-
- var ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
- var Vhs$1; // SegmentLoader stats that need to have each loader's
- // values summed to calculate the final value
-
- var loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
-
- var sumLoaderStat = function sumLoaderStat(stat) {
- return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
- };
-
- var shouldSwitchToMedia = function shouldSwitchToMedia(_ref) {
- var currentPlaylist = _ref.currentPlaylist,
- nextPlaylist = _ref.nextPlaylist,
- forwardBuffer = _ref.forwardBuffer,
- bufferLowWaterLine = _ref.bufferLowWaterLine,
- bufferHighWaterLine = _ref.bufferHighWaterLine,
- duration = _ref.duration,
- experimentalBufferBasedABR = _ref.experimentalBufferBasedABR,
- log = _ref.log;
-
- // we have no other playlist to switch to
- if (!nextPlaylist) {
- videojs__default['default'].log.warn('We received no playlist to switch to. Please check your stream.');
- return false;
- }
-
- var sharedLogLine = "allowing switch " + (currentPlaylist && currentPlaylist.id || 'null') + " -> " + nextPlaylist.id; // If the playlist is live, then we want to not take low water line into account.
- // This is because in LIVE, the player plays 3 segments from the end of the
- // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
- // in those segments, a viewer will never experience a rendition upswitch.
-
- if (!currentPlaylist || !currentPlaylist.endList) {
- log(sharedLogLine + " as current playlist " + (!currentPlaylist ? 'is not set' : 'is live'));
- return true;
- } // no need to switch playlist is the same
-
-
- if (nextPlaylist.id === currentPlaylist.id) {
- return false;
- }
-
- var maxBufferLowWaterLine = experimentalBufferBasedABR ? Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE; // For the same reason as LIVE, we ignore the low water line when the VOD
- // duration is below the max potential low water line
-
- if (duration < maxBufferLowWaterLine) {
- log(sharedLogLine + " as duration < max low water line (" + duration + " < " + maxBufferLowWaterLine + ")");
- return true;
- }
-
- var nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
- var currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
- // we can switch down
-
- if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
- var logLine = sharedLogLine + " as next bandwidth < current bandwidth (" + nextBandwidth + " < " + currBandwidth + ")";
-
- if (experimentalBufferBasedABR) {
- logLine += " and forwardBuffer < bufferHighWaterLine (" + forwardBuffer + " < " + bufferHighWaterLine + ")";
- }
-
- log(logLine);
- return true;
- } // and if our buffer is higher than the low water line,
- // we can switch up
-
-
- if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
- var _logLine = sharedLogLine + " as forwardBuffer >= bufferLowWaterLine (" + forwardBuffer + " >= " + bufferLowWaterLine + ")";
-
- if (experimentalBufferBasedABR) {
- _logLine += " and next bandwidth > current bandwidth (" + nextBandwidth + " > " + currBandwidth + ")";
- }
-
- log(_logLine);
- return true;
- }
-
- log("not " + sharedLogLine + " as no switching criteria met");
- return false;
- };
- /**
- * the master playlist controller controller all interactons
- * between playlists and segmentloaders. At this time this mainly
- * involves a master playlist and a series of audio playlists
- * if they are available
- *
- * @class MasterPlaylistController
- * @extends videojs.EventTarget
- */
-
-
- var MasterPlaylistController = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(MasterPlaylistController, _videojs$EventTarget);
-
- function MasterPlaylistController(options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- var src = options.src,
- handleManifestRedirects = options.handleManifestRedirects,
- withCredentials = options.withCredentials,
- tech = options.tech,
- bandwidth = options.bandwidth,
- externVhs = options.externVhs,
- useCueTags = options.useCueTags,
- blacklistDuration = options.blacklistDuration,
- enableLowInitialPlaylist = options.enableLowInitialPlaylist,
- sourceType = options.sourceType,
- cacheEncryptionKeys = options.cacheEncryptionKeys,
- experimentalBufferBasedABR = options.experimentalBufferBasedABR;
-
- if (!src) {
- throw new Error('A non-empty playlist URL or JSON manifest string is required');
- }
-
- var maxPlaylistRetries = options.maxPlaylistRetries;
-
- if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
- maxPlaylistRetries = Infinity;
- }
-
- Vhs$1 = externVhs;
- _this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
- _this.withCredentials = withCredentials;
- _this.tech_ = tech;
- _this.vhs_ = tech.vhs;
- _this.sourceType_ = sourceType;
- _this.useCueTags_ = useCueTags;
- _this.blacklistDuration = blacklistDuration;
- _this.maxPlaylistRetries = maxPlaylistRetries;
- _this.enableLowInitialPlaylist = enableLowInitialPlaylist;
-
- if (_this.useCueTags_) {
- _this.cueTagsTrack_ = _this.tech_.addTextTrack('metadata', 'ad-cues');
- _this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
- }
-
- _this.requestOptions_ = {
- withCredentials: withCredentials,
- handleManifestRedirects: handleManifestRedirects,
- maxPlaylistRetries: maxPlaylistRetries,
- timeout: null
- };
-
- _this.on('error', _this.pauseLoading);
-
- _this.mediaTypes_ = createMediaTypes();
- _this.mediaSource = new window__default['default'].MediaSource();
- _this.handleDurationChange_ = _this.handleDurationChange_.bind(assertThisInitialized(_this));
- _this.handleSourceOpen_ = _this.handleSourceOpen_.bind(assertThisInitialized(_this));
- _this.handleSourceEnded_ = _this.handleSourceEnded_.bind(assertThisInitialized(_this));
-
- _this.mediaSource.addEventListener('durationchange', _this.handleDurationChange_); // load the media source into the player
-
-
- _this.mediaSource.addEventListener('sourceopen', _this.handleSourceOpen_);
-
- _this.mediaSource.addEventListener('sourceended', _this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
- // everything, and the MediaSource should not be detached without a proper disposal
-
-
- _this.seekable_ = videojs__default['default'].createTimeRanges();
- _this.hasPlayed_ = false;
- _this.syncController_ = new SyncController(options);
- _this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'segment-metadata'
- }, false).track;
- _this.decrypter_ = new Decrypter();
- _this.sourceUpdater_ = new SourceUpdater(_this.mediaSource);
- _this.inbandTextTracks_ = {};
- _this.timelineChangeController_ = new TimelineChangeController();
- var segmentLoaderSettings = {
- vhs: _this.vhs_,
- parse708captions: options.parse708captions,
- mediaSource: _this.mediaSource,
- currentTime: _this.tech_.currentTime.bind(_this.tech_),
- seekable: function seekable() {
- return _this.seekable();
- },
- seeking: function seeking() {
- return _this.tech_.seeking();
- },
- duration: function duration() {
- return _this.duration();
- },
- hasPlayed: function hasPlayed() {
- return _this.hasPlayed_;
- },
- goalBufferLength: function goalBufferLength() {
- return _this.goalBufferLength();
- },
- bandwidth: bandwidth,
- syncController: _this.syncController_,
- decrypter: _this.decrypter_,
- sourceType: _this.sourceType_,
- inbandTextTracks: _this.inbandTextTracks_,
- cacheEncryptionKeys: cacheEncryptionKeys,
- sourceUpdater: _this.sourceUpdater_,
- timelineChangeController: _this.timelineChangeController_
- }; // The source type check not only determines whether a special DASH playlist loader
- // should be used, but also covers the case where the provided src is a vhs-json
- // manifest object (instead of a URL). In the case of vhs-json, the default
- // PlaylistLoader should be used.
-
- _this.masterPlaylistLoader_ = _this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, _this.vhs_, _this.requestOptions_) : new PlaylistLoader(src, _this.vhs_, _this.requestOptions_);
-
- _this.setupMasterPlaylistLoaderListeners_(); // setup segment loaders
- // combined audio/video or just video when alternate audio track is selected
-
-
- _this.mainSegmentLoader_ = new SegmentLoader(videojs__default['default'].mergeOptions(segmentLoaderSettings, {
- segmentMetadataTrack: _this.segmentMetadataTrack_,
- loaderType: 'main'
- }), options); // alternate audio track
-
- _this.audioSegmentLoader_ = new SegmentLoader(videojs__default['default'].mergeOptions(segmentLoaderSettings, {
- loaderType: 'audio'
- }), options);
- _this.subtitleSegmentLoader_ = new VTTSegmentLoader(videojs__default['default'].mergeOptions(segmentLoaderSettings, {
- loaderType: 'vtt',
- featuresNativeTextTracks: _this.tech_.featuresNativeTextTracks
- }), options);
-
- _this.setupSegmentLoaderListeners_();
-
- if (_this.experimentalBufferBasedABR) {
- _this.masterPlaylistLoader_.one('loadedplaylist', function () {
- return _this.startABRTimer_();
- });
-
- _this.tech_.on('pause', function () {
- return _this.stopABRTimer_();
- });
-
- _this.tech_.on('play', function () {
- return _this.startABRTimer_();
- });
- } // Create SegmentLoader stat-getters
- // mediaRequests_
- // mediaRequestsAborted_
- // mediaRequestsTimedout_
- // mediaRequestsErrored_
- // mediaTransferDuration_
- // mediaBytesTransferred_
- // mediaAppends_
-
-
- loaderStats.forEach(function (stat) {
- _this[stat + '_'] = sumLoaderStat.bind(assertThisInitialized(_this), stat);
- });
- _this.logger_ = logger('MPC');
- _this.triggeredFmp4Usage = false;
-
- if (_this.tech_.preload() === 'none') {
- _this.loadOnPlay_ = function () {
- _this.loadOnPlay_ = null;
-
- _this.masterPlaylistLoader_.load();
- };
-
- _this.tech_.one('play', _this.loadOnPlay_);
- } else {
- _this.masterPlaylistLoader_.load();
- }
-
- _this.timeToLoadedData__ = -1;
- _this.mainAppendsToLoadedData__ = -1;
- _this.audioAppendsToLoadedData__ = -1;
- var event = _this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
-
- _this.tech_.one(event, function () {
- var timeToLoadedDataStart = Date.now();
-
- _this.tech_.one('loadeddata', function () {
- _this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
- _this.mainAppendsToLoadedData__ = _this.mainSegmentLoader_.mediaAppends;
- _this.audioAppendsToLoadedData__ = _this.audioSegmentLoader_.mediaAppends;
- });
- });
-
- return _this;
- }
-
- var _proto = MasterPlaylistController.prototype;
-
- _proto.mainAppendsToLoadedData_ = function mainAppendsToLoadedData_() {
- return this.mainAppendsToLoadedData__;
- };
-
- _proto.audioAppendsToLoadedData_ = function audioAppendsToLoadedData_() {
- return this.audioAppendsToLoadedData__;
- };
-
- _proto.appendsToLoadedData_ = function appendsToLoadedData_() {
- var main = this.mainAppendsToLoadedData_();
- var audio = this.audioAppendsToLoadedData_();
-
- if (main === -1 || audio === -1) {
- return -1;
- }
-
- return main + audio;
- };
-
- _proto.timeToLoadedData_ = function timeToLoadedData_() {
- return this.timeToLoadedData__;
- }
- /**
- * Run selectPlaylist and switch to the new playlist if we should
- *
- * @private
- *
- */
- ;
-
- _proto.checkABR_ = function checkABR_() {
- var nextPlaylist = this.selectPlaylist();
-
- if (this.shouldSwitchToMedia_(nextPlaylist)) {
- this.switchMedia_(nextPlaylist, 'abr');
- }
- };
-
- _proto.switchMedia_ = function switchMedia_(playlist, cause, delay) {
- var oldMedia = this.media();
- var oldId = oldMedia && (oldMedia.id || oldMedia.uri);
- var newId = playlist.id || playlist.uri;
-
- if (oldId && oldId !== newId) {
- this.logger_("switch media " + oldId + " -> " + newId + " from " + cause);
- this.tech_.trigger({
- type: 'usage',
- name: "vhs-rendition-change-" + cause
- });
- }
-
- this.masterPlaylistLoader_.media(playlist, delay);
- }
- /**
- * Start a timer that periodically calls checkABR_
- *
- * @private
- */
- ;
-
- _proto.startABRTimer_ = function startABRTimer_() {
- var _this2 = this;
-
- this.stopABRTimer_();
- this.abrTimer_ = window__default['default'].setInterval(function () {
- return _this2.checkABR_();
- }, 250);
- }
- /**
- * Stop the timer that periodically calls checkABR_
- *
- * @private
- */
- ;
-
- _proto.stopABRTimer_ = function stopABRTimer_() {
- // if we're scrubbing, we don't need to pause.
- // This getter will be added to Video.js in version 7.11.
- if (this.tech_.scrubbing && this.tech_.scrubbing()) {
- return;
- }
-
- window__default['default'].clearInterval(this.abrTimer_);
- this.abrTimer_ = null;
- }
- /**
- * Get a list of playlists for the currently selected audio playlist
- *
- * @return {Array} the array of audio playlists
- */
- ;
-
- _proto.getAudioTrackPlaylists_ = function getAudioTrackPlaylists_() {
- var master = this.master(); // if we don't have any audio groups then we can only
- // assume that the audio tracks are contained in masters
- // playlist array, use that or an empty array.
-
- if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
- return master && master.playlists || [];
- }
-
- var AUDIO = master.mediaGroups.AUDIO;
- var groupKeys = Object.keys(AUDIO);
- var track; // get the current active track
-
- if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
- track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from master if mediaTypes_ isn't setup yet
- } else {
- // default group is `main` or just the first group.
- var defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
-
- for (var label in defaultGroup) {
- if (defaultGroup[label].default) {
- track = {
- label: label
- };
- break;
- }
- }
- } // no active track no playlists.
-
-
- if (!track) {
- return [];
- }
-
- var playlists = []; // get all of the playlists that are possible for the
- // active track.
-
- for (var group in AUDIO) {
- if (AUDIO[group][track.label]) {
- var properties = AUDIO[group][track.label];
-
- if (properties.playlists) {
- playlists.push.apply(playlists, properties.playlists);
- } else {
- playlists.push(properties);
- }
- }
- }
-
- return playlists;
- }
- /**
- * Register event handlers on the master playlist loader. A helper
- * function for construction time.
- *
- * @private
- */
- ;
-
- _proto.setupMasterPlaylistLoaderListeners_ = function setupMasterPlaylistLoaderListeners_() {
- var _this3 = this;
-
- this.masterPlaylistLoader_.on('loadedmetadata', function () {
- var media = _this3.masterPlaylistLoader_.media();
-
- var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
- // timeout the request.
-
- if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
- _this3.requestOptions_.timeout = 0;
- } else {
- _this3.requestOptions_.timeout = requestTimeout;
- } // if this isn't a live video and preload permits, start
- // downloading segments
-
-
- if (media.endList && _this3.tech_.preload() !== 'none') {
- _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
-
- _this3.mainSegmentLoader_.load();
- }
-
- setupMediaGroups({
- sourceType: _this3.sourceType_,
- segmentLoaders: {
- AUDIO: _this3.audioSegmentLoader_,
- SUBTITLES: _this3.subtitleSegmentLoader_,
- main: _this3.mainSegmentLoader_
- },
- tech: _this3.tech_,
- requestOptions: _this3.requestOptions_,
- masterPlaylistLoader: _this3.masterPlaylistLoader_,
- vhs: _this3.vhs_,
- master: _this3.master(),
- mediaTypes: _this3.mediaTypes_,
- blacklistCurrentPlaylist: _this3.blacklistCurrentPlaylist.bind(_this3)
- });
-
- _this3.triggerPresenceUsage_(_this3.master(), media);
-
- _this3.setupFirstPlay();
-
- if (!_this3.mediaTypes_.AUDIO.activePlaylistLoader || _this3.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
- _this3.trigger('selectedinitialmedia');
- } else {
- // We must wait for the active audio playlist loader to
- // finish setting up before triggering this event so the
- // representations API and EME setup is correct
- _this3.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', function () {
- _this3.trigger('selectedinitialmedia');
- });
- }
- });
- this.masterPlaylistLoader_.on('loadedplaylist', function () {
- if (_this3.loadOnPlay_) {
- _this3.tech_.off('play', _this3.loadOnPlay_);
- }
-
- var updatedPlaylist = _this3.masterPlaylistLoader_.media();
-
- if (!updatedPlaylist) {
- // exclude any variants that are not supported by the browser before selecting
- // an initial media as the playlist selectors do not consider browser support
- _this3.excludeUnsupportedVariants_();
-
- var selectedMedia;
-
- if (_this3.enableLowInitialPlaylist) {
- selectedMedia = _this3.selectInitialPlaylist();
- }
-
- if (!selectedMedia) {
- selectedMedia = _this3.selectPlaylist();
- }
-
- if (!selectedMedia || !_this3.shouldSwitchToMedia_(selectedMedia)) {
- return;
- }
-
- _this3.initialMedia_ = selectedMedia;
-
- _this3.switchMedia_(_this3.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
- // fire again since the playlist will be requested. In the case of vhs-json
- // (where the manifest object is provided as the source), when the media
- // playlist's `segments` list is already available, a media playlist won't be
- // requested, and loadedplaylist won't fire again, so the playlist handler must be
- // called on its own here.
-
-
- var haveJsonSource = _this3.sourceType_ === 'vhs-json' && _this3.initialMedia_.segments;
-
- if (!haveJsonSource) {
- return;
- }
-
- updatedPlaylist = _this3.initialMedia_;
- }
-
- _this3.handleUpdatedMediaPlaylist(updatedPlaylist);
- });
- this.masterPlaylistLoader_.on('error', function () {
- _this3.blacklistCurrentPlaylist(_this3.masterPlaylistLoader_.error);
- });
- this.masterPlaylistLoader_.on('mediachanging', function () {
- _this3.mainSegmentLoader_.abort();
-
- _this3.mainSegmentLoader_.pause();
- });
- this.masterPlaylistLoader_.on('mediachange', function () {
- var media = _this3.masterPlaylistLoader_.media();
-
- var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
- // timeout the request.
-
- if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
- _this3.requestOptions_.timeout = 0;
- } else {
- _this3.requestOptions_.timeout = requestTimeout;
- } // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `loadedplaylist`
-
-
- _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
-
- _this3.mainSegmentLoader_.load();
-
- _this3.tech_.trigger({
- type: 'mediachange',
- bubbles: true
- });
- });
- this.masterPlaylistLoader_.on('playlistunchanged', function () {
- var updatedPlaylist = _this3.masterPlaylistLoader_.media(); // ignore unchanged playlists that have already been
- // excluded for not-changing. We likely just have a really slowly updating
- // playlist.
-
-
- if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
- return;
- }
-
- var playlistOutdated = _this3.stuckAtPlaylistEnd_(updatedPlaylist);
-
- if (playlistOutdated) {
- // Playlist has stopped updating and we're stuck at its end. Try to
- // blacklist it and switch to another playlist in the hope that that
- // one is updating (and give the player a chance to re-adjust to the
- // safe live point).
- _this3.blacklistCurrentPlaylist({
- message: 'Playlist no longer updating.',
- reason: 'playlist-unchanged'
- }); // useful for monitoring QoS
-
-
- _this3.tech_.trigger('playliststuck');
- }
- });
- this.masterPlaylistLoader_.on('renditiondisabled', function () {
- _this3.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-disabled'
- });
-
- _this3.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-disabled'
- });
- });
- this.masterPlaylistLoader_.on('renditionenabled', function () {
- _this3.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-enabled'
- });
-
- _this3.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-enabled'
- });
- });
- }
- /**
- * Given an updated media playlist (whether it was loaded for the first time, or
- * refreshed for live playlists), update any relevant properties and state to reflect
- * changes in the media that should be accounted for (e.g., cues and duration).
- *
- * @param {Object} updatedPlaylist the updated media playlist object
- *
- * @private
- */
- ;
-
- _proto.handleUpdatedMediaPlaylist = function handleUpdatedMediaPlaylist(updatedPlaylist) {
- if (this.useCueTags_) {
- this.updateAdCues_(updatedPlaylist);
- } // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `mediachange`
-
-
- this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
- this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
- // as it is possible that it was temporarily stopped while waiting for
- // a playlist (e.g., in case the playlist errored and we re-requested it).
-
- if (!this.tech_.paused()) {
- this.mainSegmentLoader_.load();
-
- if (this.audioSegmentLoader_) {
- this.audioSegmentLoader_.load();
- }
- }
- }
- /**
- * A helper function for triggerring presence usage events once per source
- *
- * @private
- */
- ;
-
- _proto.triggerPresenceUsage_ = function triggerPresenceUsage_(master, media) {
- var mediaGroups = master.mediaGroups || {};
- var defaultDemuxed = true;
- var audioGroupKeys = Object.keys(mediaGroups.AUDIO);
-
- for (var mediaGroup in mediaGroups.AUDIO) {
- for (var label in mediaGroups.AUDIO[mediaGroup]) {
- var properties = mediaGroups.AUDIO[mediaGroup][label];
-
- if (!properties.uri) {
- defaultDemuxed = false;
- }
- }
- }
-
- if (defaultDemuxed) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-demuxed'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-demuxed'
- });
- }
-
- if (Object.keys(mediaGroups.SUBTITLES).length) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-webvtt'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-webvtt'
- });
- }
-
- if (Vhs$1.Playlist.isAes(media)) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-aes'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-aes'
- });
- }
-
- if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-alternate-audio'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-alternate-audio'
- });
- }
-
- if (this.useCueTags_) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-playlist-cue-tags'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-playlist-cue-tags'
- });
- }
- };
-
- _proto.shouldSwitchToMedia_ = function shouldSwitchToMedia_(nextPlaylist) {
- var currentPlaylist = this.masterPlaylistLoader_.media();
- var buffered = this.tech_.buffered();
- var forwardBuffer = buffered.length ? buffered.end(buffered.length - 1) - this.tech_.currentTime() : 0;
- var bufferLowWaterLine = this.bufferLowWaterLine();
- var bufferHighWaterLine = this.bufferHighWaterLine();
- return shouldSwitchToMedia({
- currentPlaylist: currentPlaylist,
- nextPlaylist: nextPlaylist,
- forwardBuffer: forwardBuffer,
- bufferLowWaterLine: bufferLowWaterLine,
- bufferHighWaterLine: bufferHighWaterLine,
- duration: this.duration(),
- experimentalBufferBasedABR: this.experimentalBufferBasedABR,
- log: this.logger_
- });
- }
- /**
- * Register event handlers on the segment loaders. A helper function
- * for construction time.
- *
- * @private
- */
- ;
-
- _proto.setupSegmentLoaderListeners_ = function setupSegmentLoaderListeners_() {
- var _this4 = this;
-
- if (!this.experimentalBufferBasedABR) {
- this.mainSegmentLoader_.on('bandwidthupdate', function () {
- var nextPlaylist = _this4.selectPlaylist();
-
- if (_this4.shouldSwitchToMedia_(nextPlaylist)) {
- _this4.switchMedia_(nextPlaylist, 'bandwidthupdate');
- }
-
- _this4.tech_.trigger('bandwidthupdate');
- });
- this.mainSegmentLoader_.on('progress', function () {
- _this4.trigger('progress');
- });
- }
-
- this.mainSegmentLoader_.on('error', function () {
- _this4.blacklistCurrentPlaylist(_this4.mainSegmentLoader_.error());
- });
- this.mainSegmentLoader_.on('appenderror', function () {
- _this4.error = _this4.mainSegmentLoader_.error_;
-
- _this4.trigger('error');
- });
- this.mainSegmentLoader_.on('syncinfoupdate', function () {
- _this4.onSyncInfoUpdate_();
- });
- this.mainSegmentLoader_.on('timestampoffset', function () {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-timestamp-offset'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-timestamp-offset'
- });
- });
- this.audioSegmentLoader_.on('syncinfoupdate', function () {
- _this4.onSyncInfoUpdate_();
- });
- this.audioSegmentLoader_.on('appenderror', function () {
- _this4.error = _this4.audioSegmentLoader_.error_;
-
- _this4.trigger('error');
- });
- this.mainSegmentLoader_.on('ended', function () {
- _this4.logger_('main segment loader ended');
-
- _this4.onEndOfStream();
- });
- this.mainSegmentLoader_.on('earlyabort', function (event) {
- // never try to early abort with the new ABR algorithm
- if (_this4.experimentalBufferBasedABR) {
- return;
- }
-
- _this4.delegateLoaders_('all', ['abort']);
-
- _this4.blacklistCurrentPlaylist({
- message: 'Aborted early because there isn\'t enough bandwidth to complete the ' + 'request without rebuffering.'
- }, ABORT_EARLY_BLACKLIST_SECONDS);
- });
-
- var updateCodecs = function updateCodecs() {
- if (!_this4.sourceUpdater_.hasCreatedSourceBuffers()) {
- return _this4.tryToCreateSourceBuffers_();
- }
-
- var codecs = _this4.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
-
-
- if (!codecs) {
- return;
- }
-
- _this4.sourceUpdater_.addOrChangeSourceBuffers(codecs);
- };
-
- this.mainSegmentLoader_.on('trackinfo', updateCodecs);
- this.audioSegmentLoader_.on('trackinfo', updateCodecs);
- this.mainSegmentLoader_.on('fmp4', function () {
- if (!_this4.triggeredFmp4Usage) {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-fmp4'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-fmp4'
- });
-
- _this4.triggeredFmp4Usage = true;
- }
- });
- this.audioSegmentLoader_.on('fmp4', function () {
- if (!_this4.triggeredFmp4Usage) {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-fmp4'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-fmp4'
- });
-
- _this4.triggeredFmp4Usage = true;
- }
- });
- this.audioSegmentLoader_.on('ended', function () {
- _this4.logger_('audioSegmentLoader ended');
-
- _this4.onEndOfStream();
- });
- };
-
- _proto.mediaSecondsLoaded_ = function mediaSecondsLoaded_() {
- return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
- }
- /**
- * Call load on our SegmentLoaders
- */
- ;
-
- _proto.load = function load() {
- this.mainSegmentLoader_.load();
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.load();
- }
-
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.load();
- }
- }
- /**
- * Re-tune playback quality level for the current player
- * conditions without performing destructive actions, like
- * removing already buffered content
- *
- * @private
- * @deprecated
- */
- ;
-
- _proto.smoothQualityChange_ = function smoothQualityChange_(media) {
- if (media === void 0) {
- media = this.selectPlaylist();
- }
-
- this.fastQualityChange_(media);
- }
- /**
- * Re-tune playback quality level for the current player
- * conditions. This method will perform destructive actions like removing
- * already buffered content in order to readjust the currently active
- * playlist quickly. This is good for manual quality changes
- *
- * @private
- */
- ;
-
- _proto.fastQualityChange_ = function fastQualityChange_(media) {
- var _this5 = this;
-
- if (media === void 0) {
- media = this.selectPlaylist();
- }
-
- if (media === this.masterPlaylistLoader_.media()) {
- this.logger_('skipping fastQualityChange because new media is same as old');
- return;
- }
-
- this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
- // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
- // ahead is roughly the minimum that will accomplish this across a variety of content
- // in IE and Edge, but seeking in place is sufficient on all other browsers)
- // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
- // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
-
- this.mainSegmentLoader_.resetEverything(function () {
- // Since this is not a typical seek, we avoid the seekTo method which can cause segments
- // from the previously enabled rendition to load before the new playlist has finished loading
- if (videojs__default['default'].browser.IE_VERSION || videojs__default['default'].browser.IS_EDGE) {
- _this5.tech_.setCurrentTime(_this5.tech_.currentTime() + 0.04);
- } else {
- _this5.tech_.setCurrentTime(_this5.tech_.currentTime());
- }
- }); // don't need to reset audio as it is reset when media changes
- }
- /**
- * Begin playback.
- */
- ;
-
- _proto.play = function play() {
- if (this.setupFirstPlay()) {
- return;
- }
-
- if (this.tech_.ended()) {
- this.tech_.setCurrentTime(0);
- }
-
- if (this.hasPlayed_) {
- this.load();
- }
-
- var seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
- // seek forward to the live point
-
- if (this.tech_.duration() === Infinity) {
- if (this.tech_.currentTime() < seekable.start(0)) {
- return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
- }
- }
- }
- /**
- * Seek to the latest media position if this is a live video and the
- * player and video are loaded and initialized.
- */
- ;
-
- _proto.setupFirstPlay = function setupFirstPlay() {
- var _this6 = this;
-
- var media = this.masterPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
- // If 1) there is no active media
- // 2) the player is paused
- // 3) the first play has already been setup
- // then exit early
-
- if (!media || this.tech_.paused() || this.hasPlayed_) {
- return false;
- } // when the video is a live stream
-
-
- if (!media.endList) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- // without a seekable range, the player cannot seek to begin buffering at the live
- // point
- return false;
- }
-
- if (videojs__default['default'].browser.IE_VERSION && this.tech_.readyState() === 0) {
- // IE11 throws an InvalidStateError if you try to set currentTime while the
- // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
- this.tech_.one('loadedmetadata', function () {
- _this6.trigger('firstplay');
-
- _this6.tech_.setCurrentTime(seekable.end(0));
-
- _this6.hasPlayed_ = true;
- });
- return false;
- } // trigger firstplay to inform the source handler to ignore the next seek event
-
-
- this.trigger('firstplay'); // seek to the live point
-
- this.tech_.setCurrentTime(seekable.end(0));
- }
-
- this.hasPlayed_ = true; // we can begin loading now that everything is ready
-
- this.load();
- return true;
- }
- /**
- * handle the sourceopen event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleSourceOpen_ = function handleSourceOpen_() {
- // Only attempt to create the source buffer if none already exist.
- // handleSourceOpen is also called when we are "re-opening" a source buffer
- // after `endOfStream` has been called (in response to a seek for instance)
- this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
- // code in video.js but is required because play() must be invoked
- // *after* the media source has opened.
-
- if (this.tech_.autoplay()) {
- var playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
- // on browsers which return a promise
-
- if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
- playPromise.then(null, function (e) {});
- }
- }
-
- this.trigger('sourceopen');
- }
- /**
- * handle the sourceended event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleSourceEnded_ = function handleSourceEnded_() {
- if (!this.inbandTextTracks_.metadataTrack_) {
- return;
- }
-
- var cues = this.inbandTextTracks_.metadataTrack_.cues;
-
- if (!cues || !cues.length) {
- return;
- }
-
- var duration = this.duration();
- cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
- }
- /**
- * handle the durationchange event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleDurationChange_ = function handleDurationChange_() {
- this.tech_.trigger('durationchange');
- }
- /**
- * Calls endOfStream on the media source when all active stream types have called
- * endOfStream
- *
- * @param {string} streamType
- * Stream type of the segment loader that called endOfStream
- * @private
- */
- ;
-
- _proto.onEndOfStream = function onEndOfStream() {
- var isEndOfStream = this.mainSegmentLoader_.ended_;
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- // if the audio playlist loader exists, then alternate audio is active
- if (!this.mainSegmentLoader_.currentMediaInfo_ || this.mainSegmentLoader_.currentMediaInfo_.hasVideo) {
- // if we do not know if the main segment loader contains video yet or if we
- // definitively know the main segment loader contains video, then we need to wait
- // for both main and audio segment loaders to call endOfStream
- isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
- } else {
- // otherwise just rely on the audio loader
- isEndOfStream = this.audioSegmentLoader_.ended_;
- }
- }
-
- if (!isEndOfStream) {
- return;
- }
-
- this.stopABRTimer_();
- this.sourceUpdater_.endOfStream();
- }
- /**
- * Check if a playlist has stopped being updated
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist has stopped being updated or not
- */
- ;
-
- _proto.stuckAtPlaylistEnd_ = function stuckAtPlaylistEnd_(playlist) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- // playlist doesn't have enough information to determine whether we are stuck
- return false;
- }
-
- var expired = this.syncController_.getExpiredTime(playlist, this.duration());
-
- if (expired === null) {
- return false;
- } // does not use the safe live end to calculate playlist end, since we
- // don't want to say we are stuck while there is still content
-
-
- var absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
-
- if (!buffered.length) {
- // return true if the playhead reached the absolute end of the playlist
- return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
- }
-
- var bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
- // end of playlist
-
- return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
- }
- /**
- * Blacklists a playlist when an error occurs for a set amount of time
- * making it unavailable for selection by the rendition selection algorithm
- * and then forces a new playlist (rendition) selection.
- *
- * @param {Object=} error an optional error that may include the playlist
- * to blacklist
- * @param {number=} blacklistDuration an optional number of seconds to blacklist the
- * playlist
- */
- ;
-
- _proto.blacklistCurrentPlaylist = function blacklistCurrentPlaylist(error, blacklistDuration) {
- if (error === void 0) {
- error = {};
- }
-
- // If the `error` was generated by the playlist loader, it will contain
- // the playlist we were trying to load (but failed) and that should be
- // blacklisted instead of the currently selected playlist which is likely
- // out-of-date in this scenario
- var currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
- blacklistDuration = blacklistDuration || error.blacklistDuration || this.blacklistDuration; // If there is no current playlist, then an error occurred while we were
- // trying to load the master OR while we were disposing of the tech
-
- if (!currentPlaylist) {
- this.error = error;
-
- if (this.mediaSource.readyState !== 'open') {
- this.trigger('error');
- } else {
- this.sourceUpdater_.endOfStream('network');
- }
-
- return;
- }
-
- currentPlaylist.playlistErrors_++;
- var playlists = this.masterPlaylistLoader_.master.playlists;
- var enabledPlaylists = playlists.filter(isEnabled);
- var isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === currentPlaylist; // Don't blacklist the only playlist unless it was blacklisted
- // forever
-
- if (playlists.length === 1 && blacklistDuration !== Infinity) {
- videojs__default['default'].log.warn("Problem encountered with playlist " + currentPlaylist.id + ". " + 'Trying again since it is the only playlist.');
- this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
-
- return this.masterPlaylistLoader_.load(isFinalRendition);
- }
-
- if (isFinalRendition) {
- // Since we're on the final non-blacklisted playlist, and we're about to blacklist
- // it, instead of erring the player or retrying this playlist, clear out the current
- // blacklist. This allows other playlists to be attempted in case any have been
- // fixed.
- var reincluded = false;
- playlists.forEach(function (playlist) {
- // skip current playlist which is about to be blacklisted
- if (playlist === currentPlaylist) {
- return;
- }
-
- var excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
-
- if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
- reincluded = true;
- delete playlist.excludeUntil;
- }
- });
-
- if (reincluded) {
- videojs__default['default'].log.warn('Removing other playlists from the exclusion list because the last ' + 'rendition is about to be excluded.'); // Technically we are retrying a playlist, in that we are simply retrying a previous
- // playlist. This is needed for users relying on the retryplaylist event to catch a
- // case where the player might be stuck and looping through "dead" playlists.
-
- this.tech_.trigger('retryplaylist');
- }
- } // Blacklist this playlist
-
-
- var excludeUntil;
-
- if (currentPlaylist.playlistErrors_ > this.maxPlaylistRetries) {
- excludeUntil = Infinity;
- } else {
- excludeUntil = Date.now() + blacklistDuration * 1000;
- }
-
- currentPlaylist.excludeUntil = excludeUntil;
-
- if (error.reason) {
- currentPlaylist.lastExcludeReason_ = error.reason;
- }
-
- this.tech_.trigger('blacklistplaylist');
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-blacklisted'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-blacklisted'
- }); // TODO: should we select a new playlist if this blacklist wasn't for the currentPlaylist?
- // Would be something like media().id !=== currentPlaylist.id and we would need something
- // like `pendingMedia` in playlist loaders to check against that too. This will prevent us
- // from loading a new playlist on any blacklist.
- // Select a new playlist
-
- var nextPlaylist = this.selectPlaylist();
-
- if (!nextPlaylist) {
- this.error = 'Playback cannot continue. No available working or supported playlists.';
- this.trigger('error');
- return;
- }
-
- var logFn = error.internal ? this.logger_ : videojs__default['default'].log.warn;
- var errorMessage = error.message ? ' ' + error.message : '';
- logFn((error.internal ? 'Internal problem' : 'Problem') + " encountered with playlist " + currentPlaylist.id + "." + (errorMessage + " Switching to playlist " + nextPlaylist.id + ".")); // if audio group changed reset audio loaders
-
- if (nextPlaylist.attributes.AUDIO !== currentPlaylist.attributes.AUDIO) {
- this.delegateLoaders_('audio', ['abort', 'pause']);
- } // if subtitle group changed reset subtitle loaders
-
-
- if (nextPlaylist.attributes.SUBTITLES !== currentPlaylist.attributes.SUBTITLES) {
- this.delegateLoaders_('subtitle', ['abort', 'pause']);
- }
-
- this.delegateLoaders_('main', ['abort', 'pause']);
- var delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
- var shouldDelay = typeof nextPlaylist.lastRequest === 'number' && Date.now() - nextPlaylist.lastRequest <= delayDuration; // delay if it's a final rendition or if the last refresh is sooner than half targetDuration
-
- return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
- }
- /**
- * Pause all segment/playlist loaders
- */
- ;
-
- _proto.pauseLoading = function pauseLoading() {
- this.delegateLoaders_('all', ['abort', 'pause']);
- this.stopABRTimer_();
- }
- /**
- * Call a set of functions in order on playlist loaders, segment loaders,
- * or both types of loaders.
- *
- * @param {string} filter
- * Filter loaders that should call fnNames using a string. Can be:
- * * all - run on all loaders
- * * audio - run on all audio loaders
- * * subtitle - run on all subtitle loaders
- * * main - run on the main/master loaders
- *
- * @param {Array|string} fnNames
- * A string or array of function names to call.
- */
- ;
-
- _proto.delegateLoaders_ = function delegateLoaders_(filter, fnNames) {
- var _this7 = this;
-
- var loaders = [];
- var dontFilterPlaylist = filter === 'all';
-
- if (dontFilterPlaylist || filter === 'main') {
- loaders.push(this.masterPlaylistLoader_);
- }
-
- var mediaTypes = [];
-
- if (dontFilterPlaylist || filter === 'audio') {
- mediaTypes.push('AUDIO');
- }
-
- if (dontFilterPlaylist || filter === 'subtitle') {
- mediaTypes.push('CLOSED-CAPTIONS');
- mediaTypes.push('SUBTITLES');
- }
-
- mediaTypes.forEach(function (mediaType) {
- var loader = _this7.mediaTypes_[mediaType] && _this7.mediaTypes_[mediaType].activePlaylistLoader;
-
- if (loader) {
- loaders.push(loader);
- }
- });
- ['main', 'audio', 'subtitle'].forEach(function (name) {
- var loader = _this7[name + "SegmentLoader_"];
-
- if (loader && (filter === name || filter === 'all')) {
- loaders.push(loader);
- }
- });
- loaders.forEach(function (loader) {
- return fnNames.forEach(function (fnName) {
- if (typeof loader[fnName] === 'function') {
- loader[fnName]();
- }
- });
- });
- }
- /**
- * set the current time on all segment loaders
- *
- * @param {TimeRange} currentTime the current time to set
- * @return {TimeRange} the current time
- */
- ;
-
- _proto.setCurrentTime = function setCurrentTime(currentTime) {
- var buffered = findRange(this.tech_.buffered(), currentTime);
-
- if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
- // return immediately if the metadata is not ready yet
- return 0;
- } // it's clearly an edge-case but don't thrown an error if asked to
- // seek within an empty playlist
-
-
- if (!this.masterPlaylistLoader_.media().segments) {
- return 0;
- } // if the seek location is already buffered, continue buffering as usual
-
-
- if (buffered && buffered.length) {
- return currentTime;
- } // cancel outstanding requests so we begin buffering at the new
- // location
-
-
- this.mainSegmentLoader_.resetEverything();
- this.mainSegmentLoader_.abort();
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.resetEverything();
- this.audioSegmentLoader_.abort();
- }
-
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.resetEverything();
- this.subtitleSegmentLoader_.abort();
- } // start segment loader loading in case they are paused
-
-
- this.load();
- }
- /**
- * get the current duration
- *
- * @return {TimeRange} the duration
- */
- ;
-
- _proto.duration = function duration() {
- if (!this.masterPlaylistLoader_) {
- return 0;
- }
-
- var media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- // no playlists loaded yet, so can't determine a duration
- return 0;
- } // Don't rely on the media source for duration in the case of a live playlist since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, just return Infinity.
-
-
- if (!media.endList) {
- return Infinity;
- } // Since this is a VOD video, it is safe to rely on the media source's duration (if
- // available). If it's not available, fall back to a playlist-calculated estimate.
-
-
- if (this.mediaSource) {
- return this.mediaSource.duration;
- }
-
- return Vhs$1.Playlist.duration(media);
- }
- /**
- * check the seekable range
- *
- * @return {TimeRange} the seekable range
- */
- ;
-
- _proto.seekable = function seekable() {
- return this.seekable_;
- };
-
- _proto.onSyncInfoUpdate_ = function onSyncInfoUpdate_() {
- var audioSeekable;
-
- if (!this.masterPlaylistLoader_) {
- return;
- }
-
- var media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- return;
- }
-
- var expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- // not enough information to update seekable
- return;
- }
-
- var master = this.masterPlaylistLoader_.master;
- var mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
-
- if (mainSeekable.length === 0) {
- return;
- }
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
- expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- return;
- }
-
- audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
-
- if (audioSeekable.length === 0) {
- return;
- }
- }
-
- var oldEnd;
- var oldStart;
-
- if (this.seekable_ && this.seekable_.length) {
- oldEnd = this.seekable_.end(0);
- oldStart = this.seekable_.start(0);
- }
-
- if (!audioSeekable) {
- // seekable has been calculated based on buffering video data so it
- // can be returned directly
- this.seekable_ = mainSeekable;
- } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
- // seekables are pretty far off, rely on main
- this.seekable_ = mainSeekable;
- } else {
- this.seekable_ = videojs__default['default'].createTimeRanges([[audioSeekable.start(0) > mainSeekable.start(0) ? audioSeekable.start(0) : mainSeekable.start(0), audioSeekable.end(0) < mainSeekable.end(0) ? audioSeekable.end(0) : mainSeekable.end(0)]]);
- } // seekable is the same as last time
-
-
- if (this.seekable_ && this.seekable_.length) {
- if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
- return;
- }
- }
-
- this.logger_("seekable updated [" + printableRange(this.seekable_) + "]");
- this.tech_.trigger('seekablechanged');
- }
- /**
- * Update the player duration
- */
- ;
-
- _proto.updateDuration = function updateDuration(isLive) {
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- this.updateDuration_ = null;
- }
-
- if (this.mediaSource.readyState !== 'open') {
- this.updateDuration_ = this.updateDuration.bind(this, isLive);
- this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
- return;
- }
-
- if (isLive) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- return;
- } // Even in the case of a live playlist, the native MediaSource's duration should not
- // be set to Infinity (even though this would be expected for a live playlist), since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, the duration should be greater than or
- // equal to the last possible seekable value.
- // MediaSource duration starts as NaN
- // It is possible (and probable) that this case will never be reached for many
- // sources, since the MediaSource reports duration as the highest value without
- // accounting for timestamp offset. For example, if the timestamp offset is -100 and
- // we buffered times 0 to 100 with real times of 100 to 200, even though current
- // time will be between 0 and 100, the native media source may report the duration
- // as 200. However, since we report duration separate from the media source (as
- // Infinity), and as long as the native media source duration value is greater than
- // our reported seekable range, seeks will work as expected. The large number as
- // duration for live is actually a strategy used by some players to work around the
- // issue of live seekable ranges cited above.
-
-
- if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
- this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
- }
-
- return;
- }
-
- var buffered = this.tech_.buffered();
- var duration = Vhs$1.Playlist.duration(this.masterPlaylistLoader_.media());
-
- if (buffered.length > 0) {
- duration = Math.max(duration, buffered.end(buffered.length - 1));
- }
-
- if (this.mediaSource.duration !== duration) {
- this.sourceUpdater_.setDuration(duration);
- }
- }
- /**
- * dispose of the MasterPlaylistController and everything
- * that it controls
- */
- ;
-
- _proto.dispose = function dispose() {
- var _this8 = this;
-
- this.trigger('dispose');
- this.decrypter_.terminate();
- this.masterPlaylistLoader_.dispose();
- this.mainSegmentLoader_.dispose();
-
- if (this.loadOnPlay_) {
- this.tech_.off('play', this.loadOnPlay_);
- }
-
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- var groups = _this8.mediaTypes_[type].groups;
-
- for (var id in groups) {
- groups[id].forEach(function (group) {
- if (group.playlistLoader) {
- group.playlistLoader.dispose();
- }
- });
- }
- });
- this.audioSegmentLoader_.dispose();
- this.subtitleSegmentLoader_.dispose();
- this.sourceUpdater_.dispose();
- this.timelineChangeController_.dispose();
- this.stopABRTimer_();
-
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- }
-
- this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
-
- this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
- this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
- this.off();
- }
- /**
- * return the master playlist object if we have one
- *
- * @return {Object} the master playlist object that we parsed
- */
- ;
-
- _proto.master = function master() {
- return this.masterPlaylistLoader_.master;
- }
- /**
- * return the currently selected playlist
- *
- * @return {Object} the currently selected playlist object that we parsed
- */
- ;
-
- _proto.media = function media() {
- // playlist loader will not return media if it has not been fully loaded
- return this.masterPlaylistLoader_.media() || this.initialMedia_;
- };
-
- _proto.areMediaTypesKnown_ = function areMediaTypesKnown_() {
- var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader; // one or both loaders has not loaded sufficently to get codecs
-
- if (!this.mainSegmentLoader_.currentMediaInfo_ || usingAudioLoader && !this.audioSegmentLoader_.currentMediaInfo_) {
- return false;
- }
-
- return true;
- };
-
- _proto.getCodecsOrExclude_ = function getCodecsOrExclude_() {
- var _this9 = this;
-
- var media = {
- main: this.mainSegmentLoader_.currentMediaInfo_ || {},
- audio: this.audioSegmentLoader_.currentMediaInfo_ || {}
- }; // set "main" media equal to video
-
- media.video = media.main;
- var playlistCodecs = codecsForPlaylist(this.master(), this.media());
- var codecs = {};
- var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
-
- if (media.main.hasVideo) {
- codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
- }
-
- if (media.main.isMuxed) {
- codecs.video += "," + (playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC);
- }
-
- if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
- codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
-
- media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
- } // no codecs, no playback.
-
-
- if (!codecs.audio && !codecs.video) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: 'Could not determine codecs for playlist.',
- blacklistDuration: Infinity
- });
- return;
- } // fmp4 relies on browser support, while ts relies on muxer support
-
-
- var supportFunction = function supportFunction(isFmp4, codec) {
- return isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
- };
-
- var unsupportedCodecs = {};
- var unsupportedAudio;
- ['video', 'audio'].forEach(function (type) {
- if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
- var supporter = media[type].isFmp4 ? 'browser' : 'muxer';
- unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
- unsupportedCodecs[supporter].push(codecs[type]);
-
- if (type === 'audio') {
- unsupportedAudio = supporter;
- }
- }
- });
-
- if (usingAudioLoader && unsupportedAudio && this.media().attributes.AUDIO) {
- var audioGroup = this.media().attributes.AUDIO;
- this.master().playlists.forEach(function (variant) {
- var variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
-
- if (variantAudioGroup === audioGroup && variant !== _this9.media()) {
- variant.excludeUntil = Infinity;
- }
- });
- this.logger_("excluding audio group " + audioGroup + " as " + unsupportedAudio + " does not support codec(s): \"" + codecs.audio + "\"");
- } // if we have any unsupported codecs blacklist this playlist.
-
-
- if (Object.keys(unsupportedCodecs).length) {
- var message = Object.keys(unsupportedCodecs).reduce(function (acc, supporter) {
- if (acc) {
- acc += ', ';
- }
-
- acc += supporter + " does not support codec(s): \"" + unsupportedCodecs[supporter].join(',') + "\"";
- return acc;
- }, '') + '.';
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- internal: true,
- message: message,
- blacklistDuration: Infinity
- });
- return;
- } // check if codec switching is happening
-
-
- if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
- var switchMessages = [];
- ['video', 'audio'].forEach(function (type) {
- var newCodec = (parseCodecs(_this9.sourceUpdater_.codecs[type] || '')[0] || {}).type;
- var oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
-
- if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
- switchMessages.push("\"" + _this9.sourceUpdater_.codecs[type] + "\" -> \"" + codecs[type] + "\"");
- }
- });
-
- if (switchMessages.length) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: "Codec switching not supported: " + switchMessages.join(', ') + ".",
- blacklistDuration: Infinity,
- internal: true
- });
- return;
- }
- } // TODO: when using the muxer shouldn't we just return
- // the codecs that the muxer outputs?
-
-
- return codecs;
- }
- /**
- * Create source buffers and exlude any incompatible renditions.
- *
- * @private
- */
- ;
-
- _proto.tryToCreateSourceBuffers_ = function tryToCreateSourceBuffers_() {
- // media source is not ready yet or sourceBuffers are already
- // created.
- if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
- return;
- }
-
- if (!this.areMediaTypesKnown_()) {
- return;
- }
-
- var codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
-
- if (!codecs) {
- return;
- }
-
- this.sourceUpdater_.createSourceBuffers(codecs);
- var codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
- this.excludeIncompatibleVariants_(codecString);
- }
- /**
- * Excludes playlists with codecs that are unsupported by the muxer and browser.
- */
- ;
-
- _proto.excludeUnsupportedVariants_ = function excludeUnsupportedVariants_() {
- var _this10 = this;
-
- var playlists = this.master().playlists;
- var ids = []; // TODO: why don't we have a property to loop through all
- // playlist? Why did we ever mix indexes and keys?
-
- Object.keys(playlists).forEach(function (key) {
- var variant = playlists[key]; // check if we already processed this playlist.
-
- if (ids.indexOf(variant.id) !== -1) {
- return;
- }
-
- ids.push(variant.id);
- var codecs = codecsForPlaylist(_this10.master, variant);
- var unsupported = [];
-
- if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
- unsupported.push("audio codec " + codecs.audio);
- }
-
- if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
- unsupported.push("video codec " + codecs.video);
- }
-
- if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
- unsupported.push("text codec " + codecs.text);
- }
-
- if (unsupported.length) {
- variant.excludeUntil = Infinity;
-
- _this10.logger_("excluding " + variant.id + " for unsupported: " + unsupported.join(', '));
- }
- });
- }
- /**
- * Blacklist playlists that are known to be codec or
- * stream-incompatible with the SourceBuffer configuration. For
- * instance, Media Source Extensions would cause the video element to
- * stall waiting for video data if you switched from a variant with
- * video and audio to an audio-only one.
- *
- * @param {Object} media a media playlist compatible with the current
- * set of SourceBuffers. Variants in the current master playlist that
- * do not appear to have compatible codec or stream configurations
- * will be excluded from the default playlist selection algorithm
- * indefinitely.
- * @private
- */
- ;
-
- _proto.excludeIncompatibleVariants_ = function excludeIncompatibleVariants_(codecString) {
- var _this11 = this;
-
- var ids = [];
- var playlists = this.master().playlists;
- var codecs = unwrapCodecList(parseCodecs(codecString));
- var codecCount_ = codecCount(codecs);
- var videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
- var audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
- Object.keys(playlists).forEach(function (key) {
- var variant = playlists[key]; // check if we already processed this playlist.
- // or it if it is already excluded forever.
-
- if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
- return;
- }
-
- ids.push(variant.id);
- var blacklistReasons = []; // get codecs from the playlist for this variant
-
- var variantCodecs = codecsForPlaylist(_this11.masterPlaylistLoader_.master, variant);
- var variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
- // variant is incompatible. Wait for mux.js to probe
-
- if (!variantCodecs.audio && !variantCodecs.video) {
- return;
- } // TODO: we can support this by removing the
- // old media source and creating a new one, but it will take some work.
- // The number of streams cannot change
-
-
- if (variantCodecCount !== codecCount_) {
- blacklistReasons.push("codec count \"" + variantCodecCount + "\" !== \"" + codecCount_ + "\"");
- } // only exclude playlists by codec change, if codecs cannot switch
- // during playback.
-
-
- if (!_this11.sourceUpdater_.canChangeType()) {
- var variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
- var variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
-
- if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
- blacklistReasons.push("video codec \"" + variantVideoDetails.type + "\" !== \"" + videoDetails.type + "\"");
- } // the audio codec cannot change
-
-
- if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
- blacklistReasons.push("audio codec \"" + variantAudioDetails.type + "\" !== \"" + audioDetails.type + "\"");
- }
- }
-
- if (blacklistReasons.length) {
- variant.excludeUntil = Infinity;
-
- _this11.logger_("blacklisting " + variant.id + ": " + blacklistReasons.join(' && '));
- }
- });
- };
-
- _proto.updateAdCues_ = function updateAdCues_(media) {
- var offset = 0;
- var seekable = this.seekable();
-
- if (seekable.length) {
- offset = seekable.start(0);
- }
-
- updateAdCues(media, this.cueTagsTrack_, offset);
- }
- /**
- * Calculates the desired forward buffer length based on current time
- *
- * @return {number} Desired forward buffer length in seconds
- */
- ;
-
- _proto.goalBufferLength = function goalBufferLength() {
- var currentTime = this.tech_.currentTime();
- var initial = Config.GOAL_BUFFER_LENGTH;
- var rate = Config.GOAL_BUFFER_LENGTH_RATE;
- var max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
- return Math.min(initial + currentTime * rate, max);
- }
- /**
- * Calculates the desired buffer low water line based on current time
- *
- * @return {number} Desired buffer low water line in seconds
- */
- ;
-
- _proto.bufferLowWaterLine = function bufferLowWaterLine() {
- var currentTime = this.tech_.currentTime();
- var initial = Config.BUFFER_LOW_WATER_LINE;
- var rate = Config.BUFFER_LOW_WATER_LINE_RATE;
- var max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
- var newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
- return Math.min(initial + currentTime * rate, this.experimentalBufferBasedABR ? newMax : max);
- };
-
- _proto.bufferHighWaterLine = function bufferHighWaterLine() {
- return Config.BUFFER_HIGH_WATER_LINE;
- };
-
- return MasterPlaylistController;
- }(videojs__default['default'].EventTarget);
-
- /**
- * Returns a function that acts as the Enable/disable playlist function.
- *
- * @param {PlaylistLoader} loader - The master playlist loader
- * @param {string} playlistID - id of the playlist
- * @param {Function} changePlaylistFn - A function to be called after a
- * playlist's enabled-state has been changed. Will NOT be called if a
- * playlist's enabled-state is unchanged
- * @param {boolean=} enable - Value to set the playlist enabled-state to
- * or if undefined returns the current enabled-state for the playlist
- * @return {Function} Function for setting/getting enabled
- */
-
- var enableFunction = function enableFunction(loader, playlistID, changePlaylistFn) {
- return function (enable) {
- var playlist = loader.master.playlists[playlistID];
- var incompatible = isIncompatible(playlist);
- var currentlyEnabled = isEnabled(playlist);
-
- if (typeof enable === 'undefined') {
- return currentlyEnabled;
- }
-
- if (enable) {
- delete playlist.disabled;
- } else {
- playlist.disabled = true;
- }
-
- if (enable !== currentlyEnabled && !incompatible) {
- // Ensure the outside world knows about our changes
- changePlaylistFn();
-
- if (enable) {
- loader.trigger('renditionenabled');
- } else {
- loader.trigger('renditiondisabled');
- }
- }
-
- return enable;
- };
- };
- /**
- * The representation object encapsulates the publicly visible information
- * in a media playlist along with a setter/getter-type function (enabled)
- * for changing the enabled-state of a particular playlist entry
- *
- * @class Representation
- */
-
-
- var Representation = function Representation(vhsHandler, playlist, id) {
- var mpc = vhsHandler.masterPlaylistController_,
- smoothQualityChange = vhsHandler.options_.smoothQualityChange; // Get a reference to a bound version of the quality change function
-
- var changeType = smoothQualityChange ? 'smooth' : 'fast';
- var qualityChangeFunction = mpc[changeType + "QualityChange_"].bind(mpc); // some playlist attributes are optional
-
- if (playlist.attributes) {
- var resolution = playlist.attributes.RESOLUTION;
- this.width = resolution && resolution.width;
- this.height = resolution && resolution.height;
- this.bandwidth = playlist.attributes.BANDWIDTH;
- }
-
- this.codecs = codecsForPlaylist(mpc.master(), playlist);
- this.playlist = playlist; // The id is simply the ordinality of the media playlist
- // within the master playlist
-
- this.id = id; // Partially-apply the enableFunction to create a playlist-
- // specific variant
-
- this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
- };
- /**
- * A mixin function that adds the `representations` api to an instance
- * of the VhsHandler class
- *
- * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
- * representation API into
- */
-
-
- var renditionSelectionMixin = function renditionSelectionMixin(vhsHandler) {
- // Add a single API-specific function to the VhsHandler instance
- vhsHandler.representations = function () {
- var master = vhsHandler.masterPlaylistController_.master();
- var playlists = isAudioOnly(master) ? vhsHandler.masterPlaylistController_.getAudioTrackPlaylists_() : master.playlists;
-
- if (!playlists) {
- return [];
- }
-
- return playlists.filter(function (media) {
- return !isIncompatible(media);
- }).map(function (e, i) {
- return new Representation(vhsHandler, e, e.id);
- });
- };
- };
-
- /**
- * @file playback-watcher.js
- *
- * Playback starts, and now my watch begins. It shall not end until my death. I shall
- * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
- * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
- * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
- * my life and honor to the Playback Watch, for this Player and all the Players to come.
- */
-
- var timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
- /**
- * Returns whether or not the current time should be considered close to buffered content,
- * taking into consideration whether there's enough buffered content for proper playback.
- *
- * @param {Object} options
- * Options object
- * @param {TimeRange} options.buffered
- * Current buffer
- * @param {number} options.targetDuration
- * The active playlist's target duration
- * @param {number} options.currentTime
- * The current time of the player
- * @return {boolean}
- * Whether the current time should be considered close to the buffer
- */
-
- var closeToBufferedContent = function closeToBufferedContent(_ref) {
- var buffered = _ref.buffered,
- targetDuration = _ref.targetDuration,
- currentTime = _ref.currentTime;
-
- if (!buffered.length) {
- return false;
- } // At least two to three segments worth of content should be buffered before there's a
- // full enough buffer to consider taking any actions.
-
-
- if (buffered.end(0) - buffered.start(0) < targetDuration * 2) {
- return false;
- } // It's possible that, on seek, a remove hasn't completed and the buffered range is
- // somewhere past the current time. In that event, don't consider the buffered content
- // close.
-
-
- if (currentTime > buffered.start(0)) {
- return false;
- } // Since target duration generally represents the max (or close to max) duration of a
- // segment, if the buffer is within a segment of the current time, the gap probably
- // won't be closed, and current time should be considered close to buffered content.
-
-
- return buffered.start(0) - currentTime < targetDuration;
- };
- /**
- * @class PlaybackWatcher
- */
-
- var PlaybackWatcher = /*#__PURE__*/function () {
- /**
- * Represents an PlaybackWatcher object.
- *
- * @class
- * @param {Object} options an object that includes the tech and settings
- */
- function PlaybackWatcher(options) {
- var _this = this;
-
- this.masterPlaylistController_ = options.masterPlaylistController;
- this.tech_ = options.tech;
- this.seekable = options.seekable;
- this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
- this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
- this.media = options.media;
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = null;
- this.timer_ = null;
- this.checkCurrentTimeTimeout_ = null;
- this.logger_ = logger('PlaybackWatcher');
- this.logger_('initialize');
-
- var playHandler = function playHandler() {
- return _this.monitorCurrentTime_();
- };
-
- var canPlayHandler = function canPlayHandler() {
- return _this.monitorCurrentTime_();
- };
-
- var waitingHandler = function waitingHandler() {
- return _this.techWaiting_();
- };
-
- var cancelTimerHandler = function cancelTimerHandler() {
- return _this.cancelTimer_();
- };
-
- var fixesBadSeeksHandler = function fixesBadSeeksHandler() {
- return _this.fixesBadSeeks_();
- };
-
- var mpc = this.masterPlaylistController_;
- var loaderTypes = ['main', 'subtitle', 'audio'];
- var loaderChecks = {};
- loaderTypes.forEach(function (type) {
- loaderChecks[type] = {
- reset: function reset() {
- return _this.resetSegmentDownloads_(type);
- },
- updateend: function updateend() {
- return _this.checkSegmentDownloads_(type);
- }
- };
- mpc[type + "SegmentLoader_"].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
- // isn't changing we want to reset. We cannot assume that the new rendition
- // will also be stalled, until after new appends.
-
- mpc[type + "SegmentLoader_"].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
- // This prevents one segment playlists (single vtt or single segment content)
- // from being detected as stalling. As the buffer will not change in those cases, since
- // the buffer is the entire video duration.
-
- _this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
- });
- this.tech_.on('seekablechanged', fixesBadSeeksHandler);
- this.tech_.on('waiting', waitingHandler);
- this.tech_.on(timerCancelEvents, cancelTimerHandler);
- this.tech_.on('canplay', canPlayHandler);
- /*
- An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
- is surfaced in one of two ways:
- 1) The `waiting` event is fired before the player has buffered content, making it impossible
- to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
- we can check if playback is stalled due to a gap, and skip the gap if necessary.
- 2) A source with a gap at the beginning of the stream is loaded programatically while the player
- is in a playing state. To catch this case, it's important that our one-time play listener is setup
- even if the player is in a playing state
- */
-
- this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
-
- this.dispose = function () {
- _this.logger_('dispose');
-
- _this.tech_.off('seekablechanged', fixesBadSeeksHandler);
-
- _this.tech_.off('waiting', waitingHandler);
-
- _this.tech_.off(timerCancelEvents, cancelTimerHandler);
-
- _this.tech_.off('canplay', canPlayHandler);
-
- _this.tech_.off('play', playHandler);
-
- loaderTypes.forEach(function (type) {
- mpc[type + "SegmentLoader_"].off('appendsdone', loaderChecks[type].updateend);
- mpc[type + "SegmentLoader_"].off('playlistupdate', loaderChecks[type].reset);
-
- _this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
- });
-
- if (_this.checkCurrentTimeTimeout_) {
- window__default['default'].clearTimeout(_this.checkCurrentTimeTimeout_);
- }
-
- _this.cancelTimer_();
- };
- }
- /**
- * Periodically check current time to see if playback stopped
- *
- * @private
- */
-
-
- var _proto = PlaybackWatcher.prototype;
-
- _proto.monitorCurrentTime_ = function monitorCurrentTime_() {
- this.checkCurrentTime_();
-
- if (this.checkCurrentTimeTimeout_) {
- window__default['default'].clearTimeout(this.checkCurrentTimeTimeout_);
- } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
-
-
- this.checkCurrentTimeTimeout_ = window__default['default'].setTimeout(this.monitorCurrentTime_.bind(this), 250);
- }
- /**
- * Reset stalled download stats for a specific type of loader
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#playlistupdate
- * @listens Tech#seeking
- * @listens Tech#seeked
- */
- ;
-
- _proto.resetSegmentDownloads_ = function resetSegmentDownloads_(type) {
- var loader = this.masterPlaylistController_[type + "SegmentLoader_"];
-
- if (this[type + "StalledDownloads_"] > 0) {
- this.logger_("resetting possible stalled download count for " + type + " loader");
- }
-
- this[type + "StalledDownloads_"] = 0;
- this[type + "Buffered_"] = loader.buffered_();
- }
- /**
- * Checks on every segment `appendsdone` to see
- * if segment appends are making progress. If they are not
- * and we are still downloading bytes. We blacklist the playlist.
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#appendsdone
- */
- ;
-
- _proto.checkSegmentDownloads_ = function checkSegmentDownloads_(type) {
- var mpc = this.masterPlaylistController_;
- var loader = mpc[type + "SegmentLoader_"];
- var buffered = loader.buffered_();
- var isBufferedDifferent = isRangeDifferent(this[type + "Buffered_"], buffered);
- this[type + "Buffered_"] = buffered; // if another watcher is going to fix the issue or
- // the buffered value for this loader changed
- // appends are working
-
- if (isBufferedDifferent) {
- this.resetSegmentDownloads_(type);
- return;
- }
-
- this[type + "StalledDownloads_"]++;
- this.logger_("found #" + this[type + "StalledDownloads_"] + " " + type + " appends that did not increase buffer (possible stalled download)", {
- playlistId: loader.playlist_ && loader.playlist_.id,
- buffered: timeRangesToArray(buffered)
- }); // after 10 possibly stalled appends with no reset, exclude
-
- if (this[type + "StalledDownloads_"] < 10) {
- return;
- }
-
- this.logger_(type + " loader stalled download exclusion");
- this.resetSegmentDownloads_(type);
- this.tech_.trigger({
- type: 'usage',
- name: "vhs-" + type + "-download-exclusion"
- });
-
- if (type === 'subtitle') {
- return;
- } // TODO: should we exclude audio tracks rather than main tracks
- // when type is audio?
-
-
- mpc.blacklistCurrentPlaylist({
- message: "Excessive " + type + " segment downloading detected."
- }, Infinity);
- }
- /**
- * The purpose of this function is to emulate the "waiting" event on
- * browsers that do not emit it when they are waiting for more
- * data to continue playback
- *
- * @private
- */
- ;
-
- _proto.checkCurrentTime_ = function checkCurrentTime_() {
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = this.tech_.currentTime();
- return;
- }
-
- if (this.tech_.paused() || this.tech_.seeking()) {
- return;
- }
-
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
-
- if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
- // If current time is at the end of the final buffered region, then any playback
- // stall is most likely caused by buffering in a low bandwidth environment. The tech
- // should fire a `waiting` event in this scenario, but due to browser and tech
- // inconsistencies. Calling `techWaiting_` here allows us to simulate
- // responding to a native `waiting` event when the tech fails to emit one.
- return this.techWaiting_();
- }
-
- if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- this.waiting_();
- } else if (currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- } else {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = currentTime;
- }
- }
- /**
- * Cancels any pending timers and resets the 'timeupdate' mechanism
- * designed to detect that we are stalled
- *
- * @private
- */
- ;
-
- _proto.cancelTimer_ = function cancelTimer_() {
- this.consecutiveUpdates = 0;
-
- if (this.timer_) {
- this.logger_('cancelTimer_');
- clearTimeout(this.timer_);
- }
-
- this.timer_ = null;
- }
- /**
- * Fixes situations where there's a bad seek
- *
- * @return {boolean} whether an action was taken to fix the seek
- * @private
- */
- ;
-
- _proto.fixesBadSeeks_ = function fixesBadSeeks_() {
- var seeking = this.tech_.seeking();
-
- if (!seeking) {
- return false;
- }
-
- var seekable = this.seekable();
- var currentTime = this.tech_.currentTime();
- var isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
- var seekTo;
-
- if (isAfterSeekableRange) {
- var seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
-
- seekTo = seekableEnd;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- var seekableStart = seekable.start(0); // sync to the beginning of the live window
- // provide a buffer of .1 seconds to handle rounding/imprecise numbers
-
- seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
- // happen in live with a 3 segment playlist), then don't use a time delta
- seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
- }
-
- if (typeof seekTo !== 'undefined') {
- this.logger_("Trying to seek outside of seekable at time " + currentTime + " with " + ("seekable range " + printableRange(seekable) + ". Seeking to ") + (seekTo + "."));
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- var buffered = this.tech_.buffered();
-
- if (closeToBufferedContent({
- buffered: buffered,
- targetDuration: this.media().targetDuration,
- currentTime: currentTime
- })) {
- seekTo = buffered.start(0) + SAFE_TIME_DELTA;
- this.logger_("Buffered region starts (" + buffered.start(0) + ") " + (" just beyond seek point (" + currentTime + "). Seeking to " + seekTo + "."));
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- return false;
- }
- /**
- * Handler for situations when we determine the player is waiting.
- *
- * @private
- */
- ;
-
- _proto.waiting_ = function waiting_() {
- if (this.techWaiting_()) {
- return;
- } // All tech waiting checks failed. Use last resort correction
-
-
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
- var currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
- // region with no indication that anything is amiss (seen in Firefox). Seeking to
- // currentTime is usually enough to kickstart the player. This checks that the player
- // is currently within a buffered region before attempting a corrective seek.
- // Chrome does not appear to continue `timeupdate` events after a `waiting` event
- // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
- // make sure there is ~3 seconds of forward buffer before taking any corrective action
- // to avoid triggering an `unknownwaiting` event when the network is slow.
-
- if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime);
- this.logger_("Stopped at " + currentTime + " while inside a buffered region " + ("[" + currentRange.start(0) + " -> " + currentRange.end(0) + "]. Attempting to resume ") + 'playback by seeking to the current time.'); // unknown waiting corrections may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-unknown-waiting'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-unknown-waiting'
- });
- return;
- }
- }
- /**
- * Handler for situations when the tech fires a `waiting` event
- *
- * @return {boolean}
- * True if an action (or none) was needed to correct the waiting. False if no
- * checks passed
- * @private
- */
- ;
-
- _proto.techWaiting_ = function techWaiting_() {
- var seekable = this.seekable();
- var currentTime = this.tech_.currentTime();
-
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- // Tech is seeking or bad seek fixed, no action needed
- return true;
- }
-
- if (this.tech_.seeking() || this.timer_ !== null) {
- // Tech is seeking or already waiting on another action, no action needed
- return true;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- var livePoint = seekable.end(seekable.length - 1);
- this.logger_("Fell out of live window at time " + currentTime + ". Seeking to " + ("live point (seekable end) " + livePoint));
- this.cancelTimer_();
- this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-live-resync'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-live-resync'
- });
- return true;
- }
-
- var sourceUpdater = this.tech_.vhs.masterPlaylistController_.sourceUpdater_;
- var buffered = this.tech_.buffered();
- var videoUnderflow = this.videoUnderflow_({
- audioBuffered: sourceUpdater.audioBuffered(),
- videoBuffered: sourceUpdater.videoBuffered(),
- currentTime: currentTime
- });
-
- if (videoUnderflow) {
- // Even though the video underflowed and was stuck in a gap, the audio overplayed
- // the gap, leading currentTime into a buffered range. Seeking to currentTime
- // allows the video to catch up to the audio position without losing any audio
- // (only suffering ~3 seconds of frozen video and a pause in audio playback).
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-video-underflow'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-video-underflow'
- });
- return true;
- }
-
- var nextRange = findNextRange(buffered, currentTime); // check for gap
-
- if (nextRange.length > 0) {
- var difference = nextRange.start(0) - currentTime;
- this.logger_("Stopped at " + currentTime + ", setting timer for " + difference + ", seeking " + ("to " + nextRange.start(0)));
- this.cancelTimer_();
- this.timer_ = setTimeout(this.skipTheGap_.bind(this), difference * 1000, currentTime);
- return true;
- } // All checks failed. Returning false to indicate failure to correct waiting
-
-
- return false;
- };
-
- _proto.afterSeekableWindow_ = function afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow) {
- if (allowSeeksWithinUnsafeLiveWindow === void 0) {
- allowSeeksWithinUnsafeLiveWindow = false;
- }
-
- if (!seekable.length) {
- // we can't make a solid case if there's no seekable, default to false
- return false;
- }
-
- var allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
- var isLive = !playlist.endList;
-
- if (isLive && allowSeeksWithinUnsafeLiveWindow) {
- allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
- }
-
- if (currentTime > allowedEnd) {
- return true;
- }
-
- return false;
- };
-
- _proto.beforeSeekableWindow_ = function beforeSeekableWindow_(seekable, currentTime) {
- if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
- seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
- return true;
- }
-
- return false;
- };
-
- _proto.videoUnderflow_ = function videoUnderflow_(_ref2) {
- var videoBuffered = _ref2.videoBuffered,
- audioBuffered = _ref2.audioBuffered,
- currentTime = _ref2.currentTime;
-
- // audio only content will not have video underflow :)
- if (!videoBuffered) {
- return;
- }
-
- var gap; // find a gap in demuxed content.
-
- if (videoBuffered.length && audioBuffered.length) {
- // in Chrome audio will continue to play for ~3s when we run out of video
- // so we have to check that the video buffer did have some buffer in the
- // past.
- var lastVideoRange = findRange(videoBuffered, currentTime - 3);
- var videoRange = findRange(videoBuffered, currentTime);
- var audioRange = findRange(audioBuffered, currentTime);
-
- if (audioRange.length && !videoRange.length && lastVideoRange.length) {
- gap = {
- start: lastVideoRange.end(0),
- end: audioRange.end(0)
- };
- } // find a gap in muxed content.
-
- } else {
- var nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
- // stuck in a gap due to video underflow.
-
- if (!nextRange.length) {
- gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
- }
- }
-
- if (gap) {
- this.logger_("Encountered a gap in video from " + gap.start + " to " + gap.end + ". " + ("Seeking to current time " + currentTime));
- return true;
- }
-
- return false;
- }
- /**
- * Timer callback. If playback still has not proceeded, then we seek
- * to the start of the next buffered region.
- *
- * @private
- */
- ;
-
- _proto.skipTheGap_ = function skipTheGap_(scheduledCurrentTime) {
- var buffered = this.tech_.buffered();
- var currentTime = this.tech_.currentTime();
- var nextRange = findNextRange(buffered, currentTime);
- this.cancelTimer_();
-
- if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
- return;
- }
-
- this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
-
- this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-gap-skip'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-gap-skip'
- });
- };
-
- _proto.gapFromVideoUnderflow_ = function gapFromVideoUnderflow_(buffered, currentTime) {
- // At least in Chrome, if there is a gap in the video buffer, the audio will continue
- // playing for ~3 seconds after the video gap starts. This is done to account for
- // video buffer underflow/underrun (note that this is not done when there is audio
- // buffer underflow/underrun -- in that case the video will stop as soon as it
- // encounters the gap, as audio stalls are more noticeable/jarring to a user than
- // video stalls). The player's time will reflect the playthrough of audio, so the
- // time will appear as if we are in a buffered region, even if we are stuck in a
- // "gap."
- //
- // Example:
- // video buffer: 0 => 10.1, 10.2 => 20
- // audio buffer: 0 => 20
- // overall buffer: 0 => 10.1, 10.2 => 20
- // current time: 13
- //
- // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
- // however, the audio continued playing until it reached ~3 seconds past the gap
- // (13 seconds), at which point it stops as well. Since current time is past the
- // gap, findNextRange will return no ranges.
- //
- // To check for this issue, we see if there is a gap that starts somewhere within
- // a 3 second range (3 seconds +/- 1 second) back from our current time.
- var gaps = findGaps(buffered);
-
- for (var i = 0; i < gaps.length; i++) {
- var start = gaps.start(i);
- var end = gaps.end(i); // gap is starts no more than 4 seconds back
-
- if (currentTime - start < 4 && currentTime - start > 2) {
- return {
- start: start,
- end: end
- };
- }
- }
-
- return null;
- };
-
- return PlaybackWatcher;
- }();
-
- var defaultOptions = {
- errorInterval: 30,
- getSource: function getSource(next) {
- var tech = this.tech({
- IWillNotUseThisInPlugins: true
- });
- var sourceObj = tech.currentSource_ || this.currentSource();
- return next(sourceObj);
- }
- };
- /**
- * Main entry point for the plugin
- *
- * @param {Player} player a reference to a videojs Player instance
- * @param {Object} [options] an object with plugin options
- * @private
- */
-
- var initPlugin = function initPlugin(player, options) {
- var lastCalled = 0;
- var seekTo = 0;
- var localOptions = videojs__default['default'].mergeOptions(defaultOptions, options);
- player.ready(function () {
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload-initialized'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload-initialized'
- });
- });
- /**
- * Player modifications to perform that must wait until `loadedmetadata`
- * has been triggered
- *
- * @private
- */
-
- var loadedMetadataHandler = function loadedMetadataHandler() {
- if (seekTo) {
- player.currentTime(seekTo);
- }
- };
- /**
- * Set the source on the player element, play, and seek if necessary
- *
- * @param {Object} sourceObj An object specifying the source url and mime-type to play
- * @private
- */
-
-
- var setSource = function setSource(sourceObj) {
- if (sourceObj === null || sourceObj === undefined) {
- return;
- }
-
- seekTo = player.duration() !== Infinity && player.currentTime() || 0;
- player.one('loadedmetadata', loadedMetadataHandler);
- player.src(sourceObj);
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload'
- });
- player.play();
- };
- /**
- * Attempt to get a source from either the built-in getSource function
- * or a custom function provided via the options
- *
- * @private
- */
-
-
- var errorHandler = function errorHandler() {
- // Do not attempt to reload the source if a source-reload occurred before
- // 'errorInterval' time has elapsed since the last source-reload
- if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload-canceled'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload-canceled'
- });
- return;
- }
-
- if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
- videojs__default['default'].log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
- return;
- }
-
- lastCalled = Date.now();
- return localOptions.getSource.call(player, setSource);
- };
- /**
- * Unbind any event handlers that were bound by the plugin
- *
- * @private
- */
-
-
- var cleanupEvents = function cleanupEvents() {
- player.off('loadedmetadata', loadedMetadataHandler);
- player.off('error', errorHandler);
- player.off('dispose', cleanupEvents);
- };
- /**
- * Cleanup before re-initializing the plugin
- *
- * @param {Object} [newOptions] an object with plugin options
- * @private
- */
-
-
- var reinitPlugin = function reinitPlugin(newOptions) {
- cleanupEvents();
- initPlugin(player, newOptions);
- };
-
- player.on('error', errorHandler);
- player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
- // initializing the plugin
-
- player.reloadSourceOnError = reinitPlugin;
- };
- /**
- * Reload the source when an error is detected as long as there
- * wasn't an error previously within the last 30 seconds
- *
- * @param {Object} [options] an object with plugin options
- */
-
-
- var reloadSourceOnError = function reloadSourceOnError(options) {
- initPlugin(this, options);
- };
-
- var version$4 = "2.9.1";
-
- var version$3 = "5.11.1";
-
- var version$2 = "0.17.0";
-
- var version$1 = "4.7.0";
-
- var version = "3.1.2";
-
- var Vhs = {
- PlaylistLoader: PlaylistLoader,
- Playlist: Playlist,
- utils: utils,
- STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
- INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
- lastBandwidthSelector: lastBandwidthSelector,
- movingAverageBandwidthSelector: movingAverageBandwidthSelector,
- comparePlaylistBandwidth: comparePlaylistBandwidth,
- comparePlaylistResolution: comparePlaylistResolution,
- xhr: xhrFactory()
- }; // Define getter/setters for config properties
-
- Object.keys(Config).forEach(function (prop) {
- Object.defineProperty(Vhs, prop, {
- get: function get() {
- videojs__default['default'].log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
- return Config[prop];
- },
- set: function set(value) {
- videojs__default['default'].log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
-
- if (typeof value !== 'number' || value < 0) {
- videojs__default['default'].log.warn("value of Vhs." + prop + " must be greater than or equal to 0");
- return;
- }
-
- Config[prop] = value;
- }
- });
- });
- var LOCAL_STORAGE_KEY = 'videojs-vhs';
- /**
- * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
- * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
- * @function handleVhsMediaChange
- */
-
- var handleVhsMediaChange = function handleVhsMediaChange(qualityLevels, playlistLoader) {
- var newPlaylist = playlistLoader.media();
- var selectedIndex = -1;
-
- for (var i = 0; i < qualityLevels.length; i++) {
- if (qualityLevels[i].id === newPlaylist.id) {
- selectedIndex = i;
- break;
- }
- }
-
- qualityLevels.selectedIndex_ = selectedIndex;
- qualityLevels.trigger({
- selectedIndex: selectedIndex,
- type: 'change'
- });
- };
- /**
- * Adds quality levels to list once playlist metadata is available
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
- * @param {Object} vhs Vhs object to listen to for media events.
- * @function handleVhsLoadedMetadata
- */
-
-
- var handleVhsLoadedMetadata = function handleVhsLoadedMetadata(qualityLevels, vhs) {
- vhs.representations().forEach(function (rep) {
- qualityLevels.addQualityLevel(rep);
- });
- handleVhsMediaChange(qualityLevels, vhs.playlists);
- }; // HLS is a source handler, not a tech. Make sure attempts to use it
- // as one do not cause exceptions.
-
-
- Vhs.canPlaySource = function () {
- return videojs__default['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
- };
-
- var emeKeySystems = function emeKeySystems(keySystemOptions, mainPlaylist, audioPlaylist) {
- if (!keySystemOptions) {
- return keySystemOptions;
- }
-
- var codecs = {};
-
- if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
- codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
- }
-
- if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
- codecs.audio = audioPlaylist.attributes.CODECS;
- }
-
- var videoContentType = getMimeForCodec(codecs.video);
- var audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
-
- var keySystemContentTypes = {};
-
- for (var keySystem in keySystemOptions) {
- keySystemContentTypes[keySystem] = {};
-
- if (audioContentType) {
- keySystemContentTypes[keySystem].audioContentType = audioContentType;
- }
-
- if (videoContentType) {
- keySystemContentTypes[keySystem].videoContentType = videoContentType;
- } // Default to using the video playlist's PSSH even though they may be different, as
- // videojs-contrib-eme will only accept one in the options.
- //
- // This shouldn't be an issue for most cases as early intialization will handle all
- // unique PSSH values, and if they aren't, then encrypted events should have the
- // specific information needed for the unique license.
-
-
- if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
- keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
- } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
- // so we need to prevent overwriting the URL entirely
-
-
- if (typeof keySystemOptions[keySystem] === 'string') {
- keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
- }
- }
-
- return videojs__default['default'].mergeOptions(keySystemOptions, keySystemContentTypes);
- };
- /**
- * @typedef {Object} KeySystems
- *
- * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
- * Note: not all options are listed here.
- *
- * @property {Uint8Array} [pssh]
- * Protection System Specific Header
- */
-
- /**
- * Goes through all the playlists and collects an array of KeySystems options objects
- * containing each playlist's keySystems and their pssh values, if available.
- *
- * @param {Object[]} playlists
- * The playlists to look through
- * @param {string[]} keySystems
- * The keySystems to collect pssh values for
- *
- * @return {KeySystems[]}
- * An array of KeySystems objects containing available key systems and their
- * pssh values
- */
-
-
- var getAllPsshKeySystemsOptions = function getAllPsshKeySystemsOptions(playlists, keySystems) {
- return playlists.reduce(function (keySystemsArr, playlist) {
- if (!playlist.contentProtection) {
- return keySystemsArr;
- }
-
- var keySystemsOptions = keySystems.reduce(function (keySystemsObj, keySystem) {
- var keySystemOptions = playlist.contentProtection[keySystem];
-
- if (keySystemOptions && keySystemOptions.pssh) {
- keySystemsObj[keySystem] = {
- pssh: keySystemOptions.pssh
- };
- }
-
- return keySystemsObj;
- }, {});
-
- if (Object.keys(keySystemsOptions).length) {
- keySystemsArr.push(keySystemsOptions);
- }
-
- return keySystemsArr;
- }, []);
- };
- /**
- * Returns a promise that waits for the
- * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
- *
- * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
- * browsers.
- *
- * As per the above ticket, this is particularly important for Chrome, where, if
- * unencrypted content is appended before encrypted content and the key session has not
- * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
- * during playback.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- * @param {Object[]} mainPlaylists
- * The playlists found on the master playlist object
- *
- * @return {Object}
- * Promise that resolves when the key session has been created
- */
-
-
- var waitForKeySessionCreation = function waitForKeySessionCreation(_ref) {
- var player = _ref.player,
- sourceKeySystems = _ref.sourceKeySystems,
- audioMedia = _ref.audioMedia,
- mainPlaylists = _ref.mainPlaylists;
-
- if (!player.eme.initializeMediaKeys) {
- return Promise.resolve();
- } // TODO should all audio PSSH values be initialized for DRM?
- //
- // All unique video rendition pssh values are initialized for DRM, but here only
- // the initial audio playlist license is initialized. In theory, an encrypted
- // event should be fired if the user switches to an alternative audio playlist
- // where a license is required, but this case hasn't yet been tested. In addition, there
- // may be many alternate audio playlists unlikely to be used (e.g., multiple different
- // languages).
-
-
- var playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
- var keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
- var initializationFinishedPromises = [];
- var keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
- // only place where it should not be deduped is for ms-prefixed APIs, but the early
- // return for IE11 above, and the existence of modern EME APIs in addition to
- // ms-prefixed APIs on Edge should prevent this from being a concern.
- // initializeMediaKeys also won't use the webkit-prefixed APIs.
-
- keySystemsOptionsArr.forEach(function (keySystemsOptions) {
- keySessionCreatedPromises.push(new Promise(function (resolve, reject) {
- player.tech_.one('keysessioncreated', resolve);
- }));
- initializationFinishedPromises.push(new Promise(function (resolve, reject) {
- player.eme.initializeMediaKeys({
- keySystems: keySystemsOptions
- }, function (err) {
- if (err) {
- reject(err);
- return;
- }
-
- resolve();
- });
- }));
- }); // The reasons Promise.race is chosen over Promise.any:
- //
- // * Promise.any is only available in Safari 14+.
- // * None of these promises are expected to reject. If they do reject, it might be
- // better here for the race to surface the rejection, rather than mask it by using
- // Promise.any.
-
- return Promise.race([// If a session was previously created, these will all finish resolving without
- // creating a new session, otherwise it will take until the end of all license
- // requests, which is why the key session check is used (to make setup much faster).
- Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
- Promise.race(keySessionCreatedPromises)]);
- };
- /**
- * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
- * there are keySystems on the source, sets up source options to prepare the source for
- * eme.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} media
- * The active media playlist
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- *
- * @return {boolean}
- * Whether or not options were configured and EME is available
- */
-
- var setupEmeOptions = function setupEmeOptions(_ref2) {
- var player = _ref2.player,
- sourceKeySystems = _ref2.sourceKeySystems,
- media = _ref2.media,
- audioMedia = _ref2.audioMedia;
- var sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
-
- if (!sourceOptions) {
- return false;
- }
-
- player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
- // do nothing.
-
- if (sourceOptions && !player.eme) {
- videojs__default['default'].log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
- return false;
- }
-
- return true;
- };
-
- var getVhsLocalStorage = function getVhsLocalStorage() {
- if (!window__default['default'].localStorage) {
- return null;
- }
-
- var storedObject = window__default['default'].localStorage.getItem(LOCAL_STORAGE_KEY);
-
- if (!storedObject) {
- return null;
- }
-
- try {
- return JSON.parse(storedObject);
- } catch (e) {
- // someone may have tampered with the value
- return null;
- }
- };
-
- var updateVhsLocalStorage = function updateVhsLocalStorage(options) {
- if (!window__default['default'].localStorage) {
- return false;
- }
-
- var objectToStore = getVhsLocalStorage();
- objectToStore = objectToStore ? videojs__default['default'].mergeOptions(objectToStore, options) : options;
-
- try {
- window__default['default'].localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
- } catch (e) {
- // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
- // storage is set to 0).
- // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
- // No need to perform any operation.
- return false;
- }
-
- return objectToStore;
- };
- /**
- * Parses VHS-supported media types from data URIs. See
- * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
- * for information on data URIs.
- *
- * @param {string} dataUri
- * The data URI
- *
- * @return {string|Object}
- * The parsed object/string, or the original string if no supported media type
- * was found
- */
-
-
- var expandDataUri = function expandDataUri(dataUri) {
- if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
- return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
- } // no known case for this data URI, return the string as-is
-
-
- return dataUri;
- };
- /**
- * Whether the browser has built-in HLS support.
- */
-
-
- Vhs.supportsNativeHls = function () {
- if (!document__default['default'] || !document__default['default'].createElement) {
- return false;
- }
-
- var video = document__default['default'].createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
-
- if (!videojs__default['default'].getTech('Html5').isSupported()) {
- return false;
- } // HLS manifests can go by many mime-types
-
-
- var canPlay = [// Apple santioned
- 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
- 'audio/mpegurl', // Very common
- 'audio/x-mpegurl', // Very common
- 'application/x-mpegurl', // Included for completeness
- 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
- return canPlay.some(function (canItPlay) {
- return /maybe|probably/i.test(video.canPlayType(canItPlay));
- });
- }();
-
- Vhs.supportsNativeDash = function () {
- if (!document__default['default'] || !document__default['default'].createElement || !videojs__default['default'].getTech('Html5').isSupported()) {
- return false;
- }
-
- return /maybe|probably/i.test(document__default['default'].createElement('video').canPlayType('application/dash+xml'));
- }();
-
- Vhs.supportsTypeNatively = function (type) {
- if (type === 'hls') {
- return Vhs.supportsNativeHls;
- }
-
- if (type === 'dash') {
- return Vhs.supportsNativeDash;
- }
-
- return false;
- };
- /**
- * HLS is a source handler, not a tech. Make sure attempts to use it
- * as one do not cause exceptions.
- */
-
-
- Vhs.isSupported = function () {
- return videojs__default['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
- };
-
- var Component = videojs__default['default'].getComponent('Component');
- /**
- * The Vhs Handler object, where we orchestrate all of the parts
- * of HLS to interact with video.js
- *
- * @class VhsHandler
- * @extends videojs.Component
- * @param {Object} source the soruce object
- * @param {Tech} tech the parent tech object
- * @param {Object} options optional and required options
- */
-
- var VhsHandler = /*#__PURE__*/function (_Component) {
- inheritsLoose(VhsHandler, _Component);
-
- function VhsHandler(source, tech, options) {
- var _this;
-
- _this = _Component.call(this, tech, videojs__default['default'].mergeOptions(options.hls, options.vhs)) || this;
-
- if (options.hls && Object.keys(options.hls).length) {
- videojs__default['default'].log.warn('Using hls options is deprecated. Use vhs instead.');
- } // if a tech level `initialBandwidth` option was passed
- // use that over the VHS level `bandwidth` option
-
-
- if (typeof options.initialBandwidth === 'number') {
- _this.options_.bandwidth = options.initialBandwidth;
- }
-
- _this.logger_ = logger('VhsHandler'); // tech.player() is deprecated but setup a reference to HLS for
- // backwards-compatibility
-
- if (tech.options_ && tech.options_.playerId) {
- var _player = videojs__default['default'](tech.options_.playerId);
-
- if (!_player.hasOwnProperty('hls')) {
- Object.defineProperty(_player, 'hls', {
- get: function get() {
- videojs__default['default'].log.warn('player.hls is deprecated. Use player.tech().vhs instead.');
- tech.trigger({
- type: 'usage',
- name: 'hls-player-access'
- });
- return assertThisInitialized(_this);
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('vhs')) {
- Object.defineProperty(_player, 'vhs', {
- get: function get() {
- videojs__default['default'].log.warn('player.vhs is deprecated. Use player.tech().vhs instead.');
- tech.trigger({
- type: 'usage',
- name: 'vhs-player-access'
- });
- return assertThisInitialized(_this);
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('dash')) {
- Object.defineProperty(_player, 'dash', {
- get: function get() {
- videojs__default['default'].log.warn('player.dash is deprecated. Use player.tech().vhs instead.');
- return assertThisInitialized(_this);
- },
- configurable: true
- });
- }
-
- _this.player_ = _player;
- }
-
- _this.tech_ = tech;
- _this.source_ = source;
- _this.stats = {};
- _this.ignoreNextSeekingEvent_ = false;
-
- _this.setOptions_();
-
- if (_this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
- tech.overrideNativeAudioTracks(true);
- tech.overrideNativeVideoTracks(true);
- } else if (_this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
- // overriding native HLS only works if audio tracks have been emulated
- // error early if we're misconfigured
- throw new Error('Overriding native HLS requires emulated tracks. ' + 'See https://git.io/vMpjB');
- } // listen for fullscreenchange events for this player so that we
- // can adjust our quality selection quickly
-
-
- _this.on(document__default['default'], ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
- var fullscreenElement = document__default['default'].fullscreenElement || document__default['default'].webkitFullscreenElement || document__default['default'].mozFullScreenElement || document__default['default'].msFullscreenElement;
-
- if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
- _this.masterPlaylistController_.fastQualityChange_();
- } else {
- // When leaving fullscreen, since the in page pixel dimensions should be smaller
- // than full screen, see if there should be a rendition switch down to preserve
- // bandwidth.
- _this.masterPlaylistController_.checkABR_();
- }
- });
-
- _this.on(_this.tech_, 'seeking', function () {
- if (this.ignoreNextSeekingEvent_) {
- this.ignoreNextSeekingEvent_ = false;
- return;
- }
-
- this.setCurrentTime(this.tech_.currentTime());
- });
-
- _this.on(_this.tech_, 'error', function () {
- // verify that the error was real and we are loaded
- // enough to have mpc loaded.
- if (this.tech_.error() && this.masterPlaylistController_) {
- this.masterPlaylistController_.pauseLoading();
- }
- });
-
- _this.on(_this.tech_, 'play', _this.play);
-
- return _this;
- }
-
- var _proto = VhsHandler.prototype;
-
- _proto.setOptions_ = function setOptions_() {
- var _this2 = this;
-
- // defaults
- this.options_.withCredentials = this.options_.withCredentials || false;
- this.options_.handleManifestRedirects = this.options_.handleManifestRedirects === false ? false : true;
- this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
- this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
- this.options_.smoothQualityChange = this.options_.smoothQualityChange || false;
- this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
- this.options_.customTagParsers = this.options_.customTagParsers || [];
- this.options_.customTagMappers = this.options_.customTagMappers || [];
- this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
-
- if (typeof this.options_.blacklistDuration !== 'number') {
- this.options_.blacklistDuration = 5 * 60;
- }
-
- if (typeof this.options_.bandwidth !== 'number') {
- if (this.options_.useBandwidthFromLocalStorage) {
- var storedObject = getVhsLocalStorage();
-
- if (storedObject && storedObject.bandwidth) {
- this.options_.bandwidth = storedObject.bandwidth;
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-bandwidth-from-local-storage'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-bandwidth-from-local-storage'
- });
- }
-
- if (storedObject && storedObject.throughput) {
- this.options_.throughput = storedObject.throughput;
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-throughput-from-local-storage'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-throughput-from-local-storage'
- });
- }
- }
- } // if bandwidth was not set by options or pulled from local storage, start playlist
- // selection at a reasonable bandwidth
-
-
- if (typeof this.options_.bandwidth !== 'number') {
- this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
- } // If the bandwidth number is unchanged from the initial setting
- // then this takes precedence over the enableLowInitialPlaylist option
-
-
- this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
-
- ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'smoothQualityChange', 'customTagParsers', 'customTagMappers', 'handleManifestRedirects', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'experimentalBufferBasedABR', 'liveRangeSafeTimeDelta', 'experimentalLLHLS'].forEach(function (option) {
- if (typeof _this2.source_[option] !== 'undefined') {
- _this2.options_[option] = _this2.source_[option];
- }
- });
- this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
- this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
- }
- /**
- * called when player.src gets called, handle a new source
- *
- * @param {Object} src the source object to handle
- */
- ;
-
- _proto.src = function src(_src, type) {
- var _this3 = this;
-
- // do nothing if the src is falsey
- if (!_src) {
- return;
- }
-
- this.setOptions_(); // add master playlist controller options
-
- this.options_.src = expandDataUri(this.source_.src);
- this.options_.tech = this.tech_;
- this.options_.externVhs = Vhs;
- this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
-
- this.options_.seekTo = function (time) {
- _this3.tech_.setCurrentTime(time);
- };
-
- if (this.options_.smoothQualityChange) {
- videojs__default['default'].log.warn('smoothQualityChange is deprecated and will be removed in the next major version');
- }
-
- this.masterPlaylistController_ = new MasterPlaylistController(this.options_);
- var playbackWatcherOptions = videojs__default['default'].mergeOptions({
- liveRangeSafeTimeDelta: SAFE_TIME_DELTA
- }, this.options_, {
- seekable: function seekable() {
- return _this3.seekable();
- },
- media: function media() {
- return _this3.masterPlaylistController_.media();
- },
- masterPlaylistController: this.masterPlaylistController_
- });
- this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
- this.masterPlaylistController_.on('error', function () {
- var player = videojs__default['default'].players[_this3.tech_.options_.playerId];
- var error = _this3.masterPlaylistController_.error;
-
- if (typeof error === 'object' && !error.code) {
- error.code = 3;
- } else if (typeof error === 'string') {
- error = {
- message: error,
- code: 3
- };
- }
-
- player.error(error);
- });
- var defaultSelector = this.options_.experimentalBufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
- // compatibility with < v2
-
- this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
- this.masterPlaylistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
-
- this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
- this.mediaSource = this.masterPlaylistController_.mediaSource; // Proxy assignment of some properties to the master playlist
- // controller. Using a custom property for backwards compatibility
- // with < v2
-
- Object.defineProperties(this, {
- selectPlaylist: {
- get: function get() {
- return this.masterPlaylistController_.selectPlaylist;
- },
- set: function set(selectPlaylist) {
- this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
- }
- },
- throughput: {
- get: function get() {
- return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
- },
- set: function set(throughput) {
- this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
- // for the cumulative average
-
- this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
- }
- },
- bandwidth: {
- get: function get() {
- return this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
- },
- set: function set(bandwidth) {
- this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
- // `count` is set to zero that current value of `rate` isn't included
- // in the cumulative average
-
- this.masterPlaylistController_.mainSegmentLoader_.throughput = {
- rate: 0,
- count: 0
- };
- }
- },
-
- /**
- * `systemBandwidth` is a combination of two serial processes bit-rates. The first
- * is the network bitrate provided by `bandwidth` and the second is the bitrate of
- * the entire process after that - decryption, transmuxing, and appending - provided
- * by `throughput`.
- *
- * Since the two process are serial, the overall system bandwidth is given by:
- * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
- */
- systemBandwidth: {
- get: function get() {
- var invBandwidth = 1 / (this.bandwidth || 1);
- var invThroughput;
-
- if (this.throughput > 0) {
- invThroughput = 1 / this.throughput;
- } else {
- invThroughput = 0;
- }
-
- var systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
- return systemBitrate;
- },
- set: function set() {
- videojs__default['default'].log.error('The "systemBandwidth" property is read-only');
- }
- }
- });
-
- if (this.options_.bandwidth) {
- this.bandwidth = this.options_.bandwidth;
- }
-
- if (this.options_.throughput) {
- this.throughput = this.options_.throughput;
- }
-
- Object.defineProperties(this.stats, {
- bandwidth: {
- get: function get() {
- return _this3.bandwidth || 0;
- },
- enumerable: true
- },
- mediaRequests: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequests_() || 0;
- },
- enumerable: true
- },
- mediaRequestsAborted: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsAborted_() || 0;
- },
- enumerable: true
- },
- mediaRequestsTimedout: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsTimedout_() || 0;
- },
- enumerable: true
- },
- mediaRequestsErrored: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsErrored_() || 0;
- },
- enumerable: true
- },
- mediaTransferDuration: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaTransferDuration_() || 0;
- },
- enumerable: true
- },
- mediaBytesTransferred: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaBytesTransferred_() || 0;
- },
- enumerable: true
- },
- mediaSecondsLoaded: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaSecondsLoaded_() || 0;
- },
- enumerable: true
- },
- mediaAppends: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaAppends_() || 0;
- },
- enumerable: true
- },
- mainAppendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.mainAppendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- audioAppendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.audioAppendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- appendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.appendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- timeToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.timeToLoadedData_() || 0;
- },
- enumerable: true
- },
- buffered: {
- get: function get() {
- return timeRangesToArray(_this3.tech_.buffered());
- },
- enumerable: true
- },
- currentTime: {
- get: function get() {
- return _this3.tech_.currentTime();
- },
- enumerable: true
- },
- currentSource: {
- get: function get() {
- return _this3.tech_.currentSource_;
- },
- enumerable: true
- },
- currentTech: {
- get: function get() {
- return _this3.tech_.name_;
- },
- enumerable: true
- },
- duration: {
- get: function get() {
- return _this3.tech_.duration();
- },
- enumerable: true
- },
- master: {
- get: function get() {
- return _this3.playlists.master;
- },
- enumerable: true
- },
- playerDimensions: {
- get: function get() {
- return _this3.tech_.currentDimensions();
- },
- enumerable: true
- },
- seekable: {
- get: function get() {
- return timeRangesToArray(_this3.tech_.seekable());
- },
- enumerable: true
- },
- timestamp: {
- get: function get() {
- return Date.now();
- },
- enumerable: true
- },
- videoPlaybackQuality: {
- get: function get() {
- return _this3.tech_.getVideoPlaybackQuality();
- },
- enumerable: true
- }
- });
- this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
- this.tech_.on('bandwidthupdate', function () {
- if (_this3.options_.useBandwidthFromLocalStorage) {
- updateVhsLocalStorage({
- bandwidth: _this3.bandwidth,
- throughput: Math.round(_this3.throughput)
- });
- }
- });
- this.masterPlaylistController_.on('selectedinitialmedia', function () {
- // Add the manual rendition mix-in to VhsHandler
- renditionSelectionMixin(_this3);
- });
- this.masterPlaylistController_.sourceUpdater_.on('createdsourcebuffers', function () {
- _this3.setupEme_();
- }); // the bandwidth of the primary segment loader is our best
- // estimate of overall bandwidth
-
- this.on(this.masterPlaylistController_, 'progress', function () {
- this.tech_.trigger('progress');
- }); // In the live case, we need to ignore the very first `seeking` event since
- // that will be the result of the seek-to-live behavior
-
- this.on(this.masterPlaylistController_, 'firstplay', function () {
- this.ignoreNextSeekingEvent_ = true;
- });
- this.setupQualityLevels_(); // do nothing if the tech has been disposed already
- // this can occur if someone sets the src in player.ready(), for instance
-
- if (!this.tech_.el()) {
- return;
- }
-
- this.mediaSourceUrl_ = window__default['default'].URL.createObjectURL(this.masterPlaylistController_.mediaSource);
- this.tech_.src(this.mediaSourceUrl_);
- }
- /**
- * If necessary and EME is available, sets up EME options and waits for key session
- * creation.
- *
- * This function also updates the source updater so taht it can be used, as for some
- * browsers, EME must be configured before content is appended (if appending unencrypted
- * content before encrypted content).
- */
- ;
-
- _proto.setupEme_ = function setupEme_() {
- var _this4 = this;
-
- var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
- var didSetupEmeOptions = setupEmeOptions({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- media: this.playlists.media(),
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
- }); // In IE11 this is too early to initialize media keys, and IE11 does not support
- // promises.
-
- if (videojs__default['default'].browser.IE_VERSION === 11 || !didSetupEmeOptions) {
- // If EME options were not set up, we've done all we could to initialize EME.
- this.masterPlaylistController_.sourceUpdater_.initializedEme();
- return;
- }
-
- this.logger_('waiting for EME key session creation');
- waitForKeySessionCreation({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
- mainPlaylists: this.playlists.master.playlists
- }).then(function () {
- _this4.logger_('created EME key session');
-
- _this4.masterPlaylistController_.sourceUpdater_.initializedEme();
- }).catch(function (err) {
- _this4.logger_('error while creating EME key session', err);
-
- _this4.player_.error({
- message: 'Failed to initialize media keys for EME',
- code: 3
- });
- });
- }
- /**
- * Initializes the quality levels and sets listeners to update them.
- *
- * @method setupQualityLevels_
- * @private
- */
- ;
-
- _proto.setupQualityLevels_ = function setupQualityLevels_() {
- var _this5 = this;
-
- var player = videojs__default['default'].players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
- // or qualityLevels_ listeners have already been setup, do nothing.
-
- if (!player || !player.qualityLevels || this.qualityLevels_) {
- return;
- }
-
- this.qualityLevels_ = player.qualityLevels();
- this.masterPlaylistController_.on('selectedinitialmedia', function () {
- handleVhsLoadedMetadata(_this5.qualityLevels_, _this5);
- });
- this.playlists.on('mediachange', function () {
- handleVhsMediaChange(_this5.qualityLevels_, _this5.playlists);
- });
- }
- /**
- * return the version
- */
- ;
-
- VhsHandler.version = function version$5() {
- return {
- '@videojs/http-streaming': version$4,
- 'mux.js': version$3,
- 'mpd-parser': version$2,
- 'm3u8-parser': version$1,
- 'aes-decrypter': version
- };
- }
- /**
- * return the version
- */
- ;
-
- _proto.version = function version() {
- return this.constructor.version();
- };
-
- _proto.canChangeType = function canChangeType() {
- return SourceUpdater.canChangeType();
- }
- /**
- * Begin playing the video.
- */
- ;
-
- _proto.play = function play() {
- this.masterPlaylistController_.play();
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.setCurrentTime = function setCurrentTime(currentTime) {
- this.masterPlaylistController_.setCurrentTime(currentTime);
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.duration = function duration() {
- return this.masterPlaylistController_.duration();
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.seekable = function seekable() {
- return this.masterPlaylistController_.seekable();
- }
- /**
- * Abort all outstanding work and cleanup.
- */
- ;
-
- _proto.dispose = function dispose() {
- if (this.playbackWatcher_) {
- this.playbackWatcher_.dispose();
- }
-
- if (this.masterPlaylistController_) {
- this.masterPlaylistController_.dispose();
- }
-
- if (this.qualityLevels_) {
- this.qualityLevels_.dispose();
- }
-
- if (this.player_) {
- delete this.player_.vhs;
- delete this.player_.dash;
- delete this.player_.hls;
- }
-
- if (this.tech_ && this.tech_.vhs) {
- delete this.tech_.vhs;
- } // don't check this.tech_.hls as it will log a deprecated warning
-
-
- if (this.tech_) {
- delete this.tech_.hls;
- }
-
- if (this.mediaSourceUrl_ && window__default['default'].URL.revokeObjectURL) {
- window__default['default'].URL.revokeObjectURL(this.mediaSourceUrl_);
- this.mediaSourceUrl_ = null;
- }
-
- _Component.prototype.dispose.call(this);
- };
-
- _proto.convertToProgramTime = function convertToProgramTime(time, callback) {
- return getProgramTime({
- playlist: this.masterPlaylistController_.media(),
- time: time,
- callback: callback
- });
- } // the player must be playing before calling this
- ;
-
- _proto.seekToProgramTime = function seekToProgramTime$1(programTime, callback, pauseAfterSeek, retryCount) {
- if (pauseAfterSeek === void 0) {
- pauseAfterSeek = true;
- }
-
- if (retryCount === void 0) {
- retryCount = 2;
- }
-
- return seekToProgramTime({
- programTime: programTime,
- playlist: this.masterPlaylistController_.media(),
- retryCount: retryCount,
- pauseAfterSeek: pauseAfterSeek,
- seekTo: this.options_.seekTo,
- tech: this.options_.tech,
- callback: callback
- });
- };
-
- return VhsHandler;
- }(Component);
- /**
- * The Source Handler object, which informs video.js what additional
- * MIME types are supported and sets up playback. It is registered
- * automatically to the appropriate tech based on the capabilities of
- * the browser it is running in. It is not necessary to use or modify
- * this object in normal usage.
- */
-
-
- var VhsSourceHandler = {
- name: 'videojs-http-streaming',
- VERSION: version$4,
- canHandleSource: function canHandleSource(srcObj, options) {
- if (options === void 0) {
- options = {};
- }
-
- var localOptions = videojs__default['default'].mergeOptions(videojs__default['default'].options, options);
- return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
- },
- handleSource: function handleSource(source, tech, options) {
- if (options === void 0) {
- options = {};
- }
-
- var localOptions = videojs__default['default'].mergeOptions(videojs__default['default'].options, options);
- tech.vhs = new VhsHandler(source, tech, localOptions);
-
- if (!videojs__default['default'].hasOwnProperty('hls')) {
- Object.defineProperty(tech, 'hls', {
- get: function get() {
- videojs__default['default'].log.warn('player.tech().hls is deprecated. Use player.tech().vhs instead.');
- return tech.vhs;
- },
- configurable: true
- });
- }
-
- tech.vhs.xhr = xhrFactory();
- tech.vhs.src(source.src, source.type);
- return tech.vhs;
- },
- canPlayType: function canPlayType(type, options) {
- if (options === void 0) {
- options = {};
- }
-
- var _videojs$mergeOptions = videojs__default['default'].mergeOptions(videojs__default['default'].options, options),
- _videojs$mergeOptions2 = _videojs$mergeOptions.vhs.overrideNative,
- overrideNative = _videojs$mergeOptions2 === void 0 ? !videojs__default['default'].browser.IS_ANY_SAFARI : _videojs$mergeOptions2;
-
- var supportedType = simpleTypeFromSourceType(type);
- var canUseMsePlayback = supportedType && (!Vhs.supportsTypeNatively(supportedType) || overrideNative);
- return canUseMsePlayback ? 'maybe' : '';
- }
- };
- /**
- * Check to see if the native MediaSource object exists and supports
- * an MP4 container with both H.264 video and AAC-LC audio.
- *
- * @return {boolean} if native media sources are supported
- */
-
- var supportsNativeMediaSources = function supportsNativeMediaSources() {
- return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
- }; // register source handlers with the appropriate techs
-
-
- if (supportsNativeMediaSources()) {
- videojs__default['default'].getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
- }
-
- videojs__default['default'].VhsHandler = VhsHandler;
- Object.defineProperty(videojs__default['default'], 'HlsHandler', {
- get: function get() {
- videojs__default['default'].log.warn('videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.');
- return VhsHandler;
- },
- configurable: true
- });
- videojs__default['default'].VhsSourceHandler = VhsSourceHandler;
- Object.defineProperty(videojs__default['default'], 'HlsSourceHandler', {
- get: function get() {
- videojs__default['default'].log.warn('videojs.HlsSourceHandler is deprecated. ' + 'Use videojs.VhsSourceHandler instead.');
- return VhsSourceHandler;
- },
- configurable: true
- });
- videojs__default['default'].Vhs = Vhs;
- Object.defineProperty(videojs__default['default'], 'Hls', {
- get: function get() {
- videojs__default['default'].log.warn('videojs.Hls is deprecated. Use videojs.Vhs instead.');
- return Vhs;
- },
- configurable: true
- });
-
- if (!videojs__default['default'].use) {
- videojs__default['default'].registerComponent('Hls', Vhs);
- videojs__default['default'].registerComponent('Vhs', Vhs);
- }
-
- videojs__default['default'].options.vhs = videojs__default['default'].options.vhs || {};
- videojs__default['default'].options.hls = videojs__default['default'].options.hls || {};
-
- if (videojs__default['default'].registerPlugin) {
- videojs__default['default'].registerPlugin('reloadSourceOnError', reloadSourceOnError);
- } else {
- videojs__default['default'].plugin('reloadSourceOnError', reloadSourceOnError);
- }
-
- exports.LOCAL_STORAGE_KEY = LOCAL_STORAGE_KEY;
- exports.Vhs = Vhs;
- exports.VhsHandler = VhsHandler;
- exports.VhsSourceHandler = VhsSourceHandler;
- exports.emeKeySystems = emeKeySystems;
- exports.expandDataUri = expandDataUri;
- exports.getAllPsshKeySystemsOptions = getAllPsshKeySystemsOptions;
- exports.setupEmeOptions = setupEmeOptions;
- exports.simpleTypeFromSourceType = simpleTypeFromSourceType;
- exports.waitForKeySessionCreation = waitForKeySessionCreation;
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
-})));
diff --git a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.cjs.js b/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.cjs.js
deleted file mode 100644
index e63b1a1..0000000
--- a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.cjs.js
+++ /dev/null
@@ -1,25720 +0,0 @@
-/*! @name @videojs/http-streaming @version 2.9.1 @license Apache-2.0 */
-'use strict';
-
-Object.defineProperty(exports, '__esModule', { value: true });
-
-var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
-var _inheritsLoose = require('@babel/runtime/helpers/inheritsLoose');
-var document = require('global/document');
-var window = require('global/window');
-var _resolveUrl = require('@videojs/vhs-utils/cjs/resolve-url.js');
-var videojs = require('video.js');
-var _extends = require('@babel/runtime/helpers/extends');
-var m3u8Parser = require('m3u8-parser');
-var codecs_js = require('@videojs/vhs-utils/cjs/codecs.js');
-var mediaTypes_js = require('@videojs/vhs-utils/cjs/media-types.js');
-var mpdParser = require('mpd-parser');
-var parseSidx = require('mux.js/lib/tools/parse-sidx');
-var id3Helpers = require('@videojs/vhs-utils/cjs/id3-helpers');
-var containers = require('@videojs/vhs-utils/cjs/containers');
-var byteHelpers = require('@videojs/vhs-utils/cjs/byte-helpers');
-var clock = require('mux.js/lib/utils/clock');
-
-function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
-
-var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
-var _inheritsLoose__default = /*#__PURE__*/_interopDefaultLegacy(_inheritsLoose);
-var document__default = /*#__PURE__*/_interopDefaultLegacy(document);
-var window__default = /*#__PURE__*/_interopDefaultLegacy(window);
-var _resolveUrl__default = /*#__PURE__*/_interopDefaultLegacy(_resolveUrl);
-var videojs__default = /*#__PURE__*/_interopDefaultLegacy(videojs);
-var _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends);
-var parseSidx__default = /*#__PURE__*/_interopDefaultLegacy(parseSidx);
-
-/**
- * @file resolve-url.js - Handling how URLs are resolved and manipulated
- */
-var resolveUrl = _resolveUrl__default['default'];
-/**
- * Checks whether xhr request was redirected and returns correct url depending
- * on `handleManifestRedirects` option
- *
- * @api private
- *
- * @param {string} url - an url being requested
- * @param {XMLHttpRequest} req - xhr request result
- *
- * @return {string}
- */
-
-var resolveManifestRedirect = function resolveManifestRedirect(handleManifestRedirect, url, req) {
- // To understand how the responseURL below is set and generated:
- // - https://fetch.spec.whatwg.org/#concept-response-url
- // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
- if (handleManifestRedirect && req && req.responseURL && url !== req.responseURL) {
- return req.responseURL;
- }
-
- return url;
-};
-
-var logger = function logger(source) {
- if (videojs__default['default'].log.debug) {
- return videojs__default['default'].log.debug.bind(videojs__default['default'], 'VHS:', source + " >");
- }
-
- return function () {};
-};
-
-/**
- * ranges
- *
- * Utilities for working with TimeRanges.
- *
- */
-
-var TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
-// can be misleading because of precision differences or when the current media has poorly
-// aligned audio and video, which can cause values to be slightly off from what you would
-// expect. This value is what we consider to be safe to use in such comparisons to account
-// for these scenarios.
-
-var SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
-
-var filterRanges = function filterRanges(timeRanges, predicate) {
- var results = [];
- var i;
-
- if (timeRanges && timeRanges.length) {
- // Search for ranges that match the predicate
- for (i = 0; i < timeRanges.length; i++) {
- if (predicate(timeRanges.start(i), timeRanges.end(i))) {
- results.push([timeRanges.start(i), timeRanges.end(i)]);
- }
- }
- }
-
- return videojs__default['default'].createTimeRanges(results);
-};
-/**
- * Attempts to find the buffered TimeRange that contains the specified
- * time.
- *
- * @param {TimeRanges} buffered - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object
- */
-
-
-var findRange = function findRange(buffered, time) {
- return filterRanges(buffered, function (start, end) {
- return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
- });
-};
-/**
- * Returns the TimeRanges that begin later than the specified time.
- *
- * @param {TimeRanges} timeRanges - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object.
- */
-
-var findNextRange = function findNextRange(timeRanges, time) {
- return filterRanges(timeRanges, function (start) {
- return start - TIME_FUDGE_FACTOR >= time;
- });
-};
-/**
- * Returns gaps within a list of TimeRanges
- *
- * @param {TimeRanges} buffered - the TimeRanges object
- * @return {TimeRanges} a TimeRanges object of gaps
- */
-
-var findGaps = function findGaps(buffered) {
- if (buffered.length < 2) {
- return videojs__default['default'].createTimeRanges();
- }
-
- var ranges = [];
-
- for (var i = 1; i < buffered.length; i++) {
- var start = buffered.end(i - 1);
- var end = buffered.start(i);
- ranges.push([start, end]);
- }
-
- return videojs__default['default'].createTimeRanges(ranges);
-};
-/**
- * Calculate the intersection of two TimeRanges
- *
- * @param {TimeRanges} bufferA
- * @param {TimeRanges} bufferB
- * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
- */
-
-var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
- var start = null;
- var end = null;
- var arity = 0;
- var extents = [];
- var ranges = [];
-
- if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
- return videojs__default['default'].createTimeRange();
- } // Handle the case where we have both buffers and create an
- // intersection of the two
-
-
- var count = bufferA.length; // A) Gather up all start and end times
-
- while (count--) {
- extents.push({
- time: bufferA.start(count),
- type: 'start'
- });
- extents.push({
- time: bufferA.end(count),
- type: 'end'
- });
- }
-
- count = bufferB.length;
-
- while (count--) {
- extents.push({
- time: bufferB.start(count),
- type: 'start'
- });
- extents.push({
- time: bufferB.end(count),
- type: 'end'
- });
- } // B) Sort them by time
-
-
- extents.sort(function (a, b) {
- return a.time - b.time;
- }); // C) Go along one by one incrementing arity for start and decrementing
- // arity for ends
-
- for (count = 0; count < extents.length; count++) {
- if (extents[count].type === 'start') {
- arity++; // D) If arity is ever incremented to 2 we are entering an
- // overlapping range
-
- if (arity === 2) {
- start = extents[count].time;
- }
- } else if (extents[count].type === 'end') {
- arity--; // E) If arity is ever decremented to 1 we leaving an
- // overlapping range
-
- if (arity === 1) {
- end = extents[count].time;
- }
- } // F) Record overlapping ranges
-
-
- if (start !== null && end !== null) {
- ranges.push([start, end]);
- start = null;
- end = null;
- }
- }
-
- return videojs__default['default'].createTimeRanges(ranges);
-};
-/**
- * Gets a human readable string for a TimeRange
- *
- * @param {TimeRange} range
- * @return {string} a human readable string
- */
-
-var printableRange = function printableRange(range) {
- var strArr = [];
-
- if (!range || !range.length) {
- return '';
- }
-
- for (var i = 0; i < range.length; i++) {
- strArr.push(range.start(i) + ' => ' + range.end(i));
- }
-
- return strArr.join(', ');
-};
-/**
- * Calculates the amount of time left in seconds until the player hits the end of the
- * buffer and causes a rebuffer
- *
- * @param {TimeRange} buffered
- * The state of the buffer
- * @param {Numnber} currentTime
- * The current time of the player
- * @param {number} playbackRate
- * The current playback rate of the player. Defaults to 1.
- * @return {number}
- * Time until the player has to start rebuffering in seconds.
- * @function timeUntilRebuffer
- */
-
-var timeUntilRebuffer = function timeUntilRebuffer(buffered, currentTime, playbackRate) {
- if (playbackRate === void 0) {
- playbackRate = 1;
- }
-
- var bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
- return (bufferedEnd - currentTime) / playbackRate;
-};
-/**
- * Converts a TimeRanges object into an array representation
- *
- * @param {TimeRanges} timeRanges
- * @return {Array}
- */
-
-var timeRangesToArray = function timeRangesToArray(timeRanges) {
- var timeRangesList = [];
-
- for (var i = 0; i < timeRanges.length; i++) {
- timeRangesList.push({
- start: timeRanges.start(i),
- end: timeRanges.end(i)
- });
- }
-
- return timeRangesList;
-};
-/**
- * Determines if two time range objects are different.
- *
- * @param {TimeRange} a
- * the first time range object to check
- *
- * @param {TimeRange} b
- * the second time range object to check
- *
- * @return {Boolean}
- * Whether the time range objects differ
- */
-
-var isRangeDifferent = function isRangeDifferent(a, b) {
- // same object
- if (a === b) {
- return false;
- } // one or the other is undefined
-
-
- if (!a && b || !b && a) {
- return true;
- } // length is different
-
-
- if (a.length !== b.length) {
- return true;
- } // see if any start/end pair is different
-
-
- for (var i = 0; i < a.length; i++) {
- if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
- return true;
- }
- } // if the length and every pair is the same
- // this is the same time range
-
-
- return false;
-};
-var lastBufferedEnd = function lastBufferedEnd(a) {
- if (!a || !a.length || !a.end) {
- return;
- }
-
- return a.end(a.length - 1);
-};
-
-/**
- * @file playlist.js
- *
- * Playlist related utilities.
- */
-var createTimeRange = videojs__default['default'].createTimeRange;
-/**
- * A function to get a combined list of parts and segments with durations
- * and indexes.
- *
- * @param {Playlist} playlist the playlist to get the list for.
- *
- * @return {Array} The part/segment list.
- */
-
-var getPartsAndSegments = function getPartsAndSegments(playlist) {
- return (playlist.segments || []).reduce(function (acc, segment, si) {
- if (segment.parts) {
- segment.parts.forEach(function (part, pi) {
- acc.push({
- duration: part.duration,
- segmentIndex: si,
- partIndex: pi,
- part: part,
- segment: segment
- });
- });
- } else {
- acc.push({
- duration: segment.duration,
- segmentIndex: si,
- partIndex: null,
- segment: segment,
- part: null
- });
- }
-
- return acc;
- }, []);
-};
-var getLastParts = function getLastParts(media) {
- var lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
- return lastSegment && lastSegment.parts || [];
-};
-var getKnownPartCount = function getKnownPartCount(_ref) {
- var preloadSegment = _ref.preloadSegment;
-
- if (!preloadSegment) {
- return;
- }
-
- var parts = preloadSegment.parts,
- preloadHints = preloadSegment.preloadHints;
- var partCount = (preloadHints || []).reduce(function (count, hint) {
- return count + (hint.type === 'PART' ? 1 : 0);
- }, 0);
- partCount += parts && parts.length ? parts.length : 0;
- return partCount;
-};
-/**
- * Get the number of seconds to delay from the end of a
- * live playlist.
- *
- * @param {Playlist} master the master playlist
- * @param {Playlist} media the media playlist
- * @return {number} the hold back in seconds.
- */
-
-var liveEdgeDelay = function liveEdgeDelay(master, media) {
- if (media.endList) {
- return 0;
- } // dash suggestedPresentationDelay trumps everything
-
-
- if (master && master.suggestedPresentationDelay) {
- return master.suggestedPresentationDelay;
- }
-
- var hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
-
- if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
- return media.serverControl.partHoldBack;
- } else if (hasParts && media.partTargetDuration) {
- return media.partTargetDuration * 3; // finally look for full segment delays
- } else if (media.serverControl && media.serverControl.holdBack) {
- return media.serverControl.holdBack;
- } else if (media.targetDuration) {
- return media.targetDuration * 3;
- }
-
- return 0;
-};
-/**
- * walk backward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {Number} endSequence the mediaSequence to stop walking on
- */
-
-var backwardDuration = function backwardDuration(playlist, endSequence) {
- var result = 0;
- var i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
- // the interval, use it
-
- var segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
- // information that is earlier than endSequence
-
- if (segment) {
- if (typeof segment.start !== 'undefined') {
- return {
- result: segment.start,
- precise: true
- };
- }
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - segment.duration,
- precise: true
- };
- }
- }
-
- while (i--) {
- segment = playlist.segments[i];
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: result + segment.end,
- precise: true
- };
- }
-
- result += segment.duration;
-
- if (typeof segment.start !== 'undefined') {
- return {
- result: result + segment.start,
- precise: true
- };
- }
- }
-
- return {
- result: result,
- precise: false
- };
-};
-/**
- * walk forward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {number} endSequence the mediaSequence to stop walking on
- */
-
-
-var forwardDuration = function forwardDuration(playlist, endSequence) {
- var result = 0;
- var segment;
- var i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
- // information
-
- for (; i < playlist.segments.length; i++) {
- segment = playlist.segments[i];
-
- if (typeof segment.start !== 'undefined') {
- return {
- result: segment.start - result,
- precise: true
- };
- }
-
- result += segment.duration;
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - result,
- precise: true
- };
- }
- } // indicate we didn't find a useful duration estimate
-
-
- return {
- result: -1,
- precise: false
- };
-};
-/**
- * Calculate the media duration from the segments associated with a
- * playlist. The duration of a subinterval of the available segments
- * may be calculated by specifying an end index.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper boundary
- * for the playlist. Defaults to playlist length.
- * @param {number} expired the amount of time that has dropped
- * off the front of the playlist in a live scenario
- * @return {number} the duration between the first available segment
- * and end index.
- */
-
-
-var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
- if (typeof endSequence === 'undefined') {
- endSequence = playlist.mediaSequence + playlist.segments.length;
- }
-
- if (endSequence < playlist.mediaSequence) {
- return 0;
- } // do a backward walk to estimate the duration
-
-
- var backward = backwardDuration(playlist, endSequence);
-
- if (backward.precise) {
- // if we were able to base our duration estimate on timing
- // information provided directly from the Media Source, return
- // it
- return backward.result;
- } // walk forward to see if a precise duration estimate can be made
- // that way
-
-
- var forward = forwardDuration(playlist, endSequence);
-
- if (forward.precise) {
- // we found a segment that has been buffered and so it's
- // position is known precisely
- return forward.result;
- } // return the less-precise, playlist-based duration estimate
-
-
- return backward.result + expired;
-};
-/**
- * Calculates the duration of a playlist. If a start and end index
- * are specified, the duration will be for the subset of the media
- * timeline between those two indices. The total duration for live
- * playlists is always Infinity.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper
- * boundary for the playlist. Defaults to the playlist media
- * sequence number plus its length.
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @return {number} the duration between the start index and end
- * index.
- */
-
-
-var duration = function duration(playlist, endSequence, expired) {
- if (!playlist) {
- return 0;
- }
-
- if (typeof expired !== 'number') {
- expired = 0;
- } // if a slice of the total duration is not requested, use
- // playlist-level duration indicators when they're present
-
-
- if (typeof endSequence === 'undefined') {
- // if present, use the duration specified in the playlist
- if (playlist.totalDuration) {
- return playlist.totalDuration;
- } // duration should be Infinity for live playlists
-
-
- if (!playlist.endList) {
- return window__default['default'].Infinity;
- }
- } // calculate the total duration based on the segment durations
-
-
- return intervalDuration(playlist, endSequence, expired);
-};
-/**
- * Calculate the time between two indexes in the current playlist
- * neight the start- nor the end-index need to be within the current
- * playlist in which case, the targetDuration of the playlist is used
- * to approximate the durations of the segments
- *
- * @param {Array} options.durationList list to iterate over for durations.
- * @param {number} options.defaultDuration duration to use for elements before or after the durationList
- * @param {number} options.startIndex partsAndSegments index to start
- * @param {number} options.endIndex partsAndSegments index to end.
- * @return {number} the number of seconds between startIndex and endIndex
- */
-
-var sumDurations = function sumDurations(_ref2) {
- var defaultDuration = _ref2.defaultDuration,
- durationList = _ref2.durationList,
- startIndex = _ref2.startIndex,
- endIndex = _ref2.endIndex;
- var durations = 0;
-
- if (startIndex > endIndex) {
- var _ref3 = [endIndex, startIndex];
- startIndex = _ref3[0];
- endIndex = _ref3[1];
- }
-
- if (startIndex < 0) {
- for (var i = startIndex; i < Math.min(0, endIndex); i++) {
- durations += defaultDuration;
- }
-
- startIndex = 0;
- }
-
- for (var _i = startIndex; _i < endIndex; _i++) {
- durations += durationList[_i].duration;
- }
-
- return durations;
-};
-/**
- * Calculates the playlist end time
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
- * playlist end calculation should consider the safe live end
- * (truncate the playlist end by three segments). This is normally
- * used for calculating the end of the playlist's seekable range.
- * This takes into account the value of liveEdgePadding.
- * Setting liveEdgePadding to 0 is equivalent to setting this to false.
- * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
- * If this is provided, it is used in the safe live end calculation.
- * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {number} the end time of playlist
- * @function playlistEnd
- */
-
-var playlistEnd = function playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding) {
- if (!playlist || !playlist.segments) {
- return null;
- }
-
- if (playlist.endList) {
- return duration(playlist);
- }
-
- if (expired === null) {
- return null;
- }
-
- expired = expired || 0;
- var lastSegmentTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
-
- if (useSafeLiveEnd) {
- liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
- lastSegmentTime -= liveEdgePadding;
- } // don't return a time less than zero
-
-
- return Math.max(0, lastSegmentTime);
-};
-/**
- * Calculates the interval of time that is currently seekable in a
- * playlist. The returned time ranges are relative to the earliest
- * moment in the specified playlist that is still available. A full
- * seekable implementation for live streams would need to offset
- * these values by the duration of content that has expired from the
- * stream.
- *
- * @param {Object} playlist a media playlist object
- * dropped off the front of the playlist in a live scenario
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {TimeRanges} the periods of time that are valid targets
- * for seeking
- */
-
-var seekable = function seekable(playlist, expired, liveEdgePadding) {
- var useSafeLiveEnd = true;
- var seekableStart = expired || 0;
- var seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
-
- if (seekableEnd === null) {
- return createTimeRange();
- }
-
- return createTimeRange(seekableStart, seekableEnd);
-};
-/**
- * Determine the index and estimated starting time of the segment that
- * contains a specified playback position in a media playlist.
- *
- * @param {Object} options.playlist the media playlist to query
- * @param {number} options.currentTime The number of seconds since the earliest
- * possible position to determine the containing segment for
- * @param {number} options.startTime the time when the segment/part starts
- * @param {number} options.startingSegmentIndex the segment index to start looking at.
- * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
- *
- * @return {Object} an object with partIndex, segmentIndex, and startTime.
- */
-
-var getMediaInfoForTime = function getMediaInfoForTime(_ref4) {
- var playlist = _ref4.playlist,
- currentTime = _ref4.currentTime,
- startingSegmentIndex = _ref4.startingSegmentIndex,
- startingPartIndex = _ref4.startingPartIndex,
- startTime = _ref4.startTime;
- var time = currentTime - startTime;
- var partsAndSegments = getPartsAndSegments(playlist);
- var startIndex = 0;
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- var partAndSegment = partsAndSegments[i];
-
- if (startingSegmentIndex !== partAndSegment.segmentIndex) {
- continue;
- } // skip this if part index does not match.
-
-
- if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
- continue;
- }
-
- startIndex = i;
- break;
- }
-
- if (time < 0) {
- // Walk backward from startIndex in the playlist, adding durations
- // until we find a segment that contains `time` and return it
- if (startIndex > 0) {
- for (var _i2 = startIndex - 1; _i2 >= 0; _i2--) {
- var _partAndSegment = partsAndSegments[_i2];
- time += _partAndSegment.duration; // TODO: consider not using TIME_FUDGE_FACTOR at all here
-
- if (time + TIME_FUDGE_FACTOR > 0) {
- return {
- partIndex: _partAndSegment.partIndex,
- segmentIndex: _partAndSegment.segmentIndex,
- startTime: startTime - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex: startIndex,
- endIndex: _i2
- })
- };
- }
- }
- } // We were unable to find a good segment within the playlist
- // so select the first segment
-
-
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- } // When startIndex is negative, we first walk forward to first segment
- // adding target durations. If we "run out of time" before getting to
- // the first segment, return the first segment
-
-
- if (startIndex < 0) {
- for (var _i3 = startIndex; _i3 < 0; _i3++) {
- time -= playlist.targetDuration;
-
- if (time < 0) {
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- }
- }
-
- startIndex = 0;
- } // Walk forward from startIndex in the playlist, subtracting durations
- // until we find a segment that contains `time` and return it
-
-
- for (var _i4 = startIndex; _i4 < partsAndSegments.length; _i4++) {
- var _partAndSegment2 = partsAndSegments[_i4];
- time -= _partAndSegment2.duration; // TODO: consider not using TIME_FUDGE_FACTOR at all here
-
- if (time - TIME_FUDGE_FACTOR < 0) {
- return {
- partIndex: _partAndSegment2.partIndex,
- segmentIndex: _partAndSegment2.segmentIndex,
- startTime: startTime + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex: startIndex,
- endIndex: _i4
- })
- };
- }
- } // We are out of possible candidates so load the last one...
-
-
- return {
- segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
- partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
- startTime: currentTime
- };
-};
-/**
- * Check whether the playlist is blacklisted or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is blacklisted or not
- * @function isBlacklisted
- */
-
-var isBlacklisted = function isBlacklisted(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil > Date.now();
-};
-/**
- * Check whether the playlist is compatible with current playback configuration or has
- * been blacklisted permanently for being incompatible.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is incompatible or not
- * @function isIncompatible
- */
-
-var isIncompatible = function isIncompatible(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil === Infinity;
-};
-/**
- * Check whether the playlist is enabled or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is enabled or not
- * @function isEnabled
- */
-
-var isEnabled = function isEnabled(playlist) {
- var blacklisted = isBlacklisted(playlist);
- return !playlist.disabled && !blacklisted;
-};
-/**
- * Check whether the playlist has been manually disabled through the representations api.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is disabled manually or not
- * @function isDisabled
- */
-
-var isDisabled = function isDisabled(playlist) {
- return playlist.disabled;
-};
-/**
- * Returns whether the current playlist is an AES encrypted HLS stream
- *
- * @return {boolean} true if it's an AES encrypted HLS stream
- */
-
-var isAes = function isAes(media) {
- for (var i = 0; i < media.segments.length; i++) {
- if (media.segments[i].key) {
- return true;
- }
- }
-
- return false;
-};
-/**
- * Checks if the playlist has a value for the specified attribute
- *
- * @param {string} attr
- * Attribute to check for
- * @param {Object} playlist
- * The media playlist object
- * @return {boolean}
- * Whether the playlist contains a value for the attribute or not
- * @function hasAttribute
- */
-
-var hasAttribute = function hasAttribute(attr, playlist) {
- return playlist.attributes && playlist.attributes[attr];
-};
-/**
- * Estimates the time required to complete a segment download from the specified playlist
- *
- * @param {number} segmentDuration
- * Duration of requested segment
- * @param {number} bandwidth
- * Current measured bandwidth of the player
- * @param {Object} playlist
- * The media playlist object
- * @param {number=} bytesReceived
- * Number of bytes already received for the request. Defaults to 0
- * @return {number|NaN}
- * The estimated time to request the segment. NaN if bandwidth information for
- * the given playlist is unavailable
- * @function estimateSegmentRequestTime
- */
-
-var estimateSegmentRequestTime = function estimateSegmentRequestTime(segmentDuration, bandwidth, playlist, bytesReceived) {
- if (bytesReceived === void 0) {
- bytesReceived = 0;
- }
-
- if (!hasAttribute('BANDWIDTH', playlist)) {
- return NaN;
- }
-
- var size = segmentDuration * playlist.attributes.BANDWIDTH;
- return (size - bytesReceived * 8) / bandwidth;
-};
-/*
- * Returns whether the current playlist is the lowest rendition
- *
- * @return {Boolean} true if on lowest rendition
- */
-
-var isLowestEnabledRendition = function isLowestEnabledRendition(master, media) {
- if (master.playlists.length === 1) {
- return true;
- }
-
- var currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
- return master.playlists.filter(function (playlist) {
- if (!isEnabled(playlist)) {
- return false;
- }
-
- return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
- }).length === 0;
-};
-var playlistMatch = function playlistMatch(a, b) {
- // both playlits are null
- // or only one playlist is non-null
- // no match
- if (!a && !b || !a && b || a && !b) {
- return false;
- } // playlist objects are the same, match
-
-
- if (a === b) {
- return true;
- } // first try to use id as it should be the most
- // accurate
-
-
- if (a.id && b.id && a.id === b.id) {
- return true;
- } // next try to use reslovedUri as it should be the
- // second most accurate.
-
-
- if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
- return true;
- } // finally try to use uri as it should be accurate
- // but might miss a few cases for relative uris
-
-
- if (a.uri && b.uri && a.uri === b.uri) {
- return true;
- }
-
- return false;
-};
-
-var someAudioVariant = function someAudioVariant(master, callback) {
- var AUDIO = master && master.mediaGroups && master.mediaGroups.AUDIO || {};
- var found = false;
-
- for (var groupName in AUDIO) {
- for (var label in AUDIO[groupName]) {
- found = callback(AUDIO[groupName][label]);
-
- if (found) {
- break;
- }
- }
-
- if (found) {
- break;
- }
- }
-
- return !!found;
-};
-
-var isAudioOnly = function isAudioOnly(master) {
- // we are audio only if we have no main playlists but do
- // have media group playlists.
- if (!master || !master.playlists || !master.playlists.length) {
- // without audio variants or playlists this
- // is not an audio only master.
- var found = someAudioVariant(master, function (variant) {
- return variant.playlists && variant.playlists.length || variant.uri;
- });
- return found;
- } // if every playlist has only an audio codec it is audio only
-
-
- var _loop = function _loop(i) {
- var playlist = master.playlists[i];
- var CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
-
- if (CODECS && CODECS.split(',').every(function (c) {
- return codecs_js.isAudioCodec(c);
- })) {
- return "continue";
- } // playlist is in an audio group it is audio only
-
-
- var found = someAudioVariant(master, function (variant) {
- return playlistMatch(playlist, variant);
- });
-
- if (found) {
- return "continue";
- } // if we make it here this playlist isn't audio and we
- // are not audio only
-
-
- return {
- v: false
- };
- };
-
- for (var i = 0; i < master.playlists.length; i++) {
- var _ret = _loop(i);
-
- if (_ret === "continue") continue;
- if (typeof _ret === "object") return _ret.v;
- } // if we make it past every playlist without returning, then
- // this is an audio only playlist.
-
-
- return true;
-}; // exports
-
-var Playlist = {
- liveEdgeDelay: liveEdgeDelay,
- duration: duration,
- seekable: seekable,
- getMediaInfoForTime: getMediaInfoForTime,
- isEnabled: isEnabled,
- isDisabled: isDisabled,
- isBlacklisted: isBlacklisted,
- isIncompatible: isIncompatible,
- playlistEnd: playlistEnd,
- isAes: isAes,
- hasAttribute: hasAttribute,
- estimateSegmentRequestTime: estimateSegmentRequestTime,
- isLowestEnabledRendition: isLowestEnabledRendition,
- isAudioOnly: isAudioOnly,
- playlistMatch: playlistMatch
-};
-
-var log = videojs__default['default'].log;
-var createPlaylistID = function createPlaylistID(index, uri) {
- return index + "-" + uri;
-};
-/**
- * Parses a given m3u8 playlist
- *
- * @param {Function} [onwarn]
- * a function to call when the parser triggers a warning event.
- * @param {Function} [oninfo]
- * a function to call when the parser triggers an info event.
- * @param {string} manifestString
- * The downloaded manifest string
- * @param {Object[]} [customTagParsers]
- * An array of custom tag parsers for the m3u8-parser instance
- * @param {Object[]} [customTagMappers]
- * An array of custom tag mappers for the m3u8-parser instance
- * @param {boolean} [experimentalLLHLS=false]
- * Whether to keep ll-hls features in the manifest after parsing.
- * @return {Object}
- * The manifest object
- */
-
-var parseManifest = function parseManifest(_ref) {
- var onwarn = _ref.onwarn,
- oninfo = _ref.oninfo,
- manifestString = _ref.manifestString,
- _ref$customTagParsers = _ref.customTagParsers,
- customTagParsers = _ref$customTagParsers === void 0 ? [] : _ref$customTagParsers,
- _ref$customTagMappers = _ref.customTagMappers,
- customTagMappers = _ref$customTagMappers === void 0 ? [] : _ref$customTagMappers,
- experimentalLLHLS = _ref.experimentalLLHLS;
- var parser = new m3u8Parser.Parser();
-
- if (onwarn) {
- parser.on('warn', onwarn);
- }
-
- if (oninfo) {
- parser.on('info', oninfo);
- }
-
- customTagParsers.forEach(function (customParser) {
- return parser.addParser(customParser);
- });
- customTagMappers.forEach(function (mapper) {
- return parser.addTagMapper(mapper);
- });
- parser.push(manifestString);
- parser.end();
- var manifest = parser.manifest; // remove llhls features from the parsed manifest
- // if we don't want llhls support.
-
- if (!experimentalLLHLS) {
- ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
- if (manifest.hasOwnProperty(k)) {
- delete manifest[k];
- }
- });
-
- if (manifest.segments) {
- manifest.segments.forEach(function (segment) {
- ['parts', 'preloadHints'].forEach(function (k) {
- if (segment.hasOwnProperty(k)) {
- delete segment[k];
- }
- });
- });
- }
- }
-
- if (!manifest.targetDuration) {
- var targetDuration = 10;
-
- if (manifest.segments && manifest.segments.length) {
- targetDuration = manifest.segments.reduce(function (acc, s) {
- return Math.max(acc, s.duration);
- }, 0);
- }
-
- if (onwarn) {
- onwarn("manifest has no targetDuration defaulting to " + targetDuration);
- }
-
- manifest.targetDuration = targetDuration;
- }
-
- var parts = getLastParts(manifest);
-
- if (parts.length && !manifest.partTargetDuration) {
- var partTargetDuration = parts.reduce(function (acc, p) {
- return Math.max(acc, p.duration);
- }, 0);
-
- if (onwarn) {
- onwarn("manifest has no partTargetDuration defaulting to " + partTargetDuration);
- log.error('LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.');
- }
-
- manifest.partTargetDuration = partTargetDuration;
- }
-
- return manifest;
-};
-/**
- * Loops through all supported media groups in master and calls the provided
- * callback for each group
- *
- * @param {Object} master
- * The parsed master manifest object
- * @param {Function} callback
- * Callback to call for each media group
- */
-
-var forEachMediaGroup = function forEachMediaGroup(master, callback) {
- if (!master.mediaGroups) {
- return;
- }
-
- ['AUDIO', 'SUBTITLES'].forEach(function (mediaType) {
- if (!master.mediaGroups[mediaType]) {
- return;
- }
-
- for (var groupKey in master.mediaGroups[mediaType]) {
- for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
- var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
- callback(mediaProperties, mediaType, groupKey, labelKey);
- }
- }
- });
-};
-/**
- * Adds properties and attributes to the playlist to keep consistent functionality for
- * playlists throughout VHS.
- *
- * @param {Object} config
- * Arguments object
- * @param {Object} config.playlist
- * The media playlist
- * @param {string} [config.uri]
- * The uri to the media playlist (if media playlist is not from within a master
- * playlist)
- * @param {string} id
- * ID to use for the playlist
- */
-
-var setupMediaPlaylist = function setupMediaPlaylist(_ref2) {
- var playlist = _ref2.playlist,
- uri = _ref2.uri,
- id = _ref2.id;
- playlist.id = id;
- playlist.playlistErrors_ = 0;
-
- if (uri) {
- // For media playlists, m3u8-parser does not have access to a URI, as HLS media
- // playlists do not contain their own source URI, but one is needed for consistency in
- // VHS.
- playlist.uri = uri;
- } // For HLS master playlists, even though certain attributes MUST be defined, the
- // stream may still be played without them.
- // For HLS media playlists, m3u8-parser does not attach an attributes object to the
- // manifest.
- //
- // To avoid undefined reference errors through the project, and make the code easier
- // to write/read, add an empty attributes object for these cases.
-
-
- playlist.attributes = playlist.attributes || {};
-};
-/**
- * Adds ID, resolvedUri, and attributes properties to each playlist of the master, where
- * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
- * playlist references to the playlists array.
- *
- * @param {Object} master
- * The master playlist
- */
-
-var setupMediaPlaylists = function setupMediaPlaylists(master) {
- var i = master.playlists.length;
-
- while (i--) {
- var playlist = master.playlists[i];
- setupMediaPlaylist({
- playlist: playlist,
- id: createPlaylistID(i, playlist.uri)
- });
- playlist.resolvedUri = resolveUrl(master.uri, playlist.uri);
- master.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
-
- master.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
- // the stream can be played without it. Although an attributes property may have been
- // added to the playlist to prevent undefined references, issue a warning to fix the
- // manifest.
-
- if (!playlist.attributes.BANDWIDTH) {
- log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
- }
- }
-};
-/**
- * Adds resolvedUri properties to each media group.
- *
- * @param {Object} master
- * The master playlist
- */
-
-var resolveMediaGroupUris = function resolveMediaGroupUris(master) {
- forEachMediaGroup(master, function (properties) {
- if (properties.uri) {
- properties.resolvedUri = resolveUrl(master.uri, properties.uri);
- }
- });
-};
-/**
- * Creates a master playlist wrapper to insert a sole media playlist into.
- *
- * @param {Object} media
- * Media playlist
- * @param {string} uri
- * The media URI
- *
- * @return {Object}
- * Master playlist
- */
-
-var masterForMedia = function masterForMedia(media, uri) {
- var id = createPlaylistID(0, uri);
- var master = {
- mediaGroups: {
- 'AUDIO': {},
- 'VIDEO': {},
- 'CLOSED-CAPTIONS': {},
- 'SUBTITLES': {}
- },
- uri: window__default['default'].location.href,
- resolvedUri: window__default['default'].location.href,
- playlists: [{
- uri: uri,
- id: id,
- resolvedUri: uri,
- // m3u8-parser does not attach an attributes property to media playlists so make
- // sure that the property is attached to avoid undefined reference errors
- attributes: {}
- }]
- }; // set up ID reference
-
- master.playlists[id] = master.playlists[0]; // URI reference added for backwards compatibility
-
- master.playlists[uri] = master.playlists[0];
- return master;
-};
-/**
- * Does an in-place update of the master manifest to add updated playlist URI references
- * as well as other properties needed by VHS that aren't included by the parser.
- *
- * @param {Object} master
- * Master manifest object
- * @param {string} uri
- * The source URI
- */
-
-var addPropertiesToMaster = function addPropertiesToMaster(master, uri) {
- master.uri = uri;
-
- for (var i = 0; i < master.playlists.length; i++) {
- if (!master.playlists[i].uri) {
- // Set up phony URIs for the playlists since playlists are referenced by their URIs
- // throughout VHS, but some formats (e.g., DASH) don't have external URIs
- // TODO: consider adding dummy URIs in mpd-parser
- var phonyUri = "placeholder-uri-" + i;
- master.playlists[i].uri = phonyUri;
- }
- }
-
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- var groupId = "placeholder-uri-" + mediaType + "-" + groupKey + "-" + labelKey;
-
- if (!properties.playlists || !properties.playlists.length) {
- properties.playlists = [_extends__default['default']({}, properties)];
- }
-
- properties.playlists.forEach(function (p, i) {
- var id = createPlaylistID(i, groupId);
-
- if (p.uri) {
- p.resolvedUri = p.resolvedUri || resolveUrl(master.uri, p.uri);
- } else {
- // DEPRECATED, this has been added to prevent a breaking change.
- // previously we only ever had a single media group playlist, so
- // we mark the first playlist uri without prepending the index as we used to
- // ideally we would do all of the playlists the same way.
- p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
- // the placeholder again
-
- p.resolvedUri = p.uri;
- }
-
- p.id = p.id || id; // add an empty attributes object, all playlists are
- // expected to have this.
-
- p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
-
- master.playlists[p.id] = p;
- master.playlists[p.uri] = p;
- });
- });
- setupMediaPlaylists(master);
- resolveMediaGroupUris(master);
-};
-
-var mergeOptions$2 = videojs__default['default'].mergeOptions,
- EventTarget$1 = videojs__default['default'].EventTarget;
-
-var addLLHLSQueryDirectives = function addLLHLSQueryDirectives(uri, media) {
- if (media.endList) {
- return uri;
- }
-
- var query = [];
-
- if (media.serverControl && media.serverControl.canBlockReload) {
- var preloadSegment = media.preloadSegment; // next msn is a zero based value, length is not.
-
- var nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
- // that we are going to request a part of that preload segment.
- // the logic below is used to determine that.
-
- if (preloadSegment) {
- var parts = preloadSegment.parts || []; // _HLS_part is a zero based index
-
- var nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
- // length of parts, then we know we had part preload hints
- // and we need to add the _HLS_part= query
-
- if (nextPart > -1 && nextPart !== parts.length - 1) {
- // add existing parts to our preload hints
- query.push("_HLS_part=" + nextPart);
- } // this if statement makes sure that we request the msn
- // of the preload segment if:
- // 1. the preload segment had parts (and was not yet a full segment)
- // but was added to our segments array
- // 2. the preload segment had preload hints for parts that are not in
- // the manifest yet.
- // in all other cases we want the segment after the preload segment
- // which will be given by using media.segments.length because it is 1 based
- // rather than 0 based.
-
-
- if (nextPart > -1 || parts.length) {
- nextMSN--;
- }
- } // add _HLS_msn= in front of any _HLS_part query
-
-
- query.unshift("_HLS_msn=" + nextMSN);
- }
-
- if (media.serverControl && media.serverControl.canSkipUntil) {
- // add _HLS_skip= infront of all other queries.
- query.unshift('_HLS_skip=' + (media.serverControl.canSkipDateranges ? 'v2' : 'YES'));
- }
-
- query.forEach(function (str, i) {
- var symbol = i === 0 ? '?' : '&';
- uri += "" + symbol + str;
- });
- return uri;
-};
-/**
- * Returns a new segment object with properties and
- * the parts array merged.
- *
- * @param {Object} a the old segment
- * @param {Object} b the new segment
- *
- * @return {Object} the merged segment
- */
-
-
-var updateSegment = function updateSegment(a, b) {
- if (!a) {
- return b;
- }
-
- var result = mergeOptions$2(a, b); // if only the old segment has preload hints
- // and the new one does not, remove preload hints.
-
- if (a.preloadHints && !b.preloadHints) {
- delete result.preloadHints;
- } // if only the old segment has parts
- // then the parts are no longer valid
-
-
- if (a.parts && !b.parts) {
- delete result.parts; // if both segments have parts
- // copy part propeties from the old segment
- // to the new one.
- } else if (a.parts && b.parts) {
- for (var i = 0; i < b.parts.length; i++) {
- if (a.parts && a.parts[i]) {
- result.parts[i] = mergeOptions$2(a.parts[i], b.parts[i]);
- }
- }
- } // set skipped to false for segments that have
- // have had information merged from the old segment.
-
-
- if (!a.skipped && b.skipped) {
- result.skipped = false;
- } // set preload to false for segments that have
- // had information added in the new segment.
-
-
- if (a.preload && !b.preload) {
- result.preload = false;
- }
-
- return result;
-};
-/**
- * Returns a new array of segments that is the result of merging
- * properties from an older list of segments onto an updated
- * list. No properties on the updated playlist will be ovewritten.
- *
- * @param {Array} original the outdated list of segments
- * @param {Array} update the updated list of segments
- * @param {number=} offset the index of the first update
- * segment in the original segment list. For non-live playlists,
- * this should always be zero and does not need to be
- * specified. For live playlists, it should be the difference
- * between the media sequence numbers in the original and updated
- * playlists.
- * @return {Array} a list of merged segment objects
- */
-
-var updateSegments = function updateSegments(original, update, offset) {
- var oldSegments = original.slice();
- var newSegments = update.slice();
- offset = offset || 0;
- var result = [];
- var currentMap;
-
- for (var newIndex = 0; newIndex < newSegments.length; newIndex++) {
- var oldSegment = oldSegments[newIndex + offset];
- var newSegment = newSegments[newIndex];
-
- if (oldSegment) {
- currentMap = oldSegment.map || currentMap;
- result.push(updateSegment(oldSegment, newSegment));
- } else {
- // carry over map to new segment if it is missing
- if (currentMap && !newSegment.map) {
- newSegment.map = currentMap;
- }
-
- result.push(newSegment);
- }
- }
-
- return result;
-};
-var resolveSegmentUris = function resolveSegmentUris(segment, baseUri) {
- // preloadSegment will not have a uri at all
- // as the segment isn't actually in the manifest yet, only parts
- if (!segment.resolvedUri && segment.uri) {
- segment.resolvedUri = resolveUrl(baseUri, segment.uri);
- }
-
- if (segment.key && !segment.key.resolvedUri) {
- segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
- }
-
- if (segment.map && !segment.map.resolvedUri) {
- segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
- }
-
- if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
- segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
- }
-
- if (segment.parts && segment.parts.length) {
- segment.parts.forEach(function (p) {
- if (p.resolvedUri) {
- return;
- }
-
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
-
- if (segment.preloadHints && segment.preloadHints.length) {
- segment.preloadHints.forEach(function (p) {
- if (p.resolvedUri) {
- return;
- }
-
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
-};
-
-var getAllSegments = function getAllSegments(media) {
- var segments = media.segments || [];
- var preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
- // a usable segment, only include a preloadSegment that has
- // parts.
-
- if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
- // if preloadHints has a MAP that means that the
- // init segment is going to change. We cannot use any of the parts
- // from this preload segment.
- if (preloadSegment.preloadHints) {
- for (var i = 0; i < preloadSegment.preloadHints.length; i++) {
- if (preloadSegment.preloadHints[i].type === 'MAP') {
- return segments;
- }
- }
- } // set the duration for our preload segment to target duration.
-
-
- preloadSegment.duration = media.targetDuration;
- preloadSegment.preload = true;
- segments.push(preloadSegment);
- }
-
- return segments;
-}; // consider the playlist unchanged if the playlist object is the same or
-// the number of segments is equal, the media sequence number is unchanged,
-// and this playlist hasn't become the end of the playlist
-
-
-var isPlaylistUnchanged = function isPlaylistUnchanged(a, b) {
- return a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence;
-};
-/**
- * Returns a new master playlist that is the result of merging an
- * updated media playlist into the original version. If the
- * updated media playlist does not match any of the playlist
- * entries in the original master playlist, null is returned.
- *
- * @param {Object} master a parsed master M3U8 object
- * @param {Object} media a parsed media M3U8 object
- * @return {Object} a new object that represents the original
- * master playlist with the updated media playlist merged in, or
- * null if the merge produced no change.
- */
-
-var updateMaster$1 = function updateMaster(master, newMedia, unchangedCheck) {
- if (unchangedCheck === void 0) {
- unchangedCheck = isPlaylistUnchanged;
- }
-
- var result = mergeOptions$2(master, {});
- var oldMedia = result.playlists[newMedia.id];
-
- if (!oldMedia) {
- return null;
- }
-
- if (unchangedCheck(oldMedia, newMedia)) {
- return null;
- }
-
- newMedia.segments = getAllSegments(newMedia);
- var mergedPlaylist = mergeOptions$2(oldMedia, newMedia); // always use the new media's preload segment
-
- if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
- delete mergedPlaylist.preloadSegment;
- } // if the update could overlap existing segment information, merge the two segment lists
-
-
- if (oldMedia.segments) {
- if (newMedia.skip) {
- newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
- // old properties into the new segments
-
- for (var i = 0; i < newMedia.skip.skippedSegments; i++) {
- newMedia.segments.unshift({
- skipped: true
- });
- }
- }
-
- mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
- } // resolve any segment URIs to prevent us from having to do it later
-
-
- mergedPlaylist.segments.forEach(function (segment) {
- resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
- }); // TODO Right now in the playlists array there are two references to each playlist, one
- // that is referenced by index, and one by URI. The index reference may no longer be
- // necessary.
-
- for (var _i = 0; _i < result.playlists.length; _i++) {
- if (result.playlists[_i].id === newMedia.id) {
- result.playlists[_i] = mergedPlaylist;
- }
- }
-
- result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
-
- result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
-
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- if (!properties.playlists) {
- return;
- }
-
- for (var _i2 = 0; _i2 < properties.playlists.length; _i2++) {
- if (newMedia.id === properties.playlists[_i2].id) {
- properties.playlists[_i2] = newMedia;
- }
- }
- });
- return result;
-};
-/**
- * Calculates the time to wait before refreshing a live playlist
- *
- * @param {Object} media
- * The current media
- * @param {boolean} update
- * True if there were any updates from the last refresh, false otherwise
- * @return {number}
- * The time in ms to wait before refreshing the live playlist
- */
-
-var refreshDelay = function refreshDelay(media, update) {
- var lastSegment = media.segments[media.segments.length - 1];
- var lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
- var lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
-
- if (update && lastDuration) {
- return lastDuration * 1000;
- } // if the playlist is unchanged since the last reload or last segment duration
- // cannot be determined, try again after half the target duration
-
-
- return (media.partTargetDuration || media.targetDuration || 10) * 500;
-};
-/**
- * Load a playlist from a remote location
- *
- * @class PlaylistLoader
- * @extends Stream
- * @param {string|Object} src url or object of manifest
- * @param {boolean} withCredentials the withCredentials xhr option
- * @class
- */
-
-var PlaylistLoader = /*#__PURE__*/function (_EventTarget) {
- _inheritsLoose__default['default'](PlaylistLoader, _EventTarget);
-
- function PlaylistLoader(src, vhs, options) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _EventTarget.call(this) || this;
-
- if (!src) {
- throw new Error('A non-empty playlist URL or object is required');
- }
-
- _this.logger_ = logger('PlaylistLoader');
- var _options = options,
- _options$withCredenti = _options.withCredentials,
- withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
- _options$handleManife = _options.handleManifestRedirects,
- handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
- _this.src = src;
- _this.vhs_ = vhs;
- _this.withCredentials = withCredentials;
- _this.handleManifestRedirects = handleManifestRedirects;
- var vhsOptions = vhs.options_;
- _this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
- _this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
- _this.experimentalLLHLS = vhsOptions && vhsOptions.experimentalLLHLS || false; // initialize the loader state
-
- _this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
-
- _this.handleMediaupdatetimeout_ = _this.handleMediaupdatetimeout_.bind(_assertThisInitialized__default['default'](_this));
-
- _this.on('mediaupdatetimeout', _this.handleMediaupdatetimeout_);
-
- return _this;
- }
-
- var _proto = PlaylistLoader.prototype;
-
- _proto.handleMediaupdatetimeout_ = function handleMediaupdatetimeout_() {
- var _this2 = this;
-
- if (this.state !== 'HAVE_METADATA') {
- // only refresh the media playlist if no other activity is going on
- return;
- }
-
- var media = this.media();
- var uri = resolveUrl(this.master.uri, media.uri);
-
- if (this.experimentalLLHLS) {
- uri = addLLHLSQueryDirectives(uri, media);
- }
-
- this.state = 'HAVE_CURRENT_METADATA';
- this.request = this.vhs_.xhr({
- uri: uri,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this2.request) {
- return;
- }
-
- if (error) {
- return _this2.playlistRequestError(_this2.request, _this2.media(), 'HAVE_METADATA');
- }
-
- _this2.haveMetadata({
- playlistString: _this2.request.responseText,
- url: _this2.media().uri,
- id: _this2.media().id
- });
- });
- };
-
- _proto.playlistRequestError = function playlistRequestError(xhr, playlist, startingState) {
- var uri = playlist.uri,
- id = playlist.id; // any in-flight request is now finished
-
- this.request = null;
-
- if (startingState) {
- this.state = startingState;
- }
-
- this.error = {
- playlist: this.master.playlists[id],
- status: xhr.status,
- message: "HLS playlist request error at URL: " + uri + ".",
- responseText: xhr.responseText,
- code: xhr.status >= 500 ? 4 : 2
- };
- this.trigger('error');
- };
-
- _proto.parseManifest_ = function parseManifest_(_ref) {
- var _this3 = this;
-
- var url = _ref.url,
- manifestString = _ref.manifestString;
- return parseManifest({
- onwarn: function onwarn(_ref2) {
- var message = _ref2.message;
- return _this3.logger_("m3u8-parser warn for " + url + ": " + message);
- },
- oninfo: function oninfo(_ref3) {
- var message = _ref3.message;
- return _this3.logger_("m3u8-parser info for " + url + ": " + message);
- },
- manifestString: manifestString,
- customTagParsers: this.customTagParsers,
- customTagMappers: this.customTagMappers,
- experimentalLLHLS: this.experimentalLLHLS
- });
- }
- /**
- * Update the playlist loader's state in response to a new or updated playlist.
- *
- * @param {string} [playlistString]
- * Playlist string (if playlistObject is not provided)
- * @param {Object} [playlistObject]
- * Playlist object (if playlistString is not provided)
- * @param {string} url
- * URL of playlist
- * @param {string} id
- * ID to use for playlist
- */
- ;
-
- _proto.haveMetadata = function haveMetadata(_ref4) {
- var _this4 = this;
-
- var playlistString = _ref4.playlistString,
- playlistObject = _ref4.playlistObject,
- url = _ref4.url,
- id = _ref4.id;
- // any in-flight request is now finished
- this.request = null;
- this.state = 'HAVE_METADATA';
- var playlist = playlistObject || this.parseManifest_({
- url: url,
- manifestString: playlistString
- });
- playlist.lastRequest = Date.now();
- setupMediaPlaylist({
- playlist: playlist,
- uri: url,
- id: id
- }); // merge this playlist into the master
-
- var update = updateMaster$1(this.master, playlist);
- this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
-
- if (update) {
- this.master = update;
- this.media_ = this.master.playlists[id];
- } else {
- this.trigger('playlistunchanged');
- } // refresh live playlists after a target duration passes
-
-
- if (!this.media().endList) {
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- _this4.trigger('mediaupdatetimeout');
- }, refreshDelay(this.media(), !!update));
- }
-
- this.trigger('loadedplaylist');
- }
- /**
- * Abort any outstanding work and clean up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.stopRequest();
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- window__default['default'].clearTimeout(this.finalRenditionTimeout);
- this.off();
- };
-
- _proto.stopRequest = function stopRequest() {
- if (this.request) {
- var oldRequest = this.request;
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- }
- /**
- * When called without any arguments, returns the currently
- * active media playlist. When called with a single argument,
- * triggers the playlist loader to asynchronously switch to the
- * specified media playlist. Calling this method while the
- * loader is in the HAVE_NOTHING causes an error to be emitted
- * but otherwise has no effect.
- *
- * @param {Object=} playlist the parsed media playlist
- * object to switch to
- * @param {boolean=} shouldDelay whether we should delay the request by half target duration
- *
- * @return {Playlist} the current loaded media
- */
- ;
-
- _proto.media = function media(playlist, shouldDelay) {
- var _this5 = this;
-
- // getter
- if (!playlist) {
- return this.media_;
- } // setter
-
-
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- } // find the playlist object if the target playlist has been
- // specified by URI
-
-
- if (typeof playlist === 'string') {
- if (!this.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
-
- playlist = this.master.playlists[playlist];
- }
-
- window__default['default'].clearTimeout(this.finalRenditionTimeout);
-
- if (shouldDelay) {
- var delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
- this.finalRenditionTimeout = window__default['default'].setTimeout(this.media.bind(this, playlist, false), delay);
- return;
- }
-
- var startingState = this.state;
- var mediaChange = !this.media_ || playlist.id !== this.media_.id;
- var masterPlaylistRef = this.master.playlists[playlist.id]; // switch to fully loaded playlists immediately
-
- if (masterPlaylistRef && masterPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
- // media playlist or, for the case of demuxed audio, a resolved audio media group)
- playlist.endList && playlist.segments.length) {
- // abort outstanding playlist requests
- if (this.request) {
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- }
-
- this.state = 'HAVE_METADATA';
- this.media_ = playlist; // trigger media change if the active media has been updated
-
- if (mediaChange) {
- this.trigger('mediachanging');
-
- if (startingState === 'HAVE_MASTER') {
- // The initial playlist was a master manifest, and the first media selected was
- // also provided (in the form of a resolved playlist object) as part of the
- // source object (rather than just a URL). Therefore, since the media playlist
- // doesn't need to be requested, loadedmetadata won't trigger as part of the
- // normal flow, and needs an explicit trigger here.
- this.trigger('loadedmetadata');
- } else {
- this.trigger('mediachange');
- }
- }
-
- return;
- } // switching to the active playlist is a no-op
-
-
- if (!mediaChange) {
- return;
- }
-
- this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
-
- if (this.request) {
- if (playlist.resolvedUri === this.request.url) {
- // requesting to switch to the same playlist multiple times
- // has no effect after the first
- return;
- }
-
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- } // request the new playlist
-
-
- if (this.media_) {
- this.trigger('mediachanging');
- }
-
- this.request = this.vhs_.xhr({
- uri: playlist.resolvedUri,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this5.request) {
- return;
- }
-
- playlist.lastRequest = Date.now();
- playlist.resolvedUri = resolveManifestRedirect(_this5.handleManifestRedirects, playlist.resolvedUri, req);
-
- if (error) {
- return _this5.playlistRequestError(_this5.request, playlist, startingState);
- }
-
- _this5.haveMetadata({
- playlistString: req.responseText,
- url: playlist.uri,
- id: playlist.id
- }); // fire loadedmetadata the first time a media playlist is loaded
-
-
- if (startingState === 'HAVE_MASTER') {
- _this5.trigger('loadedmetadata');
- } else {
- _this5.trigger('mediachange');
- }
- });
- }
- /**
- * pause loading of the playlist
- */
- ;
-
- _proto.pause = function pause() {
- this.stopRequest();
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
-
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- } // Need to restore state now that no activity is happening
-
-
- if (this.state === 'SWITCHING_MEDIA') {
- // if the loader was in the process of switching media, it should either return to
- // HAVE_MASTER or HAVE_METADATA depending on if the loader has loaded a media
- // playlist yet. This is determined by the existence of loader.media_
- if (this.media_) {
- this.state = 'HAVE_METADATA';
- } else {
- this.state = 'HAVE_MASTER';
- }
- } else if (this.state === 'HAVE_CURRENT_METADATA') {
- this.state = 'HAVE_METADATA';
- }
- }
- /**
- * start loading of the playlist
- */
- ;
-
- _proto.load = function load(shouldDelay) {
- var _this6 = this;
-
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- var media = this.media();
-
- if (shouldDelay) {
- var delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
- this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- return _this6.load();
- }, delay);
- return;
- }
-
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- }
- /**
- * start loading of the playlist
- */
- ;
-
- _proto.start = function start() {
- var _this7 = this;
-
- this.started = true;
-
- if (typeof this.src === 'object') {
- // in the case of an entirely constructed manifest object (meaning there's no actual
- // manifest on a server), default the uri to the page's href
- if (!this.src.uri) {
- this.src.uri = window__default['default'].location.href;
- } // resolvedUri is added on internally after the initial request. Since there's no
- // request for pre-resolved manifests, add on resolvedUri here.
-
-
- this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
- // request can be skipped (since the top level of the manifest, at a minimum, is
- // already available as a parsed manifest object). However, if the manifest object
- // represents a master playlist, some media playlists may need to be resolved before
- // the starting segment list is available. Therefore, go directly to setup of the
- // initial playlist, and let the normal flow continue from there.
- //
- // Note that the call to setup is asynchronous, as other sections of VHS may assume
- // that the first request is asynchronous.
-
- setTimeout(function () {
- _this7.setupInitialPlaylist(_this7.src);
- }, 0);
- return;
- } // request the specified URL
-
-
- this.request = this.vhs_.xhr({
- uri: this.src,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this7.request) {
- return;
- } // clear the loader's request reference
-
-
- _this7.request = null;
-
- if (error) {
- _this7.error = {
- status: req.status,
- message: "HLS playlist request error at URL: " + _this7.src + ".",
- responseText: req.responseText,
- // MEDIA_ERR_NETWORK
- code: 2
- };
-
- if (_this7.state === 'HAVE_NOTHING') {
- _this7.started = false;
- }
-
- return _this7.trigger('error');
- }
-
- _this7.src = resolveManifestRedirect(_this7.handleManifestRedirects, _this7.src, req);
-
- var manifest = _this7.parseManifest_({
- manifestString: req.responseText,
- url: _this7.src
- });
-
- _this7.setupInitialPlaylist(manifest);
- });
- };
-
- _proto.srcUri = function srcUri() {
- return typeof this.src === 'string' ? this.src : this.src.uri;
- }
- /**
- * Given a manifest object that's either a master or media playlist, trigger the proper
- * events and set the state of the playlist loader.
- *
- * If the manifest object represents a master playlist, `loadedplaylist` will be
- * triggered to allow listeners to select a playlist. If none is selected, the loader
- * will default to the first one in the playlists array.
- *
- * If the manifest object represents a media playlist, `loadedplaylist` will be
- * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
- *
- * In the case of a media playlist, a master playlist object wrapper with one playlist
- * will be created so that all logic can handle playlists in the same fashion (as an
- * assumed manifest object schema).
- *
- * @param {Object} manifest
- * The parsed manifest object
- */
- ;
-
- _proto.setupInitialPlaylist = function setupInitialPlaylist(manifest) {
- this.state = 'HAVE_MASTER';
-
- if (manifest.playlists) {
- this.master = manifest;
- addPropertiesToMaster(this.master, this.srcUri()); // If the initial master playlist has playlists wtih segments already resolved,
- // then resolve URIs in advance, as they are usually done after a playlist request,
- // which may not happen if the playlist is resolved.
-
- manifest.playlists.forEach(function (playlist) {
- playlist.segments = getAllSegments(playlist);
- playlist.segments.forEach(function (segment) {
- resolveSegmentUris(segment, playlist.resolvedUri);
- });
- });
- this.trigger('loadedplaylist');
-
- if (!this.request) {
- // no media playlist was specifically selected so start
- // from the first listed one
- this.media(this.master.playlists[0]);
- }
-
- return;
- } // In order to support media playlists passed in as vhs-json, the case where the uri
- // is not provided as part of the manifest should be considered, and an appropriate
- // default used.
-
-
- var uri = this.srcUri() || window__default['default'].location.href;
- this.master = masterForMedia(manifest, uri);
- this.haveMetadata({
- playlistObject: manifest,
- url: uri,
- id: this.master.playlists[0].id
- });
- this.trigger('loadedmetadata');
- };
-
- return PlaylistLoader;
-}(EventTarget$1);
-
-/**
- * @file xhr.js
- */
-var videojsXHR = videojs__default['default'].xhr,
- mergeOptions$1 = videojs__default['default'].mergeOptions;
-
-var callbackWrapper = function callbackWrapper(request, error, response, callback) {
- var reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
-
- if (!error && reqResponse) {
- request.responseTime = Date.now();
- request.roundTripTime = request.responseTime - request.requestTime;
- request.bytesReceived = reqResponse.byteLength || reqResponse.length;
-
- if (!request.bandwidth) {
- request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
- }
- }
-
- if (response.headers) {
- request.responseHeaders = response.headers;
- } // videojs.xhr now uses a specific code on the error
- // object to signal that a request has timed out instead
- // of setting a boolean on the request object
-
-
- if (error && error.code === 'ETIMEDOUT') {
- request.timedout = true;
- } // videojs.xhr no longer considers status codes outside of 200 and 0
- // (for file uris) to be errors, but the old XHR did, so emulate that
- // behavior. Status 206 may be used in response to byterange requests.
-
-
- if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
- error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
- }
-
- callback(error, request);
-};
-
-var xhrFactory = function xhrFactory() {
- var xhr = function XhrFunction(options, callback) {
- // Add a default timeout
- options = mergeOptions$1({
- timeout: 45e3
- }, options); // Allow an optional user-specified function to modify the option
- // object before we construct the xhr request
-
- var beforeRequest = XhrFunction.beforeRequest || videojs__default['default'].Vhs.xhr.beforeRequest;
-
- if (beforeRequest && typeof beforeRequest === 'function') {
- var newOptions = beforeRequest(options);
-
- if (newOptions) {
- options = newOptions;
- }
- } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
- // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
-
-
- var xhrMethod = videojs__default['default'].Vhs.xhr.original === true ? videojsXHR : videojs__default['default'].Vhs.xhr;
- var request = xhrMethod(options, function (error, response) {
- return callbackWrapper(request, error, response, callback);
- });
- var originalAbort = request.abort;
-
- request.abort = function () {
- request.aborted = true;
- return originalAbort.apply(request, arguments);
- };
-
- request.uri = options.uri;
- request.requestTime = Date.now();
- return request;
- };
-
- xhr.original = true;
- return xhr;
-};
-/**
- * Turns segment byterange into a string suitable for use in
- * HTTP Range requests
- *
- * @param {Object} byterange - an object with two values defining the start and end
- * of a byte-range
- */
-
-
-var byterangeStr = function byterangeStr(byterange) {
- // `byterangeEnd` is one less than `offset + length` because the HTTP range
- // header uses inclusive ranges
- var byterangeEnd = byterange.offset + byterange.length - 1;
- var byterangeStart = byterange.offset;
- return 'bytes=' + byterangeStart + '-' + byterangeEnd;
-};
-/**
- * Defines headers for use in the xhr request for a particular segment.
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- */
-
-
-var segmentXhrHeaders = function segmentXhrHeaders(segment) {
- var headers = {};
-
- if (segment.byterange) {
- headers.Range = byterangeStr(segment.byterange);
- }
-
- return headers;
-};
-
-/**
- * @file bin-utils.js
- */
-
-/**
- * convert a TimeRange to text
- *
- * @param {TimeRange} range the timerange to use for conversion
- * @param {number} i the iterator on the range to convert
- * @return {string} the range in string format
- */
-var textRange = function textRange(range, i) {
- return range.start(i) + '-' + range.end(i);
-};
-/**
- * format a number as hex string
- *
- * @param {number} e The number
- * @param {number} i the iterator
- * @return {string} the hex formatted number as a string
- */
-
-
-var formatHexString = function formatHexString(e, i) {
- var value = e.toString(16);
- return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
-};
-
-var formatAsciiString = function formatAsciiString(e) {
- if (e >= 0x20 && e < 0x7e) {
- return String.fromCharCode(e);
- }
-
- return '.';
-};
-/**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-
-
-var createTransferableMessage = function createTransferableMessage(message) {
- var transferable = {};
- Object.keys(message).forEach(function (key) {
- var value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
- return transferable;
-};
-/**
- * Returns a unique string identifier for a media initialization
- * segment.
- *
- * @param {Object} initSegment
- * the init segment object.
- *
- * @return {string} the generated init segment id
- */
-
-var initSegmentId = function initSegmentId(initSegment) {
- var byterange = initSegment.byterange || {
- length: Infinity,
- offset: 0
- };
- return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
-};
-/**
- * Returns a unique string identifier for a media segment key.
- *
- * @param {Object} key the encryption key
- * @return {string} the unique id for the media segment key.
- */
-
-var segmentKeyId = function segmentKeyId(key) {
- return key.resolvedUri;
-};
-/**
- * utils to help dump binary data to the console
- *
- * @param {Array|TypedArray} data
- * data to dump to a string
- *
- * @return {string} the data as a hex string.
- */
-
-var hexDump = function hexDump(data) {
- var bytes = Array.prototype.slice.call(data);
- var step = 16;
- var result = '';
- var hex;
- var ascii;
-
- for (var j = 0; j < bytes.length / step; j++) {
- hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
- ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
- result += hex + ' ' + ascii + '\n';
- }
-
- return result;
-};
-var tagDump = function tagDump(_ref) {
- var bytes = _ref.bytes;
- return hexDump(bytes);
-};
-var textRanges = function textRanges(ranges) {
- var result = '';
- var i;
-
- for (i = 0; i < ranges.length; i++) {
- result += textRange(ranges, i) + ' ';
- }
-
- return result;
-};
-
-var utils = /*#__PURE__*/Object.freeze({
- __proto__: null,
- createTransferableMessage: createTransferableMessage,
- initSegmentId: initSegmentId,
- segmentKeyId: segmentKeyId,
- hexDump: hexDump,
- tagDump: tagDump,
- textRanges: textRanges
-});
-
-// TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
-// 25% was arbitrarily chosen, and may need to be refined over time.
-
-var SEGMENT_END_FUDGE_PERCENT = 0.25;
-/**
- * Converts a player time (any time that can be gotten/set from player.currentTime(),
- * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
- * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
- *
- * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
- * point" (a point where we have a mapping from program time to player time, with player
- * time being the post transmux start of the segment).
- *
- * For more details, see [this doc](../../docs/program-time-from-player-time.md).
- *
- * @param {number} playerTime the player time
- * @param {Object} segment the segment which contains the player time
- * @return {Date} program time
- */
-
-var playerTimeToProgramTime = function playerTimeToProgramTime(playerTime, segment) {
- if (!segment.dateTimeObject) {
- // Can't convert without an "anchor point" for the program time (i.e., a time that can
- // be used to map the start of a segment with a real world time).
- return null;
- }
-
- var transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
- var transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
-
- var startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
- var offsetFromSegmentStart = playerTime - startOfSegment;
- return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
-};
-var originalSegmentVideoDuration = function originalSegmentVideoDuration(videoTimingInfo) {
- return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
-};
-/**
- * Finds a segment that contains the time requested given as an ISO-8601 string. The
- * returned segment might be an estimate or an accurate match.
- *
- * @param {string} programTime The ISO-8601 programTime to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-
-var findSegmentForProgramTime = function findSegmentForProgramTime(programTime, playlist) {
- // Assumptions:
- // - verifyProgramDateTimeTags has already been run
- // - live streams have been started
- var dateTimeObject;
-
- try {
- dateTimeObject = new Date(programTime);
- } catch (e) {
- return null;
- }
-
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- var segment = playlist.segments[0];
-
- if (dateTimeObject < segment.dateTimeObject) {
- // Requested time is before stream start.
- return null;
- }
-
- for (var i = 0; i < playlist.segments.length - 1; i++) {
- segment = playlist.segments[i];
- var nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
-
- if (dateTimeObject < nextSegmentStart) {
- break;
- }
- }
-
- var lastSegment = playlist.segments[playlist.segments.length - 1];
- var lastSegmentStart = lastSegment.dateTimeObject;
- var lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
- var lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
-
- if (dateTimeObject > lastSegmentEnd) {
- // Beyond the end of the stream, or our best guess of the end of the stream.
- return null;
- }
-
- if (dateTimeObject > lastSegmentStart) {
- segment = lastSegment;
- }
-
- return {
- segment: segment,
- estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
- // Although, given that all segments have accurate date time objects, the segment
- // selected should be accurate, unless the video has been transmuxed at some point
- // (determined by the presence of the videoTimingInfo object), the segment's "player
- // time" (the start time in the player) can't be considered accurate.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
-};
-/**
- * Finds a segment that contains the given player time(in seconds).
- *
- * @param {number} time The player time to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-
-var findSegmentForPlayerTime = function findSegmentForPlayerTime(time, playlist) {
- // Assumptions:
- // - there will always be a segment.duration
- // - we can start from zero
- // - segments are in time order
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- var segmentEnd = 0;
- var segment;
-
- for (var i = 0; i < playlist.segments.length; i++) {
- segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
- // should contain the most accurate values we have for the segment's player times.
- //
- // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
- // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
- // calculate an end value.
-
- segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
-
- if (time <= segmentEnd) {
- break;
- }
- }
-
- var lastSegment = playlist.segments[playlist.segments.length - 1];
-
- if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
- // The time requested is beyond the stream end.
- return null;
- }
-
- if (time > segmentEnd) {
- // The time is within or beyond the last segment.
- //
- // Check to see if the time is beyond a reasonable guess of the end of the stream.
- if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
- // Technically, because the duration value is only an estimate, the time may still
- // exist in the last segment, however, there isn't enough information to make even
- // a reasonable estimate.
- return null;
- }
-
- segment = lastSegment;
- }
-
- return {
- segment: segment,
- estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
- // Because videoTimingInfo is only set after transmux, it is the only way to get
- // accurate timing values.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
-};
-/**
- * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
- * If the offset returned is positive, the programTime occurs after the
- * comparisonTimestamp.
- * If the offset is negative, the programTime occurs before the comparisonTimestamp.
- *
- * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
- * @param {string} programTime The programTime as an ISO-8601 string
- * @return {number} offset
- */
-
-var getOffsetFromTimestamp = function getOffsetFromTimestamp(comparisonTimeStamp, programTime) {
- var segmentDateTime;
- var programDateTime;
-
- try {
- segmentDateTime = new Date(comparisonTimeStamp);
- programDateTime = new Date(programTime);
- } catch (e) {// TODO handle error
- }
-
- var segmentTimeEpoch = segmentDateTime.getTime();
- var programTimeEpoch = programDateTime.getTime();
- return (programTimeEpoch - segmentTimeEpoch) / 1000;
-};
-/**
- * Checks that all segments in this playlist have programDateTime tags.
- *
- * @param {Object} playlist A playlist object
- */
-
-var verifyProgramDateTimeTags = function verifyProgramDateTimeTags(playlist) {
- if (!playlist.segments || playlist.segments.length === 0) {
- return false;
- }
-
- for (var i = 0; i < playlist.segments.length; i++) {
- var segment = playlist.segments[i];
-
- if (!segment.dateTimeObject) {
- return false;
- }
- }
-
- return true;
-};
-/**
- * Returns the programTime of the media given a playlist and a playerTime.
- * The playlist must have programDateTime tags for a programDateTime tag to be returned.
- * If the segments containing the time requested have not been buffered yet, an estimate
- * may be returned to the callback.
- *
- * @param {Object} args
- * @param {Object} args.playlist A playlist object to search within
- * @param {number} time A playerTime in seconds
- * @param {Function} callback(err, programTime)
- * @return {string} err.message A detailed error message
- * @return {Object} programTime
- * @return {number} programTime.mediaSeconds The streamTime in seconds
- * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
- */
-
-var getProgramTime = function getProgramTime(_ref) {
- var playlist = _ref.playlist,
- _ref$time = _ref.time,
- time = _ref$time === void 0 ? undefined : _ref$time,
- callback = _ref.callback;
-
- if (!callback) {
- throw new Error('getProgramTime: callback must be provided');
- }
-
- if (!playlist || time === undefined) {
- return callback({
- message: 'getProgramTime: playlist and time must be provided'
- });
- }
-
- var matchedSegment = findSegmentForPlayerTime(time, playlist);
-
- if (!matchedSegment) {
- return callback({
- message: 'valid programTime was not found'
- });
- }
-
- if (matchedSegment.type === 'estimate') {
- return callback({
- message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
- seekTime: matchedSegment.estimatedStart
- });
- }
-
- var programTimeObject = {
- mediaSeconds: time
- };
- var programTime = playerTimeToProgramTime(time, matchedSegment.segment);
-
- if (programTime) {
- programTimeObject.programDateTime = programTime.toISOString();
- }
-
- return callback(null, programTimeObject);
-};
-/**
- * Seeks in the player to a time that matches the given programTime ISO-8601 string.
- *
- * @param {Object} args
- * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
- * @param {Object} args.playlist A playlist to look within
- * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
- * @param {Function} args.seekTo A method to perform a seek
- * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
- * @param {Object} args.tech The tech to seek on
- * @param {Function} args.callback(err, newTime) A callback to return the new time to
- * @return {string} err.message A detailed error message
- * @return {number} newTime The exact time that was seeked to in seconds
- */
-
-var seekToProgramTime = function seekToProgramTime(_ref2) {
- var programTime = _ref2.programTime,
- playlist = _ref2.playlist,
- _ref2$retryCount = _ref2.retryCount,
- retryCount = _ref2$retryCount === void 0 ? 2 : _ref2$retryCount,
- seekTo = _ref2.seekTo,
- _ref2$pauseAfterSeek = _ref2.pauseAfterSeek,
- pauseAfterSeek = _ref2$pauseAfterSeek === void 0 ? true : _ref2$pauseAfterSeek,
- tech = _ref2.tech,
- callback = _ref2.callback;
-
- if (!callback) {
- throw new Error('seekToProgramTime: callback must be provided');
- }
-
- if (typeof programTime === 'undefined' || !playlist || !seekTo) {
- return callback({
- message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
- });
- }
-
- if (!playlist.endList && !tech.hasStarted_) {
- return callback({
- message: 'player must be playing a live stream to start buffering'
- });
- }
-
- if (!verifyProgramDateTimeTags(playlist)) {
- return callback({
- message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
- });
- }
-
- var matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
-
- if (!matchedSegment) {
- return callback({
- message: programTime + " was not found in the stream"
- });
- }
-
- var segment = matchedSegment.segment;
- var mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
-
- if (matchedSegment.type === 'estimate') {
- // we've run out of retries
- if (retryCount === 0) {
- return callback({
- message: programTime + " is not buffered yet. Try again"
- });
- }
-
- seekTo(matchedSegment.estimatedStart + mediaOffset);
- tech.one('seeked', function () {
- seekToProgramTime({
- programTime: programTime,
- playlist: playlist,
- retryCount: retryCount - 1,
- seekTo: seekTo,
- pauseAfterSeek: pauseAfterSeek,
- tech: tech,
- callback: callback
- });
- });
- return;
- } // Since the segment.start value is determined from the buffered end or ending time
- // of the prior segment, the seekToTime doesn't need to account for any transmuxer
- // modifications.
-
-
- var seekToTime = segment.start + mediaOffset;
-
- var seekedCallback = function seekedCallback() {
- return callback(null, tech.currentTime());
- }; // listen for seeked event
-
-
- tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
-
- if (pauseAfterSeek) {
- tech.pause();
- }
-
- seekTo(seekToTime);
-};
-
-// which will only happen if the request is complete.
-
-var callbackOnCompleted = function callbackOnCompleted(request, cb) {
- if (request.readyState === 4) {
- return cb();
- }
-
- return;
-};
-
-var containerRequest = function containerRequest(uri, xhr, cb) {
- var bytes = [];
- var id3Offset;
- var finished = false;
-
- var endRequestAndCallback = function endRequestAndCallback(err, req, type, _bytes) {
- req.abort();
- finished = true;
- return cb(err, req, type, _bytes);
- };
-
- var progressListener = function progressListener(error, request) {
- if (finished) {
- return;
- }
-
- if (error) {
- return endRequestAndCallback(error, request, '', bytes);
- } // grap the new part of content that was just downloaded
-
-
- var newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
-
- bytes = byteHelpers.concatTypedArrays(bytes, byteHelpers.stringToBytes(newPart, true));
- id3Offset = id3Offset || id3Helpers.getId3Offset(bytes); // we need at least 10 bytes to determine a type
- // or we need at least two bytes after an id3Offset
-
- if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- }
-
- var type = containers.detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
- // to see the second sync byte, wait until we have enough data
- // before declaring it ts
-
- if (type === 'ts' && bytes.length < 188) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- } // this may be an unsynced ts segment
- // wait for 376 bytes before detecting no container
-
-
- if (!type && bytes.length < 376) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- }
-
- return endRequestAndCallback(null, request, type, bytes);
- };
-
- var options = {
- uri: uri,
- beforeSend: function beforeSend(request) {
- // this forces the browser to pass the bytes to us unprocessed
- request.overrideMimeType('text/plain; charset=x-user-defined');
- request.addEventListener('progress', function (_ref) {
- _ref.total;
- _ref.loaded;
- return callbackWrapper(request, null, {
- statusCode: request.status
- }, progressListener);
- });
- }
- };
- var request = xhr(options, function (error, response) {
- return callbackWrapper(request, error, response, progressListener);
- });
- return request;
-};
-
-var EventTarget = videojs__default['default'].EventTarget,
- mergeOptions = videojs__default['default'].mergeOptions;
-
-var dashPlaylistUnchanged = function dashPlaylistUnchanged(a, b) {
- if (!isPlaylistUnchanged(a, b)) {
- return false;
- } // for dash the above check will often return true in scenarios where
- // the playlist actually has changed because mediaSequence isn't a
- // dash thing, and we often set it to 1. So if the playlists have the same amount
- // of segments we return true.
- // So for dash we need to make sure that the underlying segments are different.
- // if sidx changed then the playlists are different.
-
-
- if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
- return false;
- } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
- return false;
- } // one or the other does not have segments
- // there was a change.
-
-
- if (a.segments && !b.segments || !a.segments && b.segments) {
- return false;
- } // neither has segments nothing changed
-
-
- if (!a.segments && !b.segments) {
- return true;
- } // check segments themselves
-
-
- for (var i = 0; i < a.segments.length; i++) {
- var aSegment = a.segments[i];
- var bSegment = b.segments[i]; // if uris are different between segments there was a change
-
- if (aSegment.uri !== bSegment.uri) {
- return false;
- } // neither segment has a byterange, there will be no byterange change.
-
-
- if (!aSegment.byterange && !bSegment.byterange) {
- continue;
- }
-
- var aByterange = aSegment.byterange;
- var bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
-
- if (aByterange && !bByterange || !aByterange && bByterange) {
- return false;
- } // if both segments have byterange with different offsets, there was a change.
-
-
- if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
- return false;
- }
- } // if everything was the same with segments, this is the same playlist.
-
-
- return true;
-};
-/**
- * Parses the master XML string and updates playlist URI references.
- *
- * @param {Object} config
- * Object of arguments
- * @param {string} config.masterXml
- * The mpd XML
- * @param {string} config.srcUrl
- * The mpd URL
- * @param {Date} config.clientOffset
- * A time difference between server and client
- * @param {Object} config.sidxMapping
- * SIDX mappings for moof/mdat URIs and byte ranges
- * @return {Object}
- * The parsed mpd manifest object
- */
-
-
-var parseMasterXml = function parseMasterXml(_ref) {
- var masterXml = _ref.masterXml,
- srcUrl = _ref.srcUrl,
- clientOffset = _ref.clientOffset,
- sidxMapping = _ref.sidxMapping;
- var master = mpdParser.parse(masterXml, {
- manifestUri: srcUrl,
- clientOffset: clientOffset,
- sidxMapping: sidxMapping
- });
- addPropertiesToMaster(master, srcUrl);
- return master;
-};
-/**
- * Returns a new master manifest that is the result of merging an updated master manifest
- * into the original version.
- *
- * @param {Object} oldMaster
- * The old parsed mpd object
- * @param {Object} newMaster
- * The updated parsed mpd object
- * @return {Object}
- * A new object representing the original master manifest with the updated media
- * playlists merged in
- */
-
-var updateMaster = function updateMaster(oldMaster, newMaster, sidxMapping) {
- var noChanges = true;
- var update = mergeOptions(oldMaster, {
- // These are top level properties that can be updated
- duration: newMaster.duration,
- minimumUpdatePeriod: newMaster.minimumUpdatePeriod
- }); // First update the playlists in playlist list
-
- for (var i = 0; i < newMaster.playlists.length; i++) {
- var playlist = newMaster.playlists[i];
-
- if (playlist.sidx) {
- var sidxKey = mpdParser.generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
-
- if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
- mpdParser.addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
- }
- }
-
- var playlistUpdate = updateMaster$1(update, playlist, dashPlaylistUnchanged);
-
- if (playlistUpdate) {
- update = playlistUpdate;
- noChanges = false;
- }
- } // Then update media group playlists
-
-
- forEachMediaGroup(newMaster, function (properties, type, group, label) {
- if (properties.playlists && properties.playlists.length) {
- var id = properties.playlists[0].id;
-
- var _playlistUpdate = updateMaster$1(update, properties.playlists[0], dashPlaylistUnchanged);
-
- if (_playlistUpdate) {
- update = _playlistUpdate; // update the playlist reference within media groups
-
- update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
- noChanges = false;
- }
- }
- });
-
- if (newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
- noChanges = false;
- }
-
- if (noChanges) {
- return null;
- }
-
- return update;
-}; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
-// If the SIDXs have maps, the two maps should match,
-// both `a` and `b` missing SIDXs is considered matching.
-// If `a` or `b` but not both have a map, they aren't matching.
-
-var equivalentSidx = function equivalentSidx(a, b) {
- var neitherMap = Boolean(!a.map && !b.map);
- var equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
- return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
-}; // exported for testing
-
-
-var compareSidxEntry = function compareSidxEntry(playlists, oldSidxMapping) {
- var newSidxMapping = {};
-
- for (var id in playlists) {
- var playlist = playlists[id];
- var currentSidxInfo = playlist.sidx;
-
- if (currentSidxInfo) {
- var key = mpdParser.generateSidxKey(currentSidxInfo);
-
- if (!oldSidxMapping[key]) {
- break;
- }
-
- var savedSidxInfo = oldSidxMapping[key].sidxInfo;
-
- if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
- newSidxMapping[key] = oldSidxMapping[key];
- }
- }
- }
-
- return newSidxMapping;
-};
-/**
- * A function that filters out changed items as they need to be requested separately.
- *
- * The method is exported for testing
- *
- * @param {Object} master the parsed mpd XML returned via mpd-parser
- * @param {Object} oldSidxMapping the SIDX to compare against
- */
-
-var filterChangedSidxMappings = function filterChangedSidxMappings(master, oldSidxMapping) {
- var videoSidx = compareSidxEntry(master.playlists, oldSidxMapping);
- var mediaGroupSidx = videoSidx;
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- if (properties.playlists && properties.playlists.length) {
- var playlists = properties.playlists;
- mediaGroupSidx = mergeOptions(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
- }
- });
- return mediaGroupSidx;
-};
-
-var DashPlaylistLoader = /*#__PURE__*/function (_EventTarget) {
- _inheritsLoose__default['default'](DashPlaylistLoader, _EventTarget);
-
- // DashPlaylistLoader must accept either a src url or a playlist because subsequent
- // playlist loader setups from media groups will expect to be able to pass a playlist
- // (since there aren't external URLs to media playlists with DASH)
- function DashPlaylistLoader(srcUrlOrPlaylist, vhs, options, masterPlaylistLoader) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _EventTarget.call(this) || this;
- _this.masterPlaylistLoader_ = masterPlaylistLoader || _assertThisInitialized__default['default'](_this);
-
- if (!masterPlaylistLoader) {
- _this.isMaster_ = true;
- }
-
- var _options = options,
- _options$withCredenti = _options.withCredentials,
- withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
- _options$handleManife = _options.handleManifestRedirects,
- handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
- _this.vhs_ = vhs;
- _this.withCredentials = withCredentials;
- _this.handleManifestRedirects = handleManifestRedirects;
-
- if (!srcUrlOrPlaylist) {
- throw new Error('A non-empty playlist URL or object is required');
- } // event naming?
-
-
- _this.on('minimumUpdatePeriod', function () {
- _this.refreshXml_();
- }); // live playlist staleness timeout
-
-
- _this.on('mediaupdatetimeout', function () {
- _this.refreshMedia_(_this.media().id);
- });
-
- _this.state = 'HAVE_NOTHING';
- _this.loadedPlaylists_ = {};
- _this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
- // The masterPlaylistLoader will be created with a string
-
- if (_this.isMaster_) {
- _this.masterPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
- // once multi-period is refactored
-
- _this.masterPlaylistLoader_.sidxMapping_ = {};
- } else {
- _this.childPlaylist_ = srcUrlOrPlaylist;
- }
-
- return _this;
- }
-
- var _proto = DashPlaylistLoader.prototype;
-
- _proto.requestErrored_ = function requestErrored_(err, request, startingState) {
- // disposed
- if (!this.request) {
- return true;
- } // pending request is cleared
-
-
- this.request = null;
-
- if (err) {
- // use the provided error object or create one
- // based on the request/response
- this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
- status: request.status,
- message: 'DASH request error at URL: ' + request.uri,
- response: request.response,
- // MEDIA_ERR_NETWORK
- code: 2
- };
-
- if (startingState) {
- this.state = startingState;
- }
-
- this.trigger('error');
- return true;
- }
- }
- /**
- * Verify that the container of the sidx segment can be parsed
- * and if it can, get and parse that segment.
- */
- ;
-
- _proto.addSidxSegments_ = function addSidxSegments_(playlist, startingState, cb) {
- var _this2 = this;
-
- var sidxKey = playlist.sidx && mpdParser.generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
-
- if (!playlist.sidx || !sidxKey || this.masterPlaylistLoader_.sidxMapping_[sidxKey]) {
- // keep this function async
- this.mediaRequest_ = window__default['default'].setTimeout(function () {
- return cb(false);
- }, 0);
- return;
- } // resolve the segment URL relative to the playlist
-
-
- var uri = resolveManifestRedirect(this.handleManifestRedirects, playlist.sidx.resolvedUri);
-
- var fin = function fin(err, request) {
- if (_this2.requestErrored_(err, request, startingState)) {
- return;
- }
-
- var sidxMapping = _this2.masterPlaylistLoader_.sidxMapping_;
- var sidx;
-
- try {
- sidx = parseSidx__default['default'](byteHelpers.toUint8(request.response).subarray(8));
- } catch (e) {
- // sidx parsing failed.
- _this2.requestErrored_(e, request, startingState);
-
- return;
- }
-
- sidxMapping[sidxKey] = {
- sidxInfo: playlist.sidx,
- sidx: sidx
- };
- mpdParser.addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
- return cb(true);
- };
-
- this.request = containerRequest(uri, this.vhs_.xhr, function (err, request, container, bytes) {
- if (err) {
- return fin(err, request);
- }
-
- if (!container || container !== 'mp4') {
- return fin({
- status: request.status,
- message: "Unsupported " + (container || 'unknown') + " container type for sidx segment at URL: " + uri,
- // response is just bytes in this case
- // but we really don't want to return that.
- response: '',
- playlist: playlist,
- internal: true,
- blacklistDuration: Infinity,
- // MEDIA_ERR_NETWORK
- code: 2
- }, request);
- } // if we already downloaded the sidx bytes in the container request, use them
-
-
- var _playlist$sidx$bytera = playlist.sidx.byterange,
- offset = _playlist$sidx$bytera.offset,
- length = _playlist$sidx$bytera.length;
-
- if (bytes.length >= length + offset) {
- return fin(err, {
- response: bytes.subarray(offset, offset + length),
- status: request.status,
- uri: request.uri
- });
- } // otherwise request sidx bytes
-
-
- _this2.request = _this2.vhs_.xhr({
- uri: uri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders({
- byterange: playlist.sidx.byterange
- })
- }, fin);
- });
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.stopRequest();
- this.loadedPlaylists_ = {};
- window__default['default'].clearTimeout(this.minimumUpdatePeriodTimeout_);
- window__default['default'].clearTimeout(this.mediaRequest_);
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- this.mediaRequest_ = null;
- this.minimumUpdatePeriodTimeout_ = null;
-
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
-
- this.off();
- };
-
- _proto.hasPendingRequest = function hasPendingRequest() {
- return this.request || this.mediaRequest_;
- };
-
- _proto.stopRequest = function stopRequest() {
- if (this.request) {
- var oldRequest = this.request;
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- };
-
- _proto.media = function media(playlist) {
- var _this3 = this;
-
- // getter
- if (!playlist) {
- return this.media_;
- } // setter
-
-
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- }
-
- var startingState = this.state; // find the playlist object if the target playlist has been specified by URI
-
- if (typeof playlist === 'string') {
- if (!this.masterPlaylistLoader_.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
-
- playlist = this.masterPlaylistLoader_.master.playlists[playlist];
- }
-
- var mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
-
- if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
- this.state = 'HAVE_METADATA';
- this.media_ = playlist; // trigger media change if the active media has been updated
-
- if (mediaChange) {
- this.trigger('mediachanging');
- this.trigger('mediachange');
- }
-
- return;
- } // switching to the active playlist is a no-op
-
-
- if (!mediaChange) {
- return;
- } // switching from an already loaded playlist
-
-
- if (this.media_) {
- this.trigger('mediachanging');
- }
-
- this.addSidxSegments_(playlist, startingState, function (sidxChanged) {
- // everything is ready just continue to haveMetadata
- _this3.haveMetadata({
- startingState: startingState,
- playlist: playlist
- });
- });
- };
-
- _proto.haveMetadata = function haveMetadata(_ref2) {
- var startingState = _ref2.startingState,
- playlist = _ref2.playlist;
- this.state = 'HAVE_METADATA';
- this.loadedPlaylists_[playlist.id] = playlist;
- this.mediaRequest_ = null; // This will trigger loadedplaylist
-
- this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
- // to resolve setup of media groups
-
- if (startingState === 'HAVE_MASTER') {
- this.trigger('loadedmetadata');
- } else {
- // trigger media change if the active media has been updated
- this.trigger('mediachange');
- }
- };
-
- _proto.pause = function pause() {
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
-
- this.stopRequest();
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
-
- if (this.isMaster_) {
- window__default['default'].clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_);
- this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
- }
-
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- }
- };
-
- _proto.load = function load(isFinalRendition) {
- var _this4 = this;
-
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- var media = this.media();
-
- if (isFinalRendition) {
- var delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
- this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- return _this4.load();
- }, delay);
- return;
- } // because the playlists are internal to the manifest, load should either load the
- // main manifest, or do nothing but trigger an event
-
-
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- // Check to see if this is the master loader and the MUP was cleared (this happens
- // when the loader was paused). `media` should be set at this point since one is always
- // set during `start()`.
- if (this.isMaster_ && !this.minimumUpdatePeriodTimeout_) {
- // Trigger minimumUpdatePeriod to refresh the master manifest
- this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
-
- this.updateMinimumUpdatePeriodTimeout_();
- }
-
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- };
-
- _proto.start = function start() {
- var _this5 = this;
-
- this.started = true; // We don't need to request the master manifest again
- // Call this asynchronously to match the xhr request behavior below
-
- if (!this.isMaster_) {
- this.mediaRequest_ = window__default['default'].setTimeout(function () {
- return _this5.haveMaster_();
- }, 0);
- return;
- }
-
- this.requestMaster_(function (req, masterChanged) {
- _this5.haveMaster_();
-
- if (!_this5.hasPendingRequest() && !_this5.media_) {
- _this5.media(_this5.masterPlaylistLoader_.master.playlists[0]);
- }
- });
- };
-
- _proto.requestMaster_ = function requestMaster_(cb) {
- var _this6 = this;
-
- this.request = this.vhs_.xhr({
- uri: this.masterPlaylistLoader_.srcUrl,
- withCredentials: this.withCredentials
- }, function (error, req) {
- if (_this6.requestErrored_(error, req)) {
- if (_this6.state === 'HAVE_NOTHING') {
- _this6.started = false;
- }
-
- return;
- }
-
- var masterChanged = req.responseText !== _this6.masterPlaylistLoader_.masterXml_;
- _this6.masterPlaylistLoader_.masterXml_ = req.responseText;
-
- if (req.responseHeaders && req.responseHeaders.date) {
- _this6.masterLoaded_ = Date.parse(req.responseHeaders.date);
- } else {
- _this6.masterLoaded_ = Date.now();
- }
-
- _this6.masterPlaylistLoader_.srcUrl = resolveManifestRedirect(_this6.handleManifestRedirects, _this6.masterPlaylistLoader_.srcUrl, req);
-
- if (masterChanged) {
- _this6.handleMaster_();
-
- _this6.syncClientServerClock_(function () {
- return cb(req, masterChanged);
- });
-
- return;
- }
-
- return cb(req, masterChanged);
- });
- }
- /**
- * Parses the master xml for UTCTiming node to sync the client clock to the server
- * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
- *
- * @param {Function} done
- * Function to call when clock sync has completed
- */
- ;
-
- _proto.syncClientServerClock_ = function syncClientServerClock_(done) {
- var _this7 = this;
-
- var utcTiming = mpdParser.parseUTCTiming(this.masterPlaylistLoader_.masterXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
- // server clock
-
- if (utcTiming === null) {
- this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
- return done();
- }
-
- if (utcTiming.method === 'DIRECT') {
- this.masterPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
- return done();
- }
-
- this.request = this.vhs_.xhr({
- uri: resolveUrl(this.masterPlaylistLoader_.srcUrl, utcTiming.value),
- method: utcTiming.method,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this7.request) {
- return;
- }
-
- if (error) {
- // sync request failed, fall back to using date header from mpd
- // TODO: log warning
- _this7.masterPlaylistLoader_.clientOffset_ = _this7.masterLoaded_ - Date.now();
- return done();
- }
-
- var serverTime;
-
- if (utcTiming.method === 'HEAD') {
- if (!req.responseHeaders || !req.responseHeaders.date) {
- // expected date header not preset, fall back to using date header from mpd
- // TODO: log warning
- serverTime = _this7.masterLoaded_;
- } else {
- serverTime = Date.parse(req.responseHeaders.date);
- }
- } else {
- serverTime = Date.parse(req.responseText);
- }
-
- _this7.masterPlaylistLoader_.clientOffset_ = serverTime - Date.now();
- done();
- });
- };
-
- _proto.haveMaster_ = function haveMaster_() {
- this.state = 'HAVE_MASTER';
-
- if (this.isMaster_) {
- // We have the master playlist at this point, so
- // trigger this to allow MasterPlaylistController
- // to make an initial playlist selection
- this.trigger('loadedplaylist');
- } else if (!this.media_) {
- // no media playlist was specifically selected so select
- // the one the child playlist loader was created with
- this.media(this.childPlaylist_);
- }
- };
-
- _proto.handleMaster_ = function handleMaster_() {
- // clear media request
- this.mediaRequest_ = null;
- var newMaster = parseMasterXml({
- masterXml: this.masterPlaylistLoader_.masterXml_,
- srcUrl: this.masterPlaylistLoader_.srcUrl,
- clientOffset: this.masterPlaylistLoader_.clientOffset_,
- sidxMapping: this.masterPlaylistLoader_.sidxMapping_
- });
- var oldMaster = this.masterPlaylistLoader_.master; // if we have an old master to compare the new master against
-
- if (oldMaster) {
- newMaster = updateMaster(oldMaster, newMaster, this.masterPlaylistLoader_.sidxMapping_);
- } // only update master if we have a new master
-
-
- this.masterPlaylistLoader_.master = newMaster ? newMaster : oldMaster;
- var location = this.masterPlaylistLoader_.master.locations && this.masterPlaylistLoader_.master.locations[0];
-
- if (location && location !== this.masterPlaylistLoader_.srcUrl) {
- this.masterPlaylistLoader_.srcUrl = location;
- }
-
- if (!oldMaster || newMaster && newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
- this.updateMinimumUpdatePeriodTimeout_();
- }
-
- return Boolean(newMaster);
- };
-
- _proto.updateMinimumUpdatePeriodTimeout_ = function updateMinimumUpdatePeriodTimeout_() {
- var mpl = this.masterPlaylistLoader_; // cancel any pending creation of mup on media
- // a new one will be added if needed.
-
- if (mpl.createMupOnMedia_) {
- mpl.off('loadedmetadata', mpl.createMupOnMedia_);
- mpl.createMupOnMedia_ = null;
- } // clear any pending timeouts
-
-
- if (mpl.minimumUpdatePeriodTimeout_) {
- window__default['default'].clearTimeout(mpl.minimumUpdatePeriodTimeout_);
- mpl.minimumUpdatePeriodTimeout_ = null;
- }
-
- var mup = mpl.master && mpl.master.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
- // MPD has no future validity, so a new one will need to be acquired when new
- // media segments are to be made available. Thus, we use the target duration
- // in this case
-
- if (mup === 0) {
- if (mpl.media()) {
- mup = mpl.media().targetDuration * 1000;
- } else {
- mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
- mpl.one('loadedmetadata', mpl.createMupOnMedia_);
- }
- } // if minimumUpdatePeriod is invalid or <= zero, which
- // can happen when a live video becomes VOD. skip timeout
- // creation.
-
-
- if (typeof mup !== 'number' || mup <= 0) {
- if (mup < 0) {
- this.logger_("found invalid minimumUpdatePeriod of " + mup + ", not setting a timeout");
- }
-
- return;
- }
-
- this.createMUPTimeout_(mup);
- };
-
- _proto.createMUPTimeout_ = function createMUPTimeout_(mup) {
- var mpl = this.masterPlaylistLoader_;
- mpl.minimumUpdatePeriodTimeout_ = window__default['default'].setTimeout(function () {
- mpl.minimumUpdatePeriodTimeout_ = null;
- mpl.trigger('minimumUpdatePeriod');
- mpl.createMUPTimeout_(mup);
- }, mup);
- }
- /**
- * Sends request to refresh the master xml and updates the parsed master manifest
- */
- ;
-
- _proto.refreshXml_ = function refreshXml_() {
- var _this8 = this;
-
- this.requestMaster_(function (req, masterChanged) {
- if (!masterChanged) {
- return;
- }
-
- if (_this8.media_) {
- _this8.media_ = _this8.masterPlaylistLoader_.master.playlists[_this8.media_.id];
- } // This will filter out updated sidx info from the mapping
-
-
- _this8.masterPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(_this8.masterPlaylistLoader_.master, _this8.masterPlaylistLoader_.sidxMapping_);
-
- _this8.addSidxSegments_(_this8.media(), _this8.state, function (sidxChanged) {
- // TODO: do we need to reload the current playlist?
- _this8.refreshMedia_(_this8.media().id);
- });
- });
- }
- /**
- * Refreshes the media playlist by re-parsing the master xml and updating playlist
- * references. If this is an alternate loader, the updated parsed manifest is retrieved
- * from the master loader.
- */
- ;
-
- _proto.refreshMedia_ = function refreshMedia_(mediaID) {
- var _this9 = this;
-
- if (!mediaID) {
- throw new Error('refreshMedia_ must take a media id');
- } // for master we have to reparse the master xml
- // to re-create segments based on current timing values
- // which may change media. We only skip updating master
- // if this is the first time this.media_ is being set.
- // as master was just parsed in that case.
-
-
- if (this.media_ && this.isMaster_) {
- this.handleMaster_();
- }
-
- var playlists = this.masterPlaylistLoader_.master.playlists;
- var mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
-
- if (mediaChanged) {
- this.media_ = playlists[mediaID];
- } else {
- this.trigger('playlistunchanged');
- }
-
- if (!this.mediaUpdateTimeout) {
- var createMediaUpdateTimeout = function createMediaUpdateTimeout() {
- if (_this9.media().endList) {
- return;
- }
-
- _this9.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- _this9.trigger('mediaupdatetimeout');
-
- createMediaUpdateTimeout();
- }, refreshDelay(_this9.media(), Boolean(mediaChanged)));
- };
-
- createMediaUpdateTimeout();
- }
-
- this.trigger('loadedplaylist');
- };
-
- return DashPlaylistLoader;
-}(EventTarget);
-
-var Config = {
- GOAL_BUFFER_LENGTH: 30,
- MAX_GOAL_BUFFER_LENGTH: 60,
- BACK_BUFFER_LENGTH: 30,
- GOAL_BUFFER_LENGTH_RATE: 1,
- // 0.5 MB/s
- INITIAL_BANDWIDTH: 4194304,
- // A fudge factor to apply to advertised playlist bitrates to account for
- // temporary flucations in client bandwidth
- BANDWIDTH_VARIANCE: 1.2,
- // How much of the buffer must be filled before we consider upswitching
- BUFFER_LOW_WATER_LINE: 0,
- MAX_BUFFER_LOW_WATER_LINE: 30,
- // TODO: Remove this when experimentalBufferBasedABR is removed
- EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
- BUFFER_LOW_WATER_LINE_RATE: 1,
- // If the buffer is greater than the high water line, we won't switch down
- BUFFER_HIGH_WATER_LINE: 30
-};
-
-var stringToArrayBuffer = function stringToArrayBuffer(string) {
- var view = new Uint8Array(new ArrayBuffer(string.length));
-
- for (var i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view.buffer;
-};
-
-/* global Blob, BlobBuilder, Worker */
-// unify worker interface
-var browserWorkerPolyFill = function browserWorkerPolyFill(workerObj) {
- // node only supports on/off
- workerObj.on = workerObj.addEventListener;
- workerObj.off = workerObj.removeEventListener;
- return workerObj;
-};
-
-var createObjectURL = function createObjectURL(str) {
- try {
- return URL.createObjectURL(new Blob([str], {
- type: 'application/javascript'
- }));
- } catch (e) {
- var blob = new BlobBuilder();
- blob.append(str);
- return URL.createObjectURL(blob.getBlob());
- }
-};
-
-var factory = function factory(code) {
- return function () {
- var objectUrl = createObjectURL(code);
- var worker = browserWorkerPolyFill(new Worker(objectUrl));
- worker.objURL = objectUrl;
- var terminate = worker.terminate;
- worker.on = worker.addEventListener;
- worker.off = worker.removeEventListener;
-
- worker.terminate = function () {
- URL.revokeObjectURL(objectUrl);
- return terminate.call(this);
- };
-
- return worker;
- };
-};
-var transform = function transform(code) {
- return "var browserWorkerPolyFill = " + browserWorkerPolyFill.toString() + ";\n" + 'browserWorkerPolyFill(self);\n' + code;
-};
-
-var getWorkerString = function getWorkerString(fn) {
- return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
-};
-
-/* rollup-plugin-worker-factory start for worker!/Users/gkatsevman/p/http-streaming-release/src/transmuxer-worker.js */
-var workerCode$1 = transform(getWorkerString(function () {
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * A lightweight readable stream implemention that handles event dispatching.
- * Objects that inherit from streams should call init in their constructors.
- */
-
- var Stream = function Stream() {
- this.init = function () {
- var listeners = {};
- /**
- * Add a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} the callback to be invoked when an event of
- * the specified type occurs
- */
-
- this.on = function (type, listener) {
- if (!listeners[type]) {
- listeners[type] = [];
- }
-
- listeners[type] = listeners[type].concat(listener);
- };
- /**
- * Remove a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} a function previously registered for this
- * type of event through `on`
- */
-
-
- this.off = function (type, listener) {
- var index;
-
- if (!listeners[type]) {
- return false;
- }
-
- index = listeners[type].indexOf(listener);
- listeners[type] = listeners[type].slice();
- listeners[type].splice(index, 1);
- return index > -1;
- };
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- * @param type {string} the event name
- */
-
-
- this.trigger = function (type) {
- var callbacks, i, length, args;
- callbacks = listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- args = [];
- i = arguments.length;
-
- for (i = 1; i < arguments.length; ++i) {
- args.push(arguments[i]);
- }
-
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].apply(this, args);
- }
- }
- };
- /**
- * Destroys the stream and cleans up.
- */
-
-
- this.dispose = function () {
- listeners = {};
- };
- };
- };
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- * @param destination {stream} the stream that will receive all `data` events
- * @param autoFlush {boolean} if false, we will not call `flush` on the destination
- * when the current stream emits a 'done' event
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
-
-
- Stream.prototype.pipe = function (destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- this.on('done', function (flushSource) {
- destination.flush(flushSource);
- });
- this.on('partialdone', function (flushSource) {
- destination.partialFlush(flushSource);
- });
- this.on('endedtimeline', function (flushSource) {
- destination.endTimeline(flushSource);
- });
- this.on('reset', function (flushSource) {
- destination.reset(flushSource);
- });
- return destination;
- }; // Default stream functions that are expected to be overridden to perform
- // actual work. These are provided by the prototype as a sort of no-op
- // implementation so that we don't have to check for their existence in the
- // `pipe` function above.
-
-
- Stream.prototype.push = function (data) {
- this.trigger('data', data);
- };
-
- Stream.prototype.flush = function (flushSource) {
- this.trigger('done', flushSource);
- };
-
- Stream.prototype.partialFlush = function (flushSource) {
- this.trigger('partialdone', flushSource);
- };
-
- Stream.prototype.endTimeline = function (flushSource) {
- this.trigger('endedtimeline', flushSource);
- };
-
- Stream.prototype.reset = function (flushSource) {
- this.trigger('reset', flushSource);
- };
-
- var stream = Stream;
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Functions that generate fragmented MP4s suitable for use with Media
- * Source Extensions.
- */
-
- var UINT32_MAX = Math.pow(2, 32) - 1;
- var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants
-
- (function () {
- var i;
- types = {
- avc1: [],
- // codingname
- avcC: [],
- btrt: [],
- dinf: [],
- dref: [],
- esds: [],
- ftyp: [],
- hdlr: [],
- mdat: [],
- mdhd: [],
- mdia: [],
- mfhd: [],
- minf: [],
- moof: [],
- moov: [],
- mp4a: [],
- // codingname
- mvex: [],
- mvhd: [],
- pasp: [],
- sdtp: [],
- smhd: [],
- stbl: [],
- stco: [],
- stsc: [],
- stsd: [],
- stsz: [],
- stts: [],
- styp: [],
- tfdt: [],
- tfhd: [],
- traf: [],
- trak: [],
- trun: [],
- trex: [],
- tkhd: [],
- vmhd: []
- }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
- // don't throw an error
-
- if (typeof Uint8Array === 'undefined') {
- return;
- }
-
- for (i in types) {
- if (types.hasOwnProperty(i)) {
- types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
- }
- }
-
- MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
- AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
- MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
- VIDEO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
- ]);
- AUDIO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
- ]);
- HDLR_TYPES = {
- video: VIDEO_HDLR,
- audio: AUDIO_HDLR
- };
- DREF = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // entry_count
- 0x00, 0x00, 0x00, 0x0c, // entry_size
- 0x75, 0x72, 0x6c, 0x20, // 'url' type
- 0x00, // version 0
- 0x00, 0x00, 0x01 // entry_flags
- ]);
- SMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, // balance, 0 means centered
- 0x00, 0x00 // reserved
- ]);
- STCO = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00 // entry_count
- ]);
- STSC = STCO;
- STSZ = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // sample_size
- 0x00, 0x00, 0x00, 0x00 // sample_count
- ]);
- STTS = STCO;
- VMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x01, // flags
- 0x00, 0x00, // graphicsmode
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
- ]);
- })();
-
- box = function box(type) {
- var payload = [],
- size = 0,
- i,
- result,
- view;
-
- for (i = 1; i < arguments.length; i++) {
- payload.push(arguments[i]);
- }
-
- i = payload.length; // calculate the total size we need to allocate
-
- while (i--) {
- size += payload[i].byteLength;
- }
-
- result = new Uint8Array(size + 8);
- view = new DataView(result.buffer, result.byteOffset, result.byteLength);
- view.setUint32(0, result.byteLength);
- result.set(type, 4); // copy the payload into the result
-
- for (i = 0, size = 8; i < payload.length; i++) {
- result.set(payload[i], size);
- size += payload[i].byteLength;
- }
-
- return result;
- };
-
- dinf = function dinf() {
- return box(types.dinf, box(types.dref, DREF));
- };
-
- esds = function esds(track) {
- return box(types.esds, new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- // ES_Descriptor
- 0x03, // tag, ES_DescrTag
- 0x19, // length
- 0x00, 0x00, // ES_ID
- 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
- // DecoderConfigDescriptor
- 0x04, // tag, DecoderConfigDescrTag
- 0x11, // length
- 0x40, // object type
- 0x15, // streamType
- 0x00, 0x06, 0x00, // bufferSizeDB
- 0x00, 0x00, 0xda, 0xc0, // maxBitrate
- 0x00, 0x00, 0xda, 0xc0, // avgBitrate
- // DecoderSpecificInfo
- 0x05, // tag, DecoderSpecificInfoTag
- 0x02, // length
- // ISO/IEC 14496-3, AudioSpecificConfig
- // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
- track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
- ]));
- };
-
- ftyp = function ftyp() {
- return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
- };
-
- hdlr = function hdlr(type) {
- return box(types.hdlr, HDLR_TYPES[type]);
- };
-
- mdat = function mdat(data) {
- return box(types.mdat, data);
- };
-
- mdhd = function mdhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x02, // creation_time
- 0x00, 0x00, 0x00, 0x03, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
- 0x55, 0xc4, // 'und' language (undetermined)
- 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
- // defined. The sample rate can be parsed out of an ADTS header, for
- // instance.
-
- if (track.samplerate) {
- result[12] = track.samplerate >>> 24 & 0xFF;
- result[13] = track.samplerate >>> 16 & 0xFF;
- result[14] = track.samplerate >>> 8 & 0xFF;
- result[15] = track.samplerate & 0xFF;
- }
-
- return box(types.mdhd, result);
- };
-
- mdia = function mdia(track) {
- return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
- };
-
- mfhd = function mfhd(sequenceNumber) {
- return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
- (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
- ]));
- };
-
- minf = function minf(track) {
- return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
- };
-
- moof = function moof(sequenceNumber, tracks) {
- var trackFragments = [],
- i = tracks.length; // build traf boxes for each track fragment
-
- while (i--) {
- trackFragments[i] = traf(tracks[i]);
- }
-
- return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
- };
- /**
- * Returns a movie box.
- * @param tracks {array} the tracks associated with this movie
- * @see ISO/IEC 14496-12:2012(E), section 8.2.1
- */
-
-
- moov = function moov(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trak(tracks[i]);
- }
-
- return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
- };
-
- mvex = function mvex(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trex(tracks[i]);
- }
-
- return box.apply(null, [types.mvex].concat(boxes));
- };
-
- mvhd = function mvhd(duration) {
- var bytes = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // creation_time
- 0x00, 0x00, 0x00, 0x02, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
- 0x00, 0x01, 0x00, 0x00, // 1.0 rate
- 0x01, 0x00, // 1.0 volume
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0xff, 0xff, 0xff, 0xff // next_track_ID
- ]);
- return box(types.mvhd, bytes);
- };
-
- sdtp = function sdtp(track) {
- var samples = track.samples || [],
- bytes = new Uint8Array(4 + samples.length),
- flags,
- i; // leave the full box header (4 bytes) all zero
- // write the sample table
-
- for (i = 0; i < samples.length; i++) {
- flags = samples[i].flags;
- bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
- }
-
- return box(types.sdtp, bytes);
- };
-
- stbl = function stbl(track) {
- return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
- };
-
- (function () {
- var videoSample, audioSample;
-
- stsd = function stsd(track) {
- return box(types.stsd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
- };
-
- videoSample = function videoSample(track) {
- var sps = track.sps || [],
- pps = track.pps || [],
- sequenceParameterSets = [],
- pictureParameterSets = [],
- i,
- avc1Box; // assemble the SPSs
-
- for (i = 0; i < sps.length; i++) {
- sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
- sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
-
- sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
- } // assemble the PPSs
-
-
- for (i = 0; i < pps.length; i++) {
- pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
- pictureParameterSets.push(pps[i].byteLength & 0xFF);
- pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
- }
-
- avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- (track.width & 0xff00) >> 8, track.width & 0xff, // width
- (track.height & 0xff00) >> 8, track.height & 0xff, // height
- 0x00, 0x48, 0x00, 0x00, // horizresolution
- 0x00, 0x48, 0x00, 0x00, // vertresolution
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // frame_count
- 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
- 0x00, 0x18, // depth = 24
- 0x11, 0x11 // pre_defined = -1
- ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
- track.profileIdc, // AVCProfileIndication
- track.profileCompatibility, // profile_compatibility
- track.levelIdc, // AVCLevelIndication
- 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
- ].concat([sps.length], // numOfSequenceParameterSets
- sequenceParameterSets, // "SPS"
- [pps.length], // numOfPictureParameterSets
- pictureParameterSets // "PPS"
- ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
- 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
- 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
- ]))];
-
- if (track.sarRatio) {
- var hSpacing = track.sarRatio[0],
- vSpacing = track.sarRatio[1];
- avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 0xFF000000) >> 24, (hSpacing & 0xFF0000) >> 16, (hSpacing & 0xFF00) >> 8, hSpacing & 0xFF, (vSpacing & 0xFF000000) >> 24, (vSpacing & 0xFF0000) >> 16, (vSpacing & 0xFF00) >> 8, vSpacing & 0xFF])));
- }
-
- return box.apply(null, avc1Box);
- };
-
- audioSample = function audioSample(track) {
- return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- // AudioSampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
- (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
- // MP4AudioSampleEntry, ISO/IEC 14496-14
- ]), esds(track));
- };
- })();
-
- tkhd = function tkhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x07, // flags
- 0x00, 0x00, 0x00, 0x00, // creation_time
- 0x00, 0x00, 0x00, 0x00, // modification_time
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, // layer
- 0x00, 0x00, // alternate_group
- 0x01, 0x00, // non-audio track volume
- 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
- (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
- ]);
- return box(types.tkhd, result);
- };
- /**
- * Generate a track fragment (traf) box. A traf box collects metadata
- * about tracks in a movie fragment (moof) box.
- */
-
-
- traf = function traf(track) {
- var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
- trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x3a, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x00, 0x00, 0x00 // default_sample_flags
- ]));
- upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
- lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));
- trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
- 0x00, 0x00, 0x00, // flags
- // baseMediaDecodeTime
- upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])); // the data offset specifies the number of bytes from the start of
- // the containing moof to the first payload byte of the associated
- // mdat
-
- dataOffset = 32 + // tfhd
- 20 + // tfdt
- 8 + // traf header
- 16 + // mfhd
- 8 + // moof header
- 8; // mdat header
- // audio tracks require less metadata
-
- if (track.type === 'audio') {
- trackFragmentRun = trun$1(track, dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
- } // video tracks should contain an independent and disposable samples
- // box (sdtp)
- // generate one and adjust offsets to match
-
-
- sampleDependencyTable = sdtp(track);
- trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
- };
- /**
- * Generate a track box.
- * @param track {object} a track definition
- * @return {Uint8Array} the track box
- */
-
-
- trak = function trak(track) {
- track.duration = track.duration || 0xffffffff;
- return box(types.trak, tkhd(track), mdia(track));
- };
-
- trex = function trex(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x01, 0x00, 0x01 // default_sample_flags
- ]); // the last two bytes of default_sample_flags is the sample
- // degradation priority, a hint about the importance of this sample
- // relative to others. Lower the degradation priority for all sample
- // types other than video.
-
- if (track.type !== 'video') {
- result[result.length - 1] = 0x00;
- }
-
- return box(types.trex, result);
- };
-
- (function () {
- var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
- // duration is present for the first sample, it will be present for
- // all subsequent samples.
- // see ISO/IEC 14496-12:2012, Section 8.8.8.1
-
- trunHeader = function trunHeader(samples, offset) {
- var durationPresent = 0,
- sizePresent = 0,
- flagsPresent = 0,
- compositionTimeOffset = 0; // trun flag constants
-
- if (samples.length) {
- if (samples[0].duration !== undefined) {
- durationPresent = 0x1;
- }
-
- if (samples[0].size !== undefined) {
- sizePresent = 0x2;
- }
-
- if (samples[0].flags !== undefined) {
- flagsPresent = 0x4;
- }
-
- if (samples[0].compositionTimeOffset !== undefined) {
- compositionTimeOffset = 0x8;
- }
- }
-
- return [0x00, // version 0
- 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
- (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
- (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
- ];
- };
-
- videoTrun = function videoTrun(track, offset) {
- var bytesOffest, bytes, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 16 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 16);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
-
- bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
- bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
-
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
- }
-
- return box(types.trun, bytes);
- };
-
- audioTrun = function audioTrun(track, offset) {
- var bytes, bytesOffest, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 8 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 8);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
- }
-
- return box(types.trun, bytes);
- };
-
- trun$1 = function trun(track, offset) {
- if (track.type === 'audio') {
- return audioTrun(track, offset);
- }
-
- return videoTrun(track, offset);
- };
- })();
-
- var mp4Generator = {
- ftyp: ftyp,
- mdat: mdat,
- moof: moof,
- moov: moov,
- initSegment: function initSegment(tracks) {
- var fileType = ftyp(),
- movie = moov(tracks),
- result;
- result = new Uint8Array(fileType.byteLength + movie.byteLength);
- result.set(fileType);
- result.set(movie, fileType.byteLength);
- return result;
- }
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- // Convert an array of nal units into an array of frames with each frame being
- // composed of the nal units that make up that frame
- // Also keep track of cummulative data about the frame from the nal units such
- // as the frame duration, starting pts, etc.
-
- var groupNalsIntoFrames = function groupNalsIntoFrames(nalUnits) {
- var i,
- currentNal,
- currentFrame = [],
- frames = []; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength = 0;
- frames.nalCount = 0;
- frames.duration = 0;
- currentFrame.byteLength = 0;
-
- for (i = 0; i < nalUnits.length; i++) {
- currentNal = nalUnits[i]; // Split on 'aud'-type nal units
-
- if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
- // Since the very first nal unit is expected to be an AUD
- // only push to the frames array when currentFrame is not empty
- if (currentFrame.length) {
- currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- }
-
- currentFrame = [currentNal];
- currentFrame.byteLength = currentNal.data.byteLength;
- currentFrame.pts = currentNal.pts;
- currentFrame.dts = currentNal.dts;
- } else {
- // Specifically flag key frames for ease of use later
- if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
- currentFrame.keyFrame = true;
- }
-
- currentFrame.duration = currentNal.dts - currentFrame.dts;
- currentFrame.byteLength += currentNal.data.byteLength;
- currentFrame.push(currentNal);
- }
- } // For the last frame, use the duration of the previous frame if we
- // have nothing better to go on
-
-
- if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
- currentFrame.duration = frames[frames.length - 1].duration;
- } // Push the final frame
- // TODO added for LHLS, make sure this is OK
-
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- return frames;
- }; // Convert an array of frames into an array of Gop with each Gop being composed
- // of the frames that make up that Gop
- // Also keep track of cummulative data about the Gop from the frames such as the
- // Gop duration, starting pts, etc.
-
-
- var groupFramesIntoGops = function groupFramesIntoGops(frames) {
- var i,
- currentFrame,
- currentGop = [],
- gops = []; // We must pre-set some of the values on the Gop since we
- // keep running totals of these values
-
- currentGop.byteLength = 0;
- currentGop.nalCount = 0;
- currentGop.duration = 0;
- currentGop.pts = frames[0].pts;
- currentGop.dts = frames[0].dts; // store some metadata about all the Gops
-
- gops.byteLength = 0;
- gops.nalCount = 0;
- gops.duration = 0;
- gops.pts = frames[0].pts;
- gops.dts = frames[0].dts;
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
-
- if (currentFrame.keyFrame) {
- // Since the very first frame is expected to be an keyframe
- // only push to the gops array when currentGop is not empty
- if (currentGop.length) {
- gops.push(currentGop);
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration;
- }
-
- currentGop = [currentFrame];
- currentGop.nalCount = currentFrame.length;
- currentGop.byteLength = currentFrame.byteLength;
- currentGop.pts = currentFrame.pts;
- currentGop.dts = currentFrame.dts;
- currentGop.duration = currentFrame.duration;
- } else {
- currentGop.duration += currentFrame.duration;
- currentGop.nalCount += currentFrame.length;
- currentGop.byteLength += currentFrame.byteLength;
- currentGop.push(currentFrame);
- }
- }
-
- if (gops.length && currentGop.duration <= 0) {
- currentGop.duration = gops[gops.length - 1].duration;
- }
-
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration; // push the final Gop
-
- gops.push(currentGop);
- return gops;
- };
- /*
- * Search for the first keyframe in the GOPs and throw away all frames
- * until that keyframe. Then extend the duration of the pulled keyframe
- * and pull the PTS and DTS of the keyframe so that it covers the time
- * range of the frames that were disposed.
- *
- * @param {Array} gops video GOPs
- * @returns {Array} modified video GOPs
- */
-
-
- var extendFirstKeyFrame = function extendFirstKeyFrame(gops) {
- var currentGop;
-
- if (!gops[0][0].keyFrame && gops.length > 1) {
- // Remove the first GOP
- currentGop = gops.shift();
- gops.byteLength -= currentGop.byteLength;
- gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
- // first gop to cover the time period of the
- // frames we just removed
-
- gops[0][0].dts = currentGop.dts;
- gops[0][0].pts = currentGop.pts;
- gops[0][0].duration += currentGop.duration;
- }
-
- return gops;
- };
- /**
- * Default sample object
- * see ISO/IEC 14496-12:2012, section 8.6.4.3
- */
-
-
- var createDefaultSample = function createDefaultSample() {
- return {
- size: 0,
- flags: {
- isLeading: 0,
- dependsOn: 1,
- isDependedOn: 0,
- hasRedundancy: 0,
- degradationPriority: 0,
- isNonSyncSample: 1
- }
- };
- };
- /*
- * Collates information from a video frame into an object for eventual
- * entry into an MP4 sample table.
- *
- * @param {Object} frame the video frame
- * @param {Number} dataOffset the byte offset to position the sample
- * @return {Object} object containing sample table info for a frame
- */
-
-
- var sampleForFrame = function sampleForFrame(frame, dataOffset) {
- var sample = createDefaultSample();
- sample.dataOffset = dataOffset;
- sample.compositionTimeOffset = frame.pts - frame.dts;
- sample.duration = frame.duration;
- sample.size = 4 * frame.length; // Space for nal unit size
-
- sample.size += frame.byteLength;
-
- if (frame.keyFrame) {
- sample.flags.dependsOn = 2;
- sample.flags.isNonSyncSample = 0;
- }
-
- return sample;
- }; // generate the track's sample table from an array of gops
-
-
- var generateSampleTable$1 = function generateSampleTable(gops, baseDataOffset) {
- var h,
- i,
- sample,
- currentGop,
- currentFrame,
- dataOffset = baseDataOffset || 0,
- samples = [];
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h];
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i];
- sample = sampleForFrame(currentFrame, dataOffset);
- dataOffset += sample.size;
- samples.push(sample);
- }
- }
-
- return samples;
- }; // generate the track's raw mdat data from an array of gops
-
-
- var concatenateNalData = function concatenateNalData(gops) {
- var h,
- i,
- j,
- currentGop,
- currentFrame,
- currentNal,
- dataOffset = 0,
- nalsByteLength = gops.byteLength,
- numberOfNals = gops.nalCount,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each Gop..
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h]; // For each Frame..
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i]; // For each NAL..
-
- for (j = 0; j < currentFrame.length; j++) {
- currentNal = currentFrame[j];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
- }
- }
-
- return data;
- }; // generate the track's sample table from a frame
-
-
- var generateSampleTableForFrame = function generateSampleTableForFrame(frame, baseDataOffset) {
- var sample,
- dataOffset = baseDataOffset || 0,
- samples = [];
- sample = sampleForFrame(frame, dataOffset);
- samples.push(sample);
- return samples;
- }; // generate the track's raw mdat data from a frame
-
-
- var concatenateNalDataForFrame = function concatenateNalDataForFrame(frame) {
- var i,
- currentNal,
- dataOffset = 0,
- nalsByteLength = frame.byteLength,
- numberOfNals = frame.length,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each NAL..
-
- for (i = 0; i < frame.length; i++) {
- currentNal = frame[i];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
-
- return data;
- };
-
- var frameUtils = {
- groupNalsIntoFrames: groupNalsIntoFrames,
- groupFramesIntoGops: groupFramesIntoGops,
- extendFirstKeyFrame: extendFirstKeyFrame,
- generateSampleTable: generateSampleTable$1,
- concatenateNalData: concatenateNalData,
- generateSampleTableForFrame: generateSampleTableForFrame,
- concatenateNalDataForFrame: concatenateNalDataForFrame
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var highPrefix = [33, 16, 5, 32, 164, 27];
- var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
-
- var zeroFill = function zeroFill(count) {
- var a = [];
-
- while (count--) {
- a.push(0);
- }
-
- return a;
- };
-
- var makeTable = function makeTable(metaTable) {
- return Object.keys(metaTable).reduce(function (obj, key) {
- obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
- return arr.concat(part);
- }, []));
- return obj;
- }, {});
- };
-
- var silence;
-
- var silence_1 = function silence_1() {
- if (!silence) {
- // Frames-of-silence to use for filling in missing AAC frames
- var coneOfSilence = {
- 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
- 88200: [highPrefix, [231], zeroFill(170), [56]],
- 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
- 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
- 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
- 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
- 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
- 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
- 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
- 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
- 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
- };
- silence = makeTable(coneOfSilence);
- }
-
- return silence;
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
-
- var ONE_SECOND_IN_TS$4 = 90000,
- // 90kHz clock
- secondsToVideoTs,
- secondsToAudioTs,
- videoTsToSeconds,
- audioTsToSeconds,
- audioTsToVideoTs,
- videoTsToAudioTs,
- metadataTsToSeconds;
-
- secondsToVideoTs = function secondsToVideoTs(seconds) {
- return seconds * ONE_SECOND_IN_TS$4;
- };
-
- secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
- return seconds * sampleRate;
- };
-
- videoTsToSeconds = function videoTsToSeconds(timestamp) {
- return timestamp / ONE_SECOND_IN_TS$4;
- };
-
- audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
- return timestamp / sampleRate;
- };
-
- audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
- return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
- };
-
- videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
- return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
- };
- /**
- * Adjust ID3 tag or caption timing information by the timeline pts values
- * (if keepOriginalTimestamps is false) and convert to seconds
- */
-
-
- metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
- return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
- };
-
- var clock = {
- ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
- secondsToVideoTs: secondsToVideoTs,
- secondsToAudioTs: secondsToAudioTs,
- videoTsToSeconds: videoTsToSeconds,
- audioTsToSeconds: audioTsToSeconds,
- audioTsToVideoTs: audioTsToVideoTs,
- videoTsToAudioTs: videoTsToAudioTs,
- metadataTsToSeconds: metadataTsToSeconds
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- /**
- * Sum the `byteLength` properties of the data in each AAC frame
- */
-
- var sumFrameByteLengths = function sumFrameByteLengths(array) {
- var i,
- currentObj,
- sum = 0; // sum the byteLength's all each nal unit in the frame
-
- for (i = 0; i < array.length; i++) {
- currentObj = array[i];
- sum += currentObj.data.byteLength;
- }
-
- return sum;
- }; // Possibly pad (prefix) the audio track with silence if appending this track
- // would lead to the introduction of a gap in the audio buffer
-
-
- var prefixWithSilence = function prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
- var baseMediaDecodeTimeTs,
- frameDuration = 0,
- audioGapDuration = 0,
- audioFillFrameCount = 0,
- audioFillDuration = 0,
- silentFrame,
- i,
- firstFrame;
-
- if (!frames.length) {
- return;
- }
-
- baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
-
- frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
-
- if (audioAppendStartTs && videoBaseMediaDecodeTime) {
- // insert the shortest possible amount (audio gap or audio to video gap)
- audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
-
- audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
- audioFillDuration = audioFillFrameCount * frameDuration;
- } // don't attempt to fill gaps smaller than a single frame or larger
- // than a half second
-
-
- if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
- return;
- }
-
- silentFrame = silence_1()[track.samplerate];
-
- if (!silentFrame) {
- // we don't have a silent frame pregenerated for the sample rate, so use a frame
- // from the content instead
- silentFrame = frames[0].data;
- }
-
- for (i = 0; i < audioFillFrameCount; i++) {
- firstFrame = frames[0];
- frames.splice(0, 0, {
- data: silentFrame,
- dts: firstFrame.dts - frameDuration,
- pts: firstFrame.pts - frameDuration
- });
- }
-
- track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
- return audioFillDuration;
- }; // If the audio segment extends before the earliest allowed dts
- // value, remove AAC frames until starts at or after the earliest
- // allowed DTS so that we don't end up with a negative baseMedia-
- // DecodeTime for the audio track
-
-
- var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts) {
- if (track.minSegmentDts >= earliestAllowedDts) {
- return adtsFrames;
- } // We will need to recalculate the earliest segment Dts
-
-
- track.minSegmentDts = Infinity;
- return adtsFrames.filter(function (currentFrame) {
- // If this is an allowed frame, keep it and record it's Dts
- if (currentFrame.dts >= earliestAllowedDts) {
- track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
- track.minSegmentPts = track.minSegmentDts;
- return true;
- } // Otherwise, discard it
-
-
- return false;
- });
- }; // generate the track's raw mdat data from an array of frames
-
-
- var generateSampleTable = function generateSampleTable(frames) {
- var i,
- currentFrame,
- samples = [];
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- samples.push({
- size: currentFrame.data.byteLength,
- duration: 1024 // For AAC audio, all samples contain 1024 samples
-
- });
- }
-
- return samples;
- }; // generate the track's sample table from an array of frames
-
-
- var concatenateFrameData = function concatenateFrameData(frames) {
- var i,
- currentFrame,
- dataOffset = 0,
- data = new Uint8Array(sumFrameByteLengths(frames));
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- data.set(currentFrame.data, dataOffset);
- dataOffset += currentFrame.data.byteLength;
- }
-
- return data;
- };
-
- var audioFrameUtils = {
- prefixWithSilence: prefixWithSilence,
- trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
- generateSampleTable: generateSampleTable,
- concatenateFrameData: concatenateFrameData
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ONE_SECOND_IN_TS$3 = clock.ONE_SECOND_IN_TS;
- /**
- * Store information about the start and end of the track and the
- * duration for each frame/sample we process in order to calculate
- * the baseMediaDecodeTime
- */
-
- var collectDtsInfo = function collectDtsInfo(track, data) {
- if (typeof data.pts === 'number') {
- if (track.timelineStartInfo.pts === undefined) {
- track.timelineStartInfo.pts = data.pts;
- }
-
- if (track.minSegmentPts === undefined) {
- track.minSegmentPts = data.pts;
- } else {
- track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
- }
-
- if (track.maxSegmentPts === undefined) {
- track.maxSegmentPts = data.pts;
- } else {
- track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
- }
- }
-
- if (typeof data.dts === 'number') {
- if (track.timelineStartInfo.dts === undefined) {
- track.timelineStartInfo.dts = data.dts;
- }
-
- if (track.minSegmentDts === undefined) {
- track.minSegmentDts = data.dts;
- } else {
- track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
- }
-
- if (track.maxSegmentDts === undefined) {
- track.maxSegmentDts = data.dts;
- } else {
- track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
- }
- }
- };
- /**
- * Clear values used to calculate the baseMediaDecodeTime between
- * tracks
- */
-
-
- var clearDtsInfo = function clearDtsInfo(track) {
- delete track.minSegmentDts;
- delete track.maxSegmentDts;
- delete track.minSegmentPts;
- delete track.maxSegmentPts;
- };
- /**
- * Calculate the track's baseMediaDecodeTime based on the earliest
- * DTS the transmuxer has ever seen and the minimum DTS for the
- * current track
- * @param track {object} track metadata configuration
- * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime(track, keepOriginalTimestamps) {
- var baseMediaDecodeTime,
- scale,
- minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
-
- if (!keepOriginalTimestamps) {
- minSegmentDts -= track.timelineStartInfo.dts;
- } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
- // we want the start of the first segment to be placed
-
-
- baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
-
- baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
-
- baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
-
- if (track.type === 'audio') {
- // Audio has a different clock equal to the sampling_rate so we need to
- // scale the PTS values into the clock rate of the track
- scale = track.samplerate / ONE_SECOND_IN_TS$3;
- baseMediaDecodeTime *= scale;
- baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
- }
-
- return baseMediaDecodeTime;
- };
-
- var trackDecodeInfo = {
- clearDtsInfo: clearDtsInfo,
- calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
- collectDtsInfo: collectDtsInfo
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Reads in-band caption information from a video elementary
- * stream. Captions must follow the CEA-708 standard for injection
- * into an MPEG-2 transport streams.
- * @see https://en.wikipedia.org/wiki/CEA-708
- * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
- */
- // payload type field to indicate how they are to be
- // interpreted. CEAS-708 caption content is always transmitted with
- // payload type 0x04.
-
- var USER_DATA_REGISTERED_ITU_T_T35 = 4,
- RBSP_TRAILING_BITS = 128;
- /**
- * Parse a supplemental enhancement information (SEI) NAL unit.
- * Stops parsing once a message of type ITU T T35 has been found.
- *
- * @param bytes {Uint8Array} the bytes of a SEI NAL unit
- * @return {object} the parsed SEI payload
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- */
-
- var parseSei = function parseSei(bytes) {
- var i = 0,
- result = {
- payloadType: -1,
- payloadSize: 0
- },
- payloadType = 0,
- payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
-
- while (i < bytes.byteLength) {
- // stop once we have hit the end of the sei_rbsp
- if (bytes[i] === RBSP_TRAILING_BITS) {
- break;
- } // Parse payload type
-
-
- while (bytes[i] === 0xFF) {
- payloadType += 255;
- i++;
- }
-
- payloadType += bytes[i++]; // Parse payload size
-
- while (bytes[i] === 0xFF) {
- payloadSize += 255;
- i++;
- }
-
- payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
- // there can only ever be one caption message in a frame's sei
-
- if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
- var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
-
- if (userIdentifier === 'GA94') {
- result.payloadType = payloadType;
- result.payloadSize = payloadSize;
- result.payload = bytes.subarray(i, i + payloadSize);
- break;
- } else {
- result.payload = void 0;
- }
- } // skip the payload and parse the next message
-
-
- i += payloadSize;
- payloadType = 0;
- payloadSize = 0;
- }
-
- return result;
- }; // see ANSI/SCTE 128-1 (2013), section 8.1
-
-
- var parseUserData = function parseUserData(sei) {
- // itu_t_t35_contry_code must be 181 (United States) for
- // captions
- if (sei.payload[0] !== 181) {
- return null;
- } // itu_t_t35_provider_code should be 49 (ATSC) for captions
-
-
- if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
- return null;
- } // the user_identifier should be "GA94" to indicate ATSC1 data
-
-
- if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
- return null;
- } // finally, user_data_type_code should be 0x03 for caption data
-
-
- if (sei.payload[7] !== 0x03) {
- return null;
- } // return the user_data_type_structure and strip the trailing
- // marker bits
-
-
- return sei.payload.subarray(8, sei.payload.length - 1);
- }; // see CEA-708-D, section 4.4
-
-
- var parseCaptionPackets = function parseCaptionPackets(pts, userData) {
- var results = [],
- i,
- count,
- offset,
- data; // if this is just filler, return immediately
-
- if (!(userData[0] & 0x40)) {
- return results;
- } // parse out the cc_data_1 and cc_data_2 fields
-
-
- count = userData[0] & 0x1f;
-
- for (i = 0; i < count; i++) {
- offset = i * 3;
- data = {
- type: userData[offset + 2] & 0x03,
- pts: pts
- }; // capture cc data when cc_valid is 1
-
- if (userData[offset + 2] & 0x04) {
- data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
- results.push(data);
- }
- }
-
- return results;
- };
-
- var discardEmulationPreventionBytes$1 = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- }; // exports
-
-
- var captionPacketParser = {
- parseSei: parseSei,
- parseUserData: parseUserData,
- parseCaptionPackets: parseCaptionPackets,
- discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
- USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
- }; // Link To Transport
- // -----------------
-
- var CaptionStream$1 = function CaptionStream(options) {
- options = options || {};
- CaptionStream.prototype.init.call(this); // parse708captions flag, default to true
-
- this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
- this.captionPackets_ = [];
- this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
- ];
-
- if (this.parse708captions_) {
- this.cc708Stream_ = new Cea708Stream(); // eslint-disable-line no-use-before-define
- }
-
- this.reset(); // forward data and done events from CCs to this CaptionStream
-
- this.ccStreams_.forEach(function (cc) {
- cc.on('data', this.trigger.bind(this, 'data'));
- cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
- cc.on('done', this.trigger.bind(this, 'done'));
- }, this);
-
- if (this.parse708captions_) {
- this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
- this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
- this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
- }
- };
-
- CaptionStream$1.prototype = new stream();
-
- CaptionStream$1.prototype.push = function (event) {
- var sei, userData, newCaptionPackets; // only examine SEI NALs
-
- if (event.nalUnitType !== 'sei_rbsp') {
- return;
- } // parse the sei
-
-
- sei = captionPacketParser.parseSei(event.escapedRBSP); // no payload data, skip
-
- if (!sei.payload) {
- return;
- } // ignore everything but user_data_registered_itu_t_t35
-
-
- if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
- return;
- } // parse out the user data payload
-
-
- userData = captionPacketParser.parseUserData(sei); // ignore unrecognized userData
-
- if (!userData) {
- return;
- } // Sometimes, the same segment # will be downloaded twice. To stop the
- // caption data from being processed twice, we track the latest dts we've
- // received and ignore everything with a dts before that. However, since
- // data for a specific dts can be split across packets on either side of
- // a segment boundary, we need to make sure we *don't* ignore the packets
- // from the *next* segment that have dts === this.latestDts_. By constantly
- // tracking the number of packets received with dts === this.latestDts_, we
- // know how many should be ignored once we start receiving duplicates.
-
-
- if (event.dts < this.latestDts_) {
- // We've started getting older data, so set the flag.
- this.ignoreNextEqualDts_ = true;
- return;
- } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
- this.numSameDts_--;
-
- if (!this.numSameDts_) {
- // We've received the last duplicate packet, time to start processing again
- this.ignoreNextEqualDts_ = false;
- }
-
- return;
- } // parse out CC data packets and save them for later
-
-
- newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
- this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
-
- if (this.latestDts_ !== event.dts) {
- this.numSameDts_ = 0;
- }
-
- this.numSameDts_++;
- this.latestDts_ = event.dts;
- };
-
- CaptionStream$1.prototype.flushCCStreams = function (flushType) {
- this.ccStreams_.forEach(function (cc) {
- return flushType === 'flush' ? cc.flush() : cc.partialFlush();
- }, this);
- };
-
- CaptionStream$1.prototype.flushStream = function (flushType) {
- // make sure we actually parsed captions before proceeding
- if (!this.captionPackets_.length) {
- this.flushCCStreams(flushType);
- return;
- } // In Chrome, the Array#sort function is not stable so add a
- // presortIndex that we can use to ensure we get a stable-sort
-
-
- this.captionPackets_.forEach(function (elem, idx) {
- elem.presortIndex = idx;
- }); // sort caption byte-pairs based on their PTS values
-
- this.captionPackets_.sort(function (a, b) {
- if (a.pts === b.pts) {
- return a.presortIndex - b.presortIndex;
- }
-
- return a.pts - b.pts;
- });
- this.captionPackets_.forEach(function (packet) {
- if (packet.type < 2) {
- // Dispatch packet to the right Cea608Stream
- this.dispatchCea608Packet(packet);
- } else {
- // Dispatch packet to the Cea708Stream
- this.dispatchCea708Packet(packet);
- }
- }, this);
- this.captionPackets_.length = 0;
- this.flushCCStreams(flushType);
- };
-
- CaptionStream$1.prototype.flush = function () {
- return this.flushStream('flush');
- }; // Only called if handling partial data
-
-
- CaptionStream$1.prototype.partialFlush = function () {
- return this.flushStream('partialFlush');
- };
-
- CaptionStream$1.prototype.reset = function () {
- this.latestDts_ = null;
- this.ignoreNextEqualDts_ = false;
- this.numSameDts_ = 0;
- this.activeCea608Channel_ = [null, null];
- this.ccStreams_.forEach(function (ccStream) {
- ccStream.reset();
- });
- }; // From the CEA-608 spec:
-
- /*
- * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
- * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
- * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
- * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
- * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
- * to switch to captioning or Text.
- */
- // With that in mind, we ignore any data between an XDS control code and a
- // subsequent closed-captioning control code.
-
-
- CaptionStream$1.prototype.dispatchCea608Packet = function (packet) {
- // NOTE: packet.type is the CEA608 field
- if (this.setsTextOrXDSActive(packet)) {
- this.activeCea608Channel_[packet.type] = null;
- } else if (this.setsChannel1Active(packet)) {
- this.activeCea608Channel_[packet.type] = 0;
- } else if (this.setsChannel2Active(packet)) {
- this.activeCea608Channel_[packet.type] = 1;
- }
-
- if (this.activeCea608Channel_[packet.type] === null) {
- // If we haven't received anything to set the active channel, or the
- // packets are Text/XDS data, discard the data; we don't want jumbled
- // captions
- return;
- }
-
- this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
- };
-
- CaptionStream$1.prototype.setsChannel1Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1000;
- };
-
- CaptionStream$1.prototype.setsChannel2Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1800;
- };
-
- CaptionStream$1.prototype.setsTextOrXDSActive = function (packet) {
- return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
- };
-
- CaptionStream$1.prototype.dispatchCea708Packet = function (packet) {
- if (this.parse708captions_) {
- this.cc708Stream_.push(packet);
- }
- }; // ----------------------
- // Session to Application
- // ----------------------
- // This hash maps special and extended character codes to their
- // proper Unicode equivalent. The first one-byte key is just a
- // non-standard character code. The two-byte keys that follow are
- // the extended CEA708 character codes, along with the preceding
- // 0x10 extended character byte to distinguish these codes from
- // non-extended character codes. Every CEA708 character code that
- // is not in this object maps directly to a standard unicode
- // character code.
- // The transparent space and non-breaking transparent space are
- // technically not fully supported since there is no code to
- // make them transparent, so they have normal non-transparent
- // stand-ins.
- // The special closed caption (CC) character isn't a standard
- // unicode character, so a fairly similar unicode character was
- // chosen in it's place.
-
-
- var CHARACTER_TRANSLATION_708 = {
- 0x7f: 0x266a,
- // ♪
- 0x1020: 0x20,
- // Transparent Space
- 0x1021: 0xa0,
- // Nob-breaking Transparent Space
- 0x1025: 0x2026,
- // …
- 0x102a: 0x0160,
- // Š
- 0x102c: 0x0152,
- // Œ
- 0x1030: 0x2588,
- // █
- 0x1031: 0x2018,
- // ‘
- 0x1032: 0x2019,
- // ’
- 0x1033: 0x201c,
- // “
- 0x1034: 0x201d,
- // ”
- 0x1035: 0x2022,
- // •
- 0x1039: 0x2122,
- // ™
- 0x103a: 0x0161,
- // š
- 0x103c: 0x0153,
- // œ
- 0x103d: 0x2120,
- // ℠
- 0x103f: 0x0178,
- // Ÿ
- 0x1076: 0x215b,
- // ⅛
- 0x1077: 0x215c,
- // ⅜
- 0x1078: 0x215d,
- // ⅝
- 0x1079: 0x215e,
- // ⅞
- 0x107a: 0x23d0,
- // ⏐
- 0x107b: 0x23a4,
- // ⎤
- 0x107c: 0x23a3,
- // ⎣
- 0x107d: 0x23af,
- // ⎯
- 0x107e: 0x23a6,
- // ⎦
- 0x107f: 0x23a1,
- // ⎡
- 0x10a0: 0x3138 // ㄸ (CC char)
-
- };
-
- var get708CharFromCode = function get708CharFromCode(code) {
- var newCode = CHARACTER_TRANSLATION_708[code] || code;
-
- if (code & 0x1000 && code === newCode) {
- // Invalid extended code
- return '';
- }
-
- return String.fromCharCode(newCode);
- };
-
- var within708TextBlock = function within708TextBlock(b) {
- return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
- };
-
- var Cea708Window = function Cea708Window(windowNum) {
- this.windowNum = windowNum;
- this.reset();
- };
-
- Cea708Window.prototype.reset = function () {
- this.clearText();
- this.pendingNewLine = false;
- this.winAttr = {};
- this.penAttr = {};
- this.penLoc = {};
- this.penColor = {}; // These default values are arbitrary,
- // defineWindow will usually override them
-
- this.visible = 0;
- this.rowLock = 0;
- this.columnLock = 0;
- this.priority = 0;
- this.relativePositioning = 0;
- this.anchorVertical = 0;
- this.anchorHorizontal = 0;
- this.anchorPoint = 0;
- this.rowCount = 1;
- this.virtualRowCount = this.rowCount + 1;
- this.columnCount = 41;
- this.windowStyle = 0;
- this.penStyle = 0;
- };
-
- Cea708Window.prototype.getText = function () {
- return this.rows.join('\n');
- };
-
- Cea708Window.prototype.clearText = function () {
- this.rows = [''];
- this.rowIdx = 0;
- };
-
- Cea708Window.prototype.newLine = function (pts) {
- if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
- this.beforeRowOverflow(pts);
- }
-
- if (this.rows.length > 0) {
- this.rows.push('');
- this.rowIdx++;
- } // Show all virtual rows since there's no visible scrolling
-
-
- while (this.rows.length > this.virtualRowCount) {
- this.rows.shift();
- this.rowIdx--;
- }
- };
-
- Cea708Window.prototype.isEmpty = function () {
- if (this.rows.length === 0) {
- return true;
- } else if (this.rows.length === 1) {
- return this.rows[0] === '';
- }
-
- return false;
- };
-
- Cea708Window.prototype.addText = function (text) {
- this.rows[this.rowIdx] += text;
- };
-
- Cea708Window.prototype.backspace = function () {
- if (!this.isEmpty()) {
- var row = this.rows[this.rowIdx];
- this.rows[this.rowIdx] = row.substr(0, row.length - 1);
- }
- };
-
- var Cea708Service = function Cea708Service(serviceNum) {
- this.serviceNum = serviceNum;
- this.text = '';
- this.currentWindow = new Cea708Window(-1);
- this.windows = [];
- };
- /**
- * Initialize service windows
- * Must be run before service use
- *
- * @param {Integer} pts PTS value
- * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
- */
-
-
- Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
- this.startPts = pts;
-
- for (var win = 0; win < 8; win++) {
- this.windows[win] = new Cea708Window(win);
-
- if (typeof beforeRowOverflow === 'function') {
- this.windows[win].beforeRowOverflow = beforeRowOverflow;
- }
- }
- };
- /**
- * Set current window of service to be affected by commands
- *
- * @param {Integer} windowNum Window number
- */
-
-
- Cea708Service.prototype.setCurrentWindow = function (windowNum) {
- this.currentWindow = this.windows[windowNum];
- };
-
- var Cea708Stream = function Cea708Stream() {
- Cea708Stream.prototype.init.call(this);
- var self = this;
- this.current708Packet = null;
- this.services = {};
-
- this.push = function (packet) {
- if (packet.type === 3) {
- // 708 packet start
- self.new708Packet();
- self.add708Bytes(packet);
- } else {
- if (self.current708Packet === null) {
- // This should only happen at the start of a file if there's no packet start.
- self.new708Packet();
- }
-
- self.add708Bytes(packet);
- }
- };
- };
-
- Cea708Stream.prototype = new stream();
- /**
- * Push current 708 packet, create new 708 packet.
- */
-
- Cea708Stream.prototype.new708Packet = function () {
- if (this.current708Packet !== null) {
- this.push708Packet();
- }
-
- this.current708Packet = {
- data: [],
- ptsVals: []
- };
- };
- /**
- * Add pts and both bytes from packet into current 708 packet.
- */
-
-
- Cea708Stream.prototype.add708Bytes = function (packet) {
- var data = packet.ccData;
- var byte0 = data >>> 8;
- var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
- // that service blocks will always line up with byte pairs.
-
- this.current708Packet.ptsVals.push(packet.pts);
- this.current708Packet.data.push(byte0);
- this.current708Packet.data.push(byte1);
- };
- /**
- * Parse completed 708 packet into service blocks and push each service block.
- */
-
-
- Cea708Stream.prototype.push708Packet = function () {
- var packet708 = this.current708Packet;
- var packetData = packet708.data;
- var serviceNum = null;
- var blockSize = null;
- var i = 0;
- var b = packetData[i++];
- packet708.seq = b >> 6;
- packet708.sizeCode = b & 0x3f; // 0b00111111;
-
- for (; i < packetData.length; i++) {
- b = packetData[i++];
- serviceNum = b >> 5;
- blockSize = b & 0x1f; // 0b00011111
-
- if (serviceNum === 7 && blockSize > 0) {
- // Extended service num
- b = packetData[i++];
- serviceNum = b;
- }
-
- this.pushServiceBlock(serviceNum, i, blockSize);
-
- if (blockSize > 0) {
- i += blockSize - 1;
- }
- }
- };
- /**
- * Parse service block, execute commands, read text.
- *
- * Note: While many of these commands serve important purposes,
- * many others just parse out the parameters or attributes, but
- * nothing is done with them because this is not a full and complete
- * implementation of the entire 708 spec.
- *
- * @param {Integer} serviceNum Service number
- * @param {Integer} start Start index of the 708 packet data
- * @param {Integer} size Block size
- */
-
-
- Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
- var b;
- var i = start;
- var packetData = this.current708Packet.data;
- var service = this.services[serviceNum];
-
- if (!service) {
- service = this.initService(serviceNum, i);
- }
-
- for (; i < start + size && i < packetData.length; i++) {
- b = packetData[i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service);
- } else if (b === 0x10) {
- i = this.extendedCommands(i, service);
- } else if (0x80 <= b && b <= 0x87) {
- i = this.setCurrentWindow(i, service);
- } else if (0x98 <= b && b <= 0x9f) {
- i = this.defineWindow(i, service);
- } else if (b === 0x88) {
- i = this.clearWindows(i, service);
- } else if (b === 0x8c) {
- i = this.deleteWindows(i, service);
- } else if (b === 0x89) {
- i = this.displayWindows(i, service);
- } else if (b === 0x8a) {
- i = this.hideWindows(i, service);
- } else if (b === 0x8b) {
- i = this.toggleWindows(i, service);
- } else if (b === 0x97) {
- i = this.setWindowAttributes(i, service);
- } else if (b === 0x90) {
- i = this.setPenAttributes(i, service);
- } else if (b === 0x91) {
- i = this.setPenColor(i, service);
- } else if (b === 0x92) {
- i = this.setPenLocation(i, service);
- } else if (b === 0x8f) {
- service = this.reset(i, service);
- } else if (b === 0x08) {
- // BS: Backspace
- service.currentWindow.backspace();
- } else if (b === 0x0c) {
- // FF: Form feed
- service.currentWindow.clearText();
- } else if (b === 0x0d) {
- // CR: Carriage return
- service.currentWindow.pendingNewLine = true;
- } else if (b === 0x0e) {
- // HCR: Horizontal carriage return
- service.currentWindow.clearText();
- } else if (b === 0x8d) {
- // DLY: Delay, nothing to do
- i++;
- } else ;
- }
- };
- /**
- * Execute an extended command
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.extendedCommands = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service, true);
- }
-
- return i;
- };
- /**
- * Get PTS value of a given byte index
- *
- * @param {Integer} byteIndex Index of the byte
- * @return {Integer} PTS
- */
-
-
- Cea708Stream.prototype.getPts = function (byteIndex) {
- // There's 1 pts value per 2 bytes
- return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
- };
- /**
- * Initializes a service
- *
- * @param {Integer} serviceNum Service number
- * @return {Service} Initialized service object
- */
-
-
- Cea708Stream.prototype.initService = function (serviceNum, i) {
- var self = this;
- this.services[serviceNum] = new Cea708Service(serviceNum);
- this.services[serviceNum].init(this.getPts(i), function (pts) {
- self.flushDisplayed(pts, self.services[serviceNum]);
- });
- return this.services[serviceNum];
- };
- /**
- * Execute text writing to current window
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.handleText = function (i, service, isExtended) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var extended = isExtended ? 0x1000 : 0x0000;
- var char = get708CharFromCode(extended | b);
- var win = service.currentWindow;
-
- if (win.pendingNewLine && !win.isEmpty()) {
- win.newLine(this.getPts(i));
- }
-
- win.pendingNewLine = false;
- win.addText(char);
- return i;
- };
- /**
- * Parse and execute the CW# command.
- *
- * Set the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setCurrentWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- return i;
- };
- /**
- * Parse and execute the DF# command.
- *
- * Define a window and set it as the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.defineWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- var win = service.currentWindow;
- b = packetData[++i];
- win.visible = (b & 0x20) >> 5; // v
-
- win.rowLock = (b & 0x10) >> 4; // rl
-
- win.columnLock = (b & 0x08) >> 3; // cl
-
- win.priority = b & 0x07; // p
-
- b = packetData[++i];
- win.relativePositioning = (b & 0x80) >> 7; // rp
-
- win.anchorVertical = b & 0x7f; // av
-
- b = packetData[++i];
- win.anchorHorizontal = b; // ah
-
- b = packetData[++i];
- win.anchorPoint = (b & 0xf0) >> 4; // ap
-
- win.rowCount = b & 0x0f; // rc
-
- b = packetData[++i];
- win.columnCount = b & 0x3f; // cc
-
- b = packetData[++i];
- win.windowStyle = (b & 0x38) >> 3; // ws
-
- win.penStyle = b & 0x07; // ps
- // The spec says there are (rowCount+1) "virtual rows"
-
- win.virtualRowCount = win.rowCount + 1;
- return i;
- };
- /**
- * Parse and execute the SWA command.
- *
- * Set attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setWindowAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var winAttr = service.currentWindow.winAttr;
- b = packetData[++i];
- winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
-
- winAttr.fillRed = (b & 0x30) >> 4; // fr
-
- winAttr.fillGreen = (b & 0x0c) >> 2; // fg
-
- winAttr.fillBlue = b & 0x03; // fb
-
- b = packetData[++i];
- winAttr.borderType = (b & 0xc0) >> 6; // bt
-
- winAttr.borderRed = (b & 0x30) >> 4; // br
-
- winAttr.borderGreen = (b & 0x0c) >> 2; // bg
-
- winAttr.borderBlue = b & 0x03; // bb
-
- b = packetData[++i];
- winAttr.borderType += (b & 0x80) >> 5; // bt
-
- winAttr.wordWrap = (b & 0x40) >> 6; // ww
-
- winAttr.printDirection = (b & 0x30) >> 4; // pd
-
- winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
-
- winAttr.justify = b & 0x03; // j
-
- b = packetData[++i];
- winAttr.effectSpeed = (b & 0xf0) >> 4; // es
-
- winAttr.effectDirection = (b & 0x0c) >> 2; // ed
-
- winAttr.displayEffect = b & 0x03; // de
-
- return i;
- };
- /**
- * Gather text from all displayed windows and push a caption to output.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.flushDisplayed = function (pts, service) {
- var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
- // display text in the correct order, but sample files so far have not shown any issue.
-
- for (var winId = 0; winId < 8; winId++) {
- if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
- displayedText.push(service.windows[winId].getText());
- }
- }
-
- service.endPts = pts;
- service.text = displayedText.join('\n\n');
- this.pushCaption(service);
- service.startPts = pts;
- };
- /**
- * Push a caption to output if the caption contains text.
- *
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.pushCaption = function (service) {
- if (service.text !== '') {
- this.trigger('data', {
- startPts: service.startPts,
- endPts: service.endPts,
- text: service.text,
- stream: 'cc708_' + service.serviceNum
- });
- service.text = '';
- service.startPts = service.endPts;
- }
- };
- /**
- * Parse and execute the DSW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.displayWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the HDW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.hideWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 0;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the TGW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.toggleWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible ^= 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the CLW command.
- *
- * Clear text of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.clearWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].clearText();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the DLW command.
- *
- * Re-initialize windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.deleteWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].reset();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the SPA command.
- *
- * Set pen attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penAttr = service.currentWindow.penAttr;
- b = packetData[++i];
- penAttr.textTag = (b & 0xf0) >> 4; // tt
-
- penAttr.offset = (b & 0x0c) >> 2; // o
-
- penAttr.penSize = b & 0x03; // s
-
- b = packetData[++i];
- penAttr.italics = (b & 0x80) >> 7; // i
-
- penAttr.underline = (b & 0x40) >> 6; // u
-
- penAttr.edgeType = (b & 0x38) >> 3; // et
-
- penAttr.fontStyle = b & 0x07; // fs
-
- return i;
- };
- /**
- * Parse and execute the SPC command.
- *
- * Set pen color of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenColor = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penColor = service.currentWindow.penColor;
- b = packetData[++i];
- penColor.fgOpacity = (b & 0xc0) >> 6; // fo
-
- penColor.fgRed = (b & 0x30) >> 4; // fr
-
- penColor.fgGreen = (b & 0x0c) >> 2; // fg
-
- penColor.fgBlue = b & 0x03; // fb
-
- b = packetData[++i];
- penColor.bgOpacity = (b & 0xc0) >> 6; // bo
-
- penColor.bgRed = (b & 0x30) >> 4; // br
-
- penColor.bgGreen = (b & 0x0c) >> 2; // bg
-
- penColor.bgBlue = b & 0x03; // bb
-
- b = packetData[++i];
- penColor.edgeRed = (b & 0x30) >> 4; // er
-
- penColor.edgeGreen = (b & 0x0c) >> 2; // eg
-
- penColor.edgeBlue = b & 0x03; // eb
-
- return i;
- };
- /**
- * Parse and execute the SPL command.
- *
- * Set pen location of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenLocation = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
-
- service.currentWindow.pendingNewLine = true;
- b = packetData[++i];
- penLoc.row = b & 0x0f; // r
-
- b = packetData[++i];
- penLoc.column = b & 0x3f; // c
-
- return i;
- };
- /**
- * Execute the RST command.
- *
- * Reset service to a clean slate. Re-initialize.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Service} Re-initialized service
- */
-
-
- Cea708Stream.prototype.reset = function (i, service) {
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
- return this.initService(service.serviceNum, i);
- }; // This hash maps non-ASCII, special, and extended character codes to their
- // proper Unicode equivalent. The first keys that are only a single byte
- // are the non-standard ASCII characters, which simply map the CEA608 byte
- // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
- // character codes, but have their MSB bitmasked with 0x03 so that a lookup
- // can be performed regardless of the field and data channel on which the
- // character code was received.
-
-
- var CHARACTER_TRANSLATION = {
- 0x2a: 0xe1,
- // á
- 0x5c: 0xe9,
- // é
- 0x5e: 0xed,
- // í
- 0x5f: 0xf3,
- // ó
- 0x60: 0xfa,
- // ú
- 0x7b: 0xe7,
- // ç
- 0x7c: 0xf7,
- // ÷
- 0x7d: 0xd1,
- // Ñ
- 0x7e: 0xf1,
- // ñ
- 0x7f: 0x2588,
- // █
- 0x0130: 0xae,
- // ®
- 0x0131: 0xb0,
- // °
- 0x0132: 0xbd,
- // ½
- 0x0133: 0xbf,
- // ¿
- 0x0134: 0x2122,
- // ™
- 0x0135: 0xa2,
- // ¢
- 0x0136: 0xa3,
- // £
- 0x0137: 0x266a,
- // ♪
- 0x0138: 0xe0,
- // à
- 0x0139: 0xa0,
- //
- 0x013a: 0xe8,
- // è
- 0x013b: 0xe2,
- // â
- 0x013c: 0xea,
- // ê
- 0x013d: 0xee,
- // î
- 0x013e: 0xf4,
- // ô
- 0x013f: 0xfb,
- // û
- 0x0220: 0xc1,
- // Á
- 0x0221: 0xc9,
- // É
- 0x0222: 0xd3,
- // Ó
- 0x0223: 0xda,
- // Ú
- 0x0224: 0xdc,
- // Ü
- 0x0225: 0xfc,
- // ü
- 0x0226: 0x2018,
- // ‘
- 0x0227: 0xa1,
- // ¡
- 0x0228: 0x2a,
- // *
- 0x0229: 0x27,
- // '
- 0x022a: 0x2014,
- // —
- 0x022b: 0xa9,
- // ©
- 0x022c: 0x2120,
- // ℠
- 0x022d: 0x2022,
- // •
- 0x022e: 0x201c,
- // “
- 0x022f: 0x201d,
- // ”
- 0x0230: 0xc0,
- // À
- 0x0231: 0xc2,
- // Â
- 0x0232: 0xc7,
- // Ç
- 0x0233: 0xc8,
- // È
- 0x0234: 0xca,
- // Ê
- 0x0235: 0xcb,
- // Ë
- 0x0236: 0xeb,
- // ë
- 0x0237: 0xce,
- // Î
- 0x0238: 0xcf,
- // Ï
- 0x0239: 0xef,
- // ï
- 0x023a: 0xd4,
- // Ô
- 0x023b: 0xd9,
- // Ù
- 0x023c: 0xf9,
- // ù
- 0x023d: 0xdb,
- // Û
- 0x023e: 0xab,
- // «
- 0x023f: 0xbb,
- // »
- 0x0320: 0xc3,
- // Ã
- 0x0321: 0xe3,
- // ã
- 0x0322: 0xcd,
- // Í
- 0x0323: 0xcc,
- // Ì
- 0x0324: 0xec,
- // ì
- 0x0325: 0xd2,
- // Ò
- 0x0326: 0xf2,
- // ò
- 0x0327: 0xd5,
- // Õ
- 0x0328: 0xf5,
- // õ
- 0x0329: 0x7b,
- // {
- 0x032a: 0x7d,
- // }
- 0x032b: 0x5c,
- // \
- 0x032c: 0x5e,
- // ^
- 0x032d: 0x5f,
- // _
- 0x032e: 0x7c,
- // |
- 0x032f: 0x7e,
- // ~
- 0x0330: 0xc4,
- // Ä
- 0x0331: 0xe4,
- // ä
- 0x0332: 0xd6,
- // Ö
- 0x0333: 0xf6,
- // ö
- 0x0334: 0xdf,
- // ß
- 0x0335: 0xa5,
- // ¥
- 0x0336: 0xa4,
- // ¤
- 0x0337: 0x2502,
- // │
- 0x0338: 0xc5,
- // Å
- 0x0339: 0xe5,
- // å
- 0x033a: 0xd8,
- // Ø
- 0x033b: 0xf8,
- // ø
- 0x033c: 0x250c,
- // ┌
- 0x033d: 0x2510,
- // ┐
- 0x033e: 0x2514,
- // └
- 0x033f: 0x2518 // ┘
-
- };
-
- var getCharFromCode = function getCharFromCode(code) {
- if (code === null) {
- return '';
- }
-
- code = CHARACTER_TRANSLATION[code] || code;
- return String.fromCharCode(code);
- }; // the index of the last row in a CEA-608 display buffer
-
-
- var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
- // getting it through bit logic.
-
- var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // CEA-608 captions are rendered onto a 34x15 matrix of character
- // cells. The "bottom" row is the last element in the outer array.
-
- var createDisplayBuffer = function createDisplayBuffer() {
- var result = [],
- i = BOTTOM_ROW + 1;
-
- while (i--) {
- result.push('');
- }
-
- return result;
- };
-
- var Cea608Stream = function Cea608Stream(field, dataChannel) {
- Cea608Stream.prototype.init.call(this);
- this.field_ = field || 0;
- this.dataChannel_ = dataChannel || 0;
- this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
- this.setConstants();
- this.reset();
-
- this.push = function (packet) {
- var data, swap, char0, char1, text; // remove the parity bits
-
- data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
-
- if (data === this.lastControlCode_) {
- this.lastControlCode_ = null;
- return;
- } // Store control codes
-
-
- if ((data & 0xf000) === 0x1000) {
- this.lastControlCode_ = data;
- } else if (data !== this.PADDING_) {
- this.lastControlCode_ = null;
- }
-
- char0 = data >>> 8;
- char1 = data & 0xff;
-
- if (data === this.PADDING_) {
- return;
- } else if (data === this.RESUME_CAPTION_LOADING_) {
- this.mode_ = 'popOn';
- } else if (data === this.END_OF_CAPTION_) {
- // If an EOC is received while in paint-on mode, the displayed caption
- // text should be swapped to non-displayed memory as if it was a pop-on
- // caption. Because of that, we should explicitly switch back to pop-on
- // mode
- this.mode_ = 'popOn';
- this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
-
- this.flushDisplayed(packet.pts); // flip memory
-
- swap = this.displayed_;
- this.displayed_ = this.nonDisplayed_;
- this.nonDisplayed_ = swap; // start measuring the time to display the caption
-
- this.startPts_ = packet.pts;
- } else if (data === this.ROLL_UP_2_ROWS_) {
- this.rollUpRows_ = 2;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_3_ROWS_) {
- this.rollUpRows_ = 3;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_4_ROWS_) {
- this.rollUpRows_ = 4;
- this.setRollUp(packet.pts);
- } else if (data === this.CARRIAGE_RETURN_) {
- this.clearFormatting(packet.pts);
- this.flushDisplayed(packet.pts);
- this.shiftRowsUp_();
- this.startPts_ = packet.pts;
- } else if (data === this.BACKSPACE_) {
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- }
- } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
- this.nonDisplayed_ = createDisplayBuffer();
- } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
- if (this.mode_ !== 'paintOn') {
- // NOTE: This should be removed when proper caption positioning is
- // implemented
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- }
-
- this.mode_ = 'paintOn';
- this.startPts_ = packet.pts; // Append special characters to caption text
- } else if (this.isSpecialCharacter(char0, char1)) {
- // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Append extended characters to caption text
- } else if (this.isExtCharacter(char0, char1)) {
- // Extended characters always follow their "non-extended" equivalents.
- // IE if a "è" is desired, you'll always receive "eè"; non-compliant
- // decoders are supposed to drop the "è", while compliant decoders
- // backspace the "e" and insert "è".
- // Delete the previous character
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- } // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
-
-
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Process mid-row codes
- } else if (this.isMidRowCode(char0, char1)) {
- // Attributes are not additive, so clear all formatting
- this.clearFormatting(packet.pts); // According to the standard, mid-row codes
- // should be replaced with spaces, so add one now
-
- this[this.mode_](packet.pts, ' ');
- this.column_++;
-
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
-
- if ((char1 & 0x1) === 0x1) {
- this.addFormatting(packet.pts, ['u']);
- } // Detect offset control codes and adjust cursor
-
- } else if (this.isOffsetControlCode(char0, char1)) {
- // Cursor position is set by indent PAC (see below) in 4-column
- // increments, with an additional offset code of 1-3 to reach any
- // of the 32 columns specified by CEA-608. So all we need to do
- // here is increment the column cursor by the given offset.
- this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
- } else if (this.isPAC(char0, char1)) {
- // There's no logic for PAC -> row mapping, so we have to just
- // find the row code in an array and use its index :(
- var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
-
- if (this.mode_ === 'rollUp') {
- // This implies that the base row is incorrectly set.
- // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
- // of roll-up rows set.
- if (row - this.rollUpRows_ + 1 < 0) {
- row = this.rollUpRows_ - 1;
- }
-
- this.setRollUp(packet.pts, row);
- }
-
- if (row !== this.row_) {
- // formatting is only persistent for current row
- this.clearFormatting(packet.pts);
- this.row_ = row;
- } // All PACs can apply underline, so detect and apply
- // (All odd-numbered second bytes set underline)
-
-
- if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
- this.addFormatting(packet.pts, ['u']);
- }
-
- if ((data & 0x10) === 0x10) {
- // We've got an indent level code. Each successive even number
- // increments the column cursor by 4, so we can get the desired
- // column position by bit-shifting to the right (to get n/2)
- // and multiplying by 4.
- this.column_ = ((data & 0xe) >> 1) * 4;
- }
-
- if (this.isColorPAC(char1)) {
- // it's a color code, though we only support white, which
- // can be either normal or italicized. white italics can be
- // either 0x4e or 0x6e depending on the row, so we just
- // bitwise-and with 0xe to see if italics should be turned on
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
- } // We have a normal character in char0, and possibly one in char1
-
- } else if (this.isNormalChar(char0)) {
- if (char1 === 0x00) {
- char1 = null;
- }
-
- text = getCharFromCode(char0);
- text += getCharFromCode(char1);
- this[this.mode_](packet.pts, text);
- this.column_ += text.length;
- } // finish data processing
-
- };
- };
-
- Cea608Stream.prototype = new stream(); // Trigger a cue point that captures the current state of the
- // display buffer
-
- Cea608Stream.prototype.flushDisplayed = function (pts) {
- var content = this.displayed_ // remove spaces from the start and end of the string
- .map(function (row) {
- try {
- return row.trim();
- } catch (e) {
- // Ordinarily, this shouldn't happen. However, caption
- // parsing errors should not throw exceptions and
- // break playback.
- // eslint-disable-next-line no-console
- console.error('Skipping malformed caption.');
- return '';
- }
- }) // combine all text rows to display in one cue
- .join('\n') // and remove blank rows from the start and end, but not the middle
- .replace(/^\n+|\n+$/g, '');
-
- if (content.length) {
- this.trigger('data', {
- startPts: this.startPts_,
- endPts: pts,
- text: content,
- stream: this.name_
- });
- }
- };
- /**
- * Zero out the data, used for startup and on seek
- */
-
-
- Cea608Stream.prototype.reset = function () {
- this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
- // actually display captions. If a caption is shifted to a row
- // with a lower index than this, it is cleared from the display
- // buffer
-
- this.topRow_ = 0;
- this.startPts_ = 0;
- this.displayed_ = createDisplayBuffer();
- this.nonDisplayed_ = createDisplayBuffer();
- this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
-
- this.column_ = 0;
- this.row_ = BOTTOM_ROW;
- this.rollUpRows_ = 2; // This variable holds currently-applied formatting
-
- this.formatting_ = [];
- };
- /**
- * Sets up control code and related constants for this instance
- */
-
-
- Cea608Stream.prototype.setConstants = function () {
- // The following attributes have these uses:
- // ext_ : char0 for mid-row codes, and the base for extended
- // chars (ext_+0, ext_+1, and ext_+2 are char0s for
- // extended codes)
- // control_: char0 for control codes, except byte-shifted to the
- // left so that we can do this.control_ | CONTROL_CODE
- // offset_: char0 for tab offset codes
- //
- // It's also worth noting that control codes, and _only_ control codes,
- // differ between field 1 and field2. Field 2 control codes are always
- // their field 1 value plus 1. That's why there's the "| field" on the
- // control value.
- if (this.dataChannel_ === 0) {
- this.BASE_ = 0x10;
- this.EXT_ = 0x11;
- this.CONTROL_ = (0x14 | this.field_) << 8;
- this.OFFSET_ = 0x17;
- } else if (this.dataChannel_ === 1) {
- this.BASE_ = 0x18;
- this.EXT_ = 0x19;
- this.CONTROL_ = (0x1c | this.field_) << 8;
- this.OFFSET_ = 0x1f;
- } // Constants for the LSByte command codes recognized by Cea608Stream. This
- // list is not exhaustive. For a more comprehensive listing and semantics see
- // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
- // Padding
-
-
- this.PADDING_ = 0x0000; // Pop-on Mode
-
- this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
- this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
-
- this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
- this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
- this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
- this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
-
- this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
-
- this.BACKSPACE_ = this.CONTROL_ | 0x21;
- this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
- this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
- };
- /**
- * Detects if the 2-byte packet data is a special character
- *
- * Special characters have a second byte in the range 0x30 to 0x3f,
- * with the first byte being 0x11 (for data channel 1) or 0x19 (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an special character
- */
-
-
- Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet data is an extended character
- *
- * Extended characters have a second byte in the range 0x20 to 0x3f,
- * with the first byte being 0x12 or 0x13 (for data channel 1) or
- * 0x1a or 0x1b (for data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an extended character
- */
-
-
- Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
- return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet is a mid-row code
- *
- * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
- * the first byte being 0x11 (for data channel 1) or 0x19 (for data
- * channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a mid-row code
- */
-
-
- Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
- };
- /**
- * Detects if the 2-byte packet is an offset control code
- *
- * Offset control codes have a second byte in the range 0x21 to 0x23,
- * with the first byte being 0x17 (for data channel 1) or 0x1f (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an offset control code
- */
-
-
- Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
- return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
- };
- /**
- * Detects if the 2-byte packet is a Preamble Address Code
- *
- * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
- * or 0x18 to 0x1f (for data channel 2), with the second byte in the
- * range 0x40 to 0x7f.
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a PAC
- */
-
-
- Cea608Stream.prototype.isPAC = function (char0, char1) {
- return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
- };
- /**
- * Detects if a packet's second byte is in the range of a PAC color code
- *
- * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
- * 0x60 to 0x6f.
- *
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the byte is a color PAC
- */
-
-
- Cea608Stream.prototype.isColorPAC = function (char1) {
- return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
- };
- /**
- * Detects if a single byte is in the range of a normal character
- *
- * Normal text bytes are in the range 0x20 to 0x7f.
- *
- * @param {Integer} char The byte
- * @return {Boolean} Whether the byte is a normal character
- */
-
-
- Cea608Stream.prototype.isNormalChar = function (char) {
- return char >= 0x20 && char <= 0x7f;
- };
- /**
- * Configures roll-up
- *
- * @param {Integer} pts Current PTS
- * @param {Integer} newBaseRow Used by PACs to slide the current window to
- * a new position
- */
-
-
- Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
- // Reset the base row to the bottom row when switching modes
- if (this.mode_ !== 'rollUp') {
- this.row_ = BOTTOM_ROW;
- this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
-
- this.flushDisplayed(pts);
- this.nonDisplayed_ = createDisplayBuffer();
- this.displayed_ = createDisplayBuffer();
- }
-
- if (newBaseRow !== undefined && newBaseRow !== this.row_) {
- // move currently displayed captions (up or down) to the new base row
- for (var i = 0; i < this.rollUpRows_; i++) {
- this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
- this.displayed_[this.row_ - i] = '';
- }
- }
-
- if (newBaseRow === undefined) {
- newBaseRow = this.row_;
- }
-
- this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
- }; // Adds the opening HTML tag for the passed character to the caption text,
- // and keeps track of it for later closing
-
-
- Cea608Stream.prototype.addFormatting = function (pts, format) {
- this.formatting_ = this.formatting_.concat(format);
- var text = format.reduce(function (text, format) {
- return text + '<' + format + '>';
- }, '');
- this[this.mode_](pts, text);
- }; // Adds HTML closing tags for current formatting to caption text and
- // clears remembered formatting
-
-
- Cea608Stream.prototype.clearFormatting = function (pts) {
- if (!this.formatting_.length) {
- return;
- }
-
- var text = this.formatting_.reverse().reduce(function (text, format) {
- return text + '' + format + '>';
- }, '');
- this.formatting_ = [];
- this[this.mode_](pts, text);
- }; // Mode Implementations
-
-
- Cea608Stream.prototype.popOn = function (pts, text) {
- var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
-
- baseRow += text;
- this.nonDisplayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.rollUp = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.shiftRowsUp_ = function () {
- var i; // clear out inactive rows
-
- for (i = 0; i < this.topRow_; i++) {
- this.displayed_[i] = '';
- }
-
- for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
- this.displayed_[i] = '';
- } // shift displayed rows up
-
-
- for (i = this.topRow_; i < this.row_; i++) {
- this.displayed_[i] = this.displayed_[i + 1];
- } // clear out the bottom row
-
-
- this.displayed_[this.row_] = '';
- };
-
- Cea608Stream.prototype.paintOn = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- }; // exports
-
-
- var captionStream = {
- CaptionStream: CaptionStream$1,
- Cea608Stream: Cea608Stream,
- Cea708Stream: Cea708Stream
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var streamTypes = {
- H264_STREAM_TYPE: 0x1B,
- ADTS_STREAM_TYPE: 0x0F,
- METADATA_STREAM_TYPE: 0x15
- };
- var MAX_TS = 8589934592;
- var RO_THRESH = 4294967296;
- var TYPE_SHARED = 'shared';
-
- var handleRollover$1 = function handleRollover(value, reference) {
- var direction = 1;
-
- if (value > reference) {
- // If the current timestamp value is greater than our reference timestamp and we detect a
- // timestamp rollover, this means the roll over is happening in the opposite direction.
- // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
- // point will be set to a small number, e.g. 1. The user then seeks backwards over the
- // rollover point. In loading this segment, the timestamp values will be very large,
- // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
- // the time stamp to be `value - 2^33`.
- direction = -1;
- } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
- // cause an incorrect adjustment.
-
-
- while (Math.abs(reference - value) > RO_THRESH) {
- value += direction * MAX_TS;
- }
-
- return value;
- };
-
- var TimestampRolloverStream$1 = function TimestampRolloverStream(type) {
- var lastDTS, referenceDTS;
- TimestampRolloverStream.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
- // video and audio. We could use `undefined` here, but having a string
- // makes debugging a little clearer.
-
- this.type_ = type || TYPE_SHARED;
-
- this.push = function (data) {
- // Any "shared" rollover streams will accept _all_ data. Otherwise,
- // streams will only accept data that matches their type.
- if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
- return;
- }
-
- if (referenceDTS === undefined) {
- referenceDTS = data.dts;
- }
-
- data.dts = handleRollover$1(data.dts, referenceDTS);
- data.pts = handleRollover$1(data.pts, referenceDTS);
- lastDTS = data.dts;
- this.trigger('data', data);
- };
-
- this.flush = function () {
- referenceDTS = lastDTS;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.discontinuity = function () {
- referenceDTS = void 0;
- lastDTS = void 0;
- };
-
- this.reset = function () {
- this.discontinuity();
- this.trigger('reset');
- };
- };
-
- TimestampRolloverStream$1.prototype = new stream();
- var timestampRolloverStream = {
- TimestampRolloverStream: TimestampRolloverStream$1,
- handleRollover: handleRollover$1
- };
-
- var percentEncode$1 = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- },
- // return the string representation of the specified byte range,
- // interpreted as UTf-8.
- parseUtf8 = function parseUtf8(bytes, start, end) {
- return decodeURIComponent(percentEncode$1(bytes, start, end));
- },
- // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
- parseIso88591$1 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
- },
- parseSyncSafeInteger$1 = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- },
- tagParsers = {
- TXXX: function TXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the text fields
- tag.description = parseUtf8(tag.data, 1, i); // do not include the null terminator in the tag value
-
- tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
- break;
- }
- }
-
- tag.data = tag.value;
- },
- WXXX: function WXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.description = parseUtf8(tag.data, 1, i);
- tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
- break;
- }
- }
- },
- PRIV: function PRIV(tag) {
- var i;
-
- for (i = 0; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.owner = parseIso88591$1(tag.data, 0, i);
- break;
- }
- }
-
- tag.privateData = tag.data.subarray(i + 1);
- tag.data = tag.privateData;
- }
- },
- _MetadataStream;
-
- _MetadataStream = function MetadataStream(options) {
- var settings = {
- debug: !!(options && options.debug),
- // the bytes of the program-level descriptor field in MP2T
- // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
- // program element descriptors"
- descriptor: options && options.descriptor
- },
- // the total size in bytes of the ID3 tag being parsed
- tagSize = 0,
- // tag data that is not complete enough to be parsed
- buffer = [],
- // the total number of bytes currently in the buffer
- bufferSize = 0,
- i;
-
- _MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
- // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
-
-
- this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
-
- if (settings.descriptor) {
- for (i = 0; i < settings.descriptor.length; i++) {
- this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
- }
- }
-
- this.push = function (chunk) {
- var tag, frameStart, frameSize, frame, i, frameHeader;
-
- if (chunk.type !== 'timed-metadata') {
- return;
- } // if data_alignment_indicator is set in the PES header,
- // we must have the start of a new ID3 tag. Assume anything
- // remaining in the buffer was malformed and throw it out
-
-
- if (chunk.dataAlignmentIndicator) {
- bufferSize = 0;
- buffer.length = 0;
- } // ignore events that don't look like ID3 data
-
-
- if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) {
- if (settings.debug) {
- // eslint-disable-next-line no-console
- console.log('Skipping unrecognized metadata packet');
- }
-
- return;
- } // add this chunk to the data we've collected so far
-
-
- buffer.push(chunk);
- bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
-
- if (buffer.length === 1) {
- // the frame size is transmitted as a 28-bit integer in the
- // last four bytes of the ID3 header.
- // The most significant bit of each byte is dropped and the
- // results concatenated to recover the actual value.
- tagSize = parseSyncSafeInteger$1(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
- // convenient for our comparisons to include it
-
- tagSize += 10;
- } // if the entire frame has not arrived, wait for more data
-
-
- if (bufferSize < tagSize) {
- return;
- } // collect the entire frame so it can be parsed
-
-
- tag = {
- data: new Uint8Array(tagSize),
- frames: [],
- pts: buffer[0].pts,
- dts: buffer[0].dts
- };
-
- for (i = 0; i < tagSize;) {
- tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
- i += buffer[0].data.byteLength;
- bufferSize -= buffer[0].data.byteLength;
- buffer.shift();
- } // find the start of the first frame and the end of the tag
-
-
- frameStart = 10;
-
- if (tag.data[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger$1(tag.data.subarray(10, 14)); // clip any padding off the end
-
- tagSize -= parseSyncSafeInteger$1(tag.data.subarray(16, 20));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger$1(tag.data.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- // eslint-disable-next-line no-console
- return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
- }
-
- frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
- frame = {
- id: frameHeader,
- data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
- };
- frame.key = frame.id;
-
- if (tagParsers[frame.id]) {
- tagParsers[frame.id](frame); // handle the special PRIV frame used to indicate the start
- // time for raw AAC data
-
- if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.data,
- size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
- // on the value of this frame
- // we couldn't have known the appropriate pts and dts before
- // parsing this ID3 tag so set those values now
-
- if (tag.pts === undefined && tag.dts === undefined) {
- tag.pts = frame.timeStamp;
- tag.dts = frame.timeStamp;
- }
-
- this.trigger('timestamp', frame);
- }
- }
-
- tag.frames.push(frame);
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < tagSize);
-
- this.trigger('data', tag);
- };
- };
-
- _MetadataStream.prototype = new stream();
- var metadataStream = _MetadataStream;
- var TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
-
- var _TransportPacketStream, _TransportParseStream, _ElementaryStream; // constants
-
-
- var MP2T_PACKET_LENGTH$1 = 188,
- // bytes
- SYNC_BYTE$1 = 0x47;
- /**
- * Splits an incoming stream of binary data into MPEG-2 Transport
- * Stream packets.
- */
-
- _TransportPacketStream = function TransportPacketStream() {
- var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
- bytesInBuffer = 0;
-
- _TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
-
- /**
- * Split a stream of data into M2TS packets
- **/
-
-
- this.push = function (bytes) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH$1,
- everything; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (bytesInBuffer) {
- everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
- everything.set(buffer.subarray(0, bytesInBuffer));
- everything.set(bytes, bytesInBuffer);
- bytesInBuffer = 0;
- } else {
- everything = bytes;
- } // While we have enough data for a packet
-
-
- while (endIndex < everything.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
- // We found a packet so emit it and jump one whole packet forward in
- // the stream
- this.trigger('data', everything.subarray(startIndex, endIndex));
- startIndex += MP2T_PACKET_LENGTH$1;
- endIndex += MP2T_PACKET_LENGTH$1;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // If there was some data left over at the end of the segment that couldn't
- // possibly be a whole packet, keep it because it might be the start of a packet
- // that continues in the next segment
-
-
- if (startIndex < everything.byteLength) {
- buffer.set(everything.subarray(startIndex), 0);
- bytesInBuffer = everything.byteLength - startIndex;
- }
- };
- /**
- * Passes identified M2TS packets to the TransportParseStream to be parsed
- **/
-
-
- this.flush = function () {
- // If the buffer contains a whole packet when we are being flushed, emit it
- // and empty the buffer. Otherwise hold onto the data because it may be
- // important for decoding the next segment
- if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
- this.trigger('data', buffer);
- bytesInBuffer = 0;
- }
-
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.reset = function () {
- bytesInBuffer = 0;
- this.trigger('reset');
- };
- };
-
- _TransportPacketStream.prototype = new stream();
- /**
- * Accepts an MP2T TransportPacketStream and emits data events with parsed
- * forms of the individual transport stream packets.
- */
-
- _TransportParseStream = function TransportParseStream() {
- var parsePsi, parsePat, parsePmt, self;
-
- _TransportParseStream.prototype.init.call(this);
-
- self = this;
- this.packetsWaitingForPmt = [];
- this.programMapTable = undefined;
-
- parsePsi = function parsePsi(payload, psi) {
- var offset = 0; // PSI packets may be split into multiple sections and those
- // sections may be split into multiple packets. If a PSI
- // section starts in this packet, the payload_unit_start_indicator
- // will be true and the first byte of the payload will indicate
- // the offset from the current position to the start of the
- // section.
-
- if (psi.payloadUnitStartIndicator) {
- offset += payload[offset] + 1;
- }
-
- if (psi.type === 'pat') {
- parsePat(payload.subarray(offset), psi);
- } else {
- parsePmt(payload.subarray(offset), psi);
- }
- };
-
- parsePat = function parsePat(payload, pat) {
- pat.section_number = payload[7]; // eslint-disable-line camelcase
-
- pat.last_section_number = payload[8]; // eslint-disable-line camelcase
- // skip the PSI header and parse the first PMT entry
-
- self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
- pat.pmtPid = self.pmtPid;
- };
- /**
- * Parse out the relevant fields of a Program Map Table (PMT).
- * @param payload {Uint8Array} the PMT-specific portion of an MP2T
- * packet. The first byte in this array should be the table_id
- * field.
- * @param pmt {object} the object that should be decorated with
- * fields parsed from the PMT.
- */
-
-
- parsePmt = function parsePmt(payload, pmt) {
- var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
- // take effect. We don't believe this should ever be the case
- // for HLS but we'll ignore "forward" PMT declarations if we see
- // them. Future PMT declarations have the current_next_indicator
- // set to zero.
-
- if (!(payload[5] & 0x01)) {
- return;
- } // overwrite any existing program map table
-
-
- self.programMapTable = {
- video: null,
- audio: null,
- 'timed-metadata': {}
- }; // the mapping table ends at the end of the current section
-
- sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
- tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
- // long the program info descriptors are
-
- programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
-
- offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- var streamType = payload[offset];
- var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
- // TODO: should this be done for metadata too? for now maintain behavior of
- // multiple metadata streams
-
- if (streamType === streamTypes.H264_STREAM_TYPE && self.programMapTable.video === null) {
- self.programMapTable.video = pid;
- } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
- self.programMapTable.audio = pid;
- } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
- // map pid to stream type for metadata streams
- self.programMapTable['timed-metadata'][pid] = streamType;
- } // move to the next table entry
- // skip past the elementary stream descriptors, if present
-
-
- offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
- } // record the map on the packet as well
-
-
- pmt.programMapTable = self.programMapTable;
- };
- /**
- * Deliver a new MP2T packet to the next stream in the pipeline.
- */
-
-
- this.push = function (packet) {
- var result = {},
- offset = 4;
- result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
-
- result.pid = packet[1] & 0x1f;
- result.pid <<= 8;
- result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
- // fifth byte of the TS packet header. The adaptation field is
- // used to add stuffing to PES packets that don't fill a complete
- // TS packet, and to specify some forms of timing and control data
- // that we do not currently use.
-
- if ((packet[3] & 0x30) >>> 4 > 0x01) {
- offset += packet[offset] + 1;
- } // parse the rest of the packet based on the type
-
-
- if (result.pid === 0) {
- result.type = 'pat';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result);
- } else if (result.pid === this.pmtPid) {
- result.type = 'pmt';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
-
- while (this.packetsWaitingForPmt.length) {
- this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
- }
- } else if (this.programMapTable === undefined) {
- // When we have not seen a PMT yet, defer further processing of
- // PES packets until one has been parsed
- this.packetsWaitingForPmt.push([packet, offset, result]);
- } else {
- this.processPes_(packet, offset, result);
- }
- };
-
- this.processPes_ = function (packet, offset, result) {
- // set the appropriate stream type
- if (result.pid === this.programMapTable.video) {
- result.streamType = streamTypes.H264_STREAM_TYPE;
- } else if (result.pid === this.programMapTable.audio) {
- result.streamType = streamTypes.ADTS_STREAM_TYPE;
- } else {
- // if not video or audio, it is timed-metadata or unknown
- // if unknown, streamType will be undefined
- result.streamType = this.programMapTable['timed-metadata'][result.pid];
- }
-
- result.type = 'pes';
- result.data = packet.subarray(offset);
- this.trigger('data', result);
- };
- };
-
- _TransportParseStream.prototype = new stream();
- _TransportParseStream.STREAM_TYPES = {
- h264: 0x1b,
- adts: 0x0f
- };
- /**
- * Reconsistutes program elementary stream (PES) packets from parsed
- * transport stream packets. That is, if you pipe an
- * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
- * events will be events which capture the bytes for individual PES
- * packets plus relevant metadata that has been extracted from the
- * container.
- */
-
- _ElementaryStream = function ElementaryStream() {
- var self = this,
- // PES packet fragments
- video = {
- data: [],
- size: 0
- },
- audio = {
- data: [],
- size: 0
- },
- timedMetadata = {
- data: [],
- size: 0
- },
- programMapTable,
- parsePes = function parsePes(payload, pes) {
- var ptsDtsFlags;
- var startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
-
- pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
- // that are frame data that is continuing from the previous fragment. This
- // is to check that the pes data is the start of a new pes payload
-
- if (startPrefix !== 1) {
- return;
- } // get the packet length, this will be 0 for video
-
-
- pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
-
- pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
- // and a DTS value. Determine what combination of values is
- // available to work with.
-
- ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
- // performs all bitwise operations on 32-bit integers but javascript
- // supports a much greater range (52-bits) of integer using standard
- // mathematical operations.
- // We construct a 31-bit value using bitwise operators over the 31
- // most significant bits and then multiply by 4 (equal to a left-shift
- // of 2) before we add the final 2 least significant bits of the
- // timestamp (equal to an OR.)
-
- if (ptsDtsFlags & 0xC0) {
- // the PTS and DTS are not written out directly. For information
- // on how they are encoded, see
- // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
- pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
- pes.pts *= 4; // Left shift by 2
-
- pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
-
- pes.dts = pes.pts;
-
- if (ptsDtsFlags & 0x40) {
- pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
- pes.dts *= 4; // Left shift by 2
-
- pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
- }
- } // the data section starts immediately after the PES header.
- // pes_header_data_length specifies the number of header bytes
- // that follow the last byte of the field.
-
-
- pes.data = payload.subarray(9 + payload[8]);
- },
-
- /**
- * Pass completely parsed PES packets to the next stream in the pipeline
- **/
- flushStream = function flushStream(stream, type, forceFlush) {
- var packetData = new Uint8Array(stream.size),
- event = {
- type: type
- },
- i = 0,
- offset = 0,
- packetFlushable = false,
- fragment; // do nothing if there is not enough buffered data for a complete
- // PES header
-
- if (!stream.data.length || stream.size < 9) {
- return;
- }
-
- event.trackId = stream.data[0].pid; // reassemble the packet
-
- for (i = 0; i < stream.data.length; i++) {
- fragment = stream.data[i];
- packetData.set(fragment.data, offset);
- offset += fragment.data.byteLength;
- } // parse assembled packet's PES header
-
-
- parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
- // check that there is enough stream data to fill the packet
-
- packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
-
- if (forceFlush || packetFlushable) {
- stream.size = 0;
- stream.data.length = 0;
- } // only emit packets that are complete. this is to avoid assembling
- // incomplete PES packets due to poor segmentation
-
-
- if (packetFlushable) {
- self.trigger('data', event);
- }
- };
-
- _ElementaryStream.prototype.init.call(this);
- /**
- * Identifies M2TS packet types and parses PES packets using metadata
- * parsed from the PMT
- **/
-
-
- this.push = function (data) {
- ({
- pat: function pat() {// we have to wait for the PMT to arrive as well before we
- // have any meaningful metadata
- },
- pes: function pes() {
- var stream, streamType;
-
- switch (data.streamType) {
- case streamTypes.H264_STREAM_TYPE:
- stream = video;
- streamType = 'video';
- break;
-
- case streamTypes.ADTS_STREAM_TYPE:
- stream = audio;
- streamType = 'audio';
- break;
-
- case streamTypes.METADATA_STREAM_TYPE:
- stream = timedMetadata;
- streamType = 'timed-metadata';
- break;
-
- default:
- // ignore unknown stream types
- return;
- } // if a new packet is starting, we can flush the completed
- // packet
-
-
- if (data.payloadUnitStartIndicator) {
- flushStream(stream, streamType, true);
- } // buffer this fragment until we are sure we've received the
- // complete payload
-
-
- stream.data.push(data);
- stream.size += data.data.byteLength;
- },
- pmt: function pmt() {
- var event = {
- type: 'metadata',
- tracks: []
- };
- programMapTable = data.programMapTable; // translate audio and video streams to tracks
-
- if (programMapTable.video !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.video,
- codec: 'avc',
- type: 'video'
- });
- }
-
- if (programMapTable.audio !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.audio,
- codec: 'adts',
- type: 'audio'
- });
- }
-
- self.trigger('data', event);
- }
- })[data.type]();
- };
-
- this.reset = function () {
- video.size = 0;
- video.data.length = 0;
- audio.size = 0;
- audio.data.length = 0;
- this.trigger('reset');
- };
- /**
- * Flush any remaining input. Video PES packets may be of variable
- * length. Normally, the start of a new video packet can trigger the
- * finalization of the previous packet. That is not possible if no
- * more video is forthcoming, however. In that case, some other
- * mechanism (like the end of the file) has to be employed. When it is
- * clear that no additional data is forthcoming, calling this method
- * will flush the buffered packets.
- */
-
-
- this.flushStreams_ = function () {
- // !!THIS ORDER IS IMPORTANT!!
- // video first then audio
- flushStream(video, 'video');
- flushStream(audio, 'audio');
- flushStream(timedMetadata, 'timed-metadata');
- };
-
- this.flush = function () {
- this.flushStreams_();
- this.trigger('done');
- };
- };
-
- _ElementaryStream.prototype = new stream();
- var m2ts = {
- PAT_PID: 0x0000,
- MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
- TransportPacketStream: _TransportPacketStream,
- TransportParseStream: _TransportParseStream,
- ElementaryStream: _ElementaryStream,
- TimestampRolloverStream: TimestampRolloverStream,
- CaptionStream: captionStream.CaptionStream,
- Cea608Stream: captionStream.Cea608Stream,
- Cea708Stream: captionStream.Cea708Stream,
- MetadataStream: metadataStream
- };
-
- for (var type in streamTypes) {
- if (streamTypes.hasOwnProperty(type)) {
- m2ts[type] = streamTypes[type];
- }
- }
-
- var m2ts_1 = m2ts;
- var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
-
- var _AdtsStream;
-
- var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
- /*
- * Accepts a ElementaryStream and emits data events with parsed
- * AAC Audio Frames of the individual packets. Input audio in ADTS
- * format is unpacked and re-emitted as AAC frames.
- *
- * @see http://wiki.multimedia.cx/index.php?title=ADTS
- * @see http://wiki.multimedia.cx/?title=Understanding_AAC
- */
-
- _AdtsStream = function AdtsStream(handlePartialSegments) {
- var buffer,
- frameNum = 0;
-
- _AdtsStream.prototype.init.call(this);
-
- this.push = function (packet) {
- var i = 0,
- frameLength,
- protectionSkipBytes,
- frameEnd,
- oldBuffer,
- sampleCount,
- adtsFrameDuration;
-
- if (!handlePartialSegments) {
- frameNum = 0;
- }
-
- if (packet.type !== 'audio') {
- // ignore non-audio data
- return;
- } // Prepend any data in the buffer to the input data so that we can parse
- // aac frames the cross a PES packet boundary
-
-
- if (buffer) {
- oldBuffer = buffer;
- buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
- buffer.set(oldBuffer);
- buffer.set(packet.data, oldBuffer.byteLength);
- } else {
- buffer = packet.data;
- } // unpack any ADTS frames which have been fully received
- // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
-
-
- while (i + 5 < buffer.length) {
- // Look for the start of an ADTS header..
- if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- } // The protection skip bit tells us if we have 2 bytes of CRC data at the
- // end of the ADTS header
-
-
- protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
- // end of the sync sequence
-
- frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
- sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
- adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2];
- frameEnd = i + frameLength; // If we don't have enough data to actually finish this ADTS frame, return
- // and wait for more data
-
- if (buffer.byteLength < frameEnd) {
- return;
- } // Otherwise, deliver the complete AAC frame
-
-
- this.trigger('data', {
- pts: packet.pts + frameNum * adtsFrameDuration,
- dts: packet.dts + frameNum * adtsFrameDuration,
- sampleCount: sampleCount,
- audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
- channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
- samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
- samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
- // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
- samplesize: 16,
- data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
- });
- frameNum++; // If the buffer is empty, clear it and return
-
- if (buffer.byteLength === frameEnd) {
- buffer = undefined;
- return;
- } // Remove the finished frame from the buffer and start the process again
-
-
- buffer = buffer.subarray(frameEnd);
- }
- };
-
- this.flush = function () {
- frameNum = 0;
- this.trigger('done');
- };
-
- this.reset = function () {
- buffer = void 0;
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- buffer = void 0;
- this.trigger('endedtimeline');
- };
- };
-
- _AdtsStream.prototype = new stream();
- var adts = _AdtsStream;
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ExpGolomb;
- /**
- * Parser for exponential Golomb codes, a variable-bitwidth number encoding
- * scheme used by h264.
- */
-
- ExpGolomb = function ExpGolomb(workingData) {
- var // the number of bytes left to examine in workingData
- workingBytesAvailable = workingData.byteLength,
- // the current word being examined
- workingWord = 0,
- // :uint
- // the number of bits left to examine in the current word
- workingBitsAvailable = 0; // :uint;
- // ():uint
-
- this.length = function () {
- return 8 * workingBytesAvailable;
- }; // ():uint
-
-
- this.bitsAvailable = function () {
- return 8 * workingBytesAvailable + workingBitsAvailable;
- }; // ():void
-
-
- this.loadWord = function () {
- var position = workingData.byteLength - workingBytesAvailable,
- workingBytes = new Uint8Array(4),
- availableBytes = Math.min(4, workingBytesAvailable);
-
- if (availableBytes === 0) {
- throw new Error('no bytes available');
- }
-
- workingBytes.set(workingData.subarray(position, position + availableBytes));
- workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
-
- workingBitsAvailable = availableBytes * 8;
- workingBytesAvailable -= availableBytes;
- }; // (count:int):void
-
-
- this.skipBits = function (count) {
- var skipBytes; // :int
-
- if (workingBitsAvailable > count) {
- workingWord <<= count;
- workingBitsAvailable -= count;
- } else {
- count -= workingBitsAvailable;
- skipBytes = Math.floor(count / 8);
- count -= skipBytes * 8;
- workingBytesAvailable -= skipBytes;
- this.loadWord();
- workingWord <<= count;
- workingBitsAvailable -= count;
- }
- }; // (size:int):uint
-
-
- this.readBits = function (size) {
- var bits = Math.min(workingBitsAvailable, size),
- // :uint
- valu = workingWord >>> 32 - bits; // :uint
- // if size > 31, handle error
-
- workingBitsAvailable -= bits;
-
- if (workingBitsAvailable > 0) {
- workingWord <<= bits;
- } else if (workingBytesAvailable > 0) {
- this.loadWord();
- }
-
- bits = size - bits;
-
- if (bits > 0) {
- return valu << bits | this.readBits(bits);
- }
-
- return valu;
- }; // ():uint
-
-
- this.skipLeadingZeros = function () {
- var leadingZeroCount; // :uint
-
- for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
- if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
- // the first bit of working word is 1
- workingWord <<= leadingZeroCount;
- workingBitsAvailable -= leadingZeroCount;
- return leadingZeroCount;
- }
- } // we exhausted workingWord and still have not found a 1
-
-
- this.loadWord();
- return leadingZeroCount + this.skipLeadingZeros();
- }; // ():void
-
-
- this.skipUnsignedExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():void
-
-
- this.skipExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():uint
-
-
- this.readUnsignedExpGolomb = function () {
- var clz = this.skipLeadingZeros(); // :uint
-
- return this.readBits(clz + 1) - 1;
- }; // ():int
-
-
- this.readExpGolomb = function () {
- var valu = this.readUnsignedExpGolomb(); // :int
-
- if (0x01 & valu) {
- // the number is odd if the low order bit is set
- return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
- }
-
- return -1 * (valu >>> 1); // divide by two then make it negative
- }; // Some convenience functions
- // :Boolean
-
-
- this.readBoolean = function () {
- return this.readBits(1) === 1;
- }; // ():int
-
-
- this.readUnsignedByte = function () {
- return this.readBits(8);
- };
-
- this.loadWord();
- };
-
- var expGolomb = ExpGolomb;
-
- var _H264Stream, _NalByteStream;
-
- var PROFILES_WITH_OPTIONAL_SPS_DATA;
- /**
- * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
- */
-
- _NalByteStream = function NalByteStream() {
- var syncPoint = 0,
- i,
- buffer;
-
- _NalByteStream.prototype.init.call(this);
- /*
- * Scans a byte stream and triggers a data event with the NAL units found.
- * @param {Object} data Event received from H264Stream
- * @param {Uint8Array} data.data The h264 byte stream to be scanned
- *
- * @see H264Stream.push
- */
-
-
- this.push = function (data) {
- var swapBuffer;
-
- if (!buffer) {
- buffer = data.data;
- } else {
- swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
- swapBuffer.set(buffer);
- swapBuffer.set(data.data, buffer.byteLength);
- buffer = swapBuffer;
- }
-
- var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
- // scan for NAL unit boundaries
- // a match looks like this:
- // 0 0 1 .. NAL .. 0 0 1
- // ^ sync point ^ i
- // or this:
- // 0 0 1 .. NAL .. 0 0 0
- // ^ sync point ^ i
- // advance the sync point to a NAL start, if necessary
-
- for (; syncPoint < len - 3; syncPoint++) {
- if (buffer[syncPoint + 2] === 1) {
- // the sync point is properly aligned
- i = syncPoint + 5;
- break;
- }
- }
-
- while (i < len) {
- // look at the current byte to determine if we've hit the end of
- // a NAL unit boundary
- switch (buffer[i]) {
- case 0:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0) {
- i += 2;
- break;
- } else if (buffer[i - 2] !== 0) {
- i++;
- break;
- } // deliver the NAL unit if it isn't empty
-
-
- if (syncPoint + 3 !== i - 2) {
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- } // drop trailing zeroes
-
-
- do {
- i++;
- } while (buffer[i] !== 1 && i < len);
-
- syncPoint = i - 2;
- i += 3;
- break;
-
- case 1:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
- i += 3;
- break;
- } // deliver the NAL unit
-
-
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- syncPoint = i - 2;
- i += 3;
- break;
-
- default:
- // the current byte isn't a one or zero, so it cannot be part
- // of a sync sequence
- i += 3;
- break;
- }
- } // filter out the NAL units that were delivered
-
-
- buffer = buffer.subarray(syncPoint);
- i -= syncPoint;
- syncPoint = 0;
- };
-
- this.reset = function () {
- buffer = null;
- syncPoint = 0;
- this.trigger('reset');
- };
-
- this.flush = function () {
- // deliver the last buffered NAL unit
- if (buffer && buffer.byteLength > 3) {
- this.trigger('data', buffer.subarray(syncPoint + 3));
- } // reset the stream state
-
-
- buffer = null;
- syncPoint = 0;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
- };
-
- _NalByteStream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the SPS
- // see Recommendation ITU-T H.264 (4/2013),
- // 7.3.2.1.1 Sequence parameter set data syntax
-
- PROFILES_WITH_OPTIONAL_SPS_DATA = {
- 100: true,
- 110: true,
- 122: true,
- 244: true,
- 44: true,
- 83: true,
- 86: true,
- 118: true,
- 128: true,
- 138: true,
- 139: true,
- 134: true
- };
- /**
- * Accepts input from a ElementaryStream and produces H.264 NAL unit data
- * events.
- */
-
- _H264Stream = function H264Stream() {
- var nalByteStream = new _NalByteStream(),
- self,
- trackId,
- currentPts,
- currentDts,
- discardEmulationPreventionBytes,
- readSequenceParameterSet,
- skipScalingList;
-
- _H264Stream.prototype.init.call(this);
-
- self = this;
- /*
- * Pushes a packet from a stream onto the NalByteStream
- *
- * @param {Object} packet - A packet received from a stream
- * @param {Uint8Array} packet.data - The raw bytes of the packet
- * @param {Number} packet.dts - Decode timestamp of the packet
- * @param {Number} packet.pts - Presentation timestamp of the packet
- * @param {Number} packet.trackId - The id of the h264 track this packet came from
- * @param {('video'|'audio')} packet.type - The type of packet
- *
- */
-
- this.push = function (packet) {
- if (packet.type !== 'video') {
- return;
- }
-
- trackId = packet.trackId;
- currentPts = packet.pts;
- currentDts = packet.dts;
- nalByteStream.push(packet);
- };
- /*
- * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
- * for the NALUs to the next stream component.
- * Also, preprocess caption and sequence parameter NALUs.
- *
- * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
- * @see NalByteStream.push
- */
-
-
- nalByteStream.on('data', function (data) {
- var event = {
- trackId: trackId,
- pts: currentPts,
- dts: currentDts,
- data: data
- };
-
- switch (data[0] & 0x1f) {
- case 0x05:
- event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
- break;
-
- case 0x06:
- event.nalUnitType = 'sei_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- break;
-
- case 0x07:
- event.nalUnitType = 'seq_parameter_set_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- event.config = readSequenceParameterSet(event.escapedRBSP);
- break;
-
- case 0x08:
- event.nalUnitType = 'pic_parameter_set_rbsp';
- break;
-
- case 0x09:
- event.nalUnitType = 'access_unit_delimiter_rbsp';
- break;
- } // This triggers data on the H264Stream
-
-
- self.trigger('data', event);
- });
- nalByteStream.on('done', function () {
- self.trigger('done');
- });
- nalByteStream.on('partialdone', function () {
- self.trigger('partialdone');
- });
- nalByteStream.on('reset', function () {
- self.trigger('reset');
- });
- nalByteStream.on('endedtimeline', function () {
- self.trigger('endedtimeline');
- });
-
- this.flush = function () {
- nalByteStream.flush();
- };
-
- this.partialFlush = function () {
- nalByteStream.partialFlush();
- };
-
- this.reset = function () {
- nalByteStream.reset();
- };
-
- this.endTimeline = function () {
- nalByteStream.endTimeline();
- };
- /**
- * Advance the ExpGolomb decoder past a scaling list. The scaling
- * list is optionally transmitted as part of a sequence parameter
- * set and is not relevant to transmuxing.
- * @param count {number} the number of entries in this scaling list
- * @param expGolombDecoder {object} an ExpGolomb pointed to the
- * start of a scaling list
- * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
- */
-
-
- skipScalingList = function skipScalingList(count, expGolombDecoder) {
- var lastScale = 8,
- nextScale = 8,
- j,
- deltaScale;
-
- for (j = 0; j < count; j++) {
- if (nextScale !== 0) {
- deltaScale = expGolombDecoder.readExpGolomb();
- nextScale = (lastScale + deltaScale + 256) % 256;
- }
-
- lastScale = nextScale === 0 ? lastScale : nextScale;
- }
- };
- /**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
-
- discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- };
- /**
- * Read a sequence parameter set and return some interesting video
- * properties. A sequence parameter set is the H264 metadata that
- * describes the properties of upcoming video frames.
- * @param data {Uint8Array} the bytes of a sequence parameter set
- * @return {object} an object with configuration parsed from the
- * sequence parameter set, including the dimensions of the
- * associated video frames.
- */
-
-
- readSequenceParameterSet = function readSequenceParameterSet(data) {
- var frameCropLeftOffset = 0,
- frameCropRightOffset = 0,
- frameCropTopOffset = 0,
- frameCropBottomOffset = 0,
- sarScale = 1,
- expGolombDecoder,
- profileIdc,
- levelIdc,
- profileCompatibility,
- chromaFormatIdc,
- picOrderCntType,
- numRefFramesInPicOrderCntCycle,
- picWidthInMbsMinus1,
- picHeightInMapUnitsMinus1,
- frameMbsOnlyFlag,
- scalingListCount,
- sarRatio,
- aspectRatioIdc,
- i;
- expGolombDecoder = new expGolomb(data);
- profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
-
- profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
-
- levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
-
- expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
- // some profiles have more optional data we don't need
-
- if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
- chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
-
- if (chromaFormatIdc === 3) {
- expGolombDecoder.skipBits(1); // separate_colour_plane_flag
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
-
- expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
-
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_matrix_present_flag
- scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
-
- for (i = 0; i < scalingListCount; i++) {
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_list_present_flag[ i ]
- if (i < 6) {
- skipScalingList(16, expGolombDecoder);
- } else {
- skipScalingList(64, expGolombDecoder);
- }
- }
- }
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
-
- picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
-
- if (picOrderCntType === 0) {
- expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
- } else if (picOrderCntType === 1) {
- expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
-
- expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
-
- expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
-
- numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
-
- for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
- expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
-
- expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
-
- picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- frameMbsOnlyFlag = expGolombDecoder.readBits(1);
-
- if (frameMbsOnlyFlag === 0) {
- expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
- }
-
- expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
-
- if (expGolombDecoder.readBoolean()) {
- // frame_cropping_flag
- frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
- }
-
- if (expGolombDecoder.readBoolean()) {
- // vui_parameters_present_flag
- if (expGolombDecoder.readBoolean()) {
- // aspect_ratio_info_present_flag
- aspectRatioIdc = expGolombDecoder.readUnsignedByte();
-
- switch (aspectRatioIdc) {
- case 1:
- sarRatio = [1, 1];
- break;
-
- case 2:
- sarRatio = [12, 11];
- break;
-
- case 3:
- sarRatio = [10, 11];
- break;
-
- case 4:
- sarRatio = [16, 11];
- break;
-
- case 5:
- sarRatio = [40, 33];
- break;
-
- case 6:
- sarRatio = [24, 11];
- break;
-
- case 7:
- sarRatio = [20, 11];
- break;
-
- case 8:
- sarRatio = [32, 11];
- break;
-
- case 9:
- sarRatio = [80, 33];
- break;
-
- case 10:
- sarRatio = [18, 11];
- break;
-
- case 11:
- sarRatio = [15, 11];
- break;
-
- case 12:
- sarRatio = [64, 33];
- break;
-
- case 13:
- sarRatio = [160, 99];
- break;
-
- case 14:
- sarRatio = [4, 3];
- break;
-
- case 15:
- sarRatio = [3, 2];
- break;
-
- case 16:
- sarRatio = [2, 1];
- break;
-
- case 255:
- {
- sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
- break;
- }
- }
-
- if (sarRatio) {
- sarScale = sarRatio[0] / sarRatio[1];
- }
- }
- }
-
- return {
- profileIdc: profileIdc,
- levelIdc: levelIdc,
- profileCompatibility: profileCompatibility,
- width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
- height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
- sarRatio: sarRatio
- };
- };
- };
-
- _H264Stream.prototype = new stream();
- var h264 = {
- H264Stream: _H264Stream,
- NalByteStream: _NalByteStream
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Utilities to detect basic properties and metadata about Aac data.
- */
-
- var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
-
- var parseId3TagSize = function parseId3TagSize(header, byteIndex) {
- var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
- flags = header[byteIndex + 5],
- footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
-
- returnSize = returnSize >= 0 ? returnSize : 0;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
- };
-
- var getId3Offset = function getId3Offset(data, offset) {
- if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
- return offset;
- }
-
- offset += parseId3TagSize(data, offset);
- return getId3Offset(data, offset);
- }; // TODO: use vhs-utils
-
-
- var isLikelyAacData$1 = function isLikelyAacData(data) {
- var offset = getId3Offset(data, 0);
- return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
- // is not mp3 data but aac data.
- (data[offset + 1] & 0x16) === 0x10;
- };
-
- var parseSyncSafeInteger = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- }; // return a percent-encoded representation of the specified byte range
- // @see http://en.wikipedia.org/wiki/Percent-encoding
-
-
- var percentEncode = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- }; // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
-
-
- var parseIso88591 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
- };
-
- var parseAdtsSize = function parseAdtsSize(header, byteIndex) {
- var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
- middle = header[byteIndex + 4] << 3,
- highTwo = header[byteIndex + 3] & 0x3 << 11;
- return highTwo | middle | lowThree;
- };
-
- var parseType$2 = function parseType(header, byteIndex) {
- if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
- return 'timed-metadata';
- } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
- return 'audio';
- }
-
- return null;
- };
-
- var parseSampleRate = function parseSampleRate(packet) {
- var i = 0;
-
- while (i + 5 < packet.length) {
- if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- }
-
- return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
- }
-
- return null;
- };
-
- var parseAacTimestamp = function parseAacTimestamp(packet) {
- var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
-
- frameStart = 10;
-
- if (packet[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- return null;
- }
-
- frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
-
- if (frameHeader === 'PRIV') {
- frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
-
- for (var i = 0; i < frame.byteLength; i++) {
- if (frame[i] === 0) {
- var owner = parseIso88591(frame, 0, i);
-
- if (owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.subarray(i + 1);
- var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- return size;
- }
-
- break;
- }
- }
- }
-
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < packet.byteLength);
-
- return null;
- };
-
- var utils = {
- isLikelyAacData: isLikelyAacData$1,
- parseId3TagSize: parseId3TagSize,
- parseAdtsSize: parseAdtsSize,
- parseType: parseType$2,
- parseSampleRate: parseSampleRate,
- parseAacTimestamp: parseAacTimestamp
- };
-
- var _AacStream;
- /**
- * Splits an incoming stream of binary data into ADTS and ID3 Frames.
- */
-
-
- _AacStream = function AacStream() {
- var everything = new Uint8Array(),
- timeStamp = 0;
-
- _AacStream.prototype.init.call(this);
-
- this.setTimestamp = function (timestamp) {
- timeStamp = timestamp;
- };
-
- this.push = function (bytes) {
- var frameSize = 0,
- byteIndex = 0,
- bytesLeft,
- chunk,
- packet,
- tempLength; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (everything.length) {
- tempLength = everything.length;
- everything = new Uint8Array(bytes.byteLength + tempLength);
- everything.set(everything.subarray(0, tempLength));
- everything.set(bytes, tempLength);
- } else {
- everything = bytes;
- }
-
- while (everything.length - byteIndex >= 3) {
- if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
- // Exit early because we don't have enough to parse
- // the ID3 tag header
- if (everything.length - byteIndex < 10) {
- break;
- } // check framesize
-
-
- frameSize = utils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
- // Add to byteIndex to support multiple ID3 tags in sequence
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- chunk = {
- type: 'timed-metadata',
- data: everything.subarray(byteIndex, byteIndex + frameSize)
- };
- this.trigger('data', chunk);
- byteIndex += frameSize;
- continue;
- } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
- // Exit early because we don't have enough to parse
- // the ADTS frame header
- if (everything.length - byteIndex < 7) {
- break;
- }
-
- frameSize = utils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- packet = {
- type: 'audio',
- data: everything.subarray(byteIndex, byteIndex + frameSize),
- pts: timeStamp,
- dts: timeStamp
- };
- this.trigger('data', packet);
- byteIndex += frameSize;
- continue;
- }
-
- byteIndex++;
- }
-
- bytesLeft = everything.length - byteIndex;
-
- if (bytesLeft > 0) {
- everything = everything.subarray(byteIndex);
- } else {
- everything = new Uint8Array();
- }
- };
-
- this.reset = function () {
- everything = new Uint8Array();
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- everything = new Uint8Array();
- this.trigger('endedtimeline');
- };
- };
-
- _AacStream.prototype = new stream();
- var aac = _AacStream; // constants
-
- var AUDIO_PROPERTIES = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
- var audioProperties = AUDIO_PROPERTIES;
- var VIDEO_PROPERTIES = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
- var videoProperties = VIDEO_PROPERTIES;
- var H264Stream = h264.H264Stream;
- var isLikelyAacData = utils.isLikelyAacData;
- var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS; // object types
-
- var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
- /**
- * Compare two arrays (even typed) for same-ness
- */
-
-
- var arrayEquals = function arrayEquals(a, b) {
- var i;
-
- if (a.length !== b.length) {
- return false;
- } // compare the value of each element in the array
-
-
- for (i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) {
- return false;
- }
- }
-
- return true;
- };
-
- var generateSegmentTimingInfo = function generateSegmentTimingInfo(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
- var ptsOffsetFromDts = startPts - startDts,
- decodeDuration = endDts - startDts,
- presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
- // however, the player time values will reflect a start from the baseMediaDecodeTime.
- // In order to provide relevant values for the player times, base timing info on the
- // baseMediaDecodeTime and the DTS and PTS durations of the segment.
-
- return {
- start: {
- dts: baseMediaDecodeTime,
- pts: baseMediaDecodeTime + ptsOffsetFromDts
- },
- end: {
- dts: baseMediaDecodeTime + decodeDuration,
- pts: baseMediaDecodeTime + presentationDuration
- },
- prependedContentDuration: prependedContentDuration,
- baseMediaDecodeTime: baseMediaDecodeTime
- };
- };
- /**
- * Constructs a single-track, ISO BMFF media segment from AAC data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- _AudioSegmentStream = function AudioSegmentStream(track, options) {
- var adtsFrames = [],
- sequenceNumber = 0,
- earliestAllowedDts = 0,
- audioAppendStartTs = 0,
- videoBaseMediaDecodeTime = Infinity;
- options = options || {};
-
- _AudioSegmentStream.prototype.init.call(this);
-
- this.push = function (data) {
- trackDecodeInfo.collectDtsInfo(track, data);
-
- if (track) {
- audioProperties.forEach(function (prop) {
- track[prop] = data[prop];
- });
- } // buffer audio data until end() is called
-
-
- adtsFrames.push(data);
- };
-
- this.setEarliestDts = function (earliestDts) {
- earliestAllowedDts = earliestDts;
- };
-
- this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- videoBaseMediaDecodeTime = baseMediaDecodeTime;
- };
-
- this.setAudioAppendStart = function (timestamp) {
- audioAppendStartTs = timestamp;
- };
-
- this.flush = function () {
- var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
-
- if (adtsFrames.length === 0) {
- this.trigger('done', 'AudioSegmentStream');
- return;
- }
-
- frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
-
- videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
- // samples (that is, adts frames) in the audio data
-
- track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
-
- mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
- adtsFrames = [];
- moof = mp4Generator.moof(sequenceNumber, [track]);
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- trackDecodeInfo.clearDtsInfo(track);
- frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
- // tests) on adding the timingInfo event. However, it seems unlikely that there's a
- // valid use-case where an init segment/data should be triggered without associated
- // frames. Leaving for now, but should be looked into.
-
- if (frames.length) {
- segmentDuration = frames.length * frameDuration;
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
- // frame info is in video clock cycles. Convert to match expectation of
- // listeners (that all timestamps will be based on video clock cycles).
- clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
- frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
- this.trigger('timingInfo', {
- start: frames[0].pts,
- end: frames[0].pts + segmentDuration
- });
- }
-
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.trigger('done', 'AudioSegmentStream');
- };
-
- this.reset = function () {
- trackDecodeInfo.clearDtsInfo(track);
- adtsFrames = [];
- this.trigger('reset');
- };
- };
-
- _AudioSegmentStream.prototype = new stream();
- /**
- * Constructs a single-track, ISO BMFF media segment from H264 data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
- * gopsToAlignWith list when attempting to align gop pts
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
- _VideoSegmentStream = function VideoSegmentStream(track, options) {
- var sequenceNumber = 0,
- nalUnits = [],
- gopsToAlignWith = [],
- config,
- pps;
- options = options || {};
-
- _VideoSegmentStream.prototype.init.call(this);
-
- delete track.minPTS;
- this.gopCache_ = [];
- /**
- * Constructs a ISO BMFF segment given H264 nalUnits
- * @param {Object} nalUnit A data event representing a nalUnit
- * @param {String} nalUnit.nalUnitType
- * @param {Object} nalUnit.config Properties for a mp4 track
- * @param {Uint8Array} nalUnit.data The nalUnit bytes
- * @see lib/codecs/h264.js
- **/
-
- this.push = function (nalUnit) {
- trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
-
- if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
- config = nalUnit.config;
- track.sps = [nalUnit.data];
- videoProperties.forEach(function (prop) {
- track[prop] = config[prop];
- }, this);
- }
-
- if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
- pps = nalUnit.data;
- track.pps = [nalUnit.data];
- } // buffer video until flush() is called
-
-
- nalUnits.push(nalUnit);
- };
- /**
- * Pass constructed ISO BMFF track and boxes on to the
- * next stream in the pipeline
- **/
-
-
- this.flush = function () {
- var frames,
- gopForFusion,
- gops,
- moof,
- mdat,
- boxes,
- prependedContentDuration = 0,
- firstGop,
- lastGop; // Throw away nalUnits at the start of the byte stream until
- // we find the first AUD
-
- while (nalUnits.length) {
- if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
- break;
- }
-
- nalUnits.shift();
- } // Return early if no video data has been observed
-
-
- if (nalUnits.length === 0) {
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Organize the raw nal-units into arrays that represent
- // higher-level constructs such as frames and gops
- // (group-of-pictures)
-
-
- frames = frameUtils.groupNalsIntoFrames(nalUnits);
- gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
- // a problem since MSE (on Chrome) requires a leading keyframe.
- //
- // We have two approaches to repairing this situation:
- // 1) GOP-FUSION:
- // This is where we keep track of the GOPS (group-of-pictures)
- // from previous fragments and attempt to find one that we can
- // prepend to the current fragment in order to create a valid
- // fragment.
- // 2) KEYFRAME-PULLING:
- // Here we search for the first keyframe in the fragment and
- // throw away all the frames between the start of the fragment
- // and that keyframe. We then extend the duration and pull the
- // PTS of the keyframe forward so that it covers the time range
- // of the frames that were disposed of.
- //
- // #1 is far prefereable over #2 which can cause "stuttering" but
- // requires more things to be just right.
-
- if (!gops[0][0].keyFrame) {
- // Search for a gop for fusion from our gopCache
- gopForFusion = this.getGopForFusion_(nalUnits[0], track);
-
- if (gopForFusion) {
- // in order to provide more accurate timing information about the segment, save
- // the number of seconds prepended to the original segment due to GOP fusion
- prependedContentDuration = gopForFusion.duration;
- gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
- // new gop at the beginning
-
- gops.byteLength += gopForFusion.byteLength;
- gops.nalCount += gopForFusion.nalCount;
- gops.pts = gopForFusion.pts;
- gops.dts = gopForFusion.dts;
- gops.duration += gopForFusion.duration;
- } else {
- // If we didn't find a candidate gop fall back to keyframe-pulling
- gops = frameUtils.extendFirstKeyFrame(gops);
- }
- } // Trim gops to align with gopsToAlignWith
-
-
- if (gopsToAlignWith.length) {
- var alignedGops;
-
- if (options.alignGopsAtEnd) {
- alignedGops = this.alignGopsAtEnd_(gops);
- } else {
- alignedGops = this.alignGopsAtStart_(gops);
- }
-
- if (!alignedGops) {
- // save all the nals in the last GOP into the gop cache
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
-
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
- // when recalculated before sending off to CoalesceStream
-
-
- trackDecodeInfo.clearDtsInfo(track);
- gops = alignedGops;
- }
-
- trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
- // samples (that is, frames) in the video data
-
- track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
-
- mdat = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
- this.trigger('processedGopsInfo', gops.map(function (gop) {
- return {
- pts: gop.pts,
- dts: gop.dts,
- byteLength: gop.byteLength
- };
- }));
- firstGop = gops[0];
- lastGop = gops[gops.length - 1];
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
- this.trigger('timingInfo', {
- start: gops[0].pts,
- end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
- }); // save all the nals in the last GOP into the gop cache
-
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = [];
- this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
- this.trigger('timelineStartInfo', track.timelineStartInfo);
- moof = mp4Generator.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
- // throwing away hundreds of media segment fragments
-
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.resetStream_(); // Continue with the flush process now
-
- this.trigger('done', 'VideoSegmentStream');
- };
-
- this.reset = function () {
- this.resetStream_();
- nalUnits = [];
- this.gopCache_.length = 0;
- gopsToAlignWith.length = 0;
- this.trigger('reset');
- };
-
- this.resetStream_ = function () {
- trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
- // for instance, when we are rendition switching
-
- config = undefined;
- pps = undefined;
- }; // Search for a candidate Gop for gop-fusion from the gop cache and
- // return it or return null if no good candidate was found
-
-
- this.getGopForFusion_ = function (nalUnit) {
- var halfSecond = 45000,
- // Half-a-second in a 90khz clock
- allowableOverlap = 10000,
- // About 3 frames @ 30fps
- nearestDistance = Infinity,
- dtsDistance,
- nearestGopObj,
- currentGop,
- currentGopObj,
- i; // Search for the GOP nearest to the beginning of this nal unit
-
- for (i = 0; i < this.gopCache_.length; i++) {
- currentGopObj = this.gopCache_[i];
- currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
-
- if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
- continue;
- } // Reject Gops that would require a negative baseMediaDecodeTime
-
-
- if (currentGop.dts < track.timelineStartInfo.dts) {
- continue;
- } // The distance between the end of the gop and the start of the nalUnit
-
-
- dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
- // a half-second of the nal unit
-
- if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
- // Always use the closest GOP we found if there is more than
- // one candidate
- if (!nearestGopObj || nearestDistance > dtsDistance) {
- nearestGopObj = currentGopObj;
- nearestDistance = dtsDistance;
- }
- }
- }
-
- if (nearestGopObj) {
- return nearestGopObj.gop;
- }
-
- return null;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the START of the list
-
-
- this.alignGopsAtStart_ = function (gops) {
- var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
- byteLength = gops.byteLength;
- nalCount = gops.nalCount;
- duration = gops.duration;
- alignIndex = gopIndex = 0;
-
- while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- break;
- }
-
- if (gop.pts > align.pts) {
- // this current gop starts after the current gop we want to align on, so increment
- // align index
- alignIndex++;
- continue;
- } // current gop starts before the current gop we want to align on. so increment gop
- // index
-
-
- gopIndex++;
- byteLength -= gop.byteLength;
- nalCount -= gop.nalCount;
- duration -= gop.duration;
- }
-
- if (gopIndex === 0) {
- // no gops to trim
- return gops;
- }
-
- if (gopIndex === gops.length) {
- // all gops trimmed, skip appending all gops
- return null;
- }
-
- alignedGops = gops.slice(gopIndex);
- alignedGops.byteLength = byteLength;
- alignedGops.duration = duration;
- alignedGops.nalCount = nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the END of the list
-
-
- this.alignGopsAtEnd_ = function (gops) {
- var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
- alignIndex = gopsToAlignWith.length - 1;
- gopIndex = gops.length - 1;
- alignEndIndex = null;
- matchFound = false;
-
- while (alignIndex >= 0 && gopIndex >= 0) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- matchFound = true;
- break;
- }
-
- if (align.pts > gop.pts) {
- alignIndex--;
- continue;
- }
-
- if (alignIndex === gopsToAlignWith.length - 1) {
- // gop.pts is greater than the last alignment candidate. If no match is found
- // by the end of this loop, we still want to append gops that come after this
- // point
- alignEndIndex = gopIndex;
- }
-
- gopIndex--;
- }
-
- if (!matchFound && alignEndIndex === null) {
- return null;
- }
-
- var trimIndex;
-
- if (matchFound) {
- trimIndex = gopIndex;
- } else {
- trimIndex = alignEndIndex;
- }
-
- if (trimIndex === 0) {
- return gops;
- }
-
- var alignedGops = gops.slice(trimIndex);
- var metadata = alignedGops.reduce(function (total, gop) {
- total.byteLength += gop.byteLength;
- total.duration += gop.duration;
- total.nalCount += gop.nalCount;
- return total;
- }, {
- byteLength: 0,
- duration: 0,
- nalCount: 0
- });
- alignedGops.byteLength = metadata.byteLength;
- alignedGops.duration = metadata.duration;
- alignedGops.nalCount = metadata.nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- };
-
- this.alignGopsWith = function (newGopsToAlignWith) {
- gopsToAlignWith = newGopsToAlignWith;
- };
- };
-
- _VideoSegmentStream.prototype = new stream();
- /**
- * A Stream that can combine multiple streams (ie. audio & video)
- * into a single output segment for MSE. Also supports audio-only
- * and video-only streams.
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at media timeline start.
- */
-
- _CoalesceStream = function CoalesceStream(options, metadataStream) {
- // Number of Tracks per output segment
- // If greater than 1, we combine multiple
- // tracks into a single segment
- this.numberOfTracks = 0;
- this.metadataStream = metadataStream;
- options = options || {};
-
- if (typeof options.remux !== 'undefined') {
- this.remuxTracks = !!options.remux;
- } else {
- this.remuxTracks = true;
- }
-
- if (typeof options.keepOriginalTimestamps === 'boolean') {
- this.keepOriginalTimestamps = options.keepOriginalTimestamps;
- } else {
- this.keepOriginalTimestamps = false;
- }
-
- this.pendingTracks = [];
- this.videoTrack = null;
- this.pendingBoxes = [];
- this.pendingCaptions = [];
- this.pendingMetadata = [];
- this.pendingBytes = 0;
- this.emittedTracks = 0;
-
- _CoalesceStream.prototype.init.call(this); // Take output from multiple
-
-
- this.push = function (output) {
- // buffer incoming captions until the associated video segment
- // finishes
- if (output.text) {
- return this.pendingCaptions.push(output);
- } // buffer incoming id3 tags until the final flush
-
-
- if (output.frames) {
- return this.pendingMetadata.push(output);
- } // Add this track to the list of pending tracks and store
- // important information required for the construction of
- // the final segment
-
-
- this.pendingTracks.push(output.track);
- this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
- // We unshift audio and push video because
- // as of Chrome 75 when switching from
- // one init segment to another if the video
- // mdat does not appear after the audio mdat
- // only audio will play for the duration of our transmux.
-
- if (output.track.type === 'video') {
- this.videoTrack = output.track;
- this.pendingBoxes.push(output.boxes);
- }
-
- if (output.track.type === 'audio') {
- this.audioTrack = output.track;
- this.pendingBoxes.unshift(output.boxes);
- }
- };
- };
-
- _CoalesceStream.prototype = new stream();
-
- _CoalesceStream.prototype.flush = function (flushSource) {
- var offset = 0,
- event = {
- captions: [],
- captionStreams: {},
- metadata: [],
- info: {}
- },
- caption,
- id3,
- initSegment,
- timelineStartPts = 0,
- i;
-
- if (this.pendingTracks.length < this.numberOfTracks) {
- if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
- // Return because we haven't received a flush from a data-generating
- // portion of the segment (meaning that we have only recieved meta-data
- // or captions.)
- return;
- } else if (this.remuxTracks) {
- // Return until we have enough tracks from the pipeline to remux (if we
- // are remuxing audio and video into a single MP4)
- return;
- } else if (this.pendingTracks.length === 0) {
- // In the case where we receive a flush without any data having been
- // received we consider it an emitted track for the purposes of coalescing
- // `done` events.
- // We do this for the case where there is an audio and video track in the
- // segment but no audio data. (seen in several playlists with alternate
- // audio tracks and no audio present in the main TS segments.)
- this.emittedTracks++;
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
-
- return;
- }
- }
-
- if (this.videoTrack) {
- timelineStartPts = this.videoTrack.timelineStartInfo.pts;
- videoProperties.forEach(function (prop) {
- event.info[prop] = this.videoTrack[prop];
- }, this);
- } else if (this.audioTrack) {
- timelineStartPts = this.audioTrack.timelineStartInfo.pts;
- audioProperties.forEach(function (prop) {
- event.info[prop] = this.audioTrack[prop];
- }, this);
- }
-
- if (this.videoTrack || this.audioTrack) {
- if (this.pendingTracks.length === 1) {
- event.type = this.pendingTracks[0].type;
- } else {
- event.type = 'combined';
- }
-
- this.emittedTracks += this.pendingTracks.length;
- initSegment = mp4Generator.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
-
- event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
- // and track definitions
-
- event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
-
- event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
-
- for (i = 0; i < this.pendingBoxes.length; i++) {
- event.data.set(this.pendingBoxes[i], offset);
- offset += this.pendingBoxes[i].byteLength;
- } // Translate caption PTS times into second offsets to match the
- // video timeline for the segment, and add track info
-
-
- for (i = 0; i < this.pendingCaptions.length; i++) {
- caption = this.pendingCaptions[i];
- caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
- caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
- event.captionStreams[caption.stream] = true;
- event.captions.push(caption);
- } // Translate ID3 frame PTS times into second offsets to match the
- // video timeline for the segment
-
-
- for (i = 0; i < this.pendingMetadata.length; i++) {
- id3 = this.pendingMetadata[i];
- id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
- event.metadata.push(id3);
- } // We add this to every single emitted segment even though we only need
- // it for the first
-
-
- event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
-
- this.pendingTracks.length = 0;
- this.videoTrack = null;
- this.pendingBoxes.length = 0;
- this.pendingCaptions.length = 0;
- this.pendingBytes = 0;
- this.pendingMetadata.length = 0; // Emit the built segment
- // We include captions and ID3 tags for backwards compatibility,
- // ideally we should send only video and audio in the data event
-
- this.trigger('data', event); // Emit each caption to the outside world
- // Ideally, this would happen immediately on parsing captions,
- // but we need to ensure that video data is sent back first
- // so that caption timing can be adjusted to match video timing
-
- for (i = 0; i < event.captions.length; i++) {
- caption = event.captions[i];
- this.trigger('caption', caption);
- } // Emit each id3 tag to the outside world
- // Ideally, this would happen immediately on parsing the tag,
- // but we need to ensure that video data is sent back first
- // so that ID3 frame timing can be adjusted to match video timing
-
-
- for (i = 0; i < event.metadata.length; i++) {
- id3 = event.metadata[i];
- this.trigger('id3Frame', id3);
- }
- } // Only emit `done` if all tracks have been flushed and emitted
-
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
- };
-
- _CoalesceStream.prototype.setRemux = function (val) {
- this.remuxTracks = val;
- };
- /**
- * A Stream that expects MP2T binary data as input and produces
- * corresponding media segments, suitable for use with Media Source
- * Extension (MSE) implementations that support the ISO BMFF byte
- * stream format, like Chrome.
- */
-
-
- _Transmuxer = function Transmuxer(options) {
- var self = this,
- hasFlushed = true,
- videoTrack,
- audioTrack;
-
- _Transmuxer.prototype.init.call(this);
-
- options = options || {};
- this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
- this.transmuxPipeline_ = {};
-
- this.setupAacPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'aac';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.aacStream = new aac();
- pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('audio');
- pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('timed-metadata');
- pipeline.adtsStream = new adts();
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.aacStream;
- pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
- pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
- pipeline.metadataStream.on('timestamp', function (frame) {
- pipeline.aacStream.setTimestamp(frame.timeStamp);
- });
- pipeline.aacStream.on('data', function (data) {
- if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
- return;
- }
-
- audioTrack = audioTrack || {
- timelineStartInfo: {
- baseMediaDecodeTime: self.baseMediaDecodeTime
- },
- codec: 'adts',
- type: 'audio'
- }; // hook up the audio segment stream to the first track with aac data
-
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- };
-
- this.setupTsPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'ts';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.packetStream = new m2ts_1.TransportPacketStream();
- pipeline.parseStream = new m2ts_1.TransportParseStream();
- pipeline.elementaryStream = new m2ts_1.ElementaryStream();
- pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
- pipeline.adtsStream = new adts();
- pipeline.h264Stream = new H264Stream();
- pipeline.captionStream = new m2ts_1.CaptionStream(options);
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
-
- pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
- // demux the streams
-
- pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
- pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
- pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
-
- pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
- pipeline.elementaryStream.on('data', function (data) {
- var i;
-
- if (data.type === 'metadata') {
- i = data.tracks.length; // scan the tracks listed in the metadata
-
- while (i--) {
- if (!videoTrack && data.tracks[i].type === 'video') {
- videoTrack = data.tracks[i];
- videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- } else if (!audioTrack && data.tracks[i].type === 'audio') {
- audioTrack = data.tracks[i];
- audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- }
- } // hook up the video segment stream to the first track with h264 data
-
-
- if (videoTrack && !pipeline.videoSegmentStream) {
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
- pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
- // When video emits timelineStartInfo data after a flush, we forward that
- // info to the AudioSegmentStream, if it exists, because video timeline
- // data takes precedence. Do not do this if keepOriginalTimestamps is set,
- // because this is a particularly subtle form of timestamp alteration.
- if (audioTrack && !options.keepOriginalTimestamps) {
- audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
- // very earliest DTS we have seen in video because Chrome will
- // interpret any video track with a baseMediaDecodeTime that is
- // non-zero as a gap.
-
- pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
- pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
- pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
- if (audioTrack) {
- pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
-
- pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
- }
-
- if (audioTrack && !pipeline.audioSegmentStream) {
- // hook up the audio segment stream to the first track with aac data
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
- pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
- } // emit pmt info
-
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
- pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
- id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
- self.trigger('id3Frame', id3Frame);
- });
- pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- }; // hook up the segment streams once track metadata is delivered
-
-
- this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- var pipeline = this.transmuxPipeline_;
-
- if (!options.keepOriginalTimestamps) {
- this.baseMediaDecodeTime = baseMediaDecodeTime;
- }
-
- if (audioTrack) {
- audioTrack.timelineStartInfo.dts = undefined;
- audioTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(audioTrack);
-
- if (pipeline.audioTimestampRolloverStream) {
- pipeline.audioTimestampRolloverStream.discontinuity();
- }
- }
-
- if (videoTrack) {
- if (pipeline.videoSegmentStream) {
- pipeline.videoSegmentStream.gopCache_ = [];
- }
-
- videoTrack.timelineStartInfo.dts = undefined;
- videoTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(videoTrack);
- pipeline.captionStream.reset();
- }
-
- if (pipeline.timestampRolloverStream) {
- pipeline.timestampRolloverStream.discontinuity();
- }
- };
-
- this.setAudioAppendStart = function (timestamp) {
- if (audioTrack) {
- this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
- }
- };
-
- this.setRemux = function (val) {
- var pipeline = this.transmuxPipeline_;
- options.remux = val;
-
- if (pipeline && pipeline.coalesceStream) {
- pipeline.coalesceStream.setRemux(val);
- }
- };
-
- this.alignGopsWith = function (gopsToAlignWith) {
- if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
- this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
- }
- }; // feed incoming data to the front of the parsing pipeline
-
-
- this.push = function (data) {
- if (hasFlushed) {
- var isAac = isLikelyAacData(data);
-
- if (isAac && this.transmuxPipeline_.type !== 'aac') {
- this.setupAacPipeline();
- } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
- this.setupTsPipeline();
- }
-
- hasFlushed = false;
- }
-
- this.transmuxPipeline_.headOfPipeline.push(data);
- }; // flush any buffered data
-
-
- this.flush = function () {
- hasFlushed = true; // Start at the top of the pipeline and flush all pending work
-
- this.transmuxPipeline_.headOfPipeline.flush();
- };
-
- this.endTimeline = function () {
- this.transmuxPipeline_.headOfPipeline.endTimeline();
- };
-
- this.reset = function () {
- if (this.transmuxPipeline_.headOfPipeline) {
- this.transmuxPipeline_.headOfPipeline.reset();
- }
- }; // Caption data has to be reset when seeking outside buffered range
-
-
- this.resetCaptions = function () {
- if (this.transmuxPipeline_.captionStream) {
- this.transmuxPipeline_.captionStream.reset();
- }
- };
- };
-
- _Transmuxer.prototype = new stream();
- var transmuxer = {
- Transmuxer: _Transmuxer,
- VideoSegmentStream: _VideoSegmentStream,
- AudioSegmentStream: _AudioSegmentStream,
- AUDIO_PROPERTIES: audioProperties,
- VIDEO_PROPERTIES: videoProperties,
- // exported for testing
- generateSegmentTimingInfo: generateSegmentTimingInfo
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var toUnsigned$3 = function toUnsigned(value) {
- return value >>> 0;
- };
-
- var toHexString$1 = function toHexString(value) {
- return ('00' + value.toString(16)).slice(-2);
- };
-
- var bin = {
- toUnsigned: toUnsigned$3,
- toHexString: toHexString$1
- };
-
- var parseType$1 = function parseType(buffer) {
- var result = '';
- result += String.fromCharCode(buffer[0]);
- result += String.fromCharCode(buffer[1]);
- result += String.fromCharCode(buffer[2]);
- result += String.fromCharCode(buffer[3]);
- return result;
- };
-
- var parseType_1 = parseType$1;
- var toUnsigned$2 = bin.toUnsigned;
-
- var findBox = function findBox(data, path) {
- var results = [],
- i,
- size,
- type,
- end,
- subresults;
-
- if (!path.length) {
- // short-circuit the search for empty paths
- return null;
- }
-
- for (i = 0; i < data.byteLength;) {
- size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
- type = parseType_1(data.subarray(i + 4, i + 8));
- end = size > 1 ? i + size : data.byteLength;
-
- if (type === path[0]) {
- if (path.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data.subarray(i + 8, end));
- } else {
- // recursively search for the next box along the path
- subresults = findBox(data.subarray(i + 8, end), path.slice(1));
-
- if (subresults.length) {
- results = results.concat(subresults);
- }
- }
- }
-
- i = end;
- } // we've finished searching all of data
-
-
- return results;
- };
-
- var findBox_1 = findBox;
- var toUnsigned$1 = bin.toUnsigned;
-
- var tfdt = function tfdt(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- baseMediaDecodeTime: toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7])
- };
-
- if (result.version === 1) {
- result.baseMediaDecodeTime *= Math.pow(2, 32);
- result.baseMediaDecodeTime += toUnsigned$1(data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11]);
- }
-
- return result;
- };
-
- var parseTfdt = tfdt;
-
- var parseSampleFlags = function parseSampleFlags(flags) {
- return {
- isLeading: (flags[0] & 0x0c) >>> 2,
- dependsOn: flags[0] & 0x03,
- isDependedOn: (flags[1] & 0xc0) >>> 6,
- hasRedundancy: (flags[1] & 0x30) >>> 4,
- paddingValue: (flags[1] & 0x0e) >>> 1,
- isNonSyncSample: flags[1] & 0x01,
- degradationPriority: flags[2] << 8 | flags[3]
- };
- };
-
- var parseSampleFlags_1 = parseSampleFlags;
-
- var trun = function trun(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- samples: []
- },
- view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- // Flag interpretation
- dataOffsetPresent = result.flags[2] & 0x01,
- // compare with 2nd byte of 0x1
- firstSampleFlagsPresent = result.flags[2] & 0x04,
- // compare with 2nd byte of 0x4
- sampleDurationPresent = result.flags[1] & 0x01,
- // compare with 2nd byte of 0x100
- sampleSizePresent = result.flags[1] & 0x02,
- // compare with 2nd byte of 0x200
- sampleFlagsPresent = result.flags[1] & 0x04,
- // compare with 2nd byte of 0x400
- sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
- // compare with 2nd byte of 0x800
- sampleCount = view.getUint32(4),
- offset = 8,
- sample;
-
- if (dataOffsetPresent) {
- // 32 bit signed integer
- result.dataOffset = view.getInt32(offset);
- offset += 4;
- } // Overrides the flags for the first sample only. The order of
- // optional values will be: duration, size, compositionTimeOffset
-
-
- if (firstSampleFlagsPresent && sampleCount) {
- sample = {
- flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
- };
- offset += 4;
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- sampleCount--;
- }
-
- while (sampleCount--) {
- sample = {};
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleFlagsPresent) {
- sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- }
-
- return result;
- };
-
- var parseTrun = trun;
-
- var tfhd = function tfhd(data) {
- var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- trackId: view.getUint32(4)
- },
- baseDataOffsetPresent = result.flags[2] & 0x01,
- sampleDescriptionIndexPresent = result.flags[2] & 0x02,
- defaultSampleDurationPresent = result.flags[2] & 0x08,
- defaultSampleSizePresent = result.flags[2] & 0x10,
- defaultSampleFlagsPresent = result.flags[2] & 0x20,
- durationIsEmpty = result.flags[0] & 0x010000,
- defaultBaseIsMoof = result.flags[0] & 0x020000,
- i;
- i = 8;
-
- if (baseDataOffsetPresent) {
- i += 4; // truncate top 4 bytes
- // FIXME: should we read the full 64 bits?
-
- result.baseDataOffset = view.getUint32(12);
- i += 4;
- }
-
- if (sampleDescriptionIndexPresent) {
- result.sampleDescriptionIndex = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleDurationPresent) {
- result.defaultSampleDuration = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleSizePresent) {
- result.defaultSampleSize = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleFlagsPresent) {
- result.defaultSampleFlags = view.getUint32(i);
- }
-
- if (durationIsEmpty) {
- result.durationIsEmpty = true;
- }
-
- if (!baseDataOffsetPresent && defaultBaseIsMoof) {
- result.baseDataOffsetIsMoof = true;
- }
-
- return result;
- };
-
- var parseTfhd = tfhd;
- var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
- var CaptionStream = captionStream.CaptionStream;
- /**
- * Maps an offset in the mdat to a sample based on the the size of the samples.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Number} offset - The offset into the mdat
- * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
- * @return {?Object} The matching sample, or null if no match was found.
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
- var mapToSample = function mapToSample(offset, samples) {
- var approximateOffset = offset;
-
- for (var i = 0; i < samples.length; i++) {
- var sample = samples[i];
-
- if (approximateOffset < sample.size) {
- return sample;
- }
-
- approximateOffset -= sample.size;
- }
-
- return null;
- };
- /**
- * Finds SEI nal units contained in a Media Data Box.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Uint8Array} avcStream - The bytes of the mdat
- * @param {Object[]} samples - The samples parsed out by `parseSamples`
- * @param {Number} trackId - The trackId of this video track
- * @return {Object[]} seiNals - the parsed SEI NALUs found.
- * The contents of the seiNal should match what is expected by
- * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
- *
- * @see ISO-BMFF-12/2015, Section 8.1.1
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- **/
-
-
- var findSeiNals = function findSeiNals(avcStream, samples, trackId) {
- var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
- result = [],
- seiNal,
- i,
- length,
- lastMatchedSample;
-
- for (i = 0; i + 4 < avcStream.length; i += length) {
- length = avcView.getUint32(i);
- i += 4; // Bail if this doesn't appear to be an H264 stream
-
- if (length <= 0) {
- continue;
- }
-
- switch (avcStream[i] & 0x1F) {
- case 0x06:
- var data = avcStream.subarray(i + 1, i + 1 + length);
- var matchingSample = mapToSample(i, samples);
- seiNal = {
- nalUnitType: 'sei_rbsp',
- size: length,
- data: data,
- escapedRBSP: discardEmulationPreventionBytes(data),
- trackId: trackId
- };
-
- if (matchingSample) {
- seiNal.pts = matchingSample.pts;
- seiNal.dts = matchingSample.dts;
- lastMatchedSample = matchingSample;
- } else if (lastMatchedSample) {
- // If a matching sample cannot be found, use the last
- // sample's values as they should be as close as possible
- seiNal.pts = lastMatchedSample.pts;
- seiNal.dts = lastMatchedSample.dts;
- } else {
- // eslint-disable-next-line no-console
- console.log("We've encountered a nal unit without data. See mux.js#233.");
- break;
- }
-
- result.push(seiNal);
- break;
- }
- }
-
- return result;
- };
- /**
- * Parses sample information out of Track Run Boxes and calculates
- * the absolute presentation and decode timestamps of each sample.
- *
- * @param {Array} truns - The Trun Run boxes to be parsed
- * @param {Number} baseMediaDecodeTime - base media decode time from tfdt
- @see ISO-BMFF-12/2015, Section 8.8.12
- * @param {Object} tfhd - The parsed Track Fragment Header
- * @see inspect.parseTfhd
- * @return {Object[]} the parsed samples
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
-
- var parseSamples = function parseSamples(truns, baseMediaDecodeTime, tfhd) {
- var currentDts = baseMediaDecodeTime;
- var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
- var defaultSampleSize = tfhd.defaultSampleSize || 0;
- var trackId = tfhd.trackId;
- var allSamples = [];
- truns.forEach(function (trun) {
- // Note: We currently do not parse the sample table as well
- // as the trun. It's possible some sources will require this.
- // moov > trak > mdia > minf > stbl
- var trackRun = parseTrun(trun);
- var samples = trackRun.samples;
- samples.forEach(function (sample) {
- if (sample.duration === undefined) {
- sample.duration = defaultSampleDuration;
- }
-
- if (sample.size === undefined) {
- sample.size = defaultSampleSize;
- }
-
- sample.trackId = trackId;
- sample.dts = currentDts;
-
- if (sample.compositionTimeOffset === undefined) {
- sample.compositionTimeOffset = 0;
- }
-
- sample.pts = currentDts + sample.compositionTimeOffset;
- currentDts += sample.duration;
- });
- allSamples = allSamples.concat(samples);
- });
- return allSamples;
- };
- /**
- * Parses out caption nals from an FMP4 segment's video tracks.
- *
- * @param {Uint8Array} segment - The bytes of a single segment
- * @param {Number} videoTrackId - The trackId of a video track in the segment
- * @return {Object.} A mapping of video trackId to
- * a list of seiNals found in that track
- **/
-
-
- var parseCaptionNals = function parseCaptionNals(segment, videoTrackId) {
- // To get the samples
- var trafs = findBox_1(segment, ['moof', 'traf']); // To get SEI NAL units
-
- var mdats = findBox_1(segment, ['mdat']);
- var captionNals = {};
- var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
-
- mdats.forEach(function (mdat, index) {
- var matchingTraf = trafs[index];
- mdatTrafPairs.push({
- mdat: mdat,
- traf: matchingTraf
- });
- });
- mdatTrafPairs.forEach(function (pair) {
- var mdat = pair.mdat;
- var traf = pair.traf;
- var tfhd = findBox_1(traf, ['tfhd']); // Exactly 1 tfhd per traf
-
- var headerInfo = parseTfhd(tfhd[0]);
- var trackId = headerInfo.trackId;
- var tfdt = findBox_1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
-
- var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
- var truns = findBox_1(traf, ['trun']);
- var samples;
- var seiNals; // Only parse video data for the chosen video track
-
- if (videoTrackId === trackId && truns.length > 0) {
- samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
- seiNals = findSeiNals(mdat, samples, trackId);
-
- if (!captionNals[trackId]) {
- captionNals[trackId] = [];
- }
-
- captionNals[trackId] = captionNals[trackId].concat(seiNals);
- }
- });
- return captionNals;
- };
- /**
- * Parses out inband captions from an MP4 container and returns
- * caption objects that can be used by WebVTT and the TextTrack API.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
- * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
- * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number} trackId - The id of the video track to parse
- * @param {Number} timescale - The timescale for the video track from the init segment
- *
- * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
- * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
- * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
- * @return {String} parsedCaptions[].text - The visible content of the caption
- **/
-
-
- var parseEmbeddedCaptions = function parseEmbeddedCaptions(segment, trackId, timescale) {
- var seiNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
-
- if (trackId === null) {
- return null;
- }
-
- seiNals = parseCaptionNals(segment, trackId);
- return {
- seiNals: seiNals[trackId],
- timescale: timescale
- };
- };
- /**
- * Converts SEI NALUs into captions that can be used by video.js
- **/
-
-
- var CaptionParser = function CaptionParser() {
- var isInitialized = false;
- var captionStream; // Stores segments seen before trackId and timescale are set
-
- var segmentCache; // Stores video track ID of the track being parsed
-
- var trackId; // Stores the timescale of the track being parsed
-
- var timescale; // Stores captions parsed so far
-
- var parsedCaptions; // Stores whether we are receiving partial data or not
-
- var parsingPartial;
- /**
- * A method to indicate whether a CaptionParser has been initalized
- * @returns {Boolean}
- **/
-
- this.isInitialized = function () {
- return isInitialized;
- };
- /**
- * Initializes the underlying CaptionStream, SEI NAL parsing
- * and management, and caption collection
- **/
-
-
- this.init = function (options) {
- captionStream = new CaptionStream();
- isInitialized = true;
- parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
-
- captionStream.on('data', function (event) {
- // Convert to seconds in the source's timescale
- event.startTime = event.startPts / timescale;
- event.endTime = event.endPts / timescale;
- parsedCaptions.captions.push(event);
- parsedCaptions.captionStreams[event.stream] = true;
- });
- };
- /**
- * Determines if a new video track will be selected
- * or if the timescale changed
- * @return {Boolean}
- **/
-
-
- this.isNewInit = function (videoTrackIds, timescales) {
- if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
- return false;
- }
-
- return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
- };
- /**
- * Parses out SEI captions and interacts with underlying
- * CaptionStream to return dispatched captions
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
- * @param {Object.} timescales - The timescales found in the init segment
- * @see parseEmbeddedCaptions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.parse = function (segment, videoTrackIds, timescales) {
- var parsedData;
-
- if (!this.isInitialized()) {
- return null; // This is not likely to be a video segment
- } else if (!videoTrackIds || !timescales) {
- return null;
- } else if (this.isNewInit(videoTrackIds, timescales)) {
- // Use the first video track only as there is no
- // mechanism to switch to other video tracks
- trackId = videoTrackIds[0];
- timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
- // data until we have one.
- // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
- } else if (trackId === null || !timescale) {
- segmentCache.push(segment);
- return null;
- } // Now that a timescale and trackId is set, parse cached segments
-
-
- while (segmentCache.length > 0) {
- var cachedSegment = segmentCache.shift();
- this.parse(cachedSegment, videoTrackIds, timescales);
- }
-
- parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
-
- if (parsedData === null || !parsedData.seiNals) {
- return null;
- }
-
- this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
-
- this.flushStream();
- return parsedCaptions;
- };
- /**
- * Pushes SEI NALUs onto CaptionStream
- * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
- * Assumes that `parseCaptionNals` has been called first
- * @see m2ts/caption-stream.js
- **/
-
-
- this.pushNals = function (nals) {
- if (!this.isInitialized() || !nals || nals.length === 0) {
- return null;
- }
-
- nals.forEach(function (nal) {
- captionStream.push(nal);
- });
- };
- /**
- * Flushes underlying CaptionStream to dispatch processed, displayable captions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.flushStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- if (!parsingPartial) {
- captionStream.flush();
- } else {
- captionStream.partialFlush();
- }
- };
- /**
- * Reset caption buckets for new data
- **/
-
-
- this.clearParsedCaptions = function () {
- parsedCaptions.captions = [];
- parsedCaptions.captionStreams = {};
- };
- /**
- * Resets underlying CaptionStream
- * @see m2ts/caption-stream.js
- **/
-
-
- this.resetCaptionStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- captionStream.reset();
- };
- /**
- * Convenience method to clear all captions flushed from the
- * CaptionStream and still being parsed
- * @see m2ts/caption-stream.js
- **/
-
-
- this.clearAllCaptions = function () {
- this.clearParsedCaptions();
- this.resetCaptionStream();
- };
- /**
- * Reset caption parser
- **/
-
-
- this.reset = function () {
- segmentCache = [];
- trackId = null;
- timescale = null;
-
- if (!parsedCaptions) {
- parsedCaptions = {
- captions: [],
- // CC1, CC2, CC3, CC4
- captionStreams: {}
- };
- } else {
- this.clearParsedCaptions();
- }
-
- this.resetCaptionStream();
- };
-
- this.reset();
- };
-
- var captionParser = CaptionParser;
- var toUnsigned = bin.toUnsigned;
- var toHexString = bin.toHexString;
- var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader;
- /**
- * Parses an MP4 initialization segment and extracts the timescale
- * values for any declared tracks. Timescale values indicate the
- * number of clock ticks per second to assume for time-based values
- * elsewhere in the MP4.
- *
- * To determine the start time of an MP4, you need two pieces of
- * information: the timescale unit and the earliest base media decode
- * time. Multiple timescales can be specified within an MP4 but the
- * base media decode time is always expressed in the timescale from
- * the media header box for the track:
- * ```
- * moov > trak > mdia > mdhd.timescale
- * ```
- * @param init {Uint8Array} the bytes of the init segment
- * @return {object} a hash of track ids to timescale values or null if
- * the init segment is malformed.
- */
-
- timescale = function timescale(init) {
- var result = {},
- traks = findBox_1(init, ['moov', 'trak']); // mdhd timescale
-
- return traks.reduce(function (result, trak) {
- var tkhd, version, index, id, mdhd;
- tkhd = findBox_1(trak, ['tkhd'])[0];
-
- if (!tkhd) {
- return null;
- }
-
- version = tkhd[0];
- index = version === 0 ? 12 : 20;
- id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
- mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
-
- if (!mdhd) {
- return null;
- }
-
- version = mdhd[0];
- index = version === 0 ? 12 : 20;
- result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
- return result;
- }, result);
- };
- /**
- * Determine the base media decode start time, in seconds, for an MP4
- * fragment. If multiple fragments are specified, the earliest time is
- * returned.
- *
- * The base media decode time can be parsed from track fragment
- * metadata:
- * ```
- * moof > traf > tfdt.baseMediaDecodeTime
- * ```
- * It requires the timescale value from the mdhd to interpret.
- *
- * @param timescale {object} a hash of track ids to timescale values.
- * @return {number} the earliest base media decode start time for the
- * fragment, in seconds
- */
-
-
- startTime = function startTime(timescale, fragment) {
- var trafs, baseTimes, result; // we need info from two childrend of each track fragment box
-
- trafs = findBox_1(fragment, ['moof', 'traf']); // determine the start times for each track
-
- baseTimes = [].concat.apply([], trafs.map(function (traf) {
- return findBox_1(traf, ['tfhd']).map(function (tfhd) {
- var id, scale, baseTime; // get the track id from the tfhd
-
- id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
-
- scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
-
- baseTime = findBox_1(traf, ['tfdt']).map(function (tfdt) {
- var version, result;
- version = tfdt[0];
- result = toUnsigned(tfdt[4] << 24 | tfdt[5] << 16 | tfdt[6] << 8 | tfdt[7]);
-
- if (version === 1) {
- result *= Math.pow(2, 32);
- result += toUnsigned(tfdt[8] << 24 | tfdt[9] << 16 | tfdt[10] << 8 | tfdt[11]);
- }
-
- return result;
- })[0];
- baseTime = typeof baseTime === 'number' && !isNaN(baseTime) ? baseTime : Infinity; // convert base time to seconds
-
- return baseTime / scale;
- });
- })); // return the minimum
-
- result = Math.min.apply(null, baseTimes);
- return isFinite(result) ? result : 0;
- };
- /**
- * Determine the composition start, in seconds, for an MP4
- * fragment.
- *
- * The composition start time of a fragment can be calculated using the base
- * media decode time, composition time offset, and timescale, as follows:
- *
- * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
- *
- * All of the aforementioned information is contained within a media fragment's
- * `traf` box, except for timescale info, which comes from the initialization
- * segment, so a track id (also contained within a `traf`) is also necessary to
- * associate it with a timescale
- *
- *
- * @param timescales {object} - a hash of track ids to timescale values.
- * @param fragment {Unit8Array} - the bytes of a media segment
- * @return {number} the composition start time for the fragment, in seconds
- **/
-
-
- compositionStartTime = function compositionStartTime(timescales, fragment) {
- var trafBoxes = findBox_1(fragment, ['moof', 'traf']);
- var baseMediaDecodeTime = 0;
- var compositionTimeOffset = 0;
- var trackId;
-
- if (trafBoxes && trafBoxes.length) {
- // The spec states that track run samples contained within a `traf` box are contiguous, but
- // it does not explicitly state whether the `traf` boxes themselves are contiguous.
- // We will assume that they are, so we only need the first to calculate start time.
- var tfhd = findBox_1(trafBoxes[0], ['tfhd'])[0];
- var trun = findBox_1(trafBoxes[0], ['trun'])[0];
- var tfdt = findBox_1(trafBoxes[0], ['tfdt'])[0];
-
- if (tfhd) {
- var parsedTfhd = parseTfhd(tfhd);
- trackId = parsedTfhd.trackId;
- }
-
- if (tfdt) {
- var parsedTfdt = parseTfdt(tfdt);
- baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
- }
-
- if (trun) {
- var parsedTrun = parseTrun(trun);
-
- if (parsedTrun.samples && parsedTrun.samples.length) {
- compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
- }
- }
- } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
- // specified.
-
-
- var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
-
- return (baseMediaDecodeTime + compositionTimeOffset) / timescale;
- };
- /**
- * Find the trackIds of the video tracks in this source.
- * Found by parsing the Handler Reference and Track Header Boxes:
- * moov > trak > mdia > hdlr
- * moov > trak > tkhd
- *
- * @param {Uint8Array} init - The bytes of the init segment for this source
- * @return {Number[]} A list of trackIds
- *
- * @see ISO-BMFF-12/2015, Section 8.4.3
- **/
-
-
- getVideoTrackIds = function getVideoTrackIds(init) {
- var traks = findBox_1(init, ['moov', 'trak']);
- var videoTrackIds = [];
- traks.forEach(function (trak) {
- var hdlrs = findBox_1(trak, ['mdia', 'hdlr']);
- var tkhds = findBox_1(trak, ['tkhd']);
- hdlrs.forEach(function (hdlr, index) {
- var handlerType = parseType_1(hdlr.subarray(8, 12));
- var tkhd = tkhds[index];
- var view;
- var version;
- var trackId;
-
- if (handlerType === 'vide') {
- view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- version = view.getUint8(0);
- trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
- videoTrackIds.push(trackId);
- }
- });
- });
- return videoTrackIds;
- };
-
- getTimescaleFromMediaHeader = function getTimescaleFromMediaHeader(mdhd) {
- // mdhd is a FullBox, meaning it will have its own version as the first byte
- var version = mdhd[0];
- var index = version === 0 ? 12 : 20;
- return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
- };
- /**
- * Get all the video, audio, and hint tracks from a non fragmented
- * mp4 segment
- */
-
-
- getTracks = function getTracks(init) {
- var traks = findBox_1(init, ['moov', 'trak']);
- var tracks = [];
- traks.forEach(function (trak) {
- var track = {};
- var tkhd = findBox_1(trak, ['tkhd'])[0];
- var view, tkhdVersion; // id
-
- if (tkhd) {
- view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- tkhdVersion = view.getUint8(0);
- track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
- }
-
- var hdlr = findBox_1(trak, ['mdia', 'hdlr'])[0]; // type
-
- if (hdlr) {
- var type = parseType_1(hdlr.subarray(8, 12));
-
- if (type === 'vide') {
- track.type = 'video';
- } else if (type === 'soun') {
- track.type = 'audio';
- } else {
- track.type = type;
- }
- } // codec
-
-
- var stsd = findBox_1(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
-
- if (stsd) {
- var sampleDescriptions = stsd.subarray(8); // gives the codec type string
-
- track.codec = parseType_1(sampleDescriptions.subarray(4, 8));
- var codecBox = findBox_1(sampleDescriptions, [track.codec])[0];
- var codecConfig, codecConfigType;
-
- if (codecBox) {
- // https://tools.ietf.org/html/rfc6381#section-3.3
- if (/^[a-z]vc[1-9]$/i.test(track.codec)) {
- // we don't need anything but the "config" parameter of the
- // avc1 codecBox
- codecConfig = codecBox.subarray(78);
- codecConfigType = parseType_1(codecConfig.subarray(4, 8));
-
- if (codecConfigType === 'avcC' && codecConfig.length > 11) {
- track.codec += '.'; // left padded with zeroes for single digit hex
- // profile idc
-
- track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
-
- track.codec += toHexString(codecConfig[10]); // level idc
-
- track.codec += toHexString(codecConfig[11]);
- } else {
- // TODO: show a warning that we couldn't parse the codec
- // and are using the default
- track.codec = 'avc1.4d400d';
- }
- } else if (/^mp4[a,v]$/i.test(track.codec)) {
- // we do not need anything but the streamDescriptor of the mp4a codecBox
- codecConfig = codecBox.subarray(28);
- codecConfigType = parseType_1(codecConfig.subarray(4, 8));
-
- if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
- track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
-
- track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
- } else {
- // TODO: show a warning that we couldn't parse the codec
- // and are using the default
- track.codec = 'mp4a.40.2';
- }
- } else {
- // flac, opus, etc
- track.codec = track.codec.toLowerCase();
- }
- }
- }
-
- var mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
-
- if (mdhd) {
- track.timescale = getTimescaleFromMediaHeader(mdhd);
- }
-
- tracks.push(track);
- });
- return tracks;
- };
-
- var probe$2 = {
- // export mp4 inspector's findBox and parseType for backwards compatibility
- findBox: findBox_1,
- parseType: parseType_1,
- timescale: timescale,
- startTime: startTime,
- compositionStartTime: compositionStartTime,
- videoTrackIds: getVideoTrackIds,
- tracks: getTracks,
- getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
- };
-
- var parsePid = function parsePid(packet) {
- var pid = packet[1] & 0x1f;
- pid <<= 8;
- pid |= packet[2];
- return pid;
- };
-
- var parsePayloadUnitStartIndicator = function parsePayloadUnitStartIndicator(packet) {
- return !!(packet[1] & 0x40);
- };
-
- var parseAdaptionField = function parseAdaptionField(packet) {
- var offset = 0; // if an adaption field is present, its length is specified by the
- // fifth byte of the TS packet header. The adaptation field is
- // used to add stuffing to PES packets that don't fill a complete
- // TS packet, and to specify some forms of timing and control data
- // that we do not currently use.
-
- if ((packet[3] & 0x30) >>> 4 > 0x01) {
- offset += packet[4] + 1;
- }
-
- return offset;
- };
-
- var parseType = function parseType(packet, pmtPid) {
- var pid = parsePid(packet);
-
- if (pid === 0) {
- return 'pat';
- } else if (pid === pmtPid) {
- return 'pmt';
- } else if (pmtPid) {
- return 'pes';
- }
-
- return null;
- };
-
- var parsePat = function parsePat(packet) {
- var pusi = parsePayloadUnitStartIndicator(packet);
- var offset = 4 + parseAdaptionField(packet);
-
- if (pusi) {
- offset += packet[offset] + 1;
- }
-
- return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
- };
-
- var parsePmt = function parsePmt(packet) {
- var programMapTable = {};
- var pusi = parsePayloadUnitStartIndicator(packet);
- var payloadOffset = 4 + parseAdaptionField(packet);
-
- if (pusi) {
- payloadOffset += packet[payloadOffset] + 1;
- } // PMTs can be sent ahead of the time when they should actually
- // take effect. We don't believe this should ever be the case
- // for HLS but we'll ignore "forward" PMT declarations if we see
- // them. Future PMT declarations have the current_next_indicator
- // set to zero.
-
-
- if (!(packet[payloadOffset + 5] & 0x01)) {
- return;
- }
-
- var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
-
- sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
- tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
- // long the program info descriptors are
-
- programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
-
- var offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
-
- programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
- // skip past the elementary stream descriptors, if present
-
- offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
- }
-
- return programMapTable;
- };
-
- var parsePesType = function parsePesType(packet, programMapTable) {
- var pid = parsePid(packet);
- var type = programMapTable[pid];
-
- switch (type) {
- case streamTypes.H264_STREAM_TYPE:
- return 'video';
-
- case streamTypes.ADTS_STREAM_TYPE:
- return 'audio';
-
- case streamTypes.METADATA_STREAM_TYPE:
- return 'timed-metadata';
-
- default:
- return null;
- }
- };
-
- var parsePesTime = function parsePesTime(packet) {
- var pusi = parsePayloadUnitStartIndicator(packet);
-
- if (!pusi) {
- return null;
- }
-
- var offset = 4 + parseAdaptionField(packet);
-
- if (offset >= packet.byteLength) {
- // From the H 222.0 MPEG-TS spec
- // "For transport stream packets carrying PES packets, stuffing is needed when there
- // is insufficient PES packet data to completely fill the transport stream packet
- // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
- // the sum of the lengths of the data elements in it, so that the payload bytes
- // remaining after the adaptation field exactly accommodates the available PES packet
- // data."
- //
- // If the offset is >= the length of the packet, then the packet contains no data
- // and instead is just adaption field stuffing bytes
- return null;
- }
-
- var pes = null;
- var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
- // and a DTS value. Determine what combination of values is
- // available to work with.
-
- ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
- // performs all bitwise operations on 32-bit integers but javascript
- // supports a much greater range (52-bits) of integer using standard
- // mathematical operations.
- // We construct a 31-bit value using bitwise operators over the 31
- // most significant bits and then multiply by 4 (equal to a left-shift
- // of 2) before we add the final 2 least significant bits of the
- // timestamp (equal to an OR.)
-
- if (ptsDtsFlags & 0xC0) {
- pes = {}; // the PTS and DTS are not written out directly. For information
- // on how they are encoded, see
- // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
-
- pes.pts = (packet[offset + 9] & 0x0E) << 27 | (packet[offset + 10] & 0xFF) << 20 | (packet[offset + 11] & 0xFE) << 12 | (packet[offset + 12] & 0xFF) << 5 | (packet[offset + 13] & 0xFE) >>> 3;
- pes.pts *= 4; // Left shift by 2
-
- pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
-
- pes.dts = pes.pts;
-
- if (ptsDtsFlags & 0x40) {
- pes.dts = (packet[offset + 14] & 0x0E) << 27 | (packet[offset + 15] & 0xFF) << 20 | (packet[offset + 16] & 0xFE) << 12 | (packet[offset + 17] & 0xFF) << 5 | (packet[offset + 18] & 0xFE) >>> 3;
- pes.dts *= 4; // Left shift by 2
-
- pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
- }
- }
-
- return pes;
- };
-
- var parseNalUnitType = function parseNalUnitType(type) {
- switch (type) {
- case 0x05:
- return 'slice_layer_without_partitioning_rbsp_idr';
-
- case 0x06:
- return 'sei_rbsp';
-
- case 0x07:
- return 'seq_parameter_set_rbsp';
-
- case 0x08:
- return 'pic_parameter_set_rbsp';
-
- case 0x09:
- return 'access_unit_delimiter_rbsp';
-
- default:
- return null;
- }
- };
-
- var videoPacketContainsKeyFrame = function videoPacketContainsKeyFrame(packet) {
- var offset = 4 + parseAdaptionField(packet);
- var frameBuffer = packet.subarray(offset);
- var frameI = 0;
- var frameSyncPoint = 0;
- var foundKeyFrame = false;
- var nalType; // advance the sync point to a NAL start, if necessary
-
- for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
- if (frameBuffer[frameSyncPoint + 2] === 1) {
- // the sync point is properly aligned
- frameI = frameSyncPoint + 5;
- break;
- }
- }
-
- while (frameI < frameBuffer.byteLength) {
- // look at the current byte to determine if we've hit the end of
- // a NAL unit boundary
- switch (frameBuffer[frameI]) {
- case 0:
- // skip past non-sync sequences
- if (frameBuffer[frameI - 1] !== 0) {
- frameI += 2;
- break;
- } else if (frameBuffer[frameI - 2] !== 0) {
- frameI++;
- break;
- }
-
- if (frameSyncPoint + 3 !== frameI - 2) {
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
- } // drop trailing zeroes
-
-
- do {
- frameI++;
- } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
-
- frameSyncPoint = frameI - 2;
- frameI += 3;
- break;
-
- case 1:
- // skip past non-sync sequences
- if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
- frameI += 3;
- break;
- }
-
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
-
- frameSyncPoint = frameI - 2;
- frameI += 3;
- break;
-
- default:
- // the current byte isn't a one or zero, so it cannot be part
- // of a sync sequence
- frameI += 3;
- break;
- }
- }
-
- frameBuffer = frameBuffer.subarray(frameSyncPoint);
- frameI -= frameSyncPoint;
- frameSyncPoint = 0; // parse the final nal
-
- if (frameBuffer && frameBuffer.byteLength > 3) {
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
- }
-
- return foundKeyFrame;
- };
-
- var probe$1 = {
- parseType: parseType,
- parsePat: parsePat,
- parsePmt: parsePmt,
- parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
- parsePesType: parsePesType,
- parsePesTime: parsePesTime,
- videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
- };
- var handleRollover = timestampRolloverStream.handleRollover;
- var probe = {};
- probe.ts = probe$1;
- probe.aac = utils;
- var ONE_SECOND_IN_TS = clock.ONE_SECOND_IN_TS;
- var MP2T_PACKET_LENGTH = 188,
- // bytes
- SYNC_BYTE = 0x47;
- /**
- * walks through segment data looking for pat and pmt packets to parse out
- * program map table information
- */
-
- var parsePsi_ = function parsePsi_(bytes, pmt) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type;
-
- while (endIndex < bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pat':
- pmt.pid = probe.ts.parsePat(packet);
- break;
-
- case 'pmt':
- var table = probe.ts.parsePmt(packet);
- pmt.table = pmt.table || {};
- Object.keys(table).forEach(function (key) {
- pmt.table[key] = table[key];
- });
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- }
- };
- /**
- * walks through the segment data from the start and end to get timing information
- * for the first and last audio pes packets
- */
-
-
- var parseAudioPes_ = function parseAudioPes_(bytes, pmt, result) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type,
- pesType,
- pusi,
- parsed;
- var endLoop = false; // Start walking from start of segment to get first audio packet
-
- while (endIndex <= bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'audio' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'audio';
- result.audio.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // Start walking from end of segment to get last audio packet
-
-
- endIndex = bytes.byteLength;
- startIndex = endIndex - MP2T_PACKET_LENGTH;
- endLoop = false;
-
- while (startIndex >= 0) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'audio' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'audio';
- result.audio.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex -= MP2T_PACKET_LENGTH;
- endIndex -= MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex--;
- endIndex--;
- }
- };
- /**
- * walks through the segment data from the start and end to get timing information
- * for the first and last video pes packets as well as timing information for the first
- * key frame.
- */
-
-
- var parseVideoPes_ = function parseVideoPes_(bytes, pmt, result) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type,
- pesType,
- pusi,
- parsed,
- frame,
- i,
- pes;
- var endLoop = false;
- var currentFrame = {
- data: [],
- size: 0
- }; // Start walking from start of segment to get first video packet
-
- while (endIndex < bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'video') {
- if (pusi && !endLoop) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'video';
- result.video.push(parsed);
- endLoop = true;
- }
- }
-
- if (!result.firstKeyFrame) {
- if (pusi) {
- if (currentFrame.size !== 0) {
- frame = new Uint8Array(currentFrame.size);
- i = 0;
-
- while (currentFrame.data.length) {
- pes = currentFrame.data.shift();
- frame.set(pes, i);
- i += pes.byteLength;
- }
-
- if (probe.ts.videoPacketContainsKeyFrame(frame)) {
- var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
- // the keyframe seems to work fine with HLS playback
- // and definitely preferable to a crash with TypeError...
-
- if (firstKeyFrame) {
- result.firstKeyFrame = firstKeyFrame;
- result.firstKeyFrame.type = 'video';
- } else {
- // eslint-disable-next-line
- console.warn('Failed to extract PTS/DTS from PES at first keyframe. ' + 'This could be an unusual TS segment, or else mux.js did not ' + 'parse your TS segment correctly. If you know your TS ' + 'segments do contain PTS/DTS on keyframes please file a bug ' + 'report! You can try ffprobe to double check for yourself.');
- }
- }
-
- currentFrame.size = 0;
- }
- }
-
- currentFrame.data.push(packet);
- currentFrame.size += packet.byteLength;
- }
- }
-
- break;
- }
-
- if (endLoop && result.firstKeyFrame) {
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // Start walking from end of segment to get last video packet
-
-
- endIndex = bytes.byteLength;
- startIndex = endIndex - MP2T_PACKET_LENGTH;
- endLoop = false;
-
- while (startIndex >= 0) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'video' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'video';
- result.video.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex -= MP2T_PACKET_LENGTH;
- endIndex -= MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex--;
- endIndex--;
- }
- };
- /**
- * Adjusts the timestamp information for the segment to account for
- * rollover and convert to seconds based on pes packet timescale (90khz clock)
- */
-
-
- var adjustTimestamp_ = function adjustTimestamp_(segmentInfo, baseTimestamp) {
- if (segmentInfo.audio && segmentInfo.audio.length) {
- var audioBaseTimestamp = baseTimestamp;
-
- if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
- audioBaseTimestamp = segmentInfo.audio[0].dts;
- }
-
- segmentInfo.audio.forEach(function (info) {
- info.dts = handleRollover(info.dts, audioBaseTimestamp);
- info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
-
- info.dtsTime = info.dts / ONE_SECOND_IN_TS;
- info.ptsTime = info.pts / ONE_SECOND_IN_TS;
- });
- }
-
- if (segmentInfo.video && segmentInfo.video.length) {
- var videoBaseTimestamp = baseTimestamp;
-
- if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
- videoBaseTimestamp = segmentInfo.video[0].dts;
- }
-
- segmentInfo.video.forEach(function (info) {
- info.dts = handleRollover(info.dts, videoBaseTimestamp);
- info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
-
- info.dtsTime = info.dts / ONE_SECOND_IN_TS;
- info.ptsTime = info.pts / ONE_SECOND_IN_TS;
- });
-
- if (segmentInfo.firstKeyFrame) {
- var frame = segmentInfo.firstKeyFrame;
- frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
- frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
-
- frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
- frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
- }
- }
- };
- /**
- * inspects the aac data stream for start and end time information
- */
-
-
- var inspectAac_ = function inspectAac_(bytes) {
- var endLoop = false,
- audioCount = 0,
- sampleRate = null,
- timestamp = null,
- frameSize = 0,
- byteIndex = 0,
- packet;
-
- while (bytes.length - byteIndex >= 3) {
- var type = probe.aac.parseType(bytes, byteIndex);
-
- switch (type) {
- case 'timed-metadata':
- // Exit early because we don't have enough to parse
- // the ID3 tag header
- if (bytes.length - byteIndex < 10) {
- endLoop = true;
- break;
- }
-
- frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (frameSize > bytes.length) {
- endLoop = true;
- break;
- }
-
- if (timestamp === null) {
- packet = bytes.subarray(byteIndex, byteIndex + frameSize);
- timestamp = probe.aac.parseAacTimestamp(packet);
- }
-
- byteIndex += frameSize;
- break;
-
- case 'audio':
- // Exit early because we don't have enough to parse
- // the ADTS frame header
- if (bytes.length - byteIndex < 7) {
- endLoop = true;
- break;
- }
-
- frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (frameSize > bytes.length) {
- endLoop = true;
- break;
- }
-
- if (sampleRate === null) {
- packet = bytes.subarray(byteIndex, byteIndex + frameSize);
- sampleRate = probe.aac.parseSampleRate(packet);
- }
-
- audioCount++;
- byteIndex += frameSize;
- break;
-
- default:
- byteIndex++;
- break;
- }
-
- if (endLoop) {
- return null;
- }
- }
-
- if (sampleRate === null || timestamp === null) {
- return null;
- }
-
- var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
- var result = {
- audio: [{
- type: 'audio',
- dts: timestamp,
- pts: timestamp
- }, {
- type: 'audio',
- dts: timestamp + audioCount * 1024 * audioTimescale,
- pts: timestamp + audioCount * 1024 * audioTimescale
- }]
- };
- return result;
- };
- /**
- * inspects the transport stream segment data for start and end time information
- * of the audio and video tracks (when present) as well as the first key frame's
- * start time.
- */
-
-
- var inspectTs_ = function inspectTs_(bytes) {
- var pmt = {
- pid: null,
- table: null
- };
- var result = {};
- parsePsi_(bytes, pmt);
-
- for (var pid in pmt.table) {
- if (pmt.table.hasOwnProperty(pid)) {
- var type = pmt.table[pid];
-
- switch (type) {
- case streamTypes.H264_STREAM_TYPE:
- result.video = [];
- parseVideoPes_(bytes, pmt, result);
-
- if (result.video.length === 0) {
- delete result.video;
- }
-
- break;
-
- case streamTypes.ADTS_STREAM_TYPE:
- result.audio = [];
- parseAudioPes_(bytes, pmt, result);
-
- if (result.audio.length === 0) {
- delete result.audio;
- }
-
- break;
- }
- }
- }
-
- return result;
- };
- /**
- * Inspects segment byte data and returns an object with start and end timing information
- *
- * @param {Uint8Array} bytes The segment byte data
- * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
- * timestamps for rollover. This value must be in 90khz clock.
- * @return {Object} Object containing start and end frame timing info of segment.
- */
-
-
- var inspect = function inspect(bytes, baseTimestamp) {
- var isAacData = probe.aac.isLikelyAacData(bytes);
- var result;
-
- if (isAacData) {
- result = inspectAac_(bytes);
- } else {
- result = inspectTs_(bytes);
- }
-
- if (!result || !result.audio && !result.video) {
- return null;
- }
-
- adjustTimestamp_(result, baseTimestamp);
- return result;
- };
-
- var tsInspector = {
- inspect: inspect,
- parseAudioPes_: parseAudioPes_
- };
- /* global self */
-
- /**
- * Re-emits transmuxer events by converting them into messages to the
- * world outside the worker.
- *
- * @param {Object} transmuxer the transmuxer to wire events on
- * @private
- */
-
- var wireTransmuxerEvents = function wireTransmuxerEvents(self, transmuxer) {
- transmuxer.on('data', function (segment) {
- // transfer ownership of the underlying ArrayBuffer
- // instead of doing a copy to save memory
- // ArrayBuffers are transferable but generic TypedArrays are not
- // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
- var initArray = segment.initSegment;
- segment.initSegment = {
- data: initArray.buffer,
- byteOffset: initArray.byteOffset,
- byteLength: initArray.byteLength
- };
- var typedArray = segment.data;
- segment.data = typedArray.buffer;
- self.postMessage({
- action: 'data',
- segment: segment,
- byteOffset: typedArray.byteOffset,
- byteLength: typedArray.byteLength
- }, [segment.data]);
- });
- transmuxer.on('done', function (data) {
- self.postMessage({
- action: 'done'
- });
- });
- transmuxer.on('gopInfo', function (gopInfo) {
- self.postMessage({
- action: 'gopInfo',
- gopInfo: gopInfo
- });
- });
- transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
- var videoSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- videoSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'videoSegmentTimingInfo',
- videoSegmentTimingInfo: videoSegmentTimingInfo
- });
- });
- transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
- // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
- var audioSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- audioSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'audioSegmentTimingInfo',
- audioSegmentTimingInfo: audioSegmentTimingInfo
- });
- });
- transmuxer.on('id3Frame', function (id3Frame) {
- self.postMessage({
- action: 'id3Frame',
- id3Frame: id3Frame
- });
- });
- transmuxer.on('caption', function (caption) {
- self.postMessage({
- action: 'caption',
- caption: caption
- });
- });
- transmuxer.on('trackinfo', function (trackInfo) {
- self.postMessage({
- action: 'trackinfo',
- trackInfo: trackInfo
- });
- });
- transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
- // convert to video TS since we prioritize video time over audio
- self.postMessage({
- action: 'audioTimingInfo',
- audioTimingInfo: {
- start: clock.videoTsToSeconds(audioTimingInfo.start),
- end: clock.videoTsToSeconds(audioTimingInfo.end)
- }
- });
- });
- transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
- self.postMessage({
- action: 'videoTimingInfo',
- videoTimingInfo: {
- start: clock.videoTsToSeconds(videoTimingInfo.start),
- end: clock.videoTsToSeconds(videoTimingInfo.end)
- }
- });
- });
- };
- /**
- * All incoming messages route through this hash. If no function exists
- * to handle an incoming message, then we ignore the message.
- *
- * @class MessageHandlers
- * @param {Object} options the options to initialize with
- */
-
-
- var MessageHandlers = /*#__PURE__*/function () {
- function MessageHandlers(self, options) {
- this.options = options || {};
- this.self = self;
- this.init();
- }
- /**
- * initialize our web worker and wire all the events.
- */
-
-
- var _proto = MessageHandlers.prototype;
-
- _proto.init = function init() {
- if (this.transmuxer) {
- this.transmuxer.dispose();
- }
-
- this.transmuxer = new transmuxer.Transmuxer(this.options);
- wireTransmuxerEvents(this.self, this.transmuxer);
- };
-
- _proto.pushMp4Captions = function pushMp4Captions(data) {
- if (!this.captionParser) {
- this.captionParser = new captionParser();
- this.captionParser.init();
- }
-
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- var parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
- this.self.postMessage({
- action: 'mp4Captions',
- captions: parsed && parsed.captions || [],
- data: segment.buffer
- }, [segment.buffer]);
- };
-
- _proto.probeMp4StartTime = function probeMp4StartTime(_ref) {
- var timescales = _ref.timescales,
- data = _ref.data;
- var startTime = probe$2.startTime(timescales, data);
- this.self.postMessage({
- action: 'probeMp4StartTime',
- startTime: startTime,
- data: data
- }, [data.buffer]);
- };
-
- _proto.probeMp4Tracks = function probeMp4Tracks(_ref2) {
- var data = _ref2.data;
- var tracks = probe$2.tracks(data);
- this.self.postMessage({
- action: 'probeMp4Tracks',
- tracks: tracks,
- data: data
- }, [data.buffer]);
- }
- /**
- * Probe an mpeg2-ts segment to determine the start time of the segment in it's
- * internal "media time," as well as whether it contains video and/or audio.
- *
- * @private
- * @param {Uint8Array} bytes - segment bytes
- * @param {number} baseStartTime
- * Relative reference timestamp used when adjusting frame timestamps for rollover.
- * This value should be in seconds, as it's converted to a 90khz clock within the
- * function body.
- * @return {Object} The start time of the current segment in "media time" as well as
- * whether it contains video and/or audio
- */
- ;
-
- _proto.probeTs = function probeTs(_ref3) {
- var data = _ref3.data,
- baseStartTime = _ref3.baseStartTime;
- var tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock.ONE_SECOND_IN_TS : void 0;
- var timeInfo = tsInspector.inspect(data, tsStartTime);
- var result = null;
-
- if (timeInfo) {
- result = {
- // each type's time info comes back as an array of 2 times, start and end
- hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
- hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
- };
-
- if (result.hasVideo) {
- result.videoStart = timeInfo.video[0].ptsTime;
- }
-
- if (result.hasAudio) {
- result.audioStart = timeInfo.audio[0].ptsTime;
- }
- }
-
- this.self.postMessage({
- action: 'probeTs',
- result: result,
- data: data
- }, [data.buffer]);
- };
-
- _proto.clearAllMp4Captions = function clearAllMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearAllCaptions();
- }
- };
-
- _proto.clearParsedMp4Captions = function clearParsedMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearParsedCaptions();
- }
- }
- /**
- * Adds data (a ts segment) to the start of the transmuxer pipeline for
- * processing.
- *
- * @param {ArrayBuffer} data data to push into the muxer
- */
- ;
-
- _proto.push = function push(data) {
- // Cast array buffer to correct type for transmuxer
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- this.transmuxer.push(segment);
- }
- /**
- * Recreate the transmuxer so that the next segment added via `push`
- * start with a fresh transmuxer.
- */
- ;
-
- _proto.reset = function reset() {
- this.transmuxer.reset();
- }
- /**
- * Set the value that will be used as the `baseMediaDecodeTime` time for the
- * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
- * set relative to the first based on the PTS values.
- *
- * @param {Object} data used to set the timestamp offset in the muxer
- */
- ;
-
- _proto.setTimestampOffset = function setTimestampOffset(data) {
- var timestampOffset = data.timestampOffset || 0;
- this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset)));
- };
-
- _proto.setAudioAppendStart = function setAudioAppendStart(data) {
- this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));
- };
-
- _proto.setRemux = function setRemux(data) {
- this.transmuxer.setRemux(data.remux);
- }
- /**
- * Forces the pipeline to finish processing the last segment and emit it's
- * results.
- *
- * @param {Object} data event data, not really used
- */
- ;
-
- _proto.flush = function flush(data) {
- this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
-
- self.postMessage({
- action: 'done',
- type: 'transmuxed'
- });
- };
-
- _proto.endTimeline = function endTimeline() {
- this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
- // timelines
-
- self.postMessage({
- action: 'endedtimeline',
- type: 'transmuxed'
- });
- };
-
- _proto.alignGopsWith = function alignGopsWith(data) {
- this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
- };
-
- return MessageHandlers;
- }();
- /**
- * Our web worker interface so that things can talk to mux.js
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- *
- * @param {Object} self the scope for the web worker
- */
-
-
- self.onmessage = function (event) {
- if (event.data.action === 'init' && event.data.options) {
- this.messageHandlers = new MessageHandlers(self, event.data.options);
- return;
- }
-
- if (!this.messageHandlers) {
- this.messageHandlers = new MessageHandlers(self);
- }
-
- if (event.data && event.data.action && event.data.action !== 'init') {
- if (this.messageHandlers[event.data.action]) {
- this.messageHandlers[event.data.action](event.data);
- }
- }
- };
-}));
-var TransmuxWorker = factory(workerCode$1);
-/* rollup-plugin-worker-factory end for worker!/Users/gkatsevman/p/http-streaming-release/src/transmuxer-worker.js */
-
-var handleData_ = function handleData_(event, transmuxedData, callback) {
- var _event$data$segment = event.data.segment,
- type = _event$data$segment.type,
- initSegment = _event$data$segment.initSegment,
- captions = _event$data$segment.captions,
- captionStreams = _event$data$segment.captionStreams,
- metadata = _event$data$segment.metadata,
- videoFrameDtsTime = _event$data$segment.videoFrameDtsTime,
- videoFramePtsTime = _event$data$segment.videoFramePtsTime;
- transmuxedData.buffer.push({
- captions: captions,
- captionStreams: captionStreams,
- metadata: metadata
- });
- var boxes = event.data.segment.boxes || {
- data: event.data.segment.data
- };
- var result = {
- type: type,
- // cast ArrayBuffer to TypedArray
- data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
- initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
- };
-
- if (typeof videoFrameDtsTime !== 'undefined') {
- result.videoFrameDtsTime = videoFrameDtsTime;
- }
-
- if (typeof videoFramePtsTime !== 'undefined') {
- result.videoFramePtsTime = videoFramePtsTime;
- }
-
- callback(result);
-};
-var handleDone_ = function handleDone_(_ref) {
- var transmuxedData = _ref.transmuxedData,
- callback = _ref.callback;
- // Previously we only returned data on data events,
- // not on done events. Clear out the buffer to keep that consistent.
- transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
- // have received
-
- callback(transmuxedData);
-};
-var handleGopInfo_ = function handleGopInfo_(event, transmuxedData) {
- transmuxedData.gopInfo = event.data.gopInfo;
-};
-var processTransmux = function processTransmux(options) {
- var transmuxer = options.transmuxer,
- bytes = options.bytes,
- audioAppendStart = options.audioAppendStart,
- gopsToAlignWith = options.gopsToAlignWith,
- remux = options.remux,
- onData = options.onData,
- onTrackInfo = options.onTrackInfo,
- onAudioTimingInfo = options.onAudioTimingInfo,
- onVideoTimingInfo = options.onVideoTimingInfo,
- onVideoSegmentTimingInfo = options.onVideoSegmentTimingInfo,
- onAudioSegmentTimingInfo = options.onAudioSegmentTimingInfo,
- onId3 = options.onId3,
- onCaptions = options.onCaptions,
- onDone = options.onDone,
- onEndedTimeline = options.onEndedTimeline,
- isEndOfTimeline = options.isEndOfTimeline;
- var transmuxedData = {
- buffer: []
- };
- var waitForEndedTimelineEvent = isEndOfTimeline;
-
- var handleMessage = function handleMessage(event) {
- if (transmuxer.currentTransmux !== options) {
- // disposed
- return;
- }
-
- if (event.data.action === 'data') {
- handleData_(event, transmuxedData, onData);
- }
-
- if (event.data.action === 'trackinfo') {
- onTrackInfo(event.data.trackInfo);
- }
-
- if (event.data.action === 'gopInfo') {
- handleGopInfo_(event, transmuxedData);
- }
-
- if (event.data.action === 'audioTimingInfo') {
- onAudioTimingInfo(event.data.audioTimingInfo);
- }
-
- if (event.data.action === 'videoTimingInfo') {
- onVideoTimingInfo(event.data.videoTimingInfo);
- }
-
- if (event.data.action === 'videoSegmentTimingInfo') {
- onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
- }
-
- if (event.data.action === 'audioSegmentTimingInfo') {
- onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
- }
-
- if (event.data.action === 'id3Frame') {
- onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
- }
-
- if (event.data.action === 'caption') {
- onCaptions(event.data.caption);
- }
-
- if (event.data.action === 'endedtimeline') {
- waitForEndedTimelineEvent = false;
- onEndedTimeline();
- } // wait for the transmuxed event since we may have audio and video
-
-
- if (event.data.type !== 'transmuxed') {
- return;
- } // If the "endedtimeline" event has not yet fired, and this segment represents the end
- // of a timeline, that means there may still be data events before the segment
- // processing can be considerred complete. In that case, the final event should be
- // an "endedtimeline" event with the type "transmuxed."
-
-
- if (waitForEndedTimelineEvent) {
- return;
- }
-
- transmuxer.onmessage = null;
- handleDone_({
- transmuxedData: transmuxedData,
- callback: onDone
- });
- /* eslint-disable no-use-before-define */
-
- dequeue(transmuxer);
- /* eslint-enable */
- };
-
- transmuxer.onmessage = handleMessage;
-
- if (audioAppendStart) {
- transmuxer.postMessage({
- action: 'setAudioAppendStart',
- appendStart: audioAppendStart
- });
- } // allow empty arrays to be passed to clear out GOPs
-
-
- if (Array.isArray(gopsToAlignWith)) {
- transmuxer.postMessage({
- action: 'alignGopsWith',
- gopsToAlignWith: gopsToAlignWith
- });
- }
-
- if (typeof remux !== 'undefined') {
- transmuxer.postMessage({
- action: 'setRemux',
- remux: remux
- });
- }
-
- if (bytes.byteLength) {
- var buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
- var byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
- transmuxer.postMessage({
- action: 'push',
- // Send the typed-array of data as an ArrayBuffer so that
- // it can be sent as a "Transferable" and avoid the costly
- // memory copy
- data: buffer,
- // To recreate the original typed-array, we need information
- // about what portion of the ArrayBuffer it was a view into
- byteOffset: byteOffset,
- byteLength: bytes.byteLength
- }, [buffer]);
- }
-
- if (isEndOfTimeline) {
- transmuxer.postMessage({
- action: 'endTimeline'
- });
- } // even if we didn't push any bytes, we have to make sure we flush in case we reached
- // the end of the segment
-
-
- transmuxer.postMessage({
- action: 'flush'
- });
-};
-var dequeue = function dequeue(transmuxer) {
- transmuxer.currentTransmux = null;
-
- if (transmuxer.transmuxQueue.length) {
- transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
-
- if (typeof transmuxer.currentTransmux === 'function') {
- transmuxer.currentTransmux();
- } else {
- processTransmux(transmuxer.currentTransmux);
- }
- }
-};
-var processAction = function processAction(transmuxer, action) {
- transmuxer.postMessage({
- action: action
- });
- dequeue(transmuxer);
-};
-var enqueueAction = function enqueueAction(action, transmuxer) {
- if (!transmuxer.currentTransmux) {
- transmuxer.currentTransmux = action;
- processAction(transmuxer, action);
- return;
- }
-
- transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
-};
-var reset = function reset(transmuxer) {
- enqueueAction('reset', transmuxer);
-};
-var endTimeline = function endTimeline(transmuxer) {
- enqueueAction('endTimeline', transmuxer);
-};
-var transmux = function transmux(options) {
- if (!options.transmuxer.currentTransmux) {
- options.transmuxer.currentTransmux = options;
- processTransmux(options);
- return;
- }
-
- options.transmuxer.transmuxQueue.push(options);
-};
-var createTransmuxer = function createTransmuxer(options) {
- var transmuxer = new TransmuxWorker();
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue = [];
- var term = transmuxer.terminate;
-
- transmuxer.terminate = function () {
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue.length = 0;
- return term.call(transmuxer);
- };
-
- transmuxer.postMessage({
- action: 'init',
- options: options
- });
- return transmuxer;
-};
-var segmentTransmuxer = {
- reset: reset,
- endTimeline: endTimeline,
- transmux: transmux,
- createTransmuxer: createTransmuxer
-};
-
-var workerCallback = function workerCallback(options) {
- var transmuxer = options.transmuxer;
- var endAction = options.endAction || options.action;
- var callback = options.callback;
-
- var message = _extends__default['default']({}, options, {
- endAction: null,
- transmuxer: null,
- callback: null
- });
-
- var listenForEndEvent = function listenForEndEvent(event) {
- if (event.data.action !== endAction) {
- return;
- }
-
- transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
-
- if (event.data.data) {
- event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
-
- if (options.data) {
- options.data = event.data.data;
- }
- }
-
- callback(event.data);
- };
-
- transmuxer.addEventListener('message', listenForEndEvent);
-
- if (options.data) {
- var isArrayBuffer = options.data instanceof ArrayBuffer;
- message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
- message.byteLength = options.data.byteLength;
- var transfers = [isArrayBuffer ? options.data : options.data.buffer];
- transmuxer.postMessage(message, transfers);
- } else {
- transmuxer.postMessage(message);
- }
-};
-
-var REQUEST_ERRORS = {
- FAILURE: 2,
- TIMEOUT: -101,
- ABORTED: -102
-};
-/**
- * Abort all requests
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- */
-
-var abortAll = function abortAll(activeXhrs) {
- activeXhrs.forEach(function (xhr) {
- xhr.abort();
- });
-};
-/**
- * Gather important bandwidth stats once a request has completed
- *
- * @param {Object} request - the XHR request from which to gather stats
- */
-
-
-var getRequestStats = function getRequestStats(request) {
- return {
- bandwidth: request.bandwidth,
- bytesReceived: request.bytesReceived || 0,
- roundTripTime: request.roundTripTime || 0
- };
-};
-/**
- * If possible gather bandwidth stats as a request is in
- * progress
- *
- * @param {Event} progressEvent - an event object from an XHR's progress event
- */
-
-
-var getProgressStats = function getProgressStats(progressEvent) {
- var request = progressEvent.target;
- var roundTripTime = Date.now() - request.requestTime;
- var stats = {
- bandwidth: Infinity,
- bytesReceived: 0,
- roundTripTime: roundTripTime || 0
- };
- stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
- // because we should only use bandwidth stats on progress to determine when
- // abort a request early due to insufficient bandwidth
-
- stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
- return stats;
-};
-/**
- * Handle all error conditions in one place and return an object
- * with all the information
- *
- * @param {Error|null} error - if non-null signals an error occured with the XHR
- * @param {Object} request - the XHR request that possibly generated the error
- */
-
-
-var handleErrors = function handleErrors(error, request) {
- if (request.timedout) {
- return {
- status: request.status,
- message: 'HLS request timed-out at URL: ' + request.uri,
- code: REQUEST_ERRORS.TIMEOUT,
- xhr: request
- };
- }
-
- if (request.aborted) {
- return {
- status: request.status,
- message: 'HLS request aborted at URL: ' + request.uri,
- code: REQUEST_ERRORS.ABORTED,
- xhr: request
- };
- }
-
- if (error) {
- return {
- status: request.status,
- message: 'HLS request errored at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
- return {
- status: request.status,
- message: 'Empty HLS response at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- return null;
-};
-/**
- * Handle responses for key data and convert the key data to the correct format
- * for the decryption step later
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Array} objects - objects to add the key bytes to.
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
-var handleKeyResponse = function handleKeyResponse(segment, objects, finishProcessingFn) {
- return function (error, request) {
- var response = request.response;
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- if (response.byteLength !== 16) {
- return finishProcessingFn({
- status: request.status,
- message: 'Invalid HLS key at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- }, segment);
- }
-
- var view = new DataView(response);
- var bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
-
- for (var i = 0; i < objects.length; i++) {
- objects[i].bytes = bytes;
- }
-
- return finishProcessingFn(null, segment);
- };
-};
-
-var parseInitSegment = function parseInitSegment(segment, _callback) {
- var type = containers.detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
- // only know how to parse mp4 init segments at the moment
-
- if (type !== 'mp4') {
- var uri = segment.map.resolvedUri || segment.map.uri;
- return _callback({
- internal: true,
- message: "Found unsupported " + (type || 'unknown') + " container for initialization segment at URL: " + uri,
- code: REQUEST_ERRORS.FAILURE
- });
- }
-
- workerCallback({
- action: 'probeMp4Tracks',
- data: segment.map.bytes,
- transmuxer: segment.transmuxer,
- callback: function callback(_ref) {
- var tracks = _ref.tracks,
- data = _ref.data;
- // transfer bytes back to us
- segment.map.bytes = data;
- tracks.forEach(function (track) {
- segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
-
- if (segment.map.tracks[track.type]) {
- return;
- }
-
- segment.map.tracks[track.type] = track;
-
- if (typeof track.id === 'number' && track.timescale) {
- segment.map.timescales = segment.map.timescales || {};
- segment.map.timescales[track.id] = track.timescale;
- }
- });
- return _callback(null);
- }
- });
-};
-/**
- * Handle init-segment responses
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
-var handleInitSegmentResponse = function handleInitSegmentResponse(_ref2) {
- var segment = _ref2.segment,
- finishProcessingFn = _ref2.finishProcessingFn;
- return function (error, request) {
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- var bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
- // until the key request is done to decrypt.
-
- if (segment.map.key) {
- segment.map.encryptedBytes = bytes;
- return finishProcessingFn(null, segment);
- }
-
- segment.map.bytes = bytes;
- parseInitSegment(segment, function (parseError) {
- if (parseError) {
- parseError.xhr = request;
- parseError.status = request.status;
- return finishProcessingFn(parseError, segment);
- }
-
- finishProcessingFn(null, segment);
- });
- };
-};
-/**
- * Response handler for segment-requests being sure to set the correct
- * property depending on whether the segment is encryped or not
- * Also records and keeps track of stats that are used for ABR purposes
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
-var handleSegmentResponse = function handleSegmentResponse(_ref3) {
- var segment = _ref3.segment,
- finishProcessingFn = _ref3.finishProcessingFn,
- responseType = _ref3.responseType;
- return function (error, request) {
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- var newBytes = // although responseText "should" exist, this guard serves to prevent an error being
- // thrown for two primary cases:
- // 1. the mime type override stops working, or is not implemented for a specific
- // browser
- // 2. when using mock XHR libraries like sinon that do not allow the override behavior
- responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
- segment.stats = getRequestStats(request);
-
- if (segment.key) {
- segment.encryptedBytes = new Uint8Array(newBytes);
- } else {
- segment.bytes = new Uint8Array(newBytes);
- }
-
- return finishProcessingFn(null, segment);
- };
-};
-
-var transmuxAndNotify = function transmuxAndNotify(_ref4) {
- var segment = _ref4.segment,
- bytes = _ref4.bytes,
- trackInfoFn = _ref4.trackInfoFn,
- timingInfoFn = _ref4.timingInfoFn,
- videoSegmentTimingInfoFn = _ref4.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref4.audioSegmentTimingInfoFn,
- id3Fn = _ref4.id3Fn,
- captionsFn = _ref4.captionsFn,
- isEndOfTimeline = _ref4.isEndOfTimeline,
- endedTimelineFn = _ref4.endedTimelineFn,
- dataFn = _ref4.dataFn,
- doneFn = _ref4.doneFn;
- var fmp4Tracks = segment.map && segment.map.tracks || {};
- var isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
- // One reason for this is that in the case of full segments, we want to trust start
- // times from the probe, rather than the transmuxer.
-
- var audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
- var audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
- var videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
- var videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
-
- var finish = function finish() {
- return transmux({
- bytes: bytes,
- transmuxer: segment.transmuxer,
- audioAppendStart: segment.audioAppendStart,
- gopsToAlignWith: segment.gopsToAlignWith,
- remux: isMuxed,
- onData: function onData(result) {
- result.type = result.type === 'combined' ? 'video' : result.type;
- dataFn(segment, result);
- },
- onTrackInfo: function onTrackInfo(trackInfo) {
- if (trackInfoFn) {
- if (isMuxed) {
- trackInfo.isMuxed = true;
- }
-
- trackInfoFn(segment, trackInfo);
- }
- },
- onAudioTimingInfo: function onAudioTimingInfo(audioTimingInfo) {
- // we only want the first start value we encounter
- if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
- audioStartFn(audioTimingInfo.start);
- audioStartFn = null;
- } // we want to continually update the end time
-
-
- if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
- audioEndFn(audioTimingInfo.end);
- }
- },
- onVideoTimingInfo: function onVideoTimingInfo(videoTimingInfo) {
- // we only want the first start value we encounter
- if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
- videoStartFn(videoTimingInfo.start);
- videoStartFn = null;
- } // we want to continually update the end time
-
-
- if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
- videoEndFn(videoTimingInfo.end);
- }
- },
- onVideoSegmentTimingInfo: function onVideoSegmentTimingInfo(videoSegmentTimingInfo) {
- videoSegmentTimingInfoFn(videoSegmentTimingInfo);
- },
- onAudioSegmentTimingInfo: function onAudioSegmentTimingInfo(audioSegmentTimingInfo) {
- audioSegmentTimingInfoFn(audioSegmentTimingInfo);
- },
- onId3: function onId3(id3Frames, dispatchType) {
- id3Fn(segment, id3Frames, dispatchType);
- },
- onCaptions: function onCaptions(captions) {
- captionsFn(segment, [captions]);
- },
- isEndOfTimeline: isEndOfTimeline,
- onEndedTimeline: function onEndedTimeline() {
- endedTimelineFn();
- },
- onDone: function onDone(result) {
- if (!doneFn) {
- return;
- }
-
- result.type = result.type === 'combined' ? 'video' : result.type;
- doneFn(null, segment, result);
- }
- });
- }; // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
- // Meaning cached frame data may corrupt our notion of where this segment
- // really starts. To get around this, probe for the info needed.
-
-
- workerCallback({
- action: 'probeTs',
- transmuxer: segment.transmuxer,
- data: bytes,
- baseStartTime: segment.baseStartTime,
- callback: function callback(data) {
- segment.bytes = bytes = data.data;
- var probeResult = data.result;
-
- if (probeResult) {
- trackInfoFn(segment, {
- hasAudio: probeResult.hasAudio,
- hasVideo: probeResult.hasVideo,
- isMuxed: isMuxed
- });
- trackInfoFn = null;
-
- if (probeResult.hasAudio && !isMuxed) {
- audioStartFn(probeResult.audioStart);
- }
-
- if (probeResult.hasVideo) {
- videoStartFn(probeResult.videoStart);
- }
-
- audioStartFn = null;
- videoStartFn = null;
- }
-
- finish();
- }
- });
-};
-
-var handleSegmentBytes = function handleSegmentBytes(_ref5) {
- var segment = _ref5.segment,
- bytes = _ref5.bytes,
- trackInfoFn = _ref5.trackInfoFn,
- timingInfoFn = _ref5.timingInfoFn,
- videoSegmentTimingInfoFn = _ref5.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref5.audioSegmentTimingInfoFn,
- id3Fn = _ref5.id3Fn,
- captionsFn = _ref5.captionsFn,
- isEndOfTimeline = _ref5.isEndOfTimeline,
- endedTimelineFn = _ref5.endedTimelineFn,
- dataFn = _ref5.dataFn,
- doneFn = _ref5.doneFn;
- var bytesAsUint8Array = new Uint8Array(bytes); // TODO:
- // We should have a handler that fetches the number of bytes required
- // to check if something is fmp4. This will allow us to save bandwidth
- // because we can only blacklist a playlist and abort requests
- // by codec after trackinfo triggers.
-
- if (containers.isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
- segment.isFmp4 = true;
- var tracks = segment.map.tracks;
- var trackInfo = {
- isFmp4: true,
- hasVideo: !!tracks.video,
- hasAudio: !!tracks.audio
- }; // if we have a audio track, with a codec that is not set to
- // encrypted audio
-
- if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
- trackInfo.audioCodec = tracks.audio.codec;
- } // if we have a video track, with a codec that is not set to
- // encrypted video
-
-
- if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
- trackInfo.videoCodec = tracks.video.codec;
- }
-
- if (tracks.video && tracks.audio) {
- trackInfo.isMuxed = true;
- } // since we don't support appending fmp4 data on progress, we know we have the full
- // segment here
-
-
- trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
- // time. The end time can be roughly calculated by the receiver using the duration.
- //
- // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
- // that is the true start of the segment (where the playback engine should begin
- // decoding).
-
- var finishLoading = function finishLoading(captions) {
- // if the track still has audio at this point it is only possible
- // for it to be audio only. See `tracks.video && tracks.audio` if statement
- // above.
- // we make sure to use segment.bytes here as that
- dataFn(segment, {
- data: bytesAsUint8Array,
- type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
- });
-
- if (captions && captions.length) {
- captionsFn(segment, captions);
- }
-
- doneFn(null, segment, {});
- };
-
- workerCallback({
- action: 'probeMp4StartTime',
- timescales: segment.map.timescales,
- data: bytesAsUint8Array,
- transmuxer: segment.transmuxer,
- callback: function callback(_ref6) {
- var data = _ref6.data,
- startTime = _ref6.startTime;
- // transfer bytes back to us
- bytes = data.buffer;
- segment.bytes = bytesAsUint8Array = data;
-
- if (trackInfo.hasAudio && !trackInfo.isMuxed) {
- timingInfoFn(segment, 'audio', 'start', startTime);
- }
-
- if (trackInfo.hasVideo) {
- timingInfoFn(segment, 'video', 'start', startTime);
- } // Run through the CaptionParser in case there are captions.
- // Initialize CaptionParser if it hasn't been yet
-
-
- if (!tracks.video || !data.byteLength || !segment.transmuxer) {
- finishLoading();
- return;
- }
-
- workerCallback({
- action: 'pushMp4Captions',
- endAction: 'mp4Captions',
- transmuxer: segment.transmuxer,
- data: bytesAsUint8Array,
- timescales: segment.map.timescales,
- trackIds: [tracks.video.id],
- callback: function callback(message) {
- // transfer bytes back to us
- bytes = message.data.buffer;
- segment.bytes = bytesAsUint8Array = message.data;
- finishLoading(message.captions);
- }
- });
- }
- });
- return;
- } // VTT or other segments that don't need processing
-
-
- if (!segment.transmuxer) {
- doneFn(null, segment, {});
- return;
- }
-
- if (typeof segment.container === 'undefined') {
- segment.container = containers.detectContainerForBytes(bytesAsUint8Array);
- }
-
- if (segment.container !== 'ts' && segment.container !== 'aac') {
- trackInfoFn(segment, {
- hasAudio: false,
- hasVideo: false
- });
- doneFn(null, segment, {});
- return;
- } // ts or aac
-
-
- transmuxAndNotify({
- segment: segment,
- bytes: bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
-};
-
-var decrypt = function decrypt(_ref7, callback) {
- var id = _ref7.id,
- key = _ref7.key,
- encryptedBytes = _ref7.encryptedBytes,
- decryptionWorker = _ref7.decryptionWorker;
-
- var decryptionHandler = function decryptionHandler(event) {
- if (event.data.source === id) {
- decryptionWorker.removeEventListener('message', decryptionHandler);
- var decrypted = event.data.decrypted;
- callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
- }
- };
-
- decryptionWorker.addEventListener('message', decryptionHandler);
- var keyBytes;
-
- if (key.bytes.slice) {
- keyBytes = key.bytes.slice();
- } else {
- keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
- } // incrementally decrypt the bytes
-
-
- decryptionWorker.postMessage(createTransferableMessage({
- source: id,
- encrypted: encryptedBytes,
- key: keyBytes,
- iv: key.iv
- }), [encryptedBytes.buffer, keyBytes.buffer]);
-};
-/**
- * Decrypt the segment via the decryption web worker
- *
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after decryption has completed
- */
-
-
-var decryptSegment = function decryptSegment(_ref8) {
- var decryptionWorker = _ref8.decryptionWorker,
- segment = _ref8.segment,
- trackInfoFn = _ref8.trackInfoFn,
- timingInfoFn = _ref8.timingInfoFn,
- videoSegmentTimingInfoFn = _ref8.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref8.audioSegmentTimingInfoFn,
- id3Fn = _ref8.id3Fn,
- captionsFn = _ref8.captionsFn,
- isEndOfTimeline = _ref8.isEndOfTimeline,
- endedTimelineFn = _ref8.endedTimelineFn,
- dataFn = _ref8.dataFn,
- doneFn = _ref8.doneFn;
- decrypt({
- id: segment.requestId,
- key: segment.key,
- encryptedBytes: segment.encryptedBytes,
- decryptionWorker: decryptionWorker
- }, function (decryptedBytes) {
- segment.bytes = decryptedBytes;
- handleSegmentBytes({
- segment: segment,
- bytes: segment.bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- });
-};
-/**
- * This function waits for all XHRs to finish (with either success or failure)
- * before continueing processing via it's callback. The function gathers errors
- * from each request into a single errors array so that the error status for
- * each request can be examined later.
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after all resources have been
- * downloaded and any decryption completed
- */
-
-
-var waitForCompletion = function waitForCompletion(_ref9) {
- var activeXhrs = _ref9.activeXhrs,
- decryptionWorker = _ref9.decryptionWorker,
- trackInfoFn = _ref9.trackInfoFn,
- timingInfoFn = _ref9.timingInfoFn,
- videoSegmentTimingInfoFn = _ref9.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref9.audioSegmentTimingInfoFn,
- id3Fn = _ref9.id3Fn,
- captionsFn = _ref9.captionsFn,
- isEndOfTimeline = _ref9.isEndOfTimeline,
- endedTimelineFn = _ref9.endedTimelineFn,
- dataFn = _ref9.dataFn,
- doneFn = _ref9.doneFn;
- var count = 0;
- var didError = false;
- return function (error, segment) {
- if (didError) {
- return;
- }
-
- if (error) {
- didError = true; // If there are errors, we have to abort any outstanding requests
-
- abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
- // handle the aborted events from those requests, there are some cases where we may
- // never get an aborted event. For instance, if the network connection is lost and
- // there were two requests, the first may have triggered an error immediately, while
- // the second request remains unsent. In that case, the aborted algorithm will not
- // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
- //
- // We also can't rely on the ready state of the XHR, since the request that
- // triggered the connection error may also show as a ready state of 0 (unsent).
- // Therefore, we have to finish this group of requests immediately after the first
- // seen error.
-
- return doneFn(error, segment);
- }
-
- count += 1;
-
- if (count === activeXhrs.length) {
- var segmentFinish = function segmentFinish() {
- if (segment.encryptedBytes) {
- return decryptSegment({
- decryptionWorker: decryptionWorker,
- segment: segment,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- } // Otherwise, everything is ready just continue
-
-
- handleSegmentBytes({
- segment: segment,
- bytes: segment.bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- }; // Keep track of when *all* of the requests have completed
-
-
- segment.endOfAllRequests = Date.now();
-
- if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
- return decrypt({
- decryptionWorker: decryptionWorker,
- // add -init to the "id" to differentiate between segment
- // and init segment decryption, just in case they happen
- // at the same time at some point in the future.
- id: segment.requestId + '-init',
- encryptedBytes: segment.map.encryptedBytes,
- key: segment.map.key
- }, function (decryptedBytes) {
- segment.map.bytes = decryptedBytes;
- parseInitSegment(segment, function (parseError) {
- if (parseError) {
- abortAll(activeXhrs);
- return doneFn(parseError, segment);
- }
-
- segmentFinish();
- });
- });
- }
-
- segmentFinish();
- }
- };
-};
-/**
- * Calls the abort callback if any request within the batch was aborted. Will only call
- * the callback once per batch of requests, even if multiple were aborted.
- *
- * @param {Object} loadendState - state to check to see if the abort function was called
- * @param {Function} abortFn - callback to call for abort
- */
-
-
-var handleLoadEnd = function handleLoadEnd(_ref10) {
- var loadendState = _ref10.loadendState,
- abortFn = _ref10.abortFn;
- return function (event) {
- var request = event.target;
-
- if (request.aborted && abortFn && !loadendState.calledAbortFn) {
- abortFn();
- loadendState.calledAbortFn = true;
- }
- };
-};
-/**
- * Simple progress event callback handler that gathers some stats before
- * executing a provided callback with the `segment` object
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} progressFn - a callback that is executed each time a progress event
- * is received
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Event} event - the progress event object from XMLHttpRequest
- */
-
-
-var handleProgress = function handleProgress(_ref11) {
- var segment = _ref11.segment,
- progressFn = _ref11.progressFn;
- _ref11.trackInfoFn;
- _ref11.timingInfoFn;
- _ref11.videoSegmentTimingInfoFn;
- _ref11.audioSegmentTimingInfoFn;
- _ref11.id3Fn;
- _ref11.captionsFn;
- _ref11.isEndOfTimeline;
- _ref11.endedTimelineFn;
- _ref11.dataFn;
- return function (event) {
- var request = event.target;
-
- if (request.aborted) {
- return;
- }
-
- segment.stats = videojs__default['default'].mergeOptions(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
-
- if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
- segment.stats.firstBytesReceivedAt = Date.now();
- }
-
- return progressFn(event, segment);
- };
-};
-/**
- * Load all resources and does any processing necessary for a media-segment
- *
- * Features:
- * decrypts the media-segment if it has a key uri and an iv
- * aborts *all* requests if *any* one request fails
- *
- * The segment object, at minimum, has the following format:
- * {
- * resolvedUri: String,
- * [transmuxer]: Object,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [key]: {
- * resolvedUri: String
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * iv: {
- * bytes: Uint32Array
- * }
- * },
- * [map]: {
- * resolvedUri: String,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [bytes]: Uint8Array
- * }
- * }
- * ...where [name] denotes optional properties
- *
- * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
- * @param {Object} xhrOptions - the base options to provide to all xhr requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
- * decryption routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} abortFn - a callback called (only once) if any piece of a request was
- * aborted
- * @param {Function} progressFn - a callback that receives progress events from the main
- * segment's xhr request
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that receives data from the main segment's xhr
- * request, transmuxed if needed
- * @param {Function} doneFn - a callback that is executed only once all requests have
- * succeeded or failed
- * @return {Function} a function that, when invoked, immediately aborts all
- * outstanding requests
- */
-
-
-var mediaSegmentRequest = function mediaSegmentRequest(_ref12) {
- var xhr = _ref12.xhr,
- xhrOptions = _ref12.xhrOptions,
- decryptionWorker = _ref12.decryptionWorker,
- segment = _ref12.segment,
- abortFn = _ref12.abortFn,
- progressFn = _ref12.progressFn,
- trackInfoFn = _ref12.trackInfoFn,
- timingInfoFn = _ref12.timingInfoFn,
- videoSegmentTimingInfoFn = _ref12.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref12.audioSegmentTimingInfoFn,
- id3Fn = _ref12.id3Fn,
- captionsFn = _ref12.captionsFn,
- isEndOfTimeline = _ref12.isEndOfTimeline,
- endedTimelineFn = _ref12.endedTimelineFn,
- dataFn = _ref12.dataFn,
- doneFn = _ref12.doneFn;
- var activeXhrs = [];
- var finishProcessingFn = waitForCompletion({
- activeXhrs: activeXhrs,
- decryptionWorker: decryptionWorker,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- }); // optionally, request the decryption key
-
- if (segment.key && !segment.key.bytes) {
- var objects = [segment.key];
-
- if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
- objects.push(segment.map.key);
- }
-
- var keyRequestOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- var keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
- var keyXhr = xhr(keyRequestOptions, keyRequestCallback);
- activeXhrs.push(keyXhr);
- } // optionally, request the associated media init segment
-
-
- if (segment.map && !segment.map.bytes) {
- var differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
-
- if (differentMapKey) {
- var mapKeyRequestOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.map.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- var mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
- var mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
- activeXhrs.push(mapKeyXhr);
- }
-
- var initSegmentOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.map.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment.map)
- });
- var initSegmentRequestCallback = handleInitSegmentResponse({
- segment: segment,
- finishProcessingFn: finishProcessingFn
- });
- var initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
- activeXhrs.push(initSegmentXhr);
- }
-
- var segmentRequestOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment)
- });
- var segmentRequestCallback = handleSegmentResponse({
- segment: segment,
- finishProcessingFn: finishProcessingFn,
- responseType: segmentRequestOptions.responseType
- });
- var segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
- segmentXhr.addEventListener('progress', handleProgress({
- segment: segment,
- progressFn: progressFn,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn
- }));
- activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
- // multiple times, provide a shared state object
-
- var loadendState = {};
- activeXhrs.forEach(function (activeXhr) {
- activeXhr.addEventListener('loadend', handleLoadEnd({
- loadendState: loadendState,
- abortFn: abortFn
- }));
- });
- return function () {
- return abortAll(activeXhrs);
- };
-};
-
-/**
- * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
- * codec strings, or translating codec strings into objects that can be examined.
- */
-var logFn$1 = logger('CodecUtils');
-/**
- * Returns a set of codec strings parsed from the playlist or the default
- * codec strings if no codecs were specified in the playlist
- *
- * @param {Playlist} media the current media playlist
- * @return {Object} an object with the video and audio codecs
- */
-
-var getCodecs = function getCodecs(media) {
- // if the codecs were explicitly specified, use them instead of the
- // defaults
- var mediaAttributes = media.attributes || {};
-
- if (mediaAttributes.CODECS) {
- return codecs_js.parseCodecs(mediaAttributes.CODECS);
- }
-};
-
-var isMaat = function isMaat(master, media) {
- var mediaAttributes = media.attributes || {};
- return master && master.mediaGroups && master.mediaGroups.AUDIO && mediaAttributes.AUDIO && master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
-};
-var isMuxed = function isMuxed(master, media) {
- if (!isMaat(master, media)) {
- return true;
- }
-
- var mediaAttributes = media.attributes || {};
- var audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
-
- for (var groupId in audioGroup) {
- // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
- // or there are listed playlists (the case for DASH, as the manifest will have already
- // provided all of the details necessary to generate the audio playlist, as opposed to
- // HLS' externally requested playlists), then the content is demuxed.
- if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
- return true;
- }
- }
-
- return false;
-};
-var unwrapCodecList = function unwrapCodecList(codecList) {
- var codecs = {};
- codecList.forEach(function (_ref) {
- var mediaType = _ref.mediaType,
- type = _ref.type,
- details = _ref.details;
- codecs[mediaType] = codecs[mediaType] || [];
- codecs[mediaType].push(codecs_js.translateLegacyCodec("" + type + details));
- });
- Object.keys(codecs).forEach(function (mediaType) {
- if (codecs[mediaType].length > 1) {
- logFn$1("multiple " + mediaType + " codecs found as attributes: " + codecs[mediaType].join(', ') + ". Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.");
- codecs[mediaType] = null;
- return;
- }
-
- codecs[mediaType] = codecs[mediaType][0];
- });
- return codecs;
-};
-var codecCount = function codecCount(codecObj) {
- var count = 0;
-
- if (codecObj.audio) {
- count++;
- }
-
- if (codecObj.video) {
- count++;
- }
-
- return count;
-};
-/**
- * Calculates the codec strings for a working configuration of
- * SourceBuffers to play variant streams in a master playlist. If
- * there is no possible working configuration, an empty object will be
- * returned.
- *
- * @param master {Object} the m3u8 object for the master playlist
- * @param media {Object} the m3u8 object for the variant playlist
- * @return {Object} the codec strings.
- *
- * @private
- */
-
-var codecsForPlaylist = function codecsForPlaylist(master, media) {
- var mediaAttributes = media.attributes || {};
- var codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
- // Put another way, there is no way to have a video-only multiple-audio HLS!
-
- if (isMaat(master, media) && !codecInfo.audio) {
- if (!isMuxed(master, media)) {
- // It is possible for codecs to be specified on the audio media group playlist but
- // not on the rendition playlist. This is mostly the case for DASH, where audio and
- // video are always separate (and separately specified).
- var defaultCodecs = unwrapCodecList(codecs_js.codecsFromDefault(master, mediaAttributes.AUDIO) || []);
-
- if (defaultCodecs.audio) {
- codecInfo.audio = defaultCodecs.audio;
- }
- }
- }
-
- return codecInfo;
-};
-
-var logFn = logger('PlaylistSelector');
-
-var representationToString = function representationToString(representation) {
- if (!representation || !representation.playlist) {
- return;
- }
-
- var playlist = representation.playlist;
- return JSON.stringify({
- id: playlist.id,
- bandwidth: representation.bandwidth,
- width: representation.width,
- height: representation.height,
- codecs: playlist.attributes && playlist.attributes.CODECS || ''
- });
-}; // Utilities
-
-/**
- * Returns the CSS value for the specified property on an element
- * using `getComputedStyle`. Firefox has a long-standing issue where
- * getComputedStyle() may return null when running in an iframe with
- * `display: none`.
- *
- * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
- * @param {HTMLElement} el the htmlelement to work on
- * @param {string} the proprety to get the style for
- */
-
-
-var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
- if (!el) {
- return '';
- }
-
- var result = window__default['default'].getComputedStyle(el);
-
- if (!result) {
- return '';
- }
-
- return result[property];
-};
-/**
- * Resuable stable sort function
- *
- * @param {Playlists} array
- * @param {Function} sortFn Different comparators
- * @function stableSort
- */
-
-
-var stableSort = function stableSort(array, sortFn) {
- var newArray = array.slice();
- array.sort(function (left, right) {
- var cmp = sortFn(left, right);
-
- if (cmp === 0) {
- return newArray.indexOf(left) - newArray.indexOf(right);
- }
-
- return cmp;
- });
-};
-/**
- * A comparator function to sort two playlist object by bandwidth.
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the bandwidth attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the bandwidth of right is greater than left and
- * exactly zero if the two are equal.
- */
-
-
-var comparePlaylistBandwidth = function comparePlaylistBandwidth(left, right) {
- var leftBandwidth;
- var rightBandwidth;
-
- if (left.attributes.BANDWIDTH) {
- leftBandwidth = left.attributes.BANDWIDTH;
- }
-
- leftBandwidth = leftBandwidth || window__default['default'].Number.MAX_VALUE;
-
- if (right.attributes.BANDWIDTH) {
- rightBandwidth = right.attributes.BANDWIDTH;
- }
-
- rightBandwidth = rightBandwidth || window__default['default'].Number.MAX_VALUE;
- return leftBandwidth - rightBandwidth;
-};
-/**
- * A comparator function to sort two playlist object by resolution (width).
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the resolution.width attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the resolution.width of right is greater than left and
- * exactly zero if the two are equal.
- */
-
-var comparePlaylistResolution = function comparePlaylistResolution(left, right) {
- var leftWidth;
- var rightWidth;
-
- if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
- leftWidth = left.attributes.RESOLUTION.width;
- }
-
- leftWidth = leftWidth || window__default['default'].Number.MAX_VALUE;
-
- if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
- rightWidth = right.attributes.RESOLUTION.width;
- }
-
- rightWidth = rightWidth || window__default['default'].Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
- // have the same media dimensions/ resolution
-
- if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
- return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
- }
-
- return leftWidth - rightWidth;
-};
-/**
- * Chooses the appropriate media playlist based on bandwidth and player size
- *
- * @param {Object} master
- * Object representation of the master manifest
- * @param {number} playerBandwidth
- * Current calculated bandwidth of the player
- * @param {number} playerWidth
- * Current width of the player element (should account for the device pixel ratio)
- * @param {number} playerHeight
- * Current height of the player element (should account for the device pixel ratio)
- * @param {boolean} limitRenditionByPlayerDimensions
- * True if the player width and height should be used during the selection, false otherwise
- * @param {Object} masterPlaylistController
- * the current masterPlaylistController object
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-
-var simpleSelector = function simpleSelector(master, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, masterPlaylistController) {
- // If we end up getting called before `master` is available, exit early
- if (!master) {
- return;
- }
-
- var options = {
- bandwidth: playerBandwidth,
- width: playerWidth,
- height: playerHeight,
- limitRenditionByPlayerDimensions: limitRenditionByPlayerDimensions
- };
- var playlists = master.playlists; // if playlist is audio only, select between currently active audio group playlists.
-
- if (Playlist.isAudioOnly(master)) {
- playlists = masterPlaylistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
- // at the buttom of this function for debugging.
-
- options.audioOnly = true;
- } // convert the playlists to an intermediary representation to make comparisons easier
-
-
- var sortedPlaylistReps = playlists.map(function (playlist) {
- var bandwidth;
- var width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
- var height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
- bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
- bandwidth = bandwidth || window__default['default'].Number.MAX_VALUE;
- return {
- bandwidth: bandwidth,
- width: width,
- height: height,
- playlist: playlist
- };
- });
- stableSort(sortedPlaylistReps, function (left, right) {
- return left.bandwidth - right.bandwidth;
- }); // filter out any playlists that have been excluded due to
- // incompatible configurations
-
- sortedPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return !Playlist.isIncompatible(rep.playlist);
- }); // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
-
- var enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return Playlist.isEnabled(rep.playlist);
- });
-
- if (!enabledPlaylistReps.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return !Playlist.isDisabled(rep.playlist);
- });
- } // filter out any variant that has greater effective bitrate
- // than the current estimated bandwidth
-
-
- var bandwidthPlaylistReps = enabledPlaylistReps.filter(function (rep) {
- return rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth;
- });
- var highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
- // and then taking the very first element
-
- var bandwidthBestRep = bandwidthPlaylistReps.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0]; // if we're not going to limit renditions by player size, make an early decision.
-
- if (limitRenditionByPlayerDimensions === false) {
- var _chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
-
- if (_chosenRep && _chosenRep.playlist) {
- var type = 'sortedPlaylistReps';
-
- if (bandwidthBestRep) {
- type = 'bandwidthBestRep';
- }
-
- if (enabledPlaylistReps[0]) {
- type = 'enabledPlaylistReps';
- }
-
- logFn("choosing " + representationToString(_chosenRep) + " using " + type + " with options", options);
- return _chosenRep.playlist;
- }
-
- logFn('could not choose a playlist with options', options);
- return null;
- } // filter out playlists without resolution information
-
-
- var haveResolution = bandwidthPlaylistReps.filter(function (rep) {
- return rep.width && rep.height;
- }); // sort variants by resolution
-
- stableSort(haveResolution, function (left, right) {
- return left.width - right.width;
- }); // if we have the exact resolution as the player use it
-
- var resolutionBestRepList = haveResolution.filter(function (rep) {
- return rep.width === playerWidth && rep.height === playerHeight;
- });
- highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
-
- var resolutionBestRep = resolutionBestRepList.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0];
- var resolutionPlusOneList;
- var resolutionPlusOneSmallest;
- var resolutionPlusOneRep; // find the smallest variant that is larger than the player
- // if there is no match of exact resolution
-
- if (!resolutionBestRep) {
- resolutionPlusOneList = haveResolution.filter(function (rep) {
- return rep.width > playerWidth || rep.height > playerHeight;
- }); // find all the variants have the same smallest resolution
-
- resolutionPlusOneSmallest = resolutionPlusOneList.filter(function (rep) {
- return rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height;
- }); // ensure that we also pick the highest bandwidth variant that
- // is just-larger-than the video player
-
- highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
- resolutionPlusOneRep = resolutionPlusOneSmallest.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0];
- } // fallback chain of variants
-
-
- var chosenRep = resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
-
- if (chosenRep && chosenRep.playlist) {
- var _type = 'sortedPlaylistReps';
-
- if (resolutionPlusOneRep) {
- _type = 'resolutionPlusOneRep';
- } else if (resolutionBestRep) {
- _type = 'resolutionBestRep';
- } else if (bandwidthBestRep) {
- _type = 'bandwidthBestRep';
- } else if (enabledPlaylistReps[0]) {
- _type = 'enabledPlaylistReps';
- }
-
- logFn("choosing " + representationToString(chosenRep) + " using " + _type + " with options", options);
- return chosenRep.playlist;
- }
-
- logFn('could not choose a playlist with options', options);
- return null;
-};
-
-/**
- * Chooses the appropriate media playlist based on the most recent
- * bandwidth estimate and the player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-
-var lastBandwidthSelector = function lastBandwidthSelector() {
- var pixelRatio = this.useDevicePixelRatio ? window__default['default'].devicePixelRatio || 1 : 1;
- return simpleSelector(this.playlists.master, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
-};
-/**
- * Chooses the appropriate media playlist based on an
- * exponential-weighted moving average of the bandwidth after
- * filtering for player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @param {number} decay - a number between 0 and 1. Higher values of
- * this parameter will cause previous bandwidth estimates to lose
- * significance more quickly.
- * @return {Function} a function which can be invoked to create a new
- * playlist selector function.
- * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
- */
-
-var movingAverageBandwidthSelector = function movingAverageBandwidthSelector(decay) {
- var average = -1;
- var lastSystemBandwidth = -1;
-
- if (decay < 0 || decay > 1) {
- throw new Error('Moving average bandwidth decay must be between 0 and 1.');
- }
-
- return function () {
- var pixelRatio = this.useDevicePixelRatio ? window__default['default'].devicePixelRatio || 1 : 1;
-
- if (average < 0) {
- average = this.systemBandwidth;
- lastSystemBandwidth = this.systemBandwidth;
- } // stop the average value from decaying for every 250ms
- // when the systemBandwidth is constant
- // and
- // stop average from setting to a very low value when the
- // systemBandwidth becomes 0 in case of chunk cancellation
-
-
- if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
- average = decay * this.systemBandwidth + (1 - decay) * average;
- lastSystemBandwidth = this.systemBandwidth;
- }
-
- return simpleSelector(this.playlists.master, average, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
- };
-};
-/**
- * Chooses the appropriate media playlist based on the potential to rebuffer
- *
- * @param {Object} settings
- * Object of information required to use this selector
- * @param {Object} settings.master
- * Object representation of the master manifest
- * @param {number} settings.currentTime
- * The current time of the player
- * @param {number} settings.bandwidth
- * Current measured bandwidth
- * @param {number} settings.duration
- * Duration of the media
- * @param {number} settings.segmentDuration
- * Segment duration to be used in round trip time calculations
- * @param {number} settings.timeUntilRebuffer
- * Time left in seconds until the player has to rebuffer
- * @param {number} settings.currentTimeline
- * The current timeline segments are being loaded from
- * @param {SyncController} settings.syncController
- * SyncController for determining if we have a sync point for a given playlist
- * @return {Object|null}
- * {Object} return.playlist
- * The highest bandwidth playlist with the least amount of rebuffering
- * {Number} return.rebufferingImpact
- * The amount of time in seconds switching to this playlist will rebuffer. A
- * negative value means that switching will cause zero rebuffering.
- */
-
-var minRebufferMaxBandwidthSelector = function minRebufferMaxBandwidthSelector(settings) {
- var master = settings.master,
- currentTime = settings.currentTime,
- bandwidth = settings.bandwidth,
- duration = settings.duration,
- segmentDuration = settings.segmentDuration,
- timeUntilRebuffer = settings.timeUntilRebuffer,
- currentTimeline = settings.currentTimeline,
- syncController = settings.syncController; // filter out any playlists that have been excluded due to
- // incompatible configurations
-
- var compatiblePlaylists = master.playlists.filter(function (playlist) {
- return !Playlist.isIncompatible(playlist);
- }); // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
-
- var enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
-
- if (!enabledPlaylists.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylists = compatiblePlaylists.filter(function (playlist) {
- return !Playlist.isDisabled(playlist);
- });
- }
-
- var bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
- var rebufferingEstimates = bandwidthPlaylists.map(function (playlist) {
- var syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
- // sync request first. This will double the request time
-
- var numRequests = syncPoint ? 1 : 2;
- var requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
- var rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
- return {
- playlist: playlist,
- rebufferingImpact: rebufferingImpact
- };
- });
- var noRebufferingPlaylists = rebufferingEstimates.filter(function (estimate) {
- return estimate.rebufferingImpact <= 0;
- }); // Sort by bandwidth DESC
-
- stableSort(noRebufferingPlaylists, function (a, b) {
- return comparePlaylistBandwidth(b.playlist, a.playlist);
- });
-
- if (noRebufferingPlaylists.length) {
- return noRebufferingPlaylists[0];
- }
-
- stableSort(rebufferingEstimates, function (a, b) {
- return a.rebufferingImpact - b.rebufferingImpact;
- });
- return rebufferingEstimates[0] || null;
-};
-/**
- * Chooses the appropriate media playlist, which in this case is the lowest bitrate
- * one with video. If no renditions with video exist, return the lowest audio rendition.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Object|null}
- * {Object} return.playlist
- * The lowest bitrate playlist that contains a video codec. If no such rendition
- * exists pick the lowest audio rendition.
- */
-
-var lowestBitrateCompatibleVariantSelector = function lowestBitrateCompatibleVariantSelector() {
- var _this = this;
-
- // filter out any playlists that have been excluded due to
- // incompatible configurations or playback errors
- var playlists = this.playlists.master.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
-
- stableSort(playlists, function (a, b) {
- return comparePlaylistBandwidth(a, b);
- }); // Parse and assume that playlists with no video codec have no video
- // (this is not necessarily true, although it is generally true).
- //
- // If an entire manifest has no valid videos everything will get filtered
- // out.
-
- var playlistsWithVideo = playlists.filter(function (playlist) {
- return !!codecsForPlaylist(_this.playlists.master, playlist).video;
- });
- return playlistsWithVideo[0] || null;
-};
-
-/**
- * Combine all segments into a single Uint8Array
- *
- * @param {Object} segmentObj
- * @return {Uint8Array} concatenated bytes
- * @private
- */
-var concatSegments = function concatSegments(segmentObj) {
- var offset = 0;
- var tempBuffer;
-
- if (segmentObj.bytes) {
- tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
-
- segmentObj.segments.forEach(function (segment) {
- tempBuffer.set(segment, offset);
- offset += segment.byteLength;
- });
- }
-
- return tempBuffer;
-};
-
-/**
- * @file text-tracks.js
- */
-/**
- * Create captions text tracks on video.js if they do not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {Object} tech the video.js tech
- * @param {Object} captionStream the caption stream to create
- * @private
- */
-
-var createCaptionsTrackIfNotExists = function createCaptionsTrackIfNotExists(inbandTextTracks, tech, captionStream) {
- if (!inbandTextTracks[captionStream]) {
- tech.trigger({
- type: 'usage',
- name: 'vhs-608'
- });
- tech.trigger({
- type: 'usage',
- name: 'hls-608'
- });
- var instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
-
- if (/^cc708_/.test(captionStream)) {
- instreamId = 'SERVICE' + captionStream.split('_')[1];
- }
-
- var track = tech.textTracks().getTrackById(instreamId);
-
- if (track) {
- // Resuse an existing track with a CC# id because this was
- // very likely created by videojs-contrib-hls from information
- // in the m3u8 for us to use
- inbandTextTracks[captionStream] = track;
- } else {
- // This section gets called when we have caption services that aren't specified in the manifest.
- // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
- var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
- var label = captionStream;
- var language = captionStream;
- var def = false;
- var captionService = captionServices[instreamId];
-
- if (captionService) {
- label = captionService.label;
- language = captionService.language;
- def = captionService.default;
- } // Otherwise, create a track with the default `CC#` label and
- // without a language
-
-
- inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
- kind: 'captions',
- id: instreamId,
- // TODO: investigate why this doesn't seem to turn the caption on by default
- default: def,
- label: label,
- language: language
- }, false).track;
- }
- }
-};
-/**
- * Add caption text track data to a source handler given an array of captions
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {Array} captionArray an array of caption data
- * @private
- */
-
-var addCaptionData = function addCaptionData(_ref) {
- var inbandTextTracks = _ref.inbandTextTracks,
- captionArray = _ref.captionArray,
- timestampOffset = _ref.timestampOffset;
-
- if (!captionArray) {
- return;
- }
-
- var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
- captionArray.forEach(function (caption) {
- var track = caption.stream;
- inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
- });
-};
-/**
- * Define properties on a cue for backwards compatability,
- * but warn the user that the way that they are using it
- * is depricated and will be removed at a later date.
- *
- * @param {Cue} cue the cue to add the properties on
- * @private
- */
-
-var deprecateOldCue = function deprecateOldCue(cue) {
- Object.defineProperties(cue.frame, {
- id: {
- get: function get() {
- videojs__default['default'].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
- return cue.value.key;
- }
- },
- value: {
- get: function get() {
- videojs__default['default'].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- },
- privateData: {
- get: function get() {
- videojs__default['default'].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- }
- });
-};
-/**
- * Add metadata text track data to a source handler given an array of metadata
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {Array} metadataArray an array of meta data
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {number} videoDuration the duration of the video
- * @private
- */
-
-
-var addMetadata = function addMetadata(_ref2) {
- var inbandTextTracks = _ref2.inbandTextTracks,
- metadataArray = _ref2.metadataArray,
- timestampOffset = _ref2.timestampOffset,
- videoDuration = _ref2.videoDuration;
-
- if (!metadataArray) {
- return;
- }
-
- var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
- var metadataTrack = inbandTextTracks.metadataTrack_;
-
- if (!metadataTrack) {
- return;
- }
-
- metadataArray.forEach(function (metadata) {
- var time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
- // ignore this bit of metadata.
- // This likely occurs when you have an non-timed ID3 tag like TIT2,
- // which is the "Title/Songname/Content description" frame
-
- if (typeof time !== 'number' || window__default['default'].isNaN(time) || time < 0 || !(time < Infinity)) {
- return;
- }
-
- metadata.frames.forEach(function (frame) {
- var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
- cue.frame = frame;
- cue.value = frame;
- deprecateOldCue(cue);
- metadataTrack.addCue(cue);
- });
- });
-
- if (!metadataTrack.cues || !metadataTrack.cues.length) {
- return;
- } // Updating the metadeta cues so that
- // the endTime of each cue is the startTime of the next cue
- // the endTime of last cue is the duration of the video
-
-
- var cues = metadataTrack.cues;
- var cuesArray = []; // Create a copy of the TextTrackCueList...
- // ...disregarding cues with a falsey value
-
- for (var i = 0; i < cues.length; i++) {
- if (cues[i]) {
- cuesArray.push(cues[i]);
- }
- } // Group cues by their startTime value
-
-
- var cuesGroupedByStartTime = cuesArray.reduce(function (obj, cue) {
- var timeSlot = obj[cue.startTime] || [];
- timeSlot.push(cue);
- obj[cue.startTime] = timeSlot;
- return obj;
- }, {}); // Sort startTimes by ascending order
-
- var sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort(function (a, b) {
- return Number(a) - Number(b);
- }); // Map each cue group's endTime to the next group's startTime
-
- sortedStartTimes.forEach(function (startTime, idx) {
- var cueGroup = cuesGroupedByStartTime[startTime];
- var nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
-
- cueGroup.forEach(function (cue) {
- cue.endTime = nextTime;
- });
- });
-};
-/**
- * Create metadata text track on video.js if it does not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {string} dispatchType the inband metadata track dispatch type
- * @param {Object} tech the video.js tech
- * @private
- */
-
-var createMetadataTrackIfNotExists = function createMetadataTrackIfNotExists(inbandTextTracks, dispatchType, tech) {
- if (inbandTextTracks.metadataTrack_) {
- return;
- }
-
- inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'Timed Metadata'
- }, false).track;
- inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
-};
-/**
- * Remove cues from a track on video.js.
- *
- * @param {Double} start start of where we should remove the cue
- * @param {Double} end end of where the we should remove the cue
- * @param {Object} track the text track to remove the cues from
- * @private
- */
-
-var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
- var i;
- var cue;
-
- if (!track) {
- return;
- }
-
- if (!track.cues) {
- return;
- }
-
- i = track.cues.length;
-
- while (i--) {
- cue = track.cues[i]; // Remove any cue within the provided start and end time
-
- if (cue.startTime >= start && cue.endTime <= end) {
- track.removeCue(cue);
- }
- }
-};
-/**
- * Remove duplicate cues from a track on video.js (a cue is considered a
- * duplicate if it has the same time interval and text as another)
- *
- * @param {Object} track the text track to remove the duplicate cues from
- * @private
- */
-
-var removeDuplicateCuesFromTrack = function removeDuplicateCuesFromTrack(track) {
- var cues = track.cues;
-
- if (!cues) {
- return;
- }
-
- for (var i = 0; i < cues.length; i++) {
- var duplicates = [];
- var occurrences = 0;
-
- for (var j = 0; j < cues.length; j++) {
- if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
- occurrences++;
-
- if (occurrences > 1) {
- duplicates.push(cues[j]);
- }
- }
- }
-
- if (duplicates.length) {
- duplicates.forEach(function (dupe) {
- return track.removeCue(dupe);
- });
- }
- }
-};
-
-/**
- * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
- * front of current time.
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {number} currentTime
- * The current time
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- * @return {Array}
- * List of gops considered safe to append over
- */
-
-var gopsSafeToAlignWith = function gopsSafeToAlignWith(buffer, currentTime, mapping) {
- if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
- return [];
- } // pts value for current time + 3 seconds to give a bit more wiggle room
-
-
- var currentTimePts = Math.ceil((currentTime - mapping + 3) * clock.ONE_SECOND_IN_TS);
- var i;
-
- for (i = 0; i < buffer.length; i++) {
- if (buffer[i].pts > currentTimePts) {
- break;
- }
- }
-
- return buffer.slice(i);
-};
-/**
- * Appends gop information (timing and byteLength) received by the transmuxer for the
- * gops appended in the last call to appendBuffer
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Array} gops
- * List of new gop information
- * @param {boolean} replace
- * If true, replace the buffer with the new gop information. If false, append the
- * new gop information to the buffer in the right location of time.
- * @return {Array}
- * Updated list of gop information
- */
-
-var updateGopBuffer = function updateGopBuffer(buffer, gops, replace) {
- if (!gops.length) {
- return buffer;
- }
-
- if (replace) {
- // If we are in safe append mode, then completely overwrite the gop buffer
- // with the most recent appeneded data. This will make sure that when appending
- // future segments, we only try to align with gops that are both ahead of current
- // time and in the last segment appended.
- return gops.slice();
- }
-
- var start = gops[0].pts;
- var i = 0;
-
- for (i; i < buffer.length; i++) {
- if (buffer[i].pts >= start) {
- break;
- }
- }
-
- return buffer.slice(0, i).concat(gops);
-};
-/**
- * Removes gop information in buffer that overlaps with provided start and end
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Double} start
- * position to start the remove at
- * @param {Double} end
- * position to end the remove at
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- */
-
-var removeGopBuffer = function removeGopBuffer(buffer, start, end, mapping) {
- var startPts = Math.ceil((start - mapping) * clock.ONE_SECOND_IN_TS);
- var endPts = Math.ceil((end - mapping) * clock.ONE_SECOND_IN_TS);
- var updatedBuffer = buffer.slice();
- var i = buffer.length;
-
- while (i--) {
- if (buffer[i].pts <= endPts) {
- break;
- }
- }
-
- if (i === -1) {
- // no removal because end of remove range is before start of buffer
- return updatedBuffer;
- }
-
- var j = i + 1;
-
- while (j--) {
- if (buffer[j].pts <= startPts) {
- break;
- }
- } // clamp remove range start to 0 index
-
-
- j = Math.max(j, 0);
- updatedBuffer.splice(j, i - j + 1);
- return updatedBuffer;
-};
-
-var shallowEqual = function shallowEqual(a, b) {
- // if both are undefined
- // or one or the other is undefined
- // they are not equal
- if (!a && !b || !a && b || a && !b) {
- return false;
- } // they are the same object and thus, equal
-
-
- if (a === b) {
- return true;
- } // sort keys so we can make sure they have
- // all the same keys later.
-
-
- var akeys = Object.keys(a).sort();
- var bkeys = Object.keys(b).sort(); // different number of keys, not equal
-
- if (akeys.length !== bkeys.length) {
- return false;
- }
-
- for (var i = 0; i < akeys.length; i++) {
- var key = akeys[i]; // different sorted keys, not equal
-
- if (key !== bkeys[i]) {
- return false;
- } // different values, not equal
-
-
- if (a[key] !== b[key]) {
- return false;
- }
- }
-
- return true;
-};
-
-// https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
-var QUOTA_EXCEEDED_ERR = 22;
-
-/**
- * The segment loader has no recourse except to fetch a segment in the
- * current playlist and use the internal timestamps in that segment to
- * generate a syncPoint. This function returns a good candidate index
- * for that process.
- *
- * @param {Array} segments - the segments array from a playlist.
- * @return {number} An index of a segment from the playlist to load
- */
-
-var getSyncSegmentCandidate = function getSyncSegmentCandidate(currentTimeline, segments, targetTime) {
- segments = segments || [];
- var timelineSegments = [];
- var time = 0;
-
- for (var i = 0; i < segments.length; i++) {
- var segment = segments[i];
-
- if (currentTimeline === segment.timeline) {
- timelineSegments.push(i);
- time += segment.duration;
-
- if (time > targetTime) {
- return i;
- }
- }
- }
-
- if (timelineSegments.length === 0) {
- return 0;
- } // default to the last timeline segment
-
-
- return timelineSegments[timelineSegments.length - 1];
-}; // In the event of a quota exceeded error, keep at least one second of back buffer. This
-// number was arbitrarily chosen and may be updated in the future, but seemed reasonable
-// as a start to prevent any potential issues with removing content too close to the
-// playhead.
-
-var MIN_BACK_BUFFER = 1; // in ms
-
-var CHECK_BUFFER_DELAY = 500;
-
-var finite = function finite(num) {
- return typeof num === 'number' && isFinite(num);
-}; // With most content hovering around 30fps, if a segment has a duration less than a half
-// frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
-// not accurately reflect the rest of the content.
-
-
-var MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
-var illegalMediaSwitch = function illegalMediaSwitch(loaderType, startingMedia, trackInfo) {
- // Although these checks should most likely cover non 'main' types, for now it narrows
- // the scope of our checks.
- if (loaderType !== 'main' || !startingMedia || !trackInfo) {
- return null;
- }
-
- if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
- return 'Neither audio nor video found in segment.';
- }
-
- if (startingMedia.hasVideo && !trackInfo.hasVideo) {
- return 'Only audio found in segment when we expected video.' + ' We can\'t switch to audio only from a stream that had video.' + ' To get rid of this message, please add codec information to the manifest.';
- }
-
- if (!startingMedia.hasVideo && trackInfo.hasVideo) {
- return 'Video found in segment when we expected only audio.' + ' We can\'t switch to a stream with video from an audio only stream.' + ' To get rid of this message, please add codec information to the manifest.';
- }
-
- return null;
-};
-/**
- * Calculates a time value that is safe to remove from the back buffer without interrupting
- * playback.
- *
- * @param {TimeRange} seekable
- * The current seekable range
- * @param {number} currentTime
- * The current time of the player
- * @param {number} targetDuration
- * The target duration of the current playlist
- * @return {number}
- * Time that is safe to remove from the back buffer without interrupting playback
- */
-
-var safeBackBufferTrimTime = function safeBackBufferTrimTime(seekable, currentTime, targetDuration) {
- // 30 seconds before the playhead provides a safe default for trimming.
- //
- // Choosing a reasonable default is particularly important for high bitrate content and
- // VOD videos/live streams with large windows, as the buffer may end up overfilled and
- // throw an APPEND_BUFFER_ERR.
- var trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
-
- if (seekable.length) {
- // Some live playlists may have a shorter window of content than the full allowed back
- // buffer. For these playlists, don't save content that's no longer within the window.
- trimTime = Math.max(trimTime, seekable.start(0));
- } // Don't remove within target duration of the current time to avoid the possibility of
- // removing the GOP currently being played, as removing it can cause playback stalls.
-
-
- var maxTrimTime = currentTime - targetDuration;
- return Math.min(maxTrimTime, trimTime);
-};
-
-var segmentInfoString = function segmentInfoString(segmentInfo) {
- var startOfSegment = segmentInfo.startOfSegment,
- duration = segmentInfo.duration,
- segment = segmentInfo.segment,
- part = segmentInfo.part,
- _segmentInfo$playlist = segmentInfo.playlist,
- seq = _segmentInfo$playlist.mediaSequence,
- id = _segmentInfo$playlist.id,
- _segmentInfo$playlist2 = _segmentInfo$playlist.segments,
- segments = _segmentInfo$playlist2 === void 0 ? [] : _segmentInfo$playlist2,
- index = segmentInfo.mediaIndex,
- partIndex = segmentInfo.partIndex,
- timeline = segmentInfo.timeline;
- var segmentLen = segments.length - 1;
- var selection = 'mediaIndex/partIndex increment';
-
- if (segmentInfo.getMediaInfoForTime) {
- selection = "getMediaInfoForTime (" + segmentInfo.getMediaInfoForTime + ")";
- } else if (segmentInfo.isSyncRequest) {
- selection = 'getSyncSegmentCandidate (isSyncRequest)';
- }
-
- var hasPartIndex = typeof partIndex === 'number';
- var name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
- var zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
- preloadSegment: segment
- }) - 1 : 0;
- return name + " [" + (seq + index) + "/" + (seq + segmentLen) + "]" + (hasPartIndex ? " part [" + partIndex + "/" + zeroBasedPartCount + "]" : '') + (" segment start/end [" + segment.start + " => " + segment.end + "]") + (hasPartIndex ? " part start/end [" + part.start + " => " + part.end + "]" : '') + (" startOfSegment [" + startOfSegment + "]") + (" duration [" + duration + "]") + (" timeline [" + timeline + "]") + (" selected by [" + selection + "]") + (" playlist [" + id + "]");
-};
-
-var timingInfoPropertyForMedia = function timingInfoPropertyForMedia(mediaType) {
- return mediaType + "TimingInfo";
-};
-/**
- * Returns the timestamp offset to use for the segment.
- *
- * @param {number} segmentTimeline
- * The timeline of the segment
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} startOfSegment
- * The estimated segment start
- * @param {TimeRange[]} buffered
- * The loader's buffer
- * @param {boolean} overrideCheck
- * If true, no checks are made to see if the timestamp offset value should be set,
- * but sets it directly to a value.
- *
- * @return {number|null}
- * Either a number representing a new timestamp offset, or null if the segment is
- * part of the same timeline
- */
-
-
-var timestampOffsetForSegment = function timestampOffsetForSegment(_ref) {
- var segmentTimeline = _ref.segmentTimeline,
- currentTimeline = _ref.currentTimeline,
- startOfSegment = _ref.startOfSegment,
- buffered = _ref.buffered,
- overrideCheck = _ref.overrideCheck;
-
- // Check to see if we are crossing a discontinuity to see if we need to set the
- // timestamp offset on the transmuxer and source buffer.
- //
- // Previously, we changed the timestampOffset if the start of this segment was less than
- // the currently set timestampOffset, but this isn't desirable as it can produce bad
- // behavior, especially around long running live streams.
- if (!overrideCheck && segmentTimeline === currentTimeline) {
- return null;
- } // When changing renditions, it's possible to request a segment on an older timeline. For
- // instance, given two renditions with the following:
- //
- // #EXTINF:10
- // segment1
- // #EXT-X-DISCONTINUITY
- // #EXTINF:10
- // segment2
- // #EXTINF:10
- // segment3
- //
- // And the current player state:
- //
- // current time: 8
- // buffer: 0 => 20
- //
- // The next segment on the current rendition would be segment3, filling the buffer from
- // 20s onwards. However, if a rendition switch happens after segment2 was requested,
- // then the next segment to be requested will be segment1 from the new rendition in
- // order to fill time 8 and onwards. Using the buffered end would result in repeated
- // content (since it would position segment1 of the new rendition starting at 20s). This
- // case can be identified when the new segment's timeline is a prior value. Instead of
- // using the buffered end, the startOfSegment can be used, which, hopefully, will be
- // more accurate to the actual start time of the segment.
-
-
- if (segmentTimeline < currentTimeline) {
- return startOfSegment;
- } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
- // value uses the end of the last segment if it is available. While this value
- // should often be correct, it's better to rely on the buffered end, as the new
- // content post discontinuity should line up with the buffered end as if it were
- // time 0 for the new content.
-
-
- return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
-};
-/**
- * Returns whether or not the loader should wait for a timeline change from the timeline
- * change controller before processing the segment.
- *
- * Primary timing in VHS goes by video. This is different from most media players, as
- * audio is more often used as the primary timing source. For the foreseeable future, VHS
- * will continue to use video as the primary timing source, due to the current logic and
- * expectations built around it.
-
- * Since the timing follows video, in order to maintain sync, the video loader is
- * responsible for setting both audio and video source buffer timestamp offsets.
- *
- * Setting different values for audio and video source buffers could lead to
- * desyncing. The following examples demonstrate some of the situations where this
- * distinction is important. Note that all of these cases involve demuxed content. When
- * content is muxed, the audio and video are packaged together, therefore syncing
- * separate media playlists is not an issue.
- *
- * CASE 1: Audio prepares to load a new timeline before video:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the audio loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the video loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the audio loader goes ahead and loads and appends the 6th segment before the video
- * loader crosses the discontinuity, then when appended, the 6th audio segment will use
- * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
- * the audio loader must provide the audioAppendStart value to trim the content in the
- * transmuxer, and that value relies on the audio timestamp offset. Since the audio
- * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
- * segment until that value is provided.
- *
- * CASE 2: Video prepares to load a new timeline before audio:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the video loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the audio loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the video loader goes ahead and loads and appends the 6th segment, then once the
- * segment is loaded and processed, both the video and audio timestamp offsets will be
- * set, since video is used as the primary timing source. This is to ensure content lines
- * up appropriately, as any modifications to the video timing are reflected by audio when
- * the video loader sets the audio and video timestamp offsets to the same value. However,
- * setting the timestamp offset for audio before audio has had a chance to change
- * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
- * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
- *
- * CASE 3: When seeking, audio prepares to load a new timeline before video
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, both audio and video loaders are loading segments from timeline
- * 0, but imagine that the seek originated from timeline 1.
- *
- * When seeking to a new timeline, the timestamp offset will be set based on the expected
- * segment start of the loaded video segment. In order to maintain sync, the audio loader
- * must wait for the video loader to load its segment and update both the audio and video
- * timestamp offsets before it may load and append its own segment. This is the case
- * whether the seek results in a mismatched segment request (e.g., the audio loader
- * chooses to load segment 3 and the video loader chooses to load segment 4) or the
- * loaders choose to load the same segment index from each playlist, as the segments may
- * not be aligned perfectly, even for matching segment indexes.
- *
- * @param {Object} timelinechangeController
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} segmentTimeline
- * The timeline of the segment being loaded
- * @param {('main'|'audio')} loaderType
- * The loader type
- * @param {boolean} audioDisabled
- * Whether the audio is disabled for the loader. This should only be true when the
- * loader may have muxed audio in its segment, but should not append it, e.g., for
- * the main loader when an alternate audio playlist is active.
- *
- * @return {boolean}
- * Whether the loader should wait for a timeline change from the timeline change
- * controller before processing the segment
- */
-
-var shouldWaitForTimelineChange = function shouldWaitForTimelineChange(_ref2) {
- var timelineChangeController = _ref2.timelineChangeController,
- currentTimeline = _ref2.currentTimeline,
- segmentTimeline = _ref2.segmentTimeline,
- loaderType = _ref2.loaderType,
- audioDisabled = _ref2.audioDisabled;
-
- if (currentTimeline === segmentTimeline) {
- return false;
- }
-
- if (loaderType === 'audio') {
- var lastMainTimelineChange = timelineChangeController.lastTimelineChange({
- type: 'main'
- }); // Audio loader should wait if:
- //
- // * main hasn't had a timeline change yet (thus has not loaded its first segment)
- // * main hasn't yet changed to the timeline audio is looking to load
-
- return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
- } // The main loader only needs to wait for timeline changes if there's demuxed audio.
- // Otherwise, there's nothing to wait for, since audio would be muxed into the main
- // loader's segments (or the content is audio/video only and handled by the main
- // loader).
-
-
- if (loaderType === 'main' && audioDisabled) {
- var pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
- type: 'audio'
- }); // Main loader should wait for the audio loader if audio is not pending a timeline
- // change to the current timeline.
- //
- // Since the main loader is responsible for setting the timestamp offset for both
- // audio and video, the main loader must wait for audio to be about to change to its
- // timeline before setting the offset, otherwise, if audio is behind in loading,
- // segments from the previous timeline would be adjusted by the new timestamp offset.
- //
- // This requirement means that video will not cross a timeline until the audio is
- // about to cross to it, so that way audio and video will always cross the timeline
- // together.
- //
- // In addition to normal timeline changes, these rules also apply to the start of a
- // stream (going from a non-existent timeline, -1, to timeline 0). It's important
- // that these rules apply to the first timeline change because if they did not, it's
- // possible that the main loader will cross two timelines before the audio loader has
- // crossed one. Logic may be implemented to handle the startup as a special case, but
- // it's easier to simply treat all timeline changes the same.
-
- if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
- return false;
- }
-
- return true;
- }
-
- return false;
-};
-var mediaDuration = function mediaDuration(audioTimingInfo, videoTimingInfo) {
- var audioDuration = audioTimingInfo && typeof audioTimingInfo.start === 'number' && typeof audioTimingInfo.end === 'number' ? audioTimingInfo.end - audioTimingInfo.start : 0;
- var videoDuration = videoTimingInfo && typeof videoTimingInfo.start === 'number' && typeof videoTimingInfo.end === 'number' ? videoTimingInfo.end - videoTimingInfo.start : 0;
- return Math.max(audioDuration, videoDuration);
-};
-var segmentTooLong = function segmentTooLong(_ref3) {
- var segmentDuration = _ref3.segmentDuration,
- maxDuration = _ref3.maxDuration;
-
- // 0 duration segments are most likely due to metadata only segments or a lack of
- // information.
- if (!segmentDuration) {
- return false;
- } // For HLS:
- //
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
- // The EXTINF duration of each Media Segment in the Playlist
- // file, when rounded to the nearest integer, MUST be less than or equal
- // to the target duration; longer segments can trigger playback stalls
- // or other errors.
- //
- // For DASH, the mpd-parser uses the largest reported segment duration as the target
- // duration. Although that reported duration is occasionally approximate (i.e., not
- // exact), a strict check may report that a segment is too long more often in DASH.
-
-
- return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
-};
-var getTroublesomeSegmentDurationMessage = function getTroublesomeSegmentDurationMessage(segmentInfo, sourceType) {
- // Right now we aren't following DASH's timing model exactly, so only perform
- // this check for HLS content.
- if (sourceType !== 'hls') {
- return null;
- }
-
- var segmentDuration = mediaDuration(segmentInfo.audioTimingInfo, segmentInfo.videoTimingInfo); // Don't report if we lack information.
- //
- // If the segment has a duration of 0 it is either a lack of information or a
- // metadata only segment and shouldn't be reported here.
-
- if (!segmentDuration) {
- return null;
- }
-
- var targetDuration = segmentInfo.playlist.targetDuration;
- var isSegmentWayTooLong = segmentTooLong({
- segmentDuration: segmentDuration,
- maxDuration: targetDuration * 2
- });
- var isSegmentSlightlyTooLong = segmentTooLong({
- segmentDuration: segmentDuration,
- maxDuration: targetDuration
- });
- var segmentTooLongMessage = "Segment with index " + segmentInfo.mediaIndex + " " + ("from playlist " + segmentInfo.playlist.id + " ") + ("has a duration of " + segmentDuration + " ") + ("when the reported duration is " + segmentInfo.duration + " ") + ("and the target duration is " + targetDuration + ". ") + 'For HLS content, a duration in excess of the target duration may result in ' + 'playback issues. See the HLS specification section on EXT-X-TARGETDURATION for ' + 'more details: ' + 'https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1';
-
- if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
- return {
- severity: isSegmentWayTooLong ? 'warn' : 'info',
- message: segmentTooLongMessage
- };
- }
-
- return null;
-};
-/**
- * An object that manages segment loading and appending.
- *
- * @class SegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-
-var SegmentLoader = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose__default['default'](SegmentLoader, _videojs$EventTarget);
-
- function SegmentLoader(settings, options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this; // check pre-conditions
-
- if (!settings) {
- throw new TypeError('Initialization settings are required');
- }
-
- if (typeof settings.currentTime !== 'function') {
- throw new TypeError('No currentTime getter specified');
- }
-
- if (!settings.mediaSource) {
- throw new TypeError('No MediaSource specified');
- } // public properties
-
-
- _this.bandwidth = settings.bandwidth;
- _this.throughput = {
- rate: 0,
- count: 0
- };
- _this.roundTrip = NaN;
-
- _this.resetStats_();
-
- _this.mediaIndex = null;
- _this.partIndex = null; // private settings
-
- _this.hasPlayed_ = settings.hasPlayed;
- _this.currentTime_ = settings.currentTime;
- _this.seekable_ = settings.seekable;
- _this.seeking_ = settings.seeking;
- _this.duration_ = settings.duration;
- _this.mediaSource_ = settings.mediaSource;
- _this.vhs_ = settings.vhs;
- _this.loaderType_ = settings.loaderType;
- _this.currentMediaInfo_ = void 0;
- _this.startingMediaInfo_ = void 0;
- _this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
- _this.goalBufferLength_ = settings.goalBufferLength;
- _this.sourceType_ = settings.sourceType;
- _this.sourceUpdater_ = settings.sourceUpdater;
- _this.inbandTextTracks_ = settings.inbandTextTracks;
- _this.state_ = 'INIT';
- _this.timelineChangeController_ = settings.timelineChangeController;
- _this.shouldSaveSegmentTimingInfo_ = true;
- _this.parse708captions_ = settings.parse708captions; // private instance variables
-
- _this.checkBufferTimeout_ = null;
- _this.error_ = void 0;
- _this.currentTimeline_ = -1;
- _this.pendingSegment_ = null;
- _this.xhrOptions_ = null;
- _this.pendingSegments_ = [];
- _this.audioDisabled_ = false;
- _this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
-
- _this.gopBuffer_ = [];
- _this.timeMapping_ = 0;
- _this.safeAppend_ = videojs__default['default'].browser.IE_VERSION >= 11;
- _this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- _this.playlistOfLastInitSegment_ = {
- audio: null,
- video: null
- };
- _this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
- // information yet to start the loading process (e.g., if the audio loader wants to
- // load a segment from the next timeline but the main loader hasn't yet crossed that
- // timeline), then the load call will be added to the queue until it is ready to be
- // processed.
-
- _this.loadQueue_ = [];
- _this.metadataQueue_ = {
- id3: [],
- caption: []
- };
- _this.waitingOnRemove_ = false;
- _this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
-
- _this.activeInitSegmentId_ = null;
- _this.initSegments_ = {}; // HLSe playback
-
- _this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
- _this.keyCache_ = {};
- _this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
- // between a time in the display time and a segment index within
- // a playlist
-
- _this.syncController_ = settings.syncController;
- _this.syncPoint_ = {
- segmentIndex: 0,
- time: 0
- };
- _this.transmuxer_ = _this.createTransmuxer_();
-
- _this.triggerSyncInfoUpdate_ = function () {
- return _this.trigger('syncinfoupdate');
- };
-
- _this.syncController_.on('syncinfoupdate', _this.triggerSyncInfoUpdate_);
-
- _this.mediaSource_.addEventListener('sourceopen', function () {
- if (!_this.isEndOfStream_()) {
- _this.ended_ = false;
- }
- }); // ...for determining the fetch location
-
-
- _this.fetchAtBuffer_ = false;
- _this.logger_ = logger("SegmentLoader[" + _this.loaderType_ + "]");
- Object.defineProperty(_assertThisInitialized__default['default'](_this), 'state', {
- get: function get() {
- return this.state_;
- },
- set: function set(newState) {
- if (newState !== this.state_) {
- this.logger_(this.state_ + " -> " + newState);
- this.state_ = newState;
- this.trigger('statechange');
- }
- }
- });
-
- _this.sourceUpdater_.on('ready', function () {
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- }); // Only the main loader needs to listen for pending timeline changes, as the main
- // loader should wait for audio to be ready to change its timeline so that both main
- // and audio timelines change together. For more details, see the
- // shouldWaitForTimelineChange function.
-
-
- if (_this.loaderType_ === 'main') {
- _this.timelineChangeController_.on('pendingtimelinechange', function () {
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- });
- } // The main loader only listens on pending timeline changes, but the audio loader,
- // since its loads follow main, needs to listen on timeline changes. For more details,
- // see the shouldWaitForTimelineChange function.
-
-
- if (_this.loaderType_ === 'audio') {
- _this.timelineChangeController_.on('timelinechange', function () {
- if (_this.hasEnoughInfoToLoad_()) {
- _this.processLoadQueue_();
- }
-
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- });
- }
-
- return _this;
- }
-
- var _proto = SegmentLoader.prototype;
-
- _proto.createTransmuxer_ = function createTransmuxer_() {
- return segmentTransmuxer.createTransmuxer({
- remux: false,
- alignGopsAtEnd: this.safeAppend_,
- keepOriginalTimestamps: true,
- parse708captions: this.parse708captions_
- });
- }
- /**
- * reset all of our media stats
- *
- * @private
- */
- ;
-
- _proto.resetStats_ = function resetStats_() {
- this.mediaBytesTransferred = 0;
- this.mediaRequests = 0;
- this.mediaRequestsAborted = 0;
- this.mediaRequestsTimedout = 0;
- this.mediaRequestsErrored = 0;
- this.mediaTransferDuration = 0;
- this.mediaSecondsLoaded = 0;
- this.mediaAppends = 0;
- }
- /**
- * dispose of the SegmentLoader and reset to the default state
- */
- ;
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.state = 'DISPOSED';
- this.pause();
- this.abort_();
-
- if (this.transmuxer_) {
- this.transmuxer_.terminate();
- }
-
- this.resetStats_();
-
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- }
-
- if (this.syncController_ && this.triggerSyncInfoUpdate_) {
- this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
- }
-
- this.off();
- };
-
- _proto.setAudio = function setAudio(enable) {
- this.audioDisabled_ = !enable;
-
- if (enable) {
- this.appendInitSegment_.audio = true;
- } else {
- // remove current track audio if it gets disabled
- this.sourceUpdater_.removeAudio(0, this.duration_());
- }
- }
- /**
- * abort anything that is currently doing on with the SegmentLoader
- * and reset to a default state
- */
- ;
-
- _proto.abort = function abort() {
- if (this.state !== 'WAITING') {
- if (this.pendingSegment_) {
- this.pendingSegment_ = null;
- }
-
- return;
- }
-
- this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
- // since we are no longer "waiting" on any requests. XHR callback is not always run
- // when the request is aborted. This will prevent the loader from being stuck in the
- // WAITING state indefinitely.
-
- this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
- // next segment
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
- /**
- * abort all pending xhr requests and null any pending segements
- *
- * @private
- */
- ;
-
- _proto.abort_ = function abort_() {
- if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
- this.pendingSegment_.abortRequests();
- } // clear out the segment being processed
-
-
- this.pendingSegment_ = null;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
- this.waitingOnRemove_ = false;
- window__default['default'].clearTimeout(this.quotaExceededErrorRetryTimeout_);
- this.quotaExceededErrorRetryTimeout_ = null;
- };
-
- _proto.checkForAbort_ = function checkForAbort_(requestId) {
- // If the state is APPENDING, then aborts will not modify the state, meaning the first
- // callback that happens should reset the state to READY so that loading can continue.
- if (this.state === 'APPENDING' && !this.pendingSegment_) {
- this.state = 'READY';
- return true;
- }
-
- if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
- return true;
- }
-
- return false;
- }
- /**
- * set an error on the segment loader and null out any pending segements
- *
- * @param {Error} error the error to set on the SegmentLoader
- * @return {Error} the error that was set or that is currently set
- */
- ;
-
- _proto.error = function error(_error) {
- if (typeof _error !== 'undefined') {
- this.logger_('error occurred:', _error);
- this.error_ = _error;
- }
-
- this.pendingSegment_ = null;
- return this.error_;
- };
-
- _proto.endOfStream = function endOfStream() {
- this.ended_ = true;
-
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
-
- this.gopBuffer_.length = 0;
- this.pause();
- this.trigger('ended');
- }
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- ;
-
- _proto.buffered_ = function buffered_() {
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- return videojs__default['default'].createTimeRanges();
- }
-
- if (this.loaderType_ === 'main') {
- var _this$startingMediaIn = this.startingMediaInfo_,
- hasAudio = _this$startingMediaIn.hasAudio,
- hasVideo = _this$startingMediaIn.hasVideo,
- isMuxed = _this$startingMediaIn.isMuxed;
-
- if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
- return this.sourceUpdater_.buffered();
- }
-
- if (hasVideo) {
- return this.sourceUpdater_.videoBuffered();
- }
- } // One case that can be ignored for now is audio only with alt audio,
- // as we don't yet have proper support for that.
-
-
- return this.sourceUpdater_.audioBuffered();
- }
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- ;
-
- _proto.initSegmentForMap = function initSegmentForMap(map, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!map) {
- return null;
- }
-
- var id = initSegmentId(map);
- var storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: map.bytes,
- tracks: map.tracks,
- timescales: map.timescales
- };
- }
-
- return storedMap || map;
- }
- /**
- * Gets and sets key for the provided key
- *
- * @param {Object} key
- * The key object representing the key to get or set
- * @param {boolean=} set
- * If true, the key for the provided key should be saved
- * @return {Object}
- * Key object for desired key
- */
- ;
-
- _proto.segmentKey = function segmentKey(key, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!key) {
- return null;
- }
-
- var id = segmentKeyId(key);
- var storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
-
- if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
- this.keyCache_[id] = storedKey = {
- resolvedUri: key.resolvedUri,
- bytes: key.bytes
- };
- }
-
- var result = {
- resolvedUri: (storedKey || key).resolvedUri
- };
-
- if (storedKey) {
- result.bytes = storedKey.bytes;
- }
-
- return result;
- }
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- ;
-
- _proto.couldBeginLoading_ = function couldBeginLoading_() {
- return this.playlist_ && !this.paused();
- }
- /**
- * load a playlist and start to fill the buffer
- */
- ;
-
- _proto.load = function load() {
- // un-pause
- this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
- // specified
-
- if (!this.playlist_) {
- return;
- } // if all the configuration is ready, initialize and begin loading
-
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- } // if we're in the middle of processing a segment already, don't
- // kick off an additional segment request
-
-
- if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
- return;
- }
-
- this.state = 'READY';
- }
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- ;
-
- _proto.init_ = function init_() {
- this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
- // audio data from the muxed content should be removed
-
- this.resetEverything();
- return this.monitorBuffer_();
- }
- /**
- * set a playlist on the segment loader
- *
- * @param {PlaylistLoader} media the playlist to set on the segment loader
- */
- ;
-
- _proto.playlist = function playlist(newPlaylist, options) {
- if (options === void 0) {
- options = {};
- }
-
- if (!newPlaylist) {
- return;
- }
-
- var oldPlaylist = this.playlist_;
- var segmentInfo = this.pendingSegment_;
- this.playlist_ = newPlaylist;
- this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
- // is always our zero-time so force a sync update each time the playlist
- // is refreshed from the server
- //
- // Use the INIT state to determine if playback has started, as the playlist sync info
- // should be fixed once requests begin (as sync points are generated based on sync
- // info), but not before then.
-
- if (this.state === 'INIT') {
- newPlaylist.syncInfo = {
- mediaSequence: newPlaylist.mediaSequence,
- time: 0
- }; // Setting the date time mapping means mapping the program date time (if available)
- // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
- // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
- // be updated as the playlist is refreshed before the loader starts loading, the
- // program date time mapping needs to be updated as well.
- //
- // This mapping is only done for the main loader because a program date time should
- // map equivalently between playlists.
-
- if (this.loaderType_ === 'main') {
- this.syncController_.setDateTimeMappingForStart(newPlaylist);
- }
- }
-
- var oldId = null;
-
- if (oldPlaylist) {
- if (oldPlaylist.id) {
- oldId = oldPlaylist.id;
- } else if (oldPlaylist.uri) {
- oldId = oldPlaylist.uri;
- }
- }
-
- this.logger_("playlist update [" + oldId + " => " + (newPlaylist.id || newPlaylist.uri) + "]"); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
- // in LIVE, we always want to update with new playlists (including refreshes)
-
- this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
- // buffering now
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- }
-
- if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
- if (this.mediaIndex !== null) {
- // we must "resync" the segment loader when we switch renditions and
- // the segment loader is already synced to the previous rendition
- this.resyncLoader();
- }
-
- this.currentMediaInfo_ = void 0;
- this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
-
- return;
- } // we reloaded the same playlist so we are in a live scenario
- // and we will likely need to adjust the mediaIndex
-
-
- var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
- this.logger_("live window shift [" + mediaSequenceDiff + "]"); // update the mediaIndex on the SegmentLoader
- // this is important because we can abort a request and this value must be
- // equal to the last appended mediaIndex
-
- if (this.mediaIndex !== null) {
- this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
- // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
- // new playlist was incremented by 1.
-
- if (this.mediaIndex < 0) {
- this.mediaIndex = null;
- this.partIndex = null;
- } else {
- var segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
- // unless parts fell off of the playlist for this segment.
- // In that case we need to reset partIndex and resync
-
- if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
- var mediaIndex = this.mediaIndex;
- this.logger_("currently processing part (index " + this.partIndex + ") no longer exists.");
- this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
- // as the part was dropped from our current playlists segment.
- // The mediaIndex will still be valid so keep that around.
-
- this.mediaIndex = mediaIndex;
- }
- }
- } // update the mediaIndex on the SegmentInfo object
- // this is important because we will update this.mediaIndex with this value
- // in `handleAppendsDone_` after the segment has been successfully appended
-
-
- if (segmentInfo) {
- segmentInfo.mediaIndex -= mediaSequenceDiff;
-
- if (segmentInfo.mediaIndex < 0) {
- segmentInfo.mediaIndex = null;
- segmentInfo.partIndex = null;
- } else {
- // we need to update the referenced segment so that timing information is
- // saved for the new playlist's segment, however, if the segment fell off the
- // playlist, we can leave the old reference and just lose the timing info
- if (segmentInfo.mediaIndex >= 0) {
- segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
- }
-
- if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
- segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
- }
- }
- }
-
- this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
- }
- /**
- * Prevent the loader from fetching additional segments. If there
- * is a segment request outstanding, it will finish processing
- * before the loader halts. A segment loader can be unpaused by
- * calling load().
- */
- ;
-
- _proto.pause = function pause() {
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- this.checkBufferTimeout_ = null;
- }
- }
- /**
- * Returns whether the segment loader is fetching additional
- * segments when given the opportunity. This property can be
- * modified through calls to pause() and load().
- */
- ;
-
- _proto.paused = function paused() {
- return this.checkBufferTimeout_ === null;
- }
- /**
- * Delete all the buffered data and reset the SegmentLoader
- *
- * @param {Function} [done] an optional callback to be executed when the remove
- * operation is complete
- */
- ;
-
- _proto.resetEverything = function resetEverything(done) {
- this.ended_ = false;
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
- // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
- // we then clamp the value to duration if necessary.
-
- this.remove(0, Infinity, done); // clears fmp4 captions
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
- /**
- * Force the SegmentLoader to resync and start loading around the currentTime instead
- * of starting at the end of the buffer
- *
- * Useful for fast quality changes
- */
- ;
-
- _proto.resetLoader = function resetLoader() {
- this.fetchAtBuffer_ = false;
- this.resyncLoader();
- }
- /**
- * Force the SegmentLoader to restart synchronization and make a conservative guess
- * before returning to the simple walk-forward method
- */
- ;
-
- _proto.resyncLoader = function resyncLoader() {
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
-
- this.mediaIndex = null;
- this.partIndex = null;
- this.syncPoint_ = null;
- this.isPendingTimestampOffset_ = false;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.abort();
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- }
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- * @param {Function} [done] - an optional callback to be executed when the remove
- * @param {boolean} force - force all remove operations to happen
- * operation is complete
- */
- ;
-
- _proto.remove = function remove(start, end, done, force) {
- if (done === void 0) {
- done = function done() {};
- }
-
- if (force === void 0) {
- force = false;
- }
-
- // clamp end to duration if we need to remove everything.
- // This is due to a browser bug that causes issues if we remove to Infinity.
- // videojs/videojs-contrib-hls#1225
- if (end === Infinity) {
- end = this.duration_();
- } // skip removes that would throw an error
- // commonly happens during a rendition switch at the start of a video
- // from start 0 to end 0
-
-
- if (end <= start) {
- this.logger_('skipping remove because end ${end} is <= start ${start}');
- return;
- }
-
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
-
- return;
- } // set it to one to complete this function's removes
-
-
- var removesRemaining = 1;
-
- var removeFinished = function removeFinished() {
- removesRemaining--;
-
- if (removesRemaining === 0) {
- done();
- }
- };
-
- if (force || !this.audioDisabled_) {
- removesRemaining++;
- this.sourceUpdater_.removeAudio(start, end, removeFinished);
- } // While it would be better to only remove video if the main loader has video, this
- // should be safe with audio only as removeVideo will call back even if there's no
- // video buffer.
- //
- // In theory we can check to see if there's video before calling the remove, but in
- // the event that we're switching between renditions and from video to audio only
- // (when we add support for that), we may need to clear the video contents despite
- // what the new media will contain.
-
-
- if (force || this.loaderType_ === 'main') {
- this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
- removesRemaining++;
- this.sourceUpdater_.removeVideo(start, end, removeFinished);
- } // remove any captions and ID3 tags
-
-
- for (var track in this.inbandTextTracks_) {
- removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
-
- removeFinished();
- }
- /**
- * (re-)schedule monitorBufferTick_ to run as soon as possible
- *
- * @private
- */
- ;
-
- _proto.monitorBuffer_ = function monitorBuffer_() {
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window__default['default'].setTimeout(this.monitorBufferTick_.bind(this), 1);
- }
- /**
- * As long as the SegmentLoader is in the READY state, periodically
- * invoke fillBuffer_().
- *
- * @private
- */
- ;
-
- _proto.monitorBufferTick_ = function monitorBufferTick_() {
- if (this.state === 'READY') {
- this.fillBuffer_();
- }
-
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window__default['default'].setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
- }
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- ;
-
- _proto.fillBuffer_ = function fillBuffer_() {
- // TODO since the source buffer maintains a queue, and we shouldn't call this function
- // except when we're ready for the next segment, this check can most likely be removed
- if (this.sourceUpdater_.updating()) {
- return;
- } // see if we need to begin loading immediately
-
-
- var segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- this.isPendingTimestampOffset_ = false;
- this.timelineChangeController_.pendingTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
-
- this.loadSegment_(segmentInfo);
- }
- /**
- * Determines if we should call endOfStream on the media source based
- * on the state of the buffer or if appened segment was the final
- * segment in the playlist.
- *
- * @param {number} [mediaIndex] the media index of segment we last appended
- * @param {Object} [playlist] a media playlist object
- * @return {boolean} do we need to call endOfStream on the MediaSource
- */
- ;
-
- _proto.isEndOfStream_ = function isEndOfStream_(mediaIndex, playlist, partIndex) {
- if (mediaIndex === void 0) {
- mediaIndex = this.mediaIndex;
- }
-
- if (playlist === void 0) {
- playlist = this.playlist_;
- }
-
- if (partIndex === void 0) {
- partIndex = this.partIndex;
- }
-
- if (!playlist || !this.mediaSource_) {
- return false;
- }
-
- var segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
-
- var appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
-
- var appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endOfStream
- // so that MediaSources can trigger the `ended` event when it runs out of
- // buffered data instead of waiting for me
-
- return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
- }
- /**
- * Determines what request should be made given current segment loader state.
- *
- * @return {Object} a request object that describes the segment/part to load
- */
- ;
-
- _proto.chooseNextRequest_ = function chooseNextRequest_() {
- var bufferedEnd = lastBufferedEnd(this.buffered_()) || 0;
- var bufferedTime = Math.max(0, bufferedEnd - this.currentTime_());
- var preloaded = !this.hasPlayed_() && bufferedTime >= 1;
- var haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
- var segments = this.playlist_.segments; // return no segment if:
- // 1. we don't have segments
- // 2. The video has not yet played and we already downloaded a segment
- // 3. we already have enough buffered time
-
- if (!segments.length || preloaded || haveEnoughBuffer) {
- return null;
- }
-
- this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
- var next = {
- partIndex: null,
- mediaIndex: null,
- startOfSegment: null,
- playlist: this.playlist_,
- isSyncRequest: Boolean(!this.syncPoint_)
- };
-
- if (next.isSyncRequest) {
- next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
- } else if (this.mediaIndex !== null) {
- var segment = segments[this.mediaIndex];
- var partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
- next.startOfSegment = segment.end ? segment.end : bufferedEnd;
-
- if (segment.parts && segment.parts[partIndex + 1]) {
- next.mediaIndex = this.mediaIndex;
- next.partIndex = partIndex + 1;
- } else {
- next.mediaIndex = this.mediaIndex + 1;
- }
- } else {
- // Find the segment containing the end of the buffer or current time.
- var _Playlist$getMediaInf = Playlist.getMediaInfoForTime({
- playlist: this.playlist_,
- currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
- startingPartIndex: this.syncPoint_.partIndex,
- startingSegmentIndex: this.syncPoint_.segmentIndex,
- startTime: this.syncPoint_.time
- }),
- segmentIndex = _Playlist$getMediaInf.segmentIndex,
- startTime = _Playlist$getMediaInf.startTime,
- _partIndex = _Playlist$getMediaInf.partIndex;
-
- next.getMediaInfoForTime = this.fetchAtBuffer_ ? 'bufferedEnd' : 'currentTime';
- next.mediaIndex = segmentIndex;
- next.startOfSegment = startTime;
- next.partIndex = _partIndex;
- }
-
- var nextSegment = segments[next.mediaIndex];
- var nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
- // the next partIndex is invalid do not choose a next segment.
-
- if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
- return null;
- } // if the next segment has parts, and we don't have a partIndex.
- // Set partIndex to 0
-
-
- if (typeof next.partIndex !== 'number' && nextSegment.parts) {
- next.partIndex = 0;
- }
-
- var ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
- // 1. this is the last segment in the playlist
- // 2. end of stream has been called on the media source already
- // 3. the player is not seeking
-
- if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
- return null;
- }
-
- return this.generateSegmentInfo_(next);
- };
-
- _proto.generateSegmentInfo_ = function generateSegmentInfo_(options) {
- var playlist = options.playlist,
- mediaIndex = options.mediaIndex,
- startOfSegment = options.startOfSegment,
- isSyncRequest = options.isSyncRequest,
- partIndex = options.partIndex,
- forceTimestampOffset = options.forceTimestampOffset,
- getMediaInfoForTime = options.getMediaInfoForTime;
- var segment = playlist.segments[mediaIndex];
- var part = typeof partIndex === 'number' && segment.parts[partIndex];
- var segmentInfo = {
- requestId: 'segment-loader-' + Math.random(),
- // resolve the segment URL relative to the playlist
- uri: part && part.resolvedUri || segment.resolvedUri,
- // the segment's mediaIndex at the time it was requested
- mediaIndex: mediaIndex,
- partIndex: part ? partIndex : null,
- // whether or not to update the SegmentLoader's state with this
- // segment's mediaIndex
- isSyncRequest: isSyncRequest,
- startOfSegment: startOfSegment,
- // the segment's playlist
- playlist: playlist,
- // unencrypted bytes of the segment
- bytes: null,
- // when a key is defined for this segment, the encrypted bytes
- encryptedBytes: null,
- // The target timestampOffset for this segment when we append it
- // to the source buffer
- timestampOffset: null,
- // The timeline that the segment is in
- timeline: segment.timeline,
- // The expected duration of the segment in seconds
- duration: part && part.duration || segment.duration,
- // retain the segment in case the playlist updates while doing an async process
- segment: segment,
- part: part,
- byteLength: 0,
- transmuxer: this.transmuxer_,
- // type of getMediaInfoForTime that was used to get this segment
- getMediaInfoForTime: getMediaInfoForTime
- };
- var overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
- segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
- segmentTimeline: segment.timeline,
- currentTimeline: this.currentTimeline_,
- startOfSegment: startOfSegment,
- buffered: this.buffered_(),
- overrideCheck: overrideCheck
- });
- var audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
-
- if (typeof audioBufferedEnd === 'number') {
- // since the transmuxer is using the actual timing values, but the buffer is
- // adjusted by the timestamp offset, we must adjust the value here
- segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
- }
-
- if (this.sourceUpdater_.videoBuffered().length) {
- segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
- // adjusted by the timestmap offset, we must adjust the value here
- this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
- }
-
- return segmentInfo;
- } // get the timestampoffset for a segment,
- // added so that vtt segment loader can override and prevent
- // adding timestamp offsets.
- ;
-
- _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_(options) {
- return timestampOffsetForSegment(options);
- }
- /**
- * Determines if the network has enough bandwidth to complete the current segment
- * request in a timely manner. If not, the request will be aborted early and bandwidth
- * updated to trigger a playlist switch.
- *
- * @param {Object} stats
- * Object containing stats about the request timing and size
- * @private
- */
- ;
-
- _proto.earlyAbortWhenNeeded_ = function earlyAbortWhenNeeded_(stats) {
- if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
- // TODO: Replace using timeout with a boolean indicating whether this playlist is
- // the lowestEnabledRendition.
- !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
- !this.playlist_.attributes.BANDWIDTH) {
- return;
- } // Wait at least 1 second since the first byte of data has been received before
- // using the calculated bandwidth from the progress event to allow the bitrate
- // to stabilize
-
-
- if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
- return;
- }
-
- var currentTime = this.currentTime_();
- var measuredBandwidth = stats.bandwidth;
- var segmentDuration = this.pendingSegment_.duration;
- var requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
- // if we are only left with less than 1 second when the request completes.
- // A negative timeUntilRebuffering indicates we are already rebuffering
-
- var timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
- // is larger than the estimated time until the player runs out of forward buffer
-
- if (requestTimeRemaining <= timeUntilRebuffer$1) {
- return;
- }
-
- var switchCandidate = minRebufferMaxBandwidthSelector({
- master: this.vhs_.playlists.master,
- currentTime: currentTime,
- bandwidth: measuredBandwidth,
- duration: this.duration_(),
- segmentDuration: segmentDuration,
- timeUntilRebuffer: timeUntilRebuffer$1,
- currentTimeline: this.currentTimeline_,
- syncController: this.syncController_
- });
-
- if (!switchCandidate) {
- return;
- }
-
- var rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
- var timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
- var minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
- // potential round trip time of the new request so that we are not too aggressive
- // with switching to a playlist that might save us a fraction of a second.
-
- if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
- minimumTimeSaving = 1;
- }
-
- if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
- return;
- } // set the bandwidth to that of the desired playlist being sure to scale by
- // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
- // don't trigger a bandwidthupdate as the bandwidth is artifial
-
-
- this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
- this.trigger('earlyabort');
- };
-
- _proto.handleAbort_ = function handleAbort_(segmentInfo) {
- this.logger_("Aborting " + segmentInfoString(segmentInfo));
- this.mediaRequestsAborted += 1;
- }
- /**
- * XHR `progress` event handler
- *
- * @param {Event}
- * The XHR `progress` event
- * @param {Object} simpleSegment
- * A simplified segment object copy
- * @private
- */
- ;
-
- _proto.handleProgress_ = function handleProgress_(event, simpleSegment) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- this.trigger('progress');
- };
-
- _proto.handleTrackInfo_ = function handleTrackInfo_(simpleSegment, trackInfo) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- if (this.checkForIllegalMediaSwitch(trackInfo)) {
- return;
- }
-
- trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
- // Guard against cases where we're not getting track info at all until we are
- // certain that all streams will provide it.
-
- if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.startingMediaInfo_ = trackInfo;
- this.currentMediaInfo_ = trackInfo;
- this.logger_('trackinfo update', trackInfo);
- this.trigger('trackinfo');
- } // trackinfo may cause an abort if the trackinfo
- // causes a codec change to an unsupported codec.
-
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // set trackinfo on the pending segment so that
- // it can append.
-
-
- this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
-
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- };
-
- _proto.handleTimingInfo_ = function handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- var segmentInfo = this.pendingSegment_;
- var timingInfoProperty = timingInfoPropertyForMedia(mediaType);
- segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
- segmentInfo[timingInfoProperty][timeType] = time;
- this.logger_("timinginfo: " + mediaType + " - " + timeType + " - " + time); // check if any calls were waiting on the timing info
-
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- };
-
- _proto.handleCaptions_ = function handleCaptions_(simpleSegment, captionData) {
- var _this2 = this;
-
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // This could only happen with fmp4 segments, but
- // should still not happen in general
-
-
- if (captionData.length === 0) {
- this.logger_('SegmentLoader received no captions from a caption event');
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
- // can be adjusted by the timestamp offset
-
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
- return;
- }
-
- var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
- var captionTracks = {}; // get total start/end and captions for each track/stream
-
- captionData.forEach(function (caption) {
- // caption.stream is actually a track name...
- // set to the existing values in tracks or default values
- captionTracks[caption.stream] = captionTracks[caption.stream] || {
- // Infinity, as any other value will be less than this
- startTime: Infinity,
- captions: [],
- // 0 as an other value will be more than this
- endTime: 0
- };
- var captionTrack = captionTracks[caption.stream];
- captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
- captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
- captionTrack.captions.push(caption);
- });
- Object.keys(captionTracks).forEach(function (trackName) {
- var _captionTracks$trackN = captionTracks[trackName],
- startTime = _captionTracks$trackN.startTime,
- endTime = _captionTracks$trackN.endTime,
- captions = _captionTracks$trackN.captions;
- var inbandTextTracks = _this2.inbandTextTracks_;
-
- _this2.logger_("adding cues from " + startTime + " -> " + endTime + " for " + trackName);
-
- createCaptionsTrackIfNotExists(inbandTextTracks, _this2.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
- // We do this because a rendition change that also changes the timescale for captions
- // will result in captions being re-parsed for certain segments. If we add them again
- // without clearing we will have two of the same captions visible.
-
- removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
- addCaptionData({
- captionArray: captions,
- inbandTextTracks: inbandTextTracks,
- timestampOffset: timestampOffset
- });
- }); // Reset stored captions since we added parsed
- // captions to a text track at this point
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- };
-
- _proto.handleId3_ = function handleId3_(simpleSegment, id3Frames, dispatchType) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
-
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
- return;
- }
-
- var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
- // audio/video source with a metadata track, and an alt audio with a metadata track.
- // However, this probably won't happen, and if it does it can be handled then.
-
- createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
- addMetadata({
- inbandTextTracks: this.inbandTextTracks_,
- metadataArray: id3Frames,
- timestampOffset: timestampOffset,
- videoDuration: this.duration_()
- });
- };
-
- _proto.processMetadataQueue_ = function processMetadataQueue_() {
- this.metadataQueue_.id3.forEach(function (fn) {
- return fn();
- });
- this.metadataQueue_.caption.forEach(function (fn) {
- return fn();
- });
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- };
-
- _proto.processCallQueue_ = function processCallQueue_() {
- var callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
-
- this.callQueue_ = [];
- callQueue.forEach(function (fun) {
- return fun();
- });
- };
-
- _proto.processLoadQueue_ = function processLoadQueue_() {
- var loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
-
- this.loadQueue_ = [];
- loadQueue.forEach(function (fun) {
- return fun();
- });
- }
- /**
- * Determines whether the loader has enough info to load the next segment.
- *
- * @return {boolean}
- * Whether or not the loader has enough info to load the next segment
- */
- ;
-
- _proto.hasEnoughInfoToLoad_ = function hasEnoughInfoToLoad_() {
- // Since primary timing goes by video, only the audio loader potentially needs to wait
- // to load.
- if (this.loaderType_ !== 'audio') {
- return true;
- }
-
- var segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
- // enough info to load.
-
- if (!segmentInfo) {
- return false;
- } // The first segment can and should be loaded immediately so that source buffers are
- // created together (before appending). Source buffer creation uses the presence of
- // audio and video data to determine whether to create audio/video source buffers, and
- // uses processed (transmuxed or parsed) media to determine the types required.
-
-
- if (!this.currentMediaInfo_) {
- return true;
- }
-
- if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
- // can be requested and downloaded and only wait before it is transmuxed or parsed.
- // But in practice, there are a few reasons why it is better to wait until a loader
- // is ready to append that segment before requesting and downloading:
- //
- // 1. Because audio and main loaders cross discontinuities together, if this loader
- // is waiting for the other to catch up, then instead of requesting another
- // segment and using up more bandwidth, by not yet loading, more bandwidth is
- // allotted to the loader currently behind.
- // 2. media-segment-request doesn't have to have logic to consider whether a segment
- // is ready to be processed or not, isolating the queueing behavior to the loader.
- // 3. The audio loader bases some of its segment properties on timing information
- // provided by the main loader, meaning that, if the logic for waiting on
- // processing was in media-segment-request, then it would also need to know how
- // to re-generate the segment information after the main loader caught up.
- shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })) {
- return false;
- }
-
- return true;
- };
-
- _proto.hasEnoughInfoToAppend_ = function hasEnoughInfoToAppend_() {
- if (!this.sourceUpdater_.ready()) {
- return false;
- } // If content needs to be removed or the loader is waiting on an append reattempt,
- // then no additional content should be appended until the prior append is resolved.
-
-
- if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
- return false;
- }
-
- var segmentInfo = this.pendingSegment_; // no segment to append any data for or
- // we do not have information on this specific
- // segment yet
-
- if (!segmentInfo || !segmentInfo.trackInfo) {
- return false;
- }
-
- var _this$currentMediaInf = this.currentMediaInfo_,
- hasAudio = _this$currentMediaInf.hasAudio,
- hasVideo = _this$currentMediaInf.hasVideo,
- isMuxed = _this$currentMediaInf.isMuxed;
-
- if (hasVideo && !segmentInfo.videoTimingInfo) {
- return false;
- } // muxed content only relies on video timing information for now.
-
-
- if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
- return false;
- }
-
- if (shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })) {
- return false;
- }
-
- return true;
- };
-
- _proto.handleData_ = function handleData_(simpleSegment, result) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // If there's anything in the call queue, then this data came later and should be
- // executed after the calls currently queued.
-
-
- if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
- this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
-
- this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
-
- this.updateMediaSecondsLoaded_(segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
- // logic may change behavior depending on the state, and changing state too early may
- // inflate our estimates of bandwidth. In the future this should be re-examined to
- // note more granular states.
- // don't process and append data if the mediaSource is closed
-
- if (this.mediaSource_.readyState === 'closed') {
- return;
- } // if this request included an initialization segment, save that data
- // to the initSegment cache
-
-
- if (simpleSegment.map) {
- simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
-
- segmentInfo.segment.map = simpleSegment.map;
- } // if this request included a segment key, save that data in the cache
-
-
- if (simpleSegment.key) {
- this.segmentKey(simpleSegment.key, true);
- }
-
- segmentInfo.isFmp4 = simpleSegment.isFmp4;
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
-
- if (segmentInfo.isFmp4) {
- this.trigger('fmp4');
- segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
- } else {
- var useVideoTimingInfo = this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- var firstVideoFrameTimeForData;
-
- if (useVideoTimingInfo) {
- firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
- } // Segment loader knows more about segment timing than the transmuxer (in certain
- // aspects), so make any changes required for a more accurate start time.
- // Don't set the end time yet, as the segment may not be finished processing.
-
-
- segmentInfo.timingInfo.start = this.trueSegmentStart_({
- currentStart: segmentInfo.timingInfo.start,
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex,
- currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
- useVideoTimingInfo: useVideoTimingInfo,
- firstVideoFrameTimeForData: firstVideoFrameTimeForData,
- videoTimingInfo: segmentInfo.videoTimingInfo,
- audioTimingInfo: segmentInfo.audioTimingInfo
- });
- } // Init segments for audio and video only need to be appended in certain cases. Now
- // that data is about to be appended, we can check the final cases to determine
- // whether we should append an init segment.
-
-
- this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
- // as we use the start of the segment to offset the best guess (playlist provided)
- // timestamp offset.
-
- this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
- // be appended or not.
-
- if (segmentInfo.isSyncRequest) {
- // first save/update our timing info for this segment.
- // this is what allows us to choose an accurate segment
- // and the main reason we make a sync request.
- this.updateTimingInfoEnd_(segmentInfo);
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo: segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
- var next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
- // after taking into account its timing info, do not append it.
-
- if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
- this.logger_('sync segment was incorrect, not appending');
- return;
- } // otherwise append it like any other segment as our guess was correct.
-
-
- this.logger_('sync segment was correct, appending');
- } // Save some state so that in the future anything waiting on first append (and/or
- // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
- // we need some notion of whether the timestamp offset or other relevant information
- // has had a chance to be set.
-
-
- segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
-
- this.processMetadataQueue_();
- this.appendData_(segmentInfo, result);
- };
-
- _proto.updateAppendInitSegmentStatus = function updateAppendInitSegmentStatus(segmentInfo, type) {
- // alt audio doesn't manage timestamp offset
- if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' && // in the case that we're handling partial data, we don't want to append an init
- // segment for each chunk
- !segmentInfo.changedTimestampOffset) {
- // if the timestamp offset changed, the timeline may have changed, so we have to re-
- // append init segments
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- }
-
- if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
- // make sure we append init segment on playlist changes, in case the media config
- // changed
- this.appendInitSegment_[type] = true;
- }
- };
-
- _proto.getInitSegmentAndUpdateState_ = function getInitSegmentAndUpdateState_(_ref4) {
- var type = _ref4.type,
- initSegment = _ref4.initSegment,
- map = _ref4.map,
- playlist = _ref4.playlist;
-
- // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
- // (Section 3) required to parse the applicable Media Segments. It applies to every
- // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
- // or until the end of the playlist."
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
- if (map) {
- var id = initSegmentId(map);
-
- if (this.activeInitSegmentId_ === id) {
- // don't need to re-append the init segment if the ID matches
- return null;
- } // a map-specified init segment takes priority over any transmuxed (or otherwise
- // obtained) init segment
- //
- // this also caches the init segment for later use
-
-
- initSegment = this.initSegmentForMap(map, true).bytes;
- this.activeInitSegmentId_ = id;
- } // We used to always prepend init segments for video, however, that shouldn't be
- // necessary. Instead, we should only append on changes, similar to what we've always
- // done for audio. This is more important (though may not be that important) for
- // frame-by-frame appending for LHLS, simply because of the increased quantity of
- // appends.
-
-
- if (initSegment && this.appendInitSegment_[type]) {
- // Make sure we track the playlist that we last used for the init segment, so that
- // we can re-append the init segment in the event that we get data from a new
- // playlist. Discontinuities and track changes are handled in other sections.
- this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
-
- this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
- // we are appending the muxer init segment
-
- this.activeInitSegmentId_ = null;
- return initSegment;
- }
-
- return null;
- };
-
- _proto.handleQuotaExceededError_ = function handleQuotaExceededError_(_ref5, error) {
- var _this3 = this;
-
- var segmentInfo = _ref5.segmentInfo,
- type = _ref5.type,
- bytes = _ref5.bytes;
- var audioBuffered = this.sourceUpdater_.audioBuffered();
- var videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
- // should be cleared out during the buffer removals. However, log in case it helps
- // debug.
-
- if (audioBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
- }
-
- if (videoBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
- }
-
- var audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
- var audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
- var videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
- var videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
-
- if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
- // Can't remove enough buffer to make room for new segment (or the browser doesn't
- // allow for appends of segments this size). In the future, it may be possible to
- // split up the segment and append in pieces, but for now, error out this playlist
- // in an attempt to switch to a more manageable rendition.
- this.logger_('On QUOTA_EXCEEDED_ERR, single segment too large to append to ' + 'buffer, triggering an error. ' + ("Appended byte length: " + bytes.byteLength + ", ") + ("audio buffer: " + timeRangesToArray(audioBuffered).join(', ') + ", ") + ("video buffer: " + timeRangesToArray(videoBuffered).join(', ') + ", "));
- this.error({
- message: 'Quota exceeded error with append of a single segment of content',
- excludeUntil: Infinity
- });
- this.trigger('error');
- return;
- } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
- // that the segment-loader should block on future events until this one is handled, so
- // that it doesn't keep moving onto further segments. Adding the call to the call
- // queue will prevent further appends until waitingOnRemove_ and
- // quotaExceededErrorRetryTimeout_ are cleared.
- //
- // Note that this will only block the current loader. In the case of demuxed content,
- // the other load may keep filling as fast as possible. In practice, this should be
- // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
- // source buffer, or video fills without enough room for audio to append (and without
- // the availability of clearing out seconds of back buffer to make room for audio).
- // But it might still be good to handle this case in the future as a TODO.
-
-
- this.waitingOnRemove_ = true;
- this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }));
- var currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
- // before retrying.
-
- var timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
- this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to " + timeToRemoveUntil);
- this.remove(0, timeToRemoveUntil, function () {
- _this3.logger_("On QUOTA_EXCEEDED_ERR, retrying append in " + MIN_BACK_BUFFER + "s");
-
- _this3.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
- // attempts (since we can't clear less than the minimum)
-
- _this3.quotaExceededErrorRetryTimeout_ = window__default['default'].setTimeout(function () {
- _this3.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
-
- _this3.quotaExceededErrorRetryTimeout_ = null;
-
- _this3.processCallQueue_();
- }, MIN_BACK_BUFFER * 1000);
- }, true);
- };
-
- _proto.handleAppendError_ = function handleAppendError_(_ref6, error) {
- var segmentInfo = _ref6.segmentInfo,
- type = _ref6.type,
- bytes = _ref6.bytes;
-
- // if there's no error, nothing to do
- if (!error) {
- return;
- }
-
- if (error.code === QUOTA_EXCEEDED_ERR) {
- this.handleQuotaExceededError_({
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }); // A quota exceeded error should be recoverable with a future re-append, so no need
- // to trigger an append error.
-
- return;
- }
-
- this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
- this.error(type + " append of " + bytes.length + "b failed for segment " + ("#" + segmentInfo.mediaIndex + " in playlist " + segmentInfo.playlist.id)); // If an append errors, we often can't recover.
- // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
- //
- // Trigger a special error so that it can be handled separately from normal,
- // recoverable errors.
-
- this.trigger('appenderror');
- };
-
- _proto.appendToSourceBuffer_ = function appendToSourceBuffer_(_ref7) {
- var segmentInfo = _ref7.segmentInfo,
- type = _ref7.type,
- initSegment = _ref7.initSegment,
- data = _ref7.data,
- bytes = _ref7.bytes;
-
- // If this is a re-append, bytes were already created and don't need to be recreated
- if (!bytes) {
- var segments = [data];
- var byteLength = data.byteLength;
-
- if (initSegment) {
- // if the media initialization segment is changing, append it before the content
- // segment
- segments.unshift(initSegment);
- byteLength += initSegment.byteLength;
- } // Technically we should be OK appending the init segment separately, however, we
- // haven't yet tested that, and prepending is how we have always done things.
-
-
- bytes = concatSegments({
- bytes: byteLength,
- segments: segments
- });
- }
-
- this.sourceUpdater_.appendBuffer({
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }, this.handleAppendError_.bind(this, {
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }));
- };
-
- _proto.handleSegmentTimingInfo_ = function handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
- if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
- return;
- }
-
- var segment = this.pendingSegment_.segment;
- var timingInfoProperty = type + "TimingInfo";
-
- if (!segment[timingInfoProperty]) {
- segment[timingInfoProperty] = {};
- }
-
- segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
- segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
- segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
- segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
- segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
-
- segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
- };
-
- _proto.appendData_ = function appendData_(segmentInfo, result) {
- var type = result.type,
- data = result.data;
-
- if (!data || !data.byteLength) {
- return;
- }
-
- if (type === 'audio' && this.audioDisabled_) {
- return;
- }
-
- var initSegment = this.getInitSegmentAndUpdateState_({
- type: type,
- initSegment: result.initSegment,
- playlist: segmentInfo.playlist,
- map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
- });
- this.appendToSourceBuffer_({
- segmentInfo: segmentInfo,
- type: type,
- initSegment: initSegment,
- data: data
- });
- }
- /**
- * load a specific segment from a request into the buffer
- *
- * @private
- */
- ;
-
- _proto.loadSegment_ = function loadSegment_(segmentInfo) {
- var _this4 = this;
-
- this.state = 'WAITING';
- this.pendingSegment_ = segmentInfo;
- this.trimBackBuffer_(segmentInfo);
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
-
- if (!this.hasEnoughInfoToLoad_()) {
- this.loadQueue_.push(function () {
- // regenerate the audioAppendStart, timestampOffset, etc as they
- // may have changed since this function was added to the queue.
- var options = _extends__default['default']({}, segmentInfo, {
- forceTimestampOffset: true
- });
-
- _extends__default['default'](segmentInfo, _this4.generateSegmentInfo_(options));
-
- _this4.isPendingTimestampOffset_ = false;
-
- _this4.updateTransmuxerAndRequestSegment_(segmentInfo);
- });
- return;
- }
-
- this.updateTransmuxerAndRequestSegment_(segmentInfo);
- };
-
- _proto.updateTransmuxerAndRequestSegment_ = function updateTransmuxerAndRequestSegment_(segmentInfo) {
- var _this5 = this;
-
- // We'll update the source buffer's timestamp offset once we have transmuxed data, but
- // the transmuxer still needs to be updated before then.
- //
- // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
- // offset must be passed to the transmuxer for stream correcting adjustments.
- if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
- this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
-
- segmentInfo.gopsToAlignWith = [];
- this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
-
- this.transmuxer_.postMessage({
- action: 'reset'
- });
- this.transmuxer_.postMessage({
- action: 'setTimestampOffset',
- timestampOffset: segmentInfo.timestampOffset
- });
- }
-
- var simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
- var isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
- var isWalkingForward = this.mediaIndex !== null;
- var isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
- // the first timeline
- segmentInfo.timeline > 0;
- var isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
- this.logger_("Requesting " + segmentInfoString(segmentInfo)); // If there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),
- // then this init segment has never been seen before and should be appended.
- //
- // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
- // both to true and leave the decision of whether to append the init segment to append time.
-
- if (simpleSegment.map && !simpleSegment.map.bytes) {
- this.logger_('going to request init segment.');
- this.appendInitSegment_ = {
- video: true,
- audio: true
- };
- }
-
- segmentInfo.abortRequests = mediaSegmentRequest({
- xhr: this.vhs_.xhr,
- xhrOptions: this.xhrOptions_,
- decryptionWorker: this.decrypter_,
- segment: simpleSegment,
- abortFn: this.handleAbort_.bind(this, segmentInfo),
- progressFn: this.handleProgress_.bind(this),
- trackInfoFn: this.handleTrackInfo_.bind(this),
- timingInfoFn: this.handleTimingInfo_.bind(this),
- videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
- audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
- captionsFn: this.handleCaptions_.bind(this),
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: function endedTimelineFn() {
- _this5.logger_('received endedtimeline callback');
- },
- id3Fn: this.handleId3_.bind(this),
- dataFn: this.handleData_.bind(this),
- doneFn: this.segmentRequestFinished_.bind(this)
- });
- }
- /**
- * trim the back buffer so that we don't have too much data
- * in the source buffer
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- */
- ;
-
- _proto.trimBackBuffer_ = function trimBackBuffer_(segmentInfo) {
- var removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
- // buffer and a very conservative "garbage collector"
- // We manually clear out the old buffer to ensure
- // we don't trigger the QuotaExceeded error
- // on the source buffer during subsequent appends
-
- if (removeToTime > 0) {
- this.remove(0, removeToTime);
- }
- }
- /**
- * created a simplified copy of the segment object with just the
- * information necessary to perform the XHR and decryption
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- * @return {Object} a simplified segment object copy
- */
- ;
-
- _proto.createSimplifiedSegmentObj_ = function createSimplifiedSegmentObj_(segmentInfo) {
- var segment = segmentInfo.segment;
- var part = segmentInfo.part;
- var simpleSegment = {
- resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
- byterange: part ? part.byterange : segment.byterange,
- requestId: segmentInfo.requestId,
- transmuxer: segmentInfo.transmuxer,
- audioAppendStart: segmentInfo.audioAppendStart,
- gopsToAlignWith: segmentInfo.gopsToAlignWith,
- part: segmentInfo.part
- };
- var previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
-
- if (previousSegment && previousSegment.timeline === segment.timeline) {
- // The baseStartTime of a segment is used to handle rollover when probing the TS
- // segment to retrieve timing information. Since the probe only looks at the media's
- // times (e.g., PTS and DTS values of the segment), and doesn't consider the
- // player's time (e.g., player.currentTime()), baseStartTime should reflect the
- // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
- // seconds of media time, so should be used here. The previous segment is used since
- // the end of the previous segment should represent the beginning of the current
- // segment, so long as they are on the same timeline.
- if (previousSegment.videoTimingInfo) {
- simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
- } else if (previousSegment.audioTimingInfo) {
- simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
- }
- }
-
- if (segment.key) {
- // if the media sequence is greater than 2^32, the IV will be incorrect
- // assuming 10s segments, that would be about 1300 years
- var iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
- simpleSegment.key = this.segmentKey(segment.key);
- simpleSegment.key.iv = iv;
- }
-
- if (segment.map) {
- simpleSegment.map = this.initSegmentForMap(segment.map);
- }
-
- return simpleSegment;
- };
-
- _proto.saveTransferStats_ = function saveTransferStats_(stats) {
- // every request counts as a media request even if it has been aborted
- // or canceled due to a timeout
- this.mediaRequests += 1;
-
- if (stats) {
- this.mediaBytesTransferred += stats.bytesReceived;
- this.mediaTransferDuration += stats.roundTripTime;
- }
- };
-
- _proto.saveBandwidthRelatedStats_ = function saveBandwidthRelatedStats_(duration, stats) {
- // byteLength will be used for throughput, and should be based on bytes receieved,
- // which we only know at the end of the request and should reflect total bytes
- // downloaded rather than just bytes processed from components of the segment
- this.pendingSegment_.byteLength = stats.bytesReceived;
-
- if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_("Ignoring segment's bandwidth because its duration of " + duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
- return;
- }
-
- this.bandwidth = stats.bandwidth;
- this.roundTrip = stats.roundTripTime;
- };
-
- _proto.handleTimeout_ = function handleTimeout_() {
- // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functinality between segment loaders
- this.mediaRequestsTimedout += 1;
- this.bandwidth = 1;
- this.roundTrip = NaN;
- this.trigger('bandwidthupdate');
- }
- /**
- * Handle the callback from the segmentRequest function and set the
- * associated SegmentLoader state and errors if necessary
- *
- * @private
- */
- ;
-
- _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
- // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
- // check the call queue directly since this function doesn't need to deal with any
- // data, and can continue even if the source buffers are not set up and we didn't get
- // any data from the segment
- if (this.callQueue_.length) {
- this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
-
- if (!this.pendingSegment_) {
- return;
- } // the request was aborted and the SegmentLoader has already started
- // another request. this can happen when the timeout for an aborted
- // request triggers due to a limitation in the XHR library
- // do not count this as any sort of request or we risk double-counting
-
-
- if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
- return;
- } // an error occurred from the active pendingSegment_ so reset everything
-
-
- if (error) {
- this.pendingSegment_ = null;
- this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
-
- if (error.code === REQUEST_ERRORS.ABORTED) {
- return;
- }
-
- this.pause(); // the error is really just that at least one of the requests timed-out
- // set the bandwidth to a very low value and trigger an ABR switch to
- // take emergency action
-
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- return;
- } // if control-flow has arrived here, then the error is real
- // emit an error event to blacklist the current playlist
-
-
- this.mediaRequestsErrored += 1;
- this.error(error);
- this.trigger('error');
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
- // generated for ABR purposes
-
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
- segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
-
- if (result.gopInfo) {
- this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
- } // Although we may have already started appending on progress, we shouldn't switch the
- // state away from loading until we are officially done loading the segment data.
-
-
- this.state = 'APPENDING'; // used for testing
-
- this.trigger('appending');
- this.waitForAppendsToComplete_(segmentInfo);
- };
-
- _proto.setTimeMapping_ = function setTimeMapping_(timeline) {
- var timelineMapping = this.syncController_.mappingForTimeline(timeline);
-
- if (timelineMapping !== null) {
- this.timeMapping_ = timelineMapping;
- }
- };
-
- _proto.updateMediaSecondsLoaded_ = function updateMediaSecondsLoaded_(segment) {
- if (typeof segment.start === 'number' && typeof segment.end === 'number') {
- this.mediaSecondsLoaded += segment.end - segment.start;
- } else {
- this.mediaSecondsLoaded += segment.duration;
- }
- };
-
- _proto.shouldUpdateTransmuxerTimestampOffset_ = function shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
- if (timestampOffset === null) {
- return false;
- } // note that we're potentially using the same timestamp offset for both video and
- // audio
-
-
- if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- return true;
- }
-
- if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- return true;
- }
-
- return false;
- };
-
- _proto.trueSegmentStart_ = function trueSegmentStart_(_ref8) {
- var currentStart = _ref8.currentStart,
- playlist = _ref8.playlist,
- mediaIndex = _ref8.mediaIndex,
- firstVideoFrameTimeForData = _ref8.firstVideoFrameTimeForData,
- currentVideoTimestampOffset = _ref8.currentVideoTimestampOffset,
- useVideoTimingInfo = _ref8.useVideoTimingInfo,
- videoTimingInfo = _ref8.videoTimingInfo,
- audioTimingInfo = _ref8.audioTimingInfo;
-
- if (typeof currentStart !== 'undefined') {
- // if start was set once, keep using it
- return currentStart;
- }
-
- if (!useVideoTimingInfo) {
- return audioTimingInfo.start;
- }
-
- var previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
- // within that segment. Since the transmuxer maintains a cache of incomplete data
- // from and/or the last frame seen, the start time may reflect a frame that starts
- // in the previous segment. Check for that case and ensure the start time is
- // accurate for the segment.
-
- if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
- return firstVideoFrameTimeForData;
- }
-
- return videoTimingInfo.start;
- };
-
- _proto.waitForAppendsToComplete_ = function waitForAppendsToComplete_(segmentInfo) {
- if (!this.currentMediaInfo_) {
- this.error({
- message: 'No starting media returned, likely due to an unsupported media format.',
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return;
- } // Although transmuxing is done, appends may not yet be finished. Throw a marker
- // on each queue this loader is responsible for to ensure that the appends are
- // complete.
-
-
- var _this$currentMediaInf2 = this.currentMediaInfo_,
- hasAudio = _this$currentMediaInf2.hasAudio,
- hasVideo = _this$currentMediaInf2.hasVideo,
- isMuxed = _this$currentMediaInf2.isMuxed;
- var waitForVideo = this.loaderType_ === 'main' && hasVideo;
- var waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
- segmentInfo.waitingOnAppends = 0; // segments with no data
-
- if (!segmentInfo.hasAppendedData_) {
- if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
- // When there's no audio or video data in the segment, there's no audio or video
- // timing information.
- //
- // If there's no audio or video timing information, then the timestamp offset
- // can't be adjusted to the appropriate value for the transmuxer and source
- // buffers.
- //
- // Therefore, the next segment should be used to set the timestamp offset.
- this.isPendingTimestampOffset_ = true;
- } // override settings for metadata only segments
-
-
- segmentInfo.timingInfo = {
- start: 0
- };
- segmentInfo.waitingOnAppends++;
-
- if (!this.isPendingTimestampOffset_) {
- // update the timestampoffset
- this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
- // no video/audio data.
-
- this.processMetadataQueue_();
- } // append is "done" instantly with no data.
-
-
- this.checkAppendsDone_(segmentInfo);
- return;
- } // Since source updater could call back synchronously, do the increments first.
-
-
- if (waitForVideo) {
- segmentInfo.waitingOnAppends++;
- }
-
- if (waitForAudio) {
- segmentInfo.waitingOnAppends++;
- }
-
- if (waitForVideo) {
- this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
-
- if (waitForAudio) {
- this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
- };
-
- _proto.checkAppendsDone_ = function checkAppendsDone_(segmentInfo) {
- if (this.checkForAbort_(segmentInfo.requestId)) {
- return;
- }
-
- segmentInfo.waitingOnAppends--;
-
- if (segmentInfo.waitingOnAppends === 0) {
- this.handleAppendsDone_();
- }
- };
-
- _proto.checkForIllegalMediaSwitch = function checkForIllegalMediaSwitch(trackInfo) {
- var illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.currentMediaInfo_, trackInfo);
-
- if (illegalMediaSwitchError) {
- this.error({
- message: illegalMediaSwitchError,
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return true;
- }
-
- return false;
- };
-
- _proto.updateSourceBufferTimestampOffset_ = function updateSourceBufferTimestampOffset_(segmentInfo) {
- if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
- // priority, timing-wise, so we must wait
- typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
- segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
- this.loaderType_ !== 'main') {
- return;
- }
-
- var didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
- // the timing info here comes from video. In the event that the audio is longer than
- // the video, this will trim the start of the audio.
- // This also trims any offset from 0 at the beginning of the media
-
- segmentInfo.timestampOffset -= segmentInfo.timingInfo.start; // In the event that there are part segment downloads, each will try to update the
- // timestamp offset. Retaining this bit of state prevents us from updating in the
- // future (within the same segment), however, there may be a better way to handle it.
-
- segmentInfo.changedTimestampOffset = true;
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (didChange) {
- this.trigger('timestampoffset');
- }
- };
-
- _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_(segmentInfo) {
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
- var useVideoTimingInfo = this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- var prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
-
- if (!prioritizedTimingInfo) {
- return;
- }
-
- segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
- // current example is the case of fmp4), so use the rough duration to calculate an
- // end time.
- prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
- }
- /**
- * callback to run when appendBuffer is finished. detects if we are
- * in a good state to do things with the data we got, or if we need
- * to wait for more
- *
- * @private
- */
- ;
-
- _proto.handleAppendsDone_ = function handleAppendsDone_() {
- // appendsdone can cause an abort
- if (this.pendingSegment_) {
- this.trigger('appendsdone');
- }
-
- if (!this.pendingSegment_) {
- this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
- // all appending cases?
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
-
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
- // best to wait until all appends are done so we're sure that the primary media is
- // finished (and we have its end time).
-
- this.updateTimingInfoEnd_(segmentInfo);
-
- if (this.shouldSaveSegmentTimingInfo_) {
- // Timeline mappings should only be saved for the main loader. This is for multiple
- // reasons:
- //
- // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
- // and the main loader try to save the timeline mapping, whichever comes later
- // will overwrite the first. In theory this is OK, as the mappings should be the
- // same, however, it breaks for (2)
- // 2) In the event of a live stream, the initial live point will make for a somewhat
- // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
- // the mapping will be off for one of the streams, dependent on which one was
- // first saved (see (1)).
- // 3) Primary timing goes by video in VHS, so the mapping should be video.
- //
- // Since the audio loader will wait for the main loader to load the first segment,
- // the main loader will save the first timeline mapping, and ensure that there won't
- // be a case where audio loads two segments without saving a mapping (thus leading
- // to missing segment timing info).
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo: segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
- }
-
- var segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
-
- if (segmentDurationMessage) {
- if (segmentDurationMessage.severity === 'warn') {
- videojs__default['default'].log.warn(segmentDurationMessage.message);
- } else {
- this.logger_(segmentDurationMessage.message);
- }
- }
-
- this.recordThroughput_(segmentInfo);
- this.pendingSegment_ = null;
- this.state = 'READY';
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate'); // if the sync request was not appended
- // then it was not the correct segment.
- // throw it away and use the data it gave us
- // to get the correct one.
-
- if (!segmentInfo.hasAppendedData_) {
- this.logger_("Throwing away un-appended sync request " + segmentInfoString(segmentInfo));
- return;
- }
- }
-
- this.logger_("Appended " + segmentInfoString(segmentInfo));
- this.addSegmentMetadataCue_(segmentInfo);
- this.fetchAtBuffer_ = true;
-
- if (this.currentTimeline_ !== segmentInfo.timeline) {
- this.timelineChangeController_.lastTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- }); // If audio is not disabled, the main segment loader is responsible for updating
- // the audio timeline as well. If the content is video only, this won't have any
- // impact.
-
- if (this.loaderType_ === 'main' && !this.audioDisabled_) {
- this.timelineChangeController_.lastTimelineChange({
- type: 'audio',
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
- }
-
- this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
- // the following conditional otherwise it may consider this a bad "guess"
- // and attempt to resync when the post-update seekable window and live
- // point would mean that this was the perfect segment to fetch
-
- this.trigger('syncinfoupdate');
- var segment = segmentInfo.segment; // If we previously appended a segment that ends more than 3 targetDurations before
- // the currentTime_ that means that our conservative guess was too conservative.
- // In that case, reset the loader state so that we try to use any information gained
- // from the previous request to create a new, more accurate, sync-point.
-
- if (segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3) {
- this.resetEverything();
- return;
- }
-
- var isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
- // and conservatively guess
-
- if (isWalkingForward) {
- this.trigger('bandwidthupdate');
- }
-
- this.trigger('progress');
- this.mediaIndex = segmentInfo.mediaIndex;
- this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
- // buffer, end the stream. this ensures the "ended" event will
- // fire if playback reaches that point.
-
- if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
- this.endOfStream();
- } // used for testing
-
-
- this.trigger('appended');
-
- if (segmentInfo.hasAppendedData_) {
- this.mediaAppends++;
- }
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
- /**
- * Records the current throughput of the decrypt, transmux, and append
- * portion of the semgment pipeline. `throughput.rate` is a the cumulative
- * moving average of the throughput. `throughput.count` is the number of
- * data points in the average.
- *
- * @private
- * @param {Object} segmentInfo the object returned by loadSegment
- */
- ;
-
- _proto.recordThroughput_ = function recordThroughput_(segmentInfo) {
- if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_("Ignoring segment's throughput because its duration of " + segmentInfo.duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
- return;
- }
-
- var rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
- // by zero in the case where the throughput is ridiculously high
-
- var segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
-
- var segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
- // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
-
- this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
- }
- /**
- * Adds a cue to the segment-metadata track with some metadata information about the
- * segment
- *
- * @private
- * @param {Object} segmentInfo
- * the object returned by loadSegment
- * @method addSegmentMetadataCue_
- */
- ;
-
- _proto.addSegmentMetadataCue_ = function addSegmentMetadataCue_(segmentInfo) {
- if (!this.segmentMetadataTrack_) {
- return;
- }
-
- var segment = segmentInfo.segment;
- var start = segment.start;
- var end = segment.end; // Do not try adding the cue if the start and end times are invalid.
-
- if (!finite(start) || !finite(end)) {
- return;
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
- var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
- var value = {
- custom: segment.custom,
- dateTimeObject: segment.dateTimeObject,
- dateTimeString: segment.dateTimeString,
- bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
- resolution: segmentInfo.playlist.attributes.RESOLUTION,
- codecs: segmentInfo.playlist.attributes.CODECS,
- byteLength: segmentInfo.byteLength,
- uri: segmentInfo.uri,
- timeline: segmentInfo.timeline,
- playlist: segmentInfo.playlist.id,
- start: start,
- end: end
- };
- var data = JSON.stringify(value);
- var cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
- // the differences of WebKitDataCue in safari and VTTCue in other browsers
-
- cue.value = value;
- this.segmentMetadataTrack_.addCue(cue);
- };
-
- return SegmentLoader;
-}(videojs__default['default'].EventTarget);
-
-function noop() {}
-
-var toTitleCase = function toTitleCase(string) {
- if (typeof string !== 'string') {
- return string;
- }
-
- return string.replace(/./, function (w) {
- return w.toUpperCase();
- });
-};
-
-var bufferTypes = ['video', 'audio'];
-
-var _updating = function updating(type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
-};
-
-var nextQueueIndexOfType = function nextQueueIndexOfType(type, queue) {
- for (var i = 0; i < queue.length; i++) {
- var queueEntry = queue[i];
-
- if (queueEntry.type === 'mediaSource') {
- // If the next entry is a media source entry (uses multiple source buffers), block
- // processing to allow it to go through first.
- return null;
- }
-
- if (queueEntry.type === type) {
- return i;
- }
- }
-
- return null;
-};
-
-var shiftQueue = function shiftQueue(type, sourceUpdater) {
- if (sourceUpdater.queue.length === 0) {
- return;
- }
-
- var queueIndex = 0;
- var queueEntry = sourceUpdater.queue[queueIndex];
-
- if (queueEntry.type === 'mediaSource') {
- if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
- sourceUpdater.queue.shift();
- queueEntry.action(sourceUpdater);
-
- if (queueEntry.doneFn) {
- queueEntry.doneFn();
- } // Only specific source buffer actions must wait for async updateend events. Media
- // Source actions process synchronously. Therefore, both audio and video source
- // buffers are now clear to process the next queue entries.
-
-
- shiftQueue('audio', sourceUpdater);
- shiftQueue('video', sourceUpdater);
- } // Media Source actions require both source buffers, so if the media source action
- // couldn't process yet (because one or both source buffers are busy), block other
- // queue actions until both are available and the media source action can process.
-
-
- return;
- }
-
- if (type === 'mediaSource') {
- // If the queue was shifted by a media source action (this happens when pushing a
- // media source action onto the queue), then it wasn't from an updateend event from an
- // audio or video source buffer, so there's no change from previous state, and no
- // processing should be done.
- return;
- } // Media source queue entries don't need to consider whether the source updater is
- // started (i.e., source buffers are created) as they don't need the source buffers, but
- // source buffer queue entries do.
-
-
- if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || _updating(type, sourceUpdater)) {
- return;
- }
-
- if (queueEntry.type !== type) {
- queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
-
- if (queueIndex === null) {
- // Either there's no queue entry that uses this source buffer type in the queue, or
- // there's a media source queue entry before the next entry of this type, in which
- // case wait for that action to process first.
- return;
- }
-
- queueEntry = sourceUpdater.queue[queueIndex];
- }
-
- sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
- //
- // The queue pending operation must be set before the action is performed in the event
- // that the action results in a synchronous event that is acted upon. For instance, if
- // an exception is thrown that can be handled, it's possible that new actions will be
- // appended to an empty queue and immediately executed, but would not have the correct
- // pending information if this property was set after the action was performed.
-
- sourceUpdater.queuePending[type] = queueEntry;
- queueEntry.action(type, sourceUpdater);
-
- if (!queueEntry.doneFn) {
- // synchronous operation, process next entry
- sourceUpdater.queuePending[type] = null;
- shiftQueue(type, sourceUpdater);
- return;
- }
-};
-
-var cleanupBuffer = function cleanupBuffer(type, sourceUpdater) {
- var buffer = sourceUpdater[type + "Buffer"];
- var titleType = toTitleCase(type);
-
- if (!buffer) {
- return;
- }
-
- buffer.removeEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
- buffer.removeEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
- sourceUpdater.codecs[type] = null;
- sourceUpdater[type + "Buffer"] = null;
-};
-
-var inSourceBuffers = function inSourceBuffers(mediaSource, sourceBuffer) {
- return mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
-};
-
-var actions = {
- appendBuffer: function appendBuffer(bytes, segmentInfo, onError) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Appending segment " + segmentInfo.mediaIndex + "'s " + bytes.length + " bytes to " + type + "Buffer");
-
- try {
- sourceBuffer.appendBuffer(bytes);
- } catch (e) {
- sourceUpdater.logger_("Error with code " + e.code + " " + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + ("when appending segment " + segmentInfo.mediaIndex + " to " + type + "Buffer"));
- sourceUpdater.queuePending[type] = null;
- onError(e);
- }
- };
- },
- remove: function remove(start, end) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Removing " + start + " to " + end + " from " + type + "Buffer");
-
- try {
- sourceBuffer.remove(start, end);
- } catch (e) {
- sourceUpdater.logger_("Remove " + start + " to " + end + " from " + type + "Buffer failed");
- }
- };
- },
- timestampOffset: function timestampOffset(offset) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Setting " + type + "timestampOffset to " + offset);
- sourceBuffer.timestampOffset = offset;
- };
- },
- callback: function callback(_callback) {
- return function (type, sourceUpdater) {
- _callback();
- };
- },
- endOfStream: function endOfStream(error) {
- return function (sourceUpdater) {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
-
- sourceUpdater.logger_("Calling mediaSource endOfStream(" + (error || '') + ")");
-
- try {
- sourceUpdater.mediaSource.endOfStream(error);
- } catch (e) {
- videojs__default['default'].log.warn('Failed to call media source endOfStream', e);
- }
- };
- },
- duration: function duration(_duration) {
- return function (sourceUpdater) {
- sourceUpdater.logger_("Setting mediaSource duration to " + _duration);
-
- try {
- sourceUpdater.mediaSource.duration = _duration;
- } catch (e) {
- videojs__default['default'].log.warn('Failed to set media source duration', e);
- }
- };
- },
- abort: function abort() {
- return function (type, sourceUpdater) {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
-
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("calling abort on " + type + "Buffer");
-
- try {
- sourceBuffer.abort();
- } catch (e) {
- videojs__default['default'].log.warn("Failed to abort on " + type + "Buffer", e);
- }
- };
- },
- addSourceBuffer: function addSourceBuffer(type, codec) {
- return function (sourceUpdater) {
- var titleType = toTitleCase(type);
- var mime = codecs_js.getMimeForCodec(codec);
- sourceUpdater.logger_("Adding " + type + "Buffer with codec " + codec + " to mediaSource");
- var sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
- sourceBuffer.addEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
- sourceBuffer.addEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
- sourceUpdater.codecs[type] = codec;
- sourceUpdater[type + "Buffer"] = sourceBuffer;
- };
- },
- removeSourceBuffer: function removeSourceBuffer(type) {
- return function (sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Removing " + type + "Buffer with codec " + sourceUpdater.codecs[type] + " from mediaSource");
-
- try {
- sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
- } catch (e) {
- videojs__default['default'].log.warn("Failed to removeSourceBuffer " + type + "Buffer", e);
- }
- };
- },
- changeType: function changeType(codec) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- var mime = codecs_js.getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- } // do not update codec if we don't need to.
-
-
- if (sourceUpdater.codecs[type] === codec) {
- return;
- }
-
- sourceUpdater.logger_("changing " + type + "Buffer codec from " + sourceUpdater.codecs[type] + " to " + codec);
- sourceBuffer.changeType(mime);
- sourceUpdater.codecs[type] = codec;
- };
- }
-};
-
-var pushQueue = function pushQueue(_ref) {
- var type = _ref.type,
- sourceUpdater = _ref.sourceUpdater,
- action = _ref.action,
- doneFn = _ref.doneFn,
- name = _ref.name;
- sourceUpdater.queue.push({
- type: type,
- action: action,
- doneFn: doneFn,
- name: name
- });
- shiftQueue(type, sourceUpdater);
-};
-
-var onUpdateend = function onUpdateend(type, sourceUpdater) {
- return function (e) {
- // Although there should, in theory, be a pending action for any updateend receieved,
- // there are some actions that may trigger updateend events without set definitions in
- // the w3c spec. For instance, setting the duration on the media source may trigger
- // updateend events on source buffers. This does not appear to be in the spec. As such,
- // if we encounter an updateend without a corresponding pending action from our queue
- // for that source buffer type, process the next action.
- if (sourceUpdater.queuePending[type]) {
- var doneFn = sourceUpdater.queuePending[type].doneFn;
- sourceUpdater.queuePending[type] = null;
-
- if (doneFn) {
- // if there's an error, report it
- doneFn(sourceUpdater[type + "Error_"]);
- }
- }
-
- shiftQueue(type, sourceUpdater);
- };
-};
-/**
- * A queue of callbacks to be serialized and applied when a
- * MediaSource and its associated SourceBuffers are not in the
- * updating state. It is used by the segment loader to update the
- * underlying SourceBuffers when new data is loaded, for instance.
- *
- * @class SourceUpdater
- * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
- * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
- */
-
-
-var SourceUpdater = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose__default['default'](SourceUpdater, _videojs$EventTarget);
-
- function SourceUpdater(mediaSource) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- _this.mediaSource = mediaSource;
-
- _this.sourceopenListener_ = function () {
- return shiftQueue('mediaSource', _assertThisInitialized__default['default'](_this));
- };
-
- _this.mediaSource.addEventListener('sourceopen', _this.sourceopenListener_);
-
- _this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
-
- _this.audioTimestampOffset_ = 0;
- _this.videoTimestampOffset_ = 0;
- _this.queue = [];
- _this.queuePending = {
- audio: null,
- video: null
- };
- _this.delayedAudioAppendQueue_ = [];
- _this.videoAppendQueued_ = false;
- _this.codecs = {};
- _this.onVideoUpdateEnd_ = onUpdateend('video', _assertThisInitialized__default['default'](_this));
- _this.onAudioUpdateEnd_ = onUpdateend('audio', _assertThisInitialized__default['default'](_this));
-
- _this.onVideoError_ = function (e) {
- // used for debugging
- _this.videoError_ = e;
- };
-
- _this.onAudioError_ = function (e) {
- // used for debugging
- _this.audioError_ = e;
- };
-
- _this.createdSourceBuffers_ = false;
- _this.initializedEme_ = false;
- _this.triggeredReady_ = false;
- return _this;
- }
-
- var _proto = SourceUpdater.prototype;
-
- _proto.initializedEme = function initializedEme() {
- this.initializedEme_ = true;
- this.triggerReady();
- };
-
- _proto.hasCreatedSourceBuffers = function hasCreatedSourceBuffers() {
- // if false, likely waiting on one of the segment loaders to get enough data to create
- // source buffers
- return this.createdSourceBuffers_;
- };
-
- _proto.hasInitializedAnyEme = function hasInitializedAnyEme() {
- return this.initializedEme_;
- };
-
- _proto.ready = function ready() {
- return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
- };
-
- _proto.createSourceBuffers = function createSourceBuffers(codecs) {
- if (this.hasCreatedSourceBuffers()) {
- // already created them before
- return;
- } // the intial addOrChangeSourceBuffers will always be
- // two add buffers.
-
-
- this.addOrChangeSourceBuffers(codecs);
- this.createdSourceBuffers_ = true;
- this.trigger('createdsourcebuffers');
- this.triggerReady();
- };
-
- _proto.triggerReady = function triggerReady() {
- // only allow ready to be triggered once, this prevents the case
- // where:
- // 1. we trigger createdsourcebuffers
- // 2. ie 11 synchronously initializates eme
- // 3. the synchronous initialization causes us to trigger ready
- // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
- if (this.ready() && !this.triggeredReady_) {
- this.triggeredReady_ = true;
- this.trigger('ready');
- }
- }
- /**
- * Add a type of source buffer to the media source.
- *
- * @param {string} type
- * The type of source buffer to add.
- *
- * @param {string} codec
- * The codec to add the source buffer with.
- */
- ;
-
- _proto.addSourceBuffer = function addSourceBuffer(type, codec) {
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.addSourceBuffer(type, codec),
- name: 'addSourceBuffer'
- });
- }
- /**
- * call abort on a source buffer.
- *
- * @param {string} type
- * The type of source buffer to call abort on.
- */
- ;
-
- _proto.abort = function abort(type) {
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.abort(type),
- name: 'abort'
- });
- }
- /**
- * Call removeSourceBuffer and remove a specific type
- * of source buffer on the mediaSource.
- *
- * @param {string} type
- * The type of source buffer to remove.
- */
- ;
-
- _proto.removeSourceBuffer = function removeSourceBuffer(type) {
- if (!this.canRemoveSourceBuffer()) {
- videojs__default['default'].log.error('removeSourceBuffer is not supported!');
- return;
- }
-
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.removeSourceBuffer(type),
- name: 'removeSourceBuffer'
- });
- }
- /**
- * Whether or not the removeSourceBuffer function is supported
- * on the mediaSource.
- *
- * @return {boolean}
- * if removeSourceBuffer can be called.
- */
- ;
-
- _proto.canRemoveSourceBuffer = function canRemoveSourceBuffer() {
- // IE reports that it supports removeSourceBuffer, but often throws
- // errors when attempting to use the function. So we report that it
- // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
- // throws errors, so we report that it does not support this as well.
- return !videojs__default['default'].browser.IE_VERSION && !videojs__default['default'].browser.IS_FIREFOX && window__default['default'].MediaSource && window__default['default'].MediaSource.prototype && typeof window__default['default'].MediaSource.prototype.removeSourceBuffer === 'function';
- }
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- ;
-
- SourceUpdater.canChangeType = function canChangeType() {
- return window__default['default'].SourceBuffer && window__default['default'].SourceBuffer.prototype && typeof window__default['default'].SourceBuffer.prototype.changeType === 'function';
- }
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- ;
-
- _proto.canChangeType = function canChangeType() {
- return this.constructor.canChangeType();
- }
- /**
- * Call the changeType function on a source buffer, given the code and type.
- *
- * @param {string} type
- * The type of source buffer to call changeType on.
- *
- * @param {string} codec
- * The codec string to change type with on the source buffer.
- */
- ;
-
- _proto.changeType = function changeType(type, codec) {
- if (!this.canChangeType()) {
- videojs__default['default'].log.error('changeType is not supported!');
- return;
- }
-
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.changeType(codec),
- name: 'changeType'
- });
- }
- /**
- * Add source buffers with a codec or, if they are already created,
- * call changeType on source buffers using changeType.
- *
- * @param {Object} codecs
- * Codecs to switch to
- */
- ;
-
- _proto.addOrChangeSourceBuffers = function addOrChangeSourceBuffers(codecs) {
- var _this2 = this;
-
- if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
- throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
- }
-
- Object.keys(codecs).forEach(function (type) {
- var codec = codecs[type];
-
- if (!_this2.hasCreatedSourceBuffers()) {
- return _this2.addSourceBuffer(type, codec);
- }
-
- if (_this2.canChangeType()) {
- _this2.changeType(type, codec);
- }
- });
- }
- /**
- * Queue an update to append an ArrayBuffer.
- *
- * @param {MediaObject} object containing audioBytes and/or videoBytes
- * @param {Function} done the function to call when done
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
- */
- ;
-
- _proto.appendBuffer = function appendBuffer(options, doneFn) {
- var _this3 = this;
-
- var segmentInfo = options.segmentInfo,
- type = options.type,
- bytes = options.bytes;
- this.processedAppend_ = true;
-
- if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
- this.delayedAudioAppendQueue_.push([options, doneFn]);
- this.logger_("delayed audio append of " + bytes.length + " until video append");
- return;
- } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
- // not be fired. This means that the queue will be blocked until the next action
- // taken by the segment-loader. Provide a mechanism for segment-loader to handle
- // these errors by calling the doneFn with the specific error.
-
-
- var onError = doneFn;
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.appendBuffer(bytes, segmentInfo || {
- mediaIndex: -1
- }, onError),
- doneFn: doneFn,
- name: 'appendBuffer'
- });
-
- if (type === 'video') {
- this.videoAppendQueued_ = true;
-
- if (!this.delayedAudioAppendQueue_.length) {
- return;
- }
-
- var queue = this.delayedAudioAppendQueue_.slice();
- this.logger_("queuing delayed audio " + queue.length + " appendBuffers");
- this.delayedAudioAppendQueue_.length = 0;
- queue.forEach(function (que) {
- _this3.appendBuffer.apply(_this3, que);
- });
- }
- }
- /**
- * Get the audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The audio buffer's buffered time range
- */
- ;
-
- _proto.audioBuffered = function audioBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
- return videojs__default['default'].createTimeRange();
- }
-
- return this.audioBuffer.buffered ? this.audioBuffer.buffered : videojs__default['default'].createTimeRange();
- }
- /**
- * Get the video buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The video buffer's buffered time range
- */
- ;
-
- _proto.videoBuffered = function videoBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
- return videojs__default['default'].createTimeRange();
- }
-
- return this.videoBuffer.buffered ? this.videoBuffer.buffered : videojs__default['default'].createTimeRange();
- }
- /**
- * Get a combined video/audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * the combined time range
- */
- ;
-
- _proto.buffered = function buffered() {
- var video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
- var audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
-
- if (audio && !video) {
- return this.audioBuffered();
- }
-
- if (video && !audio) {
- return this.videoBuffered();
- }
-
- return bufferIntersection(this.audioBuffered(), this.videoBuffered());
- }
- /**
- * Add a callback to the queue that will set duration on the mediaSource.
- *
- * @param {number} duration
- * The duration to set
- *
- * @param {Function} [doneFn]
- * function to run after duration has been set.
- */
- ;
-
- _proto.setDuration = function setDuration(duration, doneFn) {
- if (doneFn === void 0) {
- doneFn = noop;
- }
-
- // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.duration(duration),
- name: 'duration',
- doneFn: doneFn
- });
- }
- /**
- * Add a mediaSource endOfStream call to the queue
- *
- * @param {Error} [error]
- * Call endOfStream with an error
- *
- * @param {Function} [doneFn]
- * A function that should be called when the
- * endOfStream call has finished.
- */
- ;
-
- _proto.endOfStream = function endOfStream(error, doneFn) {
- if (error === void 0) {
- error = null;
- }
-
- if (doneFn === void 0) {
- doneFn = noop;
- }
-
- if (typeof error !== 'string') {
- error = undefined;
- } // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
-
-
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.endOfStream(error),
- name: 'endOfStream',
- doneFn: doneFn
- });
- }
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- ;
-
- _proto.removeAudio = function removeAudio(start, end, done) {
- if (done === void 0) {
- done = noop;
- }
-
- if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- ;
-
- _proto.removeVideo = function removeVideo(start, end, done) {
- if (done === void 0) {
- done = noop;
- }
-
- if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
- /**
- * Whether the underlying sourceBuffer is updating or not
- *
- * @return {boolean} the updating status of the SourceBuffer
- */
- ;
-
- _proto.updating = function updating() {
- // the audio/video source buffer is updating
- if (_updating('audio', this) || _updating('video', this)) {
- return true;
- }
-
- return false;
- }
- /**
- * Set/get the timestampoffset on the audio SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- ;
-
- _proto.audioTimestampOffset = function audioTimestampOffset(offset) {
- if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
- this.audioTimestampOffset_ !== offset) {
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.audioTimestampOffset_ = offset;
- }
-
- return this.audioTimestampOffset_;
- }
- /**
- * Set/get the timestampoffset on the video SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- ;
-
- _proto.videoTimestampOffset = function videoTimestampOffset(offset) {
- if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
- this.videoTimestampOffset !== offset) {
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.videoTimestampOffset_ = offset;
- }
-
- return this.videoTimestampOffset_;
- }
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the audio queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- ;
-
- _proto.audioQueueCallback = function audioQueueCallback(callback) {
- if (!this.audioBuffer) {
- return;
- }
-
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the video queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- ;
-
- _proto.videoQueueCallback = function videoQueueCallback(callback) {
- if (!this.videoBuffer) {
- return;
- }
-
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
- /**
- * dispose of the source updater and the underlying sourceBuffer
- */
- ;
-
- _proto.dispose = function dispose() {
- var _this4 = this;
-
- this.trigger('dispose');
- bufferTypes.forEach(function (type) {
- _this4.abort(type);
-
- if (_this4.canRemoveSourceBuffer()) {
- _this4.removeSourceBuffer(type);
- } else {
- _this4[type + "QueueCallback"](function () {
- return cleanupBuffer(type, _this4);
- });
- }
- });
- this.videoAppendQueued_ = false;
- this.delayedAudioAppendQueue_.length = 0;
-
- if (this.sourceopenListener_) {
- this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
- }
-
- this.off();
- };
-
- return SourceUpdater;
-}(videojs__default['default'].EventTarget);
-
-var uint8ToUtf8 = function uint8ToUtf8(uintArray) {
- return decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
-};
-
-var VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(function (char) {
- return char.charCodeAt(0);
-}));
-/**
- * An object that manages segment loading and appending.
- *
- * @class VTTSegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-
-var VTTSegmentLoader = /*#__PURE__*/function (_SegmentLoader) {
- _inheritsLoose__default['default'](VTTSegmentLoader, _SegmentLoader);
-
- function VTTSegmentLoader(settings, options) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _SegmentLoader.call(this, settings, options) || this; // SegmentLoader requires a MediaSource be specified or it will throw an error;
- // however, VTTSegmentLoader has no need of a media source, so delete the reference
-
- _this.mediaSource_ = null;
- _this.subtitlesTrack_ = null;
- _this.loaderType_ = 'subtitle';
- _this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
- // the sync controller leads to improper behavior.
-
- _this.shouldSaveSegmentTimingInfo_ = false;
- return _this;
- }
-
- var _proto = VTTSegmentLoader.prototype;
-
- _proto.createTransmuxer_ = function createTransmuxer_() {
- // don't need to transmux any subtitles
- return null;
- }
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- ;
-
- _proto.buffered_ = function buffered_() {
- if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
- return videojs__default['default'].createTimeRanges();
- }
-
- var cues = this.subtitlesTrack_.cues;
- var start = cues[0].startTime;
- var end = cues[cues.length - 1].startTime;
- return videojs__default['default'].createTimeRanges([[start, end]]);
- }
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- ;
-
- _proto.initSegmentForMap = function initSegmentForMap(map, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!map) {
- return null;
- }
-
- var id = initSegmentId(map);
- var storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- // append WebVTT line terminators to the media initialization segment if it exists
- // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
- // requires two or more WebVTT line terminators between the WebVTT header and the
- // rest of the file
- var combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
- var combinedSegment = new Uint8Array(combinedByteLength);
- combinedSegment.set(map.bytes);
- combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: combinedSegment
- };
- }
-
- return storedMap || map;
- }
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- ;
-
- _proto.couldBeginLoading_ = function couldBeginLoading_() {
- return this.playlist_ && this.subtitlesTrack_ && !this.paused();
- }
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- ;
-
- _proto.init_ = function init_() {
- this.state = 'READY';
- this.resetEverything();
- return this.monitorBuffer_();
- }
- /**
- * Set a subtitle track on the segment loader to add subtitles to
- *
- * @param {TextTrack=} track
- * The text track to add loaded subtitles to
- * @return {TextTrack}
- * Returns the subtitles track
- */
- ;
-
- _proto.track = function track(_track) {
- if (typeof _track === 'undefined') {
- return this.subtitlesTrack_;
- }
-
- this.subtitlesTrack_ = _track; // if we were unpaused but waiting for a sourceUpdater, start
- // buffering now
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- this.init_();
- }
-
- return this.subtitlesTrack_;
- }
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- */
- ;
-
- _proto.remove = function remove(start, end) {
- removeCuesFromTrack(start, end, this.subtitlesTrack_);
- }
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- ;
-
- _proto.fillBuffer_ = function fillBuffer_() {
- var _this2 = this;
-
- // see if we need to begin loading immediately
- var segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
- // We don't have the timestamp offset that we need to sync subtitles.
- // Rerun on a timestamp offset or user interaction.
- var checkTimestampOffset = function checkTimestampOffset() {
- _this2.state = 'READY';
-
- if (!_this2.paused()) {
- // if not paused, queue a buffer check as soon as possible
- _this2.monitorBuffer_();
- }
- };
-
- this.syncController_.one('timestampoffset', checkTimestampOffset);
- this.state = 'WAITING_ON_TIMELINE';
- return;
- }
-
- this.loadSegment_(segmentInfo);
- } // never set a timestamp offset for vtt segments.
- ;
-
- _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_() {
- return null;
- };
-
- _proto.chooseNextRequest_ = function chooseNextRequest_() {
- return this.skipEmptySegments_(_SegmentLoader.prototype.chooseNextRequest_.call(this));
- }
- /**
- * Prevents the segment loader from requesting segments we know contain no subtitles
- * by walking forward until we find the next segment that we don't know whether it is
- * empty or not.
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @return {Object}
- * a segment info object that describes the current segment
- */
- ;
-
- _proto.skipEmptySegments_ = function skipEmptySegments_(segmentInfo) {
- while (segmentInfo && segmentInfo.segment.empty) {
- // stop at the last possible segmentInfo
- if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
- segmentInfo = null;
- break;
- }
-
- segmentInfo = this.generateSegmentInfo_({
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex + 1,
- startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
- isSyncRequest: segmentInfo.isSyncRequest
- });
- }
-
- return segmentInfo;
- };
-
- _proto.stopForError = function stopForError(error) {
- this.error(error);
- this.state = 'READY';
- this.pause();
- this.trigger('error');
- }
- /**
- * append a decrypted segement to the SourceBuffer through a SourceUpdater
- *
- * @private
- */
- ;
-
- _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
- var _this3 = this;
-
- if (!this.subtitlesTrack_) {
- this.state = 'READY';
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats); // the request was aborted
-
- if (!this.pendingSegment_) {
- this.state = 'READY';
- this.mediaRequestsAborted += 1;
- return;
- }
-
- if (error) {
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- }
-
- if (error.code === REQUEST_ERRORS.ABORTED) {
- this.mediaRequestsAborted += 1;
- } else {
- this.mediaRequestsErrored += 1;
- }
-
- this.stopForError(error);
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functionality between segment loaders
-
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
- this.state = 'APPENDING'; // used for tests
-
- this.trigger('appending');
- var segment = segmentInfo.segment;
-
- if (segment.map) {
- segment.map.bytes = simpleSegment.map.bytes;
- }
-
- segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, wait till it finished loading
-
- if (typeof window__default['default'].WebVTT !== 'function' && this.subtitlesTrack_ && this.subtitlesTrack_.tech_) {
- var loadHandler;
-
- var errorHandler = function errorHandler() {
- _this3.subtitlesTrack_.tech_.off('vttjsloaded', loadHandler);
-
- _this3.stopForError({
- message: 'Error loading vtt.js'
- });
-
- return;
- };
-
- loadHandler = function loadHandler() {
- _this3.subtitlesTrack_.tech_.off('vttjserror', errorHandler);
-
- _this3.segmentRequestFinished_(error, simpleSegment, result);
- };
-
- this.state = 'WAITING_ON_VTTJS';
- this.subtitlesTrack_.tech_.one('vttjsloaded', loadHandler);
- this.subtitlesTrack_.tech_.one('vttjserror', errorHandler);
- return;
- }
-
- segment.requested = true;
-
- try {
- this.parseVTTCues_(segmentInfo);
- } catch (e) {
- this.stopForError({
- message: e.message
- });
- return;
- }
-
- this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
-
- if (segmentInfo.cues.length) {
- segmentInfo.timingInfo = {
- start: segmentInfo.cues[0].startTime,
- end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
- };
- } else {
- segmentInfo.timingInfo = {
- start: segmentInfo.startOfSegment,
- end: segmentInfo.startOfSegment + segmentInfo.duration
- };
- }
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate');
- this.pendingSegment_ = null;
- this.state = 'READY';
- return;
- }
-
- segmentInfo.byteLength = segmentInfo.bytes.byteLength;
- this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
- // the subtitle track
-
- segmentInfo.cues.forEach(function (cue) {
- _this3.subtitlesTrack_.addCue(_this3.featuresNativeTextTracks_ ? new window__default['default'].VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
- }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
- // cues to have identical time-intervals, but if the text is also identical
- // we can safely assume it is a duplicate that can be removed (ex. when a cue
- // "overlaps" VTT segments)
-
- removeDuplicateCuesFromTrack(this.subtitlesTrack_);
- this.handleAppendsDone_();
- };
-
- _proto.handleData_ = function handleData_() {// noop as we shouldn't be getting video/audio data captions
- // that we do not support here.
- };
-
- _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_() {// noop
- }
- /**
- * Uses the WebVTT parser to parse the segment response
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @private
- */
- ;
-
- _proto.parseVTTCues_ = function parseVTTCues_(segmentInfo) {
- var decoder;
- var decodeBytesToString = false;
-
- if (typeof window__default['default'].TextDecoder === 'function') {
- decoder = new window__default['default'].TextDecoder('utf8');
- } else {
- decoder = window__default['default'].WebVTT.StringDecoder();
- decodeBytesToString = true;
- }
-
- var parser = new window__default['default'].WebVTT.Parser(window__default['default'], window__default['default'].vttjs, decoder);
- segmentInfo.cues = [];
- segmentInfo.timestampmap = {
- MPEGTS: 0,
- LOCAL: 0
- };
- parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
-
- parser.ontimestampmap = function (map) {
- segmentInfo.timestampmap = map;
- };
-
- parser.onparsingerror = function (error) {
- videojs__default['default'].log.warn('Error encountered when parsing cues: ' + error.message);
- };
-
- if (segmentInfo.segment.map) {
- var mapData = segmentInfo.segment.map.bytes;
-
- if (decodeBytesToString) {
- mapData = uint8ToUtf8(mapData);
- }
-
- parser.parse(mapData);
- }
-
- var segmentData = segmentInfo.bytes;
-
- if (decodeBytesToString) {
- segmentData = uint8ToUtf8(segmentData);
- }
-
- parser.parse(segmentData);
- parser.flush();
- }
- /**
- * Updates the start and end times of any cues parsed by the WebVTT parser using
- * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
- * from the SyncController
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @param {Object} mappingObj
- * object containing a mapping from TS to media time
- * @param {Object} playlist
- * the playlist object containing the segment
- * @private
- */
- ;
-
- _proto.updateTimeMapping_ = function updateTimeMapping_(segmentInfo, mappingObj, playlist) {
- var segment = segmentInfo.segment;
-
- if (!mappingObj) {
- // If the sync controller does not have a mapping of TS to Media Time for the
- // timeline, then we don't have enough information to update the cue
- // start/end times
- return;
- }
-
- if (!segmentInfo.cues.length) {
- // If there are no cues, we also do not have enough information to figure out
- // segment timing. Mark that the segment contains no cues so we don't re-request
- // an empty segment.
- segment.empty = true;
- return;
- }
-
- var timestampmap = segmentInfo.timestampmap;
- var diff = timestampmap.MPEGTS / clock.ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
- segmentInfo.cues.forEach(function (cue) {
- // First convert cue time to TS time using the timestamp-map provided within the vtt
- cue.startTime += diff;
- cue.endTime += diff;
- });
-
- if (!playlist.syncInfo) {
- var firstStart = segmentInfo.cues[0].startTime;
- var lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
- playlist.syncInfo = {
- mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
- time: Math.min(firstStart, lastStart - segment.duration)
- };
- }
- };
-
- return VTTSegmentLoader;
-}(SegmentLoader);
-
-/**
- * @file ad-cue-tags.js
- */
-/**
- * Searches for an ad cue that overlaps with the given mediaTime
- *
- * @param {Object} track
- * the track to find the cue for
- *
- * @param {number} mediaTime
- * the time to find the cue at
- *
- * @return {Object|null}
- * the found cue or null
- */
-
-var findAdCue = function findAdCue(track, mediaTime) {
- var cues = track.cues;
-
- for (var i = 0; i < cues.length; i++) {
- var cue = cues[i];
-
- if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
- return cue;
- }
- }
-
- return null;
-};
-var updateAdCues = function updateAdCues(media, track, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- if (!media.segments) {
- return;
- }
-
- var mediaTime = offset;
- var cue;
-
- for (var i = 0; i < media.segments.length; i++) {
- var segment = media.segments[i];
-
- if (!cue) {
- // Since the cues will span for at least the segment duration, adding a fudge
- // factor of half segment duration will prevent duplicate cues from being
- // created when timing info is not exact (e.g. cue start time initialized
- // at 10.006677, but next call mediaTime is 10.003332 )
- cue = findAdCue(track, mediaTime + segment.duration / 2);
- }
-
- if (cue) {
- if ('cueIn' in segment) {
- // Found a CUE-IN so end the cue
- cue.endTime = mediaTime;
- cue.adEndTime = mediaTime;
- mediaTime += segment.duration;
- cue = null;
- continue;
- }
-
- if (mediaTime < cue.endTime) {
- // Already processed this mediaTime for this cue
- mediaTime += segment.duration;
- continue;
- } // otherwise extend cue until a CUE-IN is found
-
-
- cue.endTime += segment.duration;
- } else {
- if ('cueOut' in segment) {
- cue = new window__default['default'].VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
- cue.adStartTime = mediaTime; // Assumes tag format to be
- // #EXT-X-CUE-OUT:30
-
- cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
- track.addCue(cue);
- }
-
- if ('cueOutCont' in segment) {
- // Entered into the middle of an ad cue
- // Assumes tag formate to be
- // #EXT-X-CUE-OUT-CONT:10/30
- var _segment$cueOutCont$s = segment.cueOutCont.split('/').map(parseFloat),
- adOffset = _segment$cueOutCont$s[0],
- adTotal = _segment$cueOutCont$s[1];
-
- cue = new window__default['default'].VTTCue(mediaTime, mediaTime + segment.duration, '');
- cue.adStartTime = mediaTime - adOffset;
- cue.adEndTime = cue.adStartTime + adTotal;
- track.addCue(cue);
- }
- }
-
- mediaTime += segment.duration;
- }
-};
-
-var syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
-// the equivalence display-time 0 === segment-index 0
-{
- name: 'VOD',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (duration !== Infinity) {
- var syncPoint = {
- time: 0,
- segmentIndex: 0,
- partIndex: null
- };
- return syncPoint;
- }
-
- return null;
- }
-}, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
-{
- name: 'ProgramDateTime',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
- return null;
- }
-
- var syncPoint = null;
- var lastDistance = null;
- var partsAndSegments = getPartsAndSegments(playlist);
- currentTime = currentTime || 0;
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
- var partAndSegment = partsAndSegments[index];
- var segment = partAndSegment.segment;
- var datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
-
- if (!datetimeMapping) {
- continue;
- }
-
- if (segment.dateTimeObject) {
- var segmentTime = segment.dateTimeObject.getTime() / 1000;
- var start = segmentTime + datetimeMapping; // take part duration into account.
-
- if (segment.parts && typeof partAndSegment.partIndex === 'number') {
- for (var z = 0; z < partAndSegment.partIndex; z++) {
- start += segment.parts[z].duration;
- }
- }
-
- var distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
- break;
- }
-
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
- }
-
- return syncPoint;
- }
-}, // Stategy "Segment": We have a known time mapping for a timeline and a
-// segment in the current timeline with timing data
-{
- name: 'Segment',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- var syncPoint = null;
- var lastDistance = null;
- currentTime = currentTime || 0;
- var partsAndSegments = getPartsAndSegments(playlist);
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
- var partAndSegment = partsAndSegments[index];
- var segment = partAndSegment.segment;
- var start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
-
- if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
- var distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
- }
- }
-
- return syncPoint;
- }
-}, // Stategy "Discontinuity": We have a discontinuity with a known
-// display-time
-{
- name: 'Discontinuity',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- var syncPoint = null;
- currentTime = currentTime || 0;
-
- if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- var lastDistance = null;
-
- for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
- var segmentIndex = playlist.discontinuityStarts[i];
- var discontinuity = playlist.discontinuitySequence + i + 1;
- var discontinuitySync = syncController.discontinuities[discontinuity];
-
- if (discontinuitySync) {
- var distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: discontinuitySync.time,
- segmentIndex: segmentIndex,
- partIndex: null
- };
- }
- }
- }
- }
-
- return syncPoint;
- }
-}, // Stategy "Playlist": We have a playlist with a known mapping of
-// segment index to display time
-{
- name: 'Playlist',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (playlist.syncInfo) {
- var syncPoint = {
- time: playlist.syncInfo.time,
- segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
- partIndex: null
- };
- return syncPoint;
- }
-
- return null;
- }
-}];
-
-var SyncController = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose__default['default'](SyncController, _videojs$EventTarget);
-
- function SyncController(options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this; // ...for synching across variants
-
- _this.timelines = [];
- _this.discontinuities = [];
- _this.timelineToDatetimeMappings = {};
- _this.logger_ = logger('SyncController');
- return _this;
- }
- /**
- * Find a sync-point for the playlist specified
- *
- * A sync-point is defined as a known mapping from display-time to
- * a segment-index in the current playlist.
- *
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinite if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Object}
- * A sync-point object
- */
-
-
- var _proto = SyncController.prototype;
-
- _proto.getSyncPoint = function getSyncPoint(playlist, duration, currentTimeline, currentTime) {
- var syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
-
- if (!syncPoints.length) {
- // Signal that we need to attempt to get a sync-point manually
- // by fetching a segment in the playlist and constructing
- // a sync-point from that information
- return null;
- } // Now find the sync-point that is closest to the currentTime because
- // that should result in the most accurate guess about which segment
- // to fetch
-
-
- return this.selectSyncPoint_(syncPoints, {
- key: 'time',
- value: currentTime
- });
- }
- /**
- * Calculate the amount of time that has expired off the playlist during playback
- *
- * @param {Playlist} playlist
- * Playlist object to calculate expired from
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playling a live source)
- * @return {number|null}
- * The amount of time that has expired off the playlist during playback. Null
- * if no sync-points for the playlist can be found.
- */
- ;
-
- _proto.getExpiredTime = function getExpiredTime(playlist, duration) {
- if (!playlist || !playlist.segments) {
- return null;
- }
-
- var syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
-
- if (!syncPoints.length) {
- return null;
- }
-
- var syncPoint = this.selectSyncPoint_(syncPoints, {
- key: 'segmentIndex',
- value: 0
- }); // If the sync-point is beyond the start of the playlist, we want to subtract the
- // duration from index 0 to syncPoint.segmentIndex instead of adding.
-
- if (syncPoint.segmentIndex > 0) {
- syncPoint.time *= -1;
- }
-
- return Math.abs(syncPoint.time + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: syncPoint.segmentIndex,
- endIndex: 0
- }));
- }
- /**
- * Runs each sync-point strategy and returns a list of sync-points returned by the
- * strategies
- *
- * @private
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Array}
- * A list of sync-point objects
- */
- ;
-
- _proto.runStrategies_ = function runStrategies_(playlist, duration, currentTimeline, currentTime) {
- var syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
-
- for (var i = 0; i < syncPointStrategies.length; i++) {
- var strategy = syncPointStrategies[i];
- var syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
-
- if (syncPoint) {
- syncPoint.strategy = strategy.name;
- syncPoints.push({
- strategy: strategy.name,
- syncPoint: syncPoint
- });
- }
- }
-
- return syncPoints;
- }
- /**
- * Selects the sync-point nearest the specified target
- *
- * @private
- * @param {Array} syncPoints
- * List of sync-points to select from
- * @param {Object} target
- * Object specifying the property and value we are targeting
- * @param {string} target.key
- * Specifies the property to target. Must be either 'time' or 'segmentIndex'
- * @param {number} target.value
- * The value to target for the specified key.
- * @return {Object}
- * The sync-point nearest the target
- */
- ;
-
- _proto.selectSyncPoint_ = function selectSyncPoint_(syncPoints, target) {
- var bestSyncPoint = syncPoints[0].syncPoint;
- var bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
- var bestStrategy = syncPoints[0].strategy;
-
- for (var i = 1; i < syncPoints.length; i++) {
- var newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
-
- if (newDistance < bestDistance) {
- bestDistance = newDistance;
- bestSyncPoint = syncPoints[i].syncPoint;
- bestStrategy = syncPoints[i].strategy;
- }
- }
-
- this.logger_("syncPoint for [" + target.key + ": " + target.value + "] chosen with strategy" + (" [" + bestStrategy + "]: [time:" + bestSyncPoint.time + ",") + (" segmentIndex:" + bestSyncPoint.segmentIndex) + (typeof bestSyncPoint.partIndex === 'number' ? ",partIndex:" + bestSyncPoint.partIndex : '') + ']');
- return bestSyncPoint;
- }
- /**
- * Save any meta-data present on the segments when segments leave
- * the live window to the playlist to allow for synchronization at the
- * playlist level later.
- *
- * @param {Playlist} oldPlaylist - The previous active playlist
- * @param {Playlist} newPlaylist - The updated and most current playlist
- */
- ;
-
- _proto.saveExpiredSegmentInfo = function saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
- var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // When a segment expires from the playlist and it has a start time
- // save that information as a possible sync-point reference in future
-
- for (var i = mediaSequenceDiff - 1; i >= 0; i--) {
- var lastRemovedSegment = oldPlaylist.segments[i];
-
- if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
- newPlaylist.syncInfo = {
- mediaSequence: oldPlaylist.mediaSequence + i,
- time: lastRemovedSegment.start
- };
- this.logger_("playlist refresh sync: [time:" + newPlaylist.syncInfo.time + "," + (" mediaSequence: " + newPlaylist.syncInfo.mediaSequence + "]"));
- this.trigger('syncinfoupdate');
- break;
- }
- }
- }
- /**
- * Save the mapping from playlist's ProgramDateTime to display. This should only happen
- * before segments start to load.
- *
- * @param {Playlist} playlist - The currently active playlist
- */
- ;
-
- _proto.setDateTimeMappingForStart = function setDateTimeMappingForStart(playlist) {
- // It's possible for the playlist to be updated before playback starts, meaning time
- // zero is not yet set. If, during these playlist refreshes, a discontinuity is
- // crossed, then the old time zero mapping (for the prior timeline) would be retained
- // unless the mappings are cleared.
- this.timelineToDatetimeMappings = {};
-
- if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
- var firstSegment = playlist.segments[0];
- var playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
- this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
- }
- }
- /**
- * Calculates and saves timeline mappings, playlist sync info, and segment timing values
- * based on the latest timing information.
- *
- * @param {Object} options
- * Options object
- * @param {SegmentInfo} options.segmentInfo
- * The current active request information
- * @param {boolean} options.shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved for timeline mapping and program date time mappings.
- */
- ;
-
- _proto.saveSegmentTimingInfo = function saveSegmentTimingInfo(_ref) {
- var segmentInfo = _ref.segmentInfo,
- shouldSaveTimelineMapping = _ref.shouldSaveTimelineMapping;
- var didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
- var segment = segmentInfo.segment;
-
- if (didCalculateSegmentTimeMapping) {
- this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
- // now with segment timing information
-
- if (!segmentInfo.playlist.syncInfo) {
- segmentInfo.playlist.syncInfo = {
- mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
- time: segment.start
- };
- }
- }
-
- var dateTime = segment.dateTimeObject;
-
- if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
- this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
- }
- };
-
- _proto.timestampOffsetForTimeline = function timestampOffsetForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
-
- return this.timelines[timeline].time;
- };
-
- _proto.mappingForTimeline = function mappingForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
-
- return this.timelines[timeline].mapping;
- }
- /**
- * Use the "media time" for a segment to generate a mapping to "display time" and
- * save that display time to the segment.
- *
- * @private
- * @param {SegmentInfo} segmentInfo
- * The current active request information
- * @param {Object} timingInfo
- * The start and end time of the current segment in "media time"
- * @param {boolean} shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved in timelines.
- * @return {boolean}
- * Returns false if segment time mapping could not be calculated
- */
- ;
-
- _proto.calculateSegmentTimeMapping_ = function calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
- // TODO: remove side effects
- var segment = segmentInfo.segment;
- var part = segmentInfo.part;
- var mappingObj = this.timelines[segmentInfo.timeline];
- var start;
- var end;
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- mappingObj = {
- time: segmentInfo.startOfSegment,
- mapping: segmentInfo.startOfSegment - timingInfo.start
- };
-
- if (shouldSaveTimelineMapping) {
- this.timelines[segmentInfo.timeline] = mappingObj;
- this.trigger('timestampoffset');
- this.logger_("time mapping for timeline " + segmentInfo.timeline + ": " + ("[time: " + mappingObj.time + "] [mapping: " + mappingObj.mapping + "]"));
- }
-
- start = segmentInfo.startOfSegment;
- end = timingInfo.end + mappingObj.mapping;
- } else if (mappingObj) {
- start = timingInfo.start + mappingObj.mapping;
- end = timingInfo.end + mappingObj.mapping;
- } else {
- return false;
- }
-
- if (part) {
- part.start = start;
- part.end = end;
- } // If we don't have a segment start yet or the start value we got
- // is less than our current segment.start value, save a new start value.
- // We have to do this because parts will have segment timing info saved
- // multiple times and we want segment start to be the earliest part start
- // value for that segment.
-
-
- if (!segment.start || start < segment.start) {
- segment.start = start;
- }
-
- segment.end = end;
- return true;
- }
- /**
- * Each time we have discontinuity in the playlist, attempt to calculate the location
- * in display of the start of the discontinuity and save that. We also save an accuracy
- * value so that we save values with the most accuracy (closest to 0.)
- *
- * @private
- * @param {SegmentInfo} segmentInfo - The current active request information
- */
- ;
-
- _proto.saveDiscontinuitySyncInfo_ = function saveDiscontinuitySyncInfo_(segmentInfo) {
- var playlist = segmentInfo.playlist;
- var segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
- // the start of the range and it's accuracy is 0 (greater accuracy values
- // mean more approximation)
-
- if (segment.discontinuity) {
- this.discontinuities[segment.timeline] = {
- time: segment.start,
- accuracy: 0
- };
- } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- // Search for future discontinuities that we can provide better timing
- // information for and save that information for sync purposes
- for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
- var segmentIndex = playlist.discontinuityStarts[i];
- var discontinuity = playlist.discontinuitySequence + i + 1;
- var mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
- var accuracy = Math.abs(mediaIndexDiff);
-
- if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
- var time = void 0;
-
- if (mediaIndexDiff < 0) {
- time = segment.start - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex,
- endIndex: segmentIndex
- });
- } else {
- time = segment.end + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex + 1,
- endIndex: segmentIndex
- });
- }
-
- this.discontinuities[discontinuity] = {
- time: time,
- accuracy: accuracy
- };
- }
- }
- }
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.off();
- };
-
- return SyncController;
-}(videojs__default['default'].EventTarget);
-
-/**
- * The TimelineChangeController acts as a source for segment loaders to listen for and
- * keep track of latest and pending timeline changes. This is useful to ensure proper
- * sync, as each loader may need to make a consideration for what timeline the other
- * loader is on before making changes which could impact the other loader's media.
- *
- * @class TimelineChangeController
- * @extends videojs.EventTarget
- */
-
-var TimelineChangeController = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose__default['default'](TimelineChangeController, _videojs$EventTarget);
-
- function TimelineChangeController() {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- _this.pendingTimelineChanges_ = {};
- _this.lastTimelineChanges_ = {};
- return _this;
- }
-
- var _proto = TimelineChangeController.prototype;
-
- _proto.clearPendingTimelineChange = function clearPendingTimelineChange(type) {
- this.pendingTimelineChanges_[type] = null;
- this.trigger('pendingtimelinechange');
- };
-
- _proto.pendingTimelineChange = function pendingTimelineChange(_ref) {
- var type = _ref.type,
- from = _ref.from,
- to = _ref.to;
-
- if (typeof from === 'number' && typeof to === 'number') {
- this.pendingTimelineChanges_[type] = {
- type: type,
- from: from,
- to: to
- };
- this.trigger('pendingtimelinechange');
- }
-
- return this.pendingTimelineChanges_[type];
- };
-
- _proto.lastTimelineChange = function lastTimelineChange(_ref2) {
- var type = _ref2.type,
- from = _ref2.from,
- to = _ref2.to;
-
- if (typeof from === 'number' && typeof to === 'number') {
- this.lastTimelineChanges_[type] = {
- type: type,
- from: from,
- to: to
- };
- delete this.pendingTimelineChanges_[type];
- this.trigger('timelinechange');
- }
-
- return this.lastTimelineChanges_[type];
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.pendingTimelineChanges_ = {};
- this.lastTimelineChanges_ = {};
- this.off();
- };
-
- return TimelineChangeController;
-}(videojs__default['default'].EventTarget);
-
-/* rollup-plugin-worker-factory start for worker!/Users/gkatsevman/p/http-streaming-release/src/decrypter-worker.js */
-var workerCode = transform(getWorkerString(function () {
-
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function require(path, base) {
- return commonjsRequire(path, base === undefined || base === null ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
-
- function commonjsRequire() {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
-
- var createClass = createCommonjsModule(function (module) {
- 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);
- }
- }
-
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
-
- module.exports = _createClass;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- var setPrototypeOf = createCommonjsModule(function (module) {
- function _setPrototypeOf(o, p) {
- module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _setPrototypeOf(o, p);
- }
-
- module.exports = _setPrototypeOf;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- var inheritsLoose = createCommonjsModule(function (module) {
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- setPrototypeOf(subClass, superClass);
- }
-
- module.exports = _inheritsLoose;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- /**
- * @file stream.js
- */
-
- /**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
-
- var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
- }();
- /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
-
- /**
- * Returns the subarray of a Uint8Array without PKCS#7 padding.
- *
- * @param padded {Uint8Array} unencrypted bytes that have been padded
- * @return {Uint8Array} the unpadded bytes
- * @see http://tools.ietf.org/html/rfc5652
- */
-
-
- function unpad(padded) {
- return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
- }
- /*! @name aes-decrypter @version 3.1.2 @license Apache-2.0 */
-
- /**
- * @file aes.js
- *
- * This file contains an adaptation of the AES decryption algorithm
- * from the Standford Javascript Cryptography Library. That work is
- * covered by the following copyright and permissions notice:
- *
- * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. 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 AUTHORS ``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 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.
- *
- * The views and conclusions contained in the software and documentation
- * are those of the authors and should not be interpreted as representing
- * official policies, either expressed or implied, of the authors.
- */
-
- /**
- * Expand the S-box tables.
- *
- * @private
- */
-
-
- var precompute = function precompute() {
- var tables = [[[], [], [], [], []], [[], [], [], [], []]];
- var encTable = tables[0];
- var decTable = tables[1];
- var sbox = encTable[4];
- var sboxInv = decTable[4];
- var i;
- var x;
- var xInv;
- var d = [];
- var th = [];
- var x2;
- var x4;
- var x8;
- var s;
- var tEnc;
- var tDec; // Compute double and third tables
-
- for (i = 0; i < 256; i++) {
- th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
- }
-
- for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
- // Compute sbox
- s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
- s = s >> 8 ^ s & 255 ^ 99;
- sbox[x] = s;
- sboxInv[s] = x; // Compute MixColumns
-
- x8 = d[x4 = d[x2 = d[x]]];
- tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- tEnc = d[s] * 0x101 ^ s * 0x1010100;
-
- for (i = 0; i < 4; i++) {
- encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
- decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
- }
- } // Compactify. Considerable speedup on Firefox.
-
-
- for (i = 0; i < 5; i++) {
- encTable[i] = encTable[i].slice(0);
- decTable[i] = decTable[i].slice(0);
- }
-
- return tables;
- };
-
- var aesTables = null;
- /**
- * Schedule out an AES key for both encryption and decryption. This
- * is a low-level class. Use a cipher mode to do bulk encryption.
- *
- * @class AES
- * @param key {Array} The key as an array of 4, 6 or 8 words.
- */
-
- var AES = /*#__PURE__*/function () {
- function AES(key) {
- /**
- * The expanded S-box and inverse S-box tables. These will be computed
- * on the client so that we don't have to send them down the wire.
- *
- * There are two tables, _tables[0] is for encryption and
- * _tables[1] is for decryption.
- *
- * The first 4 sub-tables are the expanded S-box with MixColumns. The
- * last (_tables[01][4]) is the S-box itself.
- *
- * @private
- */
- // if we have yet to precompute the S-box tables
- // do so now
- if (!aesTables) {
- aesTables = precompute();
- } // then make a copy of that object for use
-
-
- this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
- var i;
- var j;
- var tmp;
- var sbox = this._tables[0][4];
- var decTable = this._tables[1];
- var keyLen = key.length;
- var rcon = 1;
-
- if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
- throw new Error('Invalid aes key size');
- }
-
- var encKey = key.slice(0);
- var decKey = [];
- this._key = [encKey, decKey]; // schedule encryption keys
-
- for (i = keyLen; i < 4 * keyLen + 28; i++) {
- tmp = encKey[i - 1]; // apply sbox
-
- if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
- tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
-
- if (i % keyLen === 0) {
- tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
- rcon = rcon << 1 ^ (rcon >> 7) * 283;
- }
- }
-
- encKey[i] = encKey[i - keyLen] ^ tmp;
- } // schedule decryption keys
-
-
- for (j = 0; i; j++, i--) {
- tmp = encKey[j & 3 ? i : i - 4];
-
- if (i <= 4 || j < 4) {
- decKey[j] = tmp;
- } else {
- decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
- }
- }
- }
- /**
- * Decrypt 16 bytes, specified as four 32-bit words.
- *
- * @param {number} encrypted0 the first word to decrypt
- * @param {number} encrypted1 the second word to decrypt
- * @param {number} encrypted2 the third word to decrypt
- * @param {number} encrypted3 the fourth word to decrypt
- * @param {Int32Array} out the array to write the decrypted words
- * into
- * @param {number} offset the offset into the output array to start
- * writing results
- * @return {Array} The plaintext.
- */
-
-
- var _proto = AES.prototype;
-
- _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
- var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
-
- var a = encrypted0 ^ key[0];
- var b = encrypted3 ^ key[1];
- var c = encrypted2 ^ key[2];
- var d = encrypted1 ^ key[3];
- var a2;
- var b2;
- var c2; // key.length === 2 ?
-
- var nInnerRounds = key.length / 4 - 2;
- var i;
- var kIndex = 4;
- var table = this._tables[1]; // load up the tables
-
- var table0 = table[0];
- var table1 = table[1];
- var table2 = table[2];
- var table3 = table[3];
- var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
-
- for (i = 0; i < nInnerRounds; i++) {
- a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
- b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
- c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
- d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
- kIndex += 4;
- a = a2;
- b = b2;
- c = c2;
- } // Last round.
-
-
- for (i = 0; i < 4; i++) {
- out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
- a2 = a;
- a = b;
- b = c;
- c = d;
- d = a2;
- }
- };
-
- return AES;
- }();
- /**
- * A wrapper around the Stream class to use setTimeout
- * and run stream "jobs" Asynchronously
- *
- * @class AsyncStream
- * @extends Stream
- */
-
-
- var AsyncStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(AsyncStream, _Stream);
-
- function AsyncStream() {
- var _this;
-
- _this = _Stream.call(this, Stream) || this;
- _this.jobs = [];
- _this.delay = 1;
- _this.timeout_ = null;
- return _this;
- }
- /**
- * process an async job
- *
- * @private
- */
-
-
- var _proto = AsyncStream.prototype;
-
- _proto.processJob_ = function processJob_() {
- this.jobs.shift()();
-
- if (this.jobs.length) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- } else {
- this.timeout_ = null;
- }
- }
- /**
- * push a job into the stream
- *
- * @param {Function} job the job to push into the stream
- */
- ;
-
- _proto.push = function push(job) {
- this.jobs.push(job);
-
- if (!this.timeout_) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- }
- };
-
- return AsyncStream;
- }(Stream);
- /**
- * Convert network-order (big-endian) bytes into their little-endian
- * representation.
- */
-
-
- var ntoh = function ntoh(word) {
- return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
- };
- /**
- * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * use for the first round of CBC.
- * @return {Uint8Array} the decrypted bytes
- *
- * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
- * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
- * @see https://tools.ietf.org/html/rfc2315
- */
-
-
- var decrypt = function decrypt(encrypted, key, initVector) {
- // word-level access to the encrypted bytes
- var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
- var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
-
- var decrypted = new Uint8Array(encrypted.byteLength);
- var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
- // decrypted data
-
- var init0;
- var init1;
- var init2;
- var init3;
- var encrypted0;
- var encrypted1;
- var encrypted2;
- var encrypted3; // iteration variable
-
- var wordIx; // pull out the words of the IV to ensure we don't modify the
- // passed-in reference and easier access
-
- init0 = initVector[0];
- init1 = initVector[1];
- init2 = initVector[2];
- init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
- // to each decrypted block
-
- for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
- // convert big-endian (network order) words into little-endian
- // (javascript order)
- encrypted0 = ntoh(encrypted32[wordIx]);
- encrypted1 = ntoh(encrypted32[wordIx + 1]);
- encrypted2 = ntoh(encrypted32[wordIx + 2]);
- encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
-
- decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
- // plaintext
-
- decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
- decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
- decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
- decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
-
- init0 = encrypted0;
- init1 = encrypted1;
- init2 = encrypted2;
- init3 = encrypted3;
- }
-
- return decrypted;
- };
- /**
- * The `Decrypter` class that manages decryption of AES
- * data through `AsyncStream` objects and the `decrypt`
- * function
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * @param {Function} done the function to run when done
- * @class Decrypter
- */
-
-
- var Decrypter = /*#__PURE__*/function () {
- function Decrypter(encrypted, key, initVector, done) {
- var step = Decrypter.STEP;
- var encrypted32 = new Int32Array(encrypted.buffer);
- var decrypted = new Uint8Array(encrypted.byteLength);
- var i = 0;
- this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
-
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
-
- for (i = step; i < encrypted32.length; i += step) {
- initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
- } // invoke the done() callback when everything is finished
-
-
- this.asyncStream_.push(function () {
- // remove pkcs#7 padding from the decrypted bytes
- done(null, unpad(decrypted));
- });
- }
- /**
- * a getter for step the maximum number of bytes to process at one time
- *
- * @return {number} the value of step 32000
- */
-
-
- var _proto = Decrypter.prototype;
- /**
- * @private
- */
-
- _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
- return function () {
- var bytes = decrypt(encrypted, key, initVector);
- decrypted.set(bytes, encrypted.byteOffset);
- };
- };
-
- createClass(Decrypter, null, [{
- key: "STEP",
- get: function get() {
- // 4 * 8000;
- return 32000;
- }
- }]);
- return Decrypter;
- }();
- /**
- * @file bin-utils.js
- */
-
- /**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-
-
- var createTransferableMessage = function createTransferableMessage(message) {
- var transferable = {};
- Object.keys(message).forEach(function (key) {
- var value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
- return transferable;
- };
- /* global self */
-
- /**
- * Our web worker interface so that things can talk to aes-decrypter
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- */
-
-
- self.onmessage = function (event) {
- var data = event.data;
- var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
- var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
- var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
- /* eslint-disable no-new, handle-callback-err */
-
- new Decrypter(encrypted, key, iv, function (err, bytes) {
- self.postMessage(createTransferableMessage({
- source: data.source,
- decrypted: bytes
- }), [bytes.buffer]);
- });
- /* eslint-enable */
- };
-}));
-var Decrypter = factory(workerCode);
-/* rollup-plugin-worker-factory end for worker!/Users/gkatsevman/p/http-streaming-release/src/decrypter-worker.js */
-
-/**
- * Convert the properties of an HLS track into an audioTrackKind.
- *
- * @private
- */
-
-var audioTrackKind_ = function audioTrackKind_(properties) {
- var kind = properties.default ? 'main' : 'alternative';
-
- if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
- kind = 'main-desc';
- }
-
- return kind;
-};
-/**
- * Pause provided segment loader and playlist loader if active
- *
- * @param {SegmentLoader} segmentLoader
- * SegmentLoader to pause
- * @param {Object} mediaType
- * Active media type
- * @function stopLoaders
- */
-
-
-var stopLoaders = function stopLoaders(segmentLoader, mediaType) {
- segmentLoader.abort();
- segmentLoader.pause();
-
- if (mediaType && mediaType.activePlaylistLoader) {
- mediaType.activePlaylistLoader.pause();
- mediaType.activePlaylistLoader = null;
- }
-};
-/**
- * Start loading provided segment loader and playlist loader
- *
- * @param {PlaylistLoader} playlistLoader
- * PlaylistLoader to start loading
- * @param {Object} mediaType
- * Active media type
- * @function startLoaders
- */
-
-var startLoaders = function startLoaders(playlistLoader, mediaType) {
- // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
- // playlist loader
- mediaType.activePlaylistLoader = playlistLoader;
- playlistLoader.load();
-};
-/**
- * Returns a function to be called when the media group changes. It performs a
- * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
- * change of group is merely a rendition switch of the same content at another encoding,
- * rather than a change of content, such as switching audio from English to Spanish.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a non-destructive resync of SegmentLoader when the active media
- * group changes.
- * @function onGroupChanged
- */
-
-var onGroupChanged = function onGroupChanged(type, settings) {
- return function () {
- var _settings$segmentLoad = settings.segmentLoaders,
- segmentLoader = _settings$segmentLoad[type],
- mainSegmentLoader = _settings$segmentLoad.main,
- mediaType = settings.mediaTypes[type];
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.getActiveGroup();
- var previousActiveLoader = mediaType.activePlaylistLoader;
- var lastGroup = mediaType.lastGroup_; // the group did not change do nothing
-
- if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup || activeGroup.isMasterPlaylist) {
- // there is no group active or active group is a main playlist and won't change
- return;
- }
-
- if (!activeGroup.playlistLoader) {
- if (previousActiveLoader) {
- // The previous group had a playlist loader but the new active group does not
- // this means we are switching from demuxed to muxed audio. In this case we want to
- // do a destructive reset of the main segment loader and not restart the audio
- // loaders.
- mainSegmentLoader.resetEverything();
- }
-
- return;
- } // Non-destructive resync
-
-
- segmentLoader.resyncLoader();
- startLoaders(activeGroup.playlistLoader, mediaType);
- };
-};
-var onGroupChanging = function onGroupChanging(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- mediaType.lastGroup_ = null;
- segmentLoader.abort();
- segmentLoader.pause();
- };
-};
-/**
- * Returns a function to be called when the media track changes. It performs a
- * destructive reset of the SegmentLoader to ensure we start loading as close to
- * currentTime as possible.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a destructive reset of SegmentLoader when the active media
- * track changes.
- * @function onTrackChanged
- */
-
-var onTrackChanged = function onTrackChanged(type, settings) {
- return function () {
- var masterPlaylistLoader = settings.masterPlaylistLoader,
- _settings$segmentLoad2 = settings.segmentLoaders,
- segmentLoader = _settings$segmentLoad2[type],
- mainSegmentLoader = _settings$segmentLoad2.main,
- mediaType = settings.mediaTypes[type];
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.getActiveGroup();
- var previousActiveLoader = mediaType.activePlaylistLoader;
- var lastTrack = mediaType.lastTrack_; // track did not change, do nothing
-
- if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup) {
- // there is no group active so we do not want to restart loaders
- return;
- }
-
- if (activeGroup.isMasterPlaylist) {
- // track did not change, do nothing
- if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
- return;
- }
-
- var mpc = settings.vhs.masterPlaylistController_;
- var newPlaylist = mpc.selectPlaylist(); // media will not change do nothing
-
- if (mpc.media() === newPlaylist) {
- return;
- }
-
- mediaType.logger_("track change. Switching master audio from " + lastTrack.id + " to " + activeTrack.id);
- masterPlaylistLoader.pause();
- mainSegmentLoader.resetEverything();
- mpc.fastQualityChange_(newPlaylist);
- return;
- }
-
- if (type === 'AUDIO') {
- if (!activeGroup.playlistLoader) {
- // when switching from demuxed audio/video to muxed audio/video (noted by no
- // playlist loader for the audio group), we want to do a destructive reset of the
- // main segment loader and not restart the audio loaders
- mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
- // it should be stopped
-
- mainSegmentLoader.resetEverything();
- return;
- } // although the segment loader is an audio segment loader, call the setAudio
- // function to ensure it is prepared to re-append the init segment (or handle other
- // config changes)
-
-
- segmentLoader.setAudio(true);
- mainSegmentLoader.setAudio(false);
- }
-
- if (previousActiveLoader === activeGroup.playlistLoader) {
- // Nothing has actually changed. This can happen because track change events can fire
- // multiple times for a "single" change. One for enabling the new active track, and
- // one for disabling the track that was active
- startLoaders(activeGroup.playlistLoader, mediaType);
- return;
- }
-
- if (segmentLoader.track) {
- // For WebVTT, set the new text track in the segmentloader
- segmentLoader.track(activeTrack);
- } // destructive reset
-
-
- segmentLoader.resetEverything();
- startLoaders(activeGroup.playlistLoader, mediaType);
- };
-};
-var onError = {
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning (or error if the playlist is blacklisted) to
- * console and switches back to default audio track.
- * @function onError.AUDIO
- */
- AUDIO: function AUDIO(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type],
- blacklistCurrentPlaylist = settings.blacklistCurrentPlaylist;
- stopLoaders(segmentLoader, mediaType); // switch back to default audio track
-
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.activeGroup();
- var id = (activeGroup.filter(function (group) {
- return group.default;
- })[0] || activeGroup[0]).id;
- var defaultTrack = mediaType.tracks[id];
-
- if (activeTrack === defaultTrack) {
- // Default track encountered an error. All we can do now is blacklist the current
- // rendition and hope another will switch audio groups
- blacklistCurrentPlaylist({
- message: 'Problem encountered loading the default audio track.'
- });
- return;
- }
-
- videojs__default['default'].log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
-
- for (var trackId in mediaType.tracks) {
- mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
- }
-
- mediaType.onTrackChanged();
- };
- },
-
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning to console and disables the active subtitle track
- * @function onError.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- videojs__default['default'].log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
- stopLoaders(segmentLoader, mediaType);
- var track = mediaType.activeTrack();
-
- if (track) {
- track.mode = 'disabled';
- }
-
- mediaType.onTrackChanged();
- };
- }
-};
-var setupListeners = {
- /**
- * Setup event listeners for audio playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.AUDIO
- */
- AUDIO: function AUDIO(type, playlistLoader, settings) {
- if (!playlistLoader) {
- // no playlist loader means audio will be muxed with the video
- return;
- }
-
- var tech = settings.tech,
- requestOptions = settings.requestOptions,
- segmentLoader = settings.segmentLoaders[type];
- playlistLoader.on('loadedmetadata', function () {
- var media = playlistLoader.media();
- segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
-
- if (!tech.paused() || media.endList && tech.preload() !== 'none') {
- segmentLoader.load();
- }
- });
- playlistLoader.on('loadedplaylist', function () {
- segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
-
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
- playlistLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup event listeners for subtitle playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, playlistLoader, settings) {
- var tech = settings.tech,
- requestOptions = settings.requestOptions,
- segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- playlistLoader.on('loadedmetadata', function () {
- var media = playlistLoader.media();
- segmentLoader.playlist(media, requestOptions);
- segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
-
- if (!tech.paused() || media.endList && tech.preload() !== 'none') {
- segmentLoader.load();
- }
- });
- playlistLoader.on('loadedplaylist', function () {
- segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
-
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
- playlistLoader.on('error', onError[type](type, settings));
- }
-};
-var initialize = {
- /**
- * Setup PlaylistLoaders and AudioTracks for the audio groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.AUDIO
- */
- 'AUDIO': function AUDIO(type, settings) {
- var vhs = settings.vhs,
- sourceType = settings.sourceType,
- segmentLoader = settings.segmentLoaders[type],
- requestOptions = settings.requestOptions,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$ = settings.mediaTypes[type],
- groups = _settings$mediaTypes$.groups,
- tracks = _settings$mediaTypes$.tracks,
- logger_ = _settings$mediaTypes$.logger_,
- masterPlaylistLoader = settings.masterPlaylistLoader;
- var audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master); // force a default if we have none
-
- if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
- mediaGroups[type] = {
- main: {
- default: {
- default: true
- }
- }
- };
- }
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- var properties = mediaGroups[type][groupId][variantLabel];
- var playlistLoader = void 0;
-
- if (audioOnlyMaster) {
- logger_("AUDIO group '" + groupId + "' label '" + variantLabel + "' is a master playlist");
- properties.isMasterPlaylist = true;
- playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
- // use the resolved media playlist object
- } else if (sourceType === 'vhs-json' && properties.playlists) {
- playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
- } else if (properties.resolvedUri) {
- playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
- // should we even have properties.playlists in this check.
- } else if (properties.playlists && sourceType === 'dash') {
- playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
- } else {
- // no resolvedUri means the audio is muxed with the video when using this
- // audio track
- playlistLoader = null;
- }
-
- properties = videojs__default['default'].mergeOptions({
- id: variantLabel,
- playlistLoader: playlistLoader
- }, properties);
- setupListeners[type](type, properties.playlistLoader, settings);
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = new videojs__default['default'].AudioTrack({
- id: variantLabel,
- kind: audioTrackKind_(properties),
- enabled: false,
- language: properties.language,
- default: properties.default,
- label: variantLabel
- });
- tracks[variantLabel] = track;
- }
- }
- } // setup single error event handler for the segment loader
-
-
- segmentLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup PlaylistLoaders and TextTracks for the subtitle groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.SUBTITLES
- */
- 'SUBTITLES': function SUBTITLES(type, settings) {
- var tech = settings.tech,
- vhs = settings.vhs,
- sourceType = settings.sourceType,
- segmentLoader = settings.segmentLoaders[type],
- requestOptions = settings.requestOptions,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$2 = settings.mediaTypes[type],
- groups = _settings$mediaTypes$2.groups,
- tracks = _settings$mediaTypes$2.tracks,
- masterPlaylistLoader = settings.masterPlaylistLoader;
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- if (mediaGroups[type][groupId][variantLabel].forced) {
- // Subtitle playlists with the forced attribute are not selectable in Safari.
- // According to Apple's HLS Authoring Specification:
- // If content has forced subtitles and regular subtitles in a given language,
- // the regular subtitles track in that language MUST contain both the forced
- // subtitles and the regular subtitles for that language.
- // Because of this requirement and that Safari does not add forced subtitles,
- // forced subtitles are skipped here to maintain consistent experience across
- // all platforms
- continue;
- }
-
- var properties = mediaGroups[type][groupId][variantLabel];
- var playlistLoader = void 0;
-
- if (sourceType === 'hls') {
- playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
- } else if (sourceType === 'dash') {
- var playlists = properties.playlists.filter(function (p) {
- return p.excludeUntil !== Infinity;
- });
-
- if (!playlists.length) {
- return;
- }
-
- playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
- } else if (sourceType === 'vhs-json') {
- playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
- // as provided, otherwise use the resolved URI to load the playlist
- properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
- }
-
- properties = videojs__default['default'].mergeOptions({
- id: variantLabel,
- playlistLoader: playlistLoader
- }, properties);
- setupListeners[type](type, properties.playlistLoader, settings);
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = tech.addRemoteTextTrack({
- id: variantLabel,
- kind: 'subtitles',
- default: properties.default && properties.autoselect,
- language: properties.language,
- label: variantLabel
- }, false).track;
- tracks[variantLabel] = track;
- }
- }
- } // setup single error event handler for the segment loader
-
-
- segmentLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup TextTracks for the closed-caption groups
- *
- * @param {String} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize['CLOSED-CAPTIONS']
- */
- 'CLOSED-CAPTIONS': function CLOSEDCAPTIONS(type, settings) {
- var tech = settings.tech,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$3 = settings.mediaTypes[type],
- groups = _settings$mediaTypes$3.groups,
- tracks = _settings$mediaTypes$3.tracks;
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- var properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
-
- if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
- continue;
- }
-
- var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
- var newProps = {
- label: variantLabel,
- language: properties.language,
- instreamId: properties.instreamId,
- default: properties.default && properties.autoselect
- };
-
- if (captionServices[newProps.instreamId]) {
- newProps = videojs__default['default'].mergeOptions(newProps, captionServices[newProps.instreamId]);
- }
-
- if (newProps.default === undefined) {
- delete newProps.default;
- } // No PlaylistLoader is required for Closed-Captions because the captions are
- // embedded within the video stream
-
-
- groups[groupId].push(videojs__default['default'].mergeOptions({
- id: variantLabel
- }, properties));
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = tech.addRemoteTextTrack({
- id: newProps.instreamId,
- kind: 'captions',
- default: newProps.default,
- language: newProps.language,
- label: newProps.label
- }, false).track;
- tracks[variantLabel] = track;
- }
- }
- }
- }
-};
-
-var groupMatch = function groupMatch(list, media) {
- for (var i = 0; i < list.length; i++) {
- if (playlistMatch(media, list[i])) {
- return true;
- }
-
- if (list[i].playlists && groupMatch(list[i].playlists, media)) {
- return true;
- }
- }
-
- return false;
-};
-/**
- * Returns a function used to get the active group of the provided type
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media group for the provided type. Takes an
- * optional parameter {TextTrack} track. If no track is provided, a list of all
- * variants in the group, otherwise the variant corresponding to the provided
- * track is returned.
- * @function activeGroup
- */
-
-
-var activeGroup = function activeGroup(type, settings) {
- return function (track) {
- var masterPlaylistLoader = settings.masterPlaylistLoader,
- groups = settings.mediaTypes[type].groups;
- var media = masterPlaylistLoader.media();
-
- if (!media) {
- return null;
- }
-
- var variants = null; // set to variants to main media active group
-
- if (media.attributes[type]) {
- variants = groups[media.attributes[type]];
- }
-
- var groupKeys = Object.keys(groups);
-
- if (!variants) {
- // find the masterPlaylistLoader media
- // that is in a media group if we are dealing
- // with audio only
- if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.master)) {
- for (var i = 0; i < groupKeys.length; i++) {
- var groupPropertyList = groups[groupKeys[i]];
-
- if (groupMatch(groupPropertyList, media)) {
- variants = groupPropertyList;
- break;
- }
- } // use the main group if it exists
-
- } else if (groups.main) {
- variants = groups.main; // only one group, use that one
- } else if (groupKeys.length === 1) {
- variants = groups[groupKeys[0]];
- }
- }
-
- if (typeof track === 'undefined') {
- return variants;
- }
-
- if (track === null || !variants) {
- // An active track was specified so a corresponding group is expected. track === null
- // means no track is currently active so there is no corresponding group
- return null;
- }
-
- return variants.filter(function (props) {
- return props.id === track.id;
- })[0] || null;
- };
-};
-var activeTrack = {
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.AUDIO
- */
- AUDIO: function AUDIO(type, settings) {
- return function () {
- var tracks = settings.mediaTypes[type].tracks;
-
- for (var id in tracks) {
- if (tracks[id].enabled) {
- return tracks[id];
- }
- }
-
- return null;
- };
- },
-
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, settings) {
- return function () {
- var tracks = settings.mediaTypes[type].tracks;
-
- for (var id in tracks) {
- if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
- return tracks[id];
- }
- }
-
- return null;
- };
- }
-};
-var getActiveGroup = function getActiveGroup(type, _ref) {
- var mediaTypes = _ref.mediaTypes;
- return function () {
- var activeTrack_ = mediaTypes[type].activeTrack();
-
- if (!activeTrack_) {
- return null;
- }
-
- return mediaTypes[type].activeGroup(activeTrack_);
- };
-};
-/**
- * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
- * Closed-Captions) specified in the master manifest.
- *
- * @param {Object} settings
- * Object containing required information for setting up the media groups
- * @param {Tech} settings.tech
- * The tech of the player
- * @param {Object} settings.requestOptions
- * XHR request options used by the segment loaders
- * @param {PlaylistLoader} settings.masterPlaylistLoader
- * PlaylistLoader for the master source
- * @param {VhsHandler} settings.vhs
- * VHS SourceHandler
- * @param {Object} settings.master
- * The parsed master manifest
- * @param {Object} settings.mediaTypes
- * Object to store the loaders, tracks, and utility methods for each media type
- * @param {Function} settings.blacklistCurrentPlaylist
- * Blacklists the current rendition and forces a rendition switch.
- * @function setupMediaGroups
- */
-
-var setupMediaGroups = function setupMediaGroups(settings) {
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
- initialize[type](type, settings);
- });
- var mediaTypes = settings.mediaTypes,
- masterPlaylistLoader = settings.masterPlaylistLoader,
- tech = settings.tech,
- vhs = settings.vhs,
- _settings$segmentLoad3 = settings.segmentLoaders,
- audioSegmentLoader = _settings$segmentLoad3['AUDIO'],
- mainSegmentLoader = _settings$segmentLoad3.main; // setup active group and track getters and change event handlers
-
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- mediaTypes[type].activeGroup = activeGroup(type, settings);
- mediaTypes[type].activeTrack = activeTrack[type](type, settings);
- mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
- mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
- mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
- mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
- }); // DO NOT enable the default subtitle or caption track.
- // DO enable the default audio track
-
- var audioGroup = mediaTypes.AUDIO.activeGroup();
-
- if (audioGroup) {
- var groupId = (audioGroup.filter(function (group) {
- return group.default;
- })[0] || audioGroup[0]).id;
- mediaTypes.AUDIO.tracks[groupId].enabled = true;
- mediaTypes.AUDIO.onGroupChanged();
- mediaTypes.AUDIO.onTrackChanged();
- var activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
- // track is changed, but needs to be handled here since the track may not be considered
- // changed on the first call to onTrackChanged
-
- if (!activeAudioGroup.playlistLoader) {
- // either audio is muxed with video or the stream is audio only
- mainSegmentLoader.setAudio(true);
- } else {
- // audio is demuxed
- mainSegmentLoader.setAudio(false);
- audioSegmentLoader.setAudio(true);
- }
- }
-
- masterPlaylistLoader.on('mediachange', function () {
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- return mediaTypes[type].onGroupChanged();
- });
- });
- masterPlaylistLoader.on('mediachanging', function () {
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- return mediaTypes[type].onGroupChanging();
- });
- }); // custom audio track change event handler for usage event
-
- var onAudioTrackChanged = function onAudioTrackChanged() {
- mediaTypes.AUDIO.onTrackChanged();
- tech.trigger({
- type: 'usage',
- name: 'vhs-audio-change'
- });
- tech.trigger({
- type: 'usage',
- name: 'hls-audio-change'
- });
- };
-
- tech.audioTracks().addEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
- vhs.on('dispose', function () {
- tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
- }); // clear existing audio tracks and add the ones we just created
-
- tech.clearTracks('audio');
-
- for (var id in mediaTypes.AUDIO.tracks) {
- tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
- }
-};
-/**
- * Creates skeleton object used to store the loaders, tracks, and utility methods for each
- * media type
- *
- * @return {Object}
- * Object to store the loaders, tracks, and utility methods for each media type
- * @function createMediaTypes
- */
-
-var createMediaTypes = function createMediaTypes() {
- var mediaTypes = {};
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
- mediaTypes[type] = {
- groups: {},
- tracks: {},
- activePlaylistLoader: null,
- activeGroup: noop,
- activeTrack: noop,
- getActiveGroup: noop,
- onGroupChanged: noop,
- onTrackChanged: noop,
- lastTrack_: null,
- logger_: logger("MediaGroups[" + type + "]")
- };
- });
- return mediaTypes;
-};
-
-var ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
-var Vhs$1; // SegmentLoader stats that need to have each loader's
-// values summed to calculate the final value
-
-var loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
-
-var sumLoaderStat = function sumLoaderStat(stat) {
- return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
-};
-
-var shouldSwitchToMedia = function shouldSwitchToMedia(_ref) {
- var currentPlaylist = _ref.currentPlaylist,
- nextPlaylist = _ref.nextPlaylist,
- forwardBuffer = _ref.forwardBuffer,
- bufferLowWaterLine = _ref.bufferLowWaterLine,
- bufferHighWaterLine = _ref.bufferHighWaterLine,
- duration = _ref.duration,
- experimentalBufferBasedABR = _ref.experimentalBufferBasedABR,
- log = _ref.log;
-
- // we have no other playlist to switch to
- if (!nextPlaylist) {
- videojs__default['default'].log.warn('We received no playlist to switch to. Please check your stream.');
- return false;
- }
-
- var sharedLogLine = "allowing switch " + (currentPlaylist && currentPlaylist.id || 'null') + " -> " + nextPlaylist.id; // If the playlist is live, then we want to not take low water line into account.
- // This is because in LIVE, the player plays 3 segments from the end of the
- // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
- // in those segments, a viewer will never experience a rendition upswitch.
-
- if (!currentPlaylist || !currentPlaylist.endList) {
- log(sharedLogLine + " as current playlist " + (!currentPlaylist ? 'is not set' : 'is live'));
- return true;
- } // no need to switch playlist is the same
-
-
- if (nextPlaylist.id === currentPlaylist.id) {
- return false;
- }
-
- var maxBufferLowWaterLine = experimentalBufferBasedABR ? Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE; // For the same reason as LIVE, we ignore the low water line when the VOD
- // duration is below the max potential low water line
-
- if (duration < maxBufferLowWaterLine) {
- log(sharedLogLine + " as duration < max low water line (" + duration + " < " + maxBufferLowWaterLine + ")");
- return true;
- }
-
- var nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
- var currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
- // we can switch down
-
- if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
- var logLine = sharedLogLine + " as next bandwidth < current bandwidth (" + nextBandwidth + " < " + currBandwidth + ")";
-
- if (experimentalBufferBasedABR) {
- logLine += " and forwardBuffer < bufferHighWaterLine (" + forwardBuffer + " < " + bufferHighWaterLine + ")";
- }
-
- log(logLine);
- return true;
- } // and if our buffer is higher than the low water line,
- // we can switch up
-
-
- if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
- var _logLine = sharedLogLine + " as forwardBuffer >= bufferLowWaterLine (" + forwardBuffer + " >= " + bufferLowWaterLine + ")";
-
- if (experimentalBufferBasedABR) {
- _logLine += " and next bandwidth > current bandwidth (" + nextBandwidth + " > " + currBandwidth + ")";
- }
-
- log(_logLine);
- return true;
- }
-
- log("not " + sharedLogLine + " as no switching criteria met");
- return false;
-};
-/**
- * the master playlist controller controller all interactons
- * between playlists and segmentloaders. At this time this mainly
- * involves a master playlist and a series of audio playlists
- * if they are available
- *
- * @class MasterPlaylistController
- * @extends videojs.EventTarget
- */
-
-
-var MasterPlaylistController = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose__default['default'](MasterPlaylistController, _videojs$EventTarget);
-
- function MasterPlaylistController(options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- var src = options.src,
- handleManifestRedirects = options.handleManifestRedirects,
- withCredentials = options.withCredentials,
- tech = options.tech,
- bandwidth = options.bandwidth,
- externVhs = options.externVhs,
- useCueTags = options.useCueTags,
- blacklistDuration = options.blacklistDuration,
- enableLowInitialPlaylist = options.enableLowInitialPlaylist,
- sourceType = options.sourceType,
- cacheEncryptionKeys = options.cacheEncryptionKeys,
- experimentalBufferBasedABR = options.experimentalBufferBasedABR;
-
- if (!src) {
- throw new Error('A non-empty playlist URL or JSON manifest string is required');
- }
-
- var maxPlaylistRetries = options.maxPlaylistRetries;
-
- if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
- maxPlaylistRetries = Infinity;
- }
-
- Vhs$1 = externVhs;
- _this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
- _this.withCredentials = withCredentials;
- _this.tech_ = tech;
- _this.vhs_ = tech.vhs;
- _this.sourceType_ = sourceType;
- _this.useCueTags_ = useCueTags;
- _this.blacklistDuration = blacklistDuration;
- _this.maxPlaylistRetries = maxPlaylistRetries;
- _this.enableLowInitialPlaylist = enableLowInitialPlaylist;
-
- if (_this.useCueTags_) {
- _this.cueTagsTrack_ = _this.tech_.addTextTrack('metadata', 'ad-cues');
- _this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
- }
-
- _this.requestOptions_ = {
- withCredentials: withCredentials,
- handleManifestRedirects: handleManifestRedirects,
- maxPlaylistRetries: maxPlaylistRetries,
- timeout: null
- };
-
- _this.on('error', _this.pauseLoading);
-
- _this.mediaTypes_ = createMediaTypes();
- _this.mediaSource = new window__default['default'].MediaSource();
- _this.handleDurationChange_ = _this.handleDurationChange_.bind(_assertThisInitialized__default['default'](_this));
- _this.handleSourceOpen_ = _this.handleSourceOpen_.bind(_assertThisInitialized__default['default'](_this));
- _this.handleSourceEnded_ = _this.handleSourceEnded_.bind(_assertThisInitialized__default['default'](_this));
-
- _this.mediaSource.addEventListener('durationchange', _this.handleDurationChange_); // load the media source into the player
-
-
- _this.mediaSource.addEventListener('sourceopen', _this.handleSourceOpen_);
-
- _this.mediaSource.addEventListener('sourceended', _this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
- // everything, and the MediaSource should not be detached without a proper disposal
-
-
- _this.seekable_ = videojs__default['default'].createTimeRanges();
- _this.hasPlayed_ = false;
- _this.syncController_ = new SyncController(options);
- _this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'segment-metadata'
- }, false).track;
- _this.decrypter_ = new Decrypter();
- _this.sourceUpdater_ = new SourceUpdater(_this.mediaSource);
- _this.inbandTextTracks_ = {};
- _this.timelineChangeController_ = new TimelineChangeController();
- var segmentLoaderSettings = {
- vhs: _this.vhs_,
- parse708captions: options.parse708captions,
- mediaSource: _this.mediaSource,
- currentTime: _this.tech_.currentTime.bind(_this.tech_),
- seekable: function seekable() {
- return _this.seekable();
- },
- seeking: function seeking() {
- return _this.tech_.seeking();
- },
- duration: function duration() {
- return _this.duration();
- },
- hasPlayed: function hasPlayed() {
- return _this.hasPlayed_;
- },
- goalBufferLength: function goalBufferLength() {
- return _this.goalBufferLength();
- },
- bandwidth: bandwidth,
- syncController: _this.syncController_,
- decrypter: _this.decrypter_,
- sourceType: _this.sourceType_,
- inbandTextTracks: _this.inbandTextTracks_,
- cacheEncryptionKeys: cacheEncryptionKeys,
- sourceUpdater: _this.sourceUpdater_,
- timelineChangeController: _this.timelineChangeController_
- }; // The source type check not only determines whether a special DASH playlist loader
- // should be used, but also covers the case where the provided src is a vhs-json
- // manifest object (instead of a URL). In the case of vhs-json, the default
- // PlaylistLoader should be used.
-
- _this.masterPlaylistLoader_ = _this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, _this.vhs_, _this.requestOptions_) : new PlaylistLoader(src, _this.vhs_, _this.requestOptions_);
-
- _this.setupMasterPlaylistLoaderListeners_(); // setup segment loaders
- // combined audio/video or just video when alternate audio track is selected
-
-
- _this.mainSegmentLoader_ = new SegmentLoader(videojs__default['default'].mergeOptions(segmentLoaderSettings, {
- segmentMetadataTrack: _this.segmentMetadataTrack_,
- loaderType: 'main'
- }), options); // alternate audio track
-
- _this.audioSegmentLoader_ = new SegmentLoader(videojs__default['default'].mergeOptions(segmentLoaderSettings, {
- loaderType: 'audio'
- }), options);
- _this.subtitleSegmentLoader_ = new VTTSegmentLoader(videojs__default['default'].mergeOptions(segmentLoaderSettings, {
- loaderType: 'vtt',
- featuresNativeTextTracks: _this.tech_.featuresNativeTextTracks
- }), options);
-
- _this.setupSegmentLoaderListeners_();
-
- if (_this.experimentalBufferBasedABR) {
- _this.masterPlaylistLoader_.one('loadedplaylist', function () {
- return _this.startABRTimer_();
- });
-
- _this.tech_.on('pause', function () {
- return _this.stopABRTimer_();
- });
-
- _this.tech_.on('play', function () {
- return _this.startABRTimer_();
- });
- } // Create SegmentLoader stat-getters
- // mediaRequests_
- // mediaRequestsAborted_
- // mediaRequestsTimedout_
- // mediaRequestsErrored_
- // mediaTransferDuration_
- // mediaBytesTransferred_
- // mediaAppends_
-
-
- loaderStats.forEach(function (stat) {
- _this[stat + '_'] = sumLoaderStat.bind(_assertThisInitialized__default['default'](_this), stat);
- });
- _this.logger_ = logger('MPC');
- _this.triggeredFmp4Usage = false;
-
- if (_this.tech_.preload() === 'none') {
- _this.loadOnPlay_ = function () {
- _this.loadOnPlay_ = null;
-
- _this.masterPlaylistLoader_.load();
- };
-
- _this.tech_.one('play', _this.loadOnPlay_);
- } else {
- _this.masterPlaylistLoader_.load();
- }
-
- _this.timeToLoadedData__ = -1;
- _this.mainAppendsToLoadedData__ = -1;
- _this.audioAppendsToLoadedData__ = -1;
- var event = _this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
-
- _this.tech_.one(event, function () {
- var timeToLoadedDataStart = Date.now();
-
- _this.tech_.one('loadeddata', function () {
- _this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
- _this.mainAppendsToLoadedData__ = _this.mainSegmentLoader_.mediaAppends;
- _this.audioAppendsToLoadedData__ = _this.audioSegmentLoader_.mediaAppends;
- });
- });
-
- return _this;
- }
-
- var _proto = MasterPlaylistController.prototype;
-
- _proto.mainAppendsToLoadedData_ = function mainAppendsToLoadedData_() {
- return this.mainAppendsToLoadedData__;
- };
-
- _proto.audioAppendsToLoadedData_ = function audioAppendsToLoadedData_() {
- return this.audioAppendsToLoadedData__;
- };
-
- _proto.appendsToLoadedData_ = function appendsToLoadedData_() {
- var main = this.mainAppendsToLoadedData_();
- var audio = this.audioAppendsToLoadedData_();
-
- if (main === -1 || audio === -1) {
- return -1;
- }
-
- return main + audio;
- };
-
- _proto.timeToLoadedData_ = function timeToLoadedData_() {
- return this.timeToLoadedData__;
- }
- /**
- * Run selectPlaylist and switch to the new playlist if we should
- *
- * @private
- *
- */
- ;
-
- _proto.checkABR_ = function checkABR_() {
- var nextPlaylist = this.selectPlaylist();
-
- if (this.shouldSwitchToMedia_(nextPlaylist)) {
- this.switchMedia_(nextPlaylist, 'abr');
- }
- };
-
- _proto.switchMedia_ = function switchMedia_(playlist, cause, delay) {
- var oldMedia = this.media();
- var oldId = oldMedia && (oldMedia.id || oldMedia.uri);
- var newId = playlist.id || playlist.uri;
-
- if (oldId && oldId !== newId) {
- this.logger_("switch media " + oldId + " -> " + newId + " from " + cause);
- this.tech_.trigger({
- type: 'usage',
- name: "vhs-rendition-change-" + cause
- });
- }
-
- this.masterPlaylistLoader_.media(playlist, delay);
- }
- /**
- * Start a timer that periodically calls checkABR_
- *
- * @private
- */
- ;
-
- _proto.startABRTimer_ = function startABRTimer_() {
- var _this2 = this;
-
- this.stopABRTimer_();
- this.abrTimer_ = window__default['default'].setInterval(function () {
- return _this2.checkABR_();
- }, 250);
- }
- /**
- * Stop the timer that periodically calls checkABR_
- *
- * @private
- */
- ;
-
- _proto.stopABRTimer_ = function stopABRTimer_() {
- // if we're scrubbing, we don't need to pause.
- // This getter will be added to Video.js in version 7.11.
- if (this.tech_.scrubbing && this.tech_.scrubbing()) {
- return;
- }
-
- window__default['default'].clearInterval(this.abrTimer_);
- this.abrTimer_ = null;
- }
- /**
- * Get a list of playlists for the currently selected audio playlist
- *
- * @return {Array} the array of audio playlists
- */
- ;
-
- _proto.getAudioTrackPlaylists_ = function getAudioTrackPlaylists_() {
- var master = this.master(); // if we don't have any audio groups then we can only
- // assume that the audio tracks are contained in masters
- // playlist array, use that or an empty array.
-
- if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
- return master && master.playlists || [];
- }
-
- var AUDIO = master.mediaGroups.AUDIO;
- var groupKeys = Object.keys(AUDIO);
- var track; // get the current active track
-
- if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
- track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from master if mediaTypes_ isn't setup yet
- } else {
- // default group is `main` or just the first group.
- var defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
-
- for (var label in defaultGroup) {
- if (defaultGroup[label].default) {
- track = {
- label: label
- };
- break;
- }
- }
- } // no active track no playlists.
-
-
- if (!track) {
- return [];
- }
-
- var playlists = []; // get all of the playlists that are possible for the
- // active track.
-
- for (var group in AUDIO) {
- if (AUDIO[group][track.label]) {
- var properties = AUDIO[group][track.label];
-
- if (properties.playlists) {
- playlists.push.apply(playlists, properties.playlists);
- } else {
- playlists.push(properties);
- }
- }
- }
-
- return playlists;
- }
- /**
- * Register event handlers on the master playlist loader. A helper
- * function for construction time.
- *
- * @private
- */
- ;
-
- _proto.setupMasterPlaylistLoaderListeners_ = function setupMasterPlaylistLoaderListeners_() {
- var _this3 = this;
-
- this.masterPlaylistLoader_.on('loadedmetadata', function () {
- var media = _this3.masterPlaylistLoader_.media();
-
- var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
- // timeout the request.
-
- if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
- _this3.requestOptions_.timeout = 0;
- } else {
- _this3.requestOptions_.timeout = requestTimeout;
- } // if this isn't a live video and preload permits, start
- // downloading segments
-
-
- if (media.endList && _this3.tech_.preload() !== 'none') {
- _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
-
- _this3.mainSegmentLoader_.load();
- }
-
- setupMediaGroups({
- sourceType: _this3.sourceType_,
- segmentLoaders: {
- AUDIO: _this3.audioSegmentLoader_,
- SUBTITLES: _this3.subtitleSegmentLoader_,
- main: _this3.mainSegmentLoader_
- },
- tech: _this3.tech_,
- requestOptions: _this3.requestOptions_,
- masterPlaylistLoader: _this3.masterPlaylistLoader_,
- vhs: _this3.vhs_,
- master: _this3.master(),
- mediaTypes: _this3.mediaTypes_,
- blacklistCurrentPlaylist: _this3.blacklistCurrentPlaylist.bind(_this3)
- });
-
- _this3.triggerPresenceUsage_(_this3.master(), media);
-
- _this3.setupFirstPlay();
-
- if (!_this3.mediaTypes_.AUDIO.activePlaylistLoader || _this3.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
- _this3.trigger('selectedinitialmedia');
- } else {
- // We must wait for the active audio playlist loader to
- // finish setting up before triggering this event so the
- // representations API and EME setup is correct
- _this3.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', function () {
- _this3.trigger('selectedinitialmedia');
- });
- }
- });
- this.masterPlaylistLoader_.on('loadedplaylist', function () {
- if (_this3.loadOnPlay_) {
- _this3.tech_.off('play', _this3.loadOnPlay_);
- }
-
- var updatedPlaylist = _this3.masterPlaylistLoader_.media();
-
- if (!updatedPlaylist) {
- // exclude any variants that are not supported by the browser before selecting
- // an initial media as the playlist selectors do not consider browser support
- _this3.excludeUnsupportedVariants_();
-
- var selectedMedia;
-
- if (_this3.enableLowInitialPlaylist) {
- selectedMedia = _this3.selectInitialPlaylist();
- }
-
- if (!selectedMedia) {
- selectedMedia = _this3.selectPlaylist();
- }
-
- if (!selectedMedia || !_this3.shouldSwitchToMedia_(selectedMedia)) {
- return;
- }
-
- _this3.initialMedia_ = selectedMedia;
-
- _this3.switchMedia_(_this3.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
- // fire again since the playlist will be requested. In the case of vhs-json
- // (where the manifest object is provided as the source), when the media
- // playlist's `segments` list is already available, a media playlist won't be
- // requested, and loadedplaylist won't fire again, so the playlist handler must be
- // called on its own here.
-
-
- var haveJsonSource = _this3.sourceType_ === 'vhs-json' && _this3.initialMedia_.segments;
-
- if (!haveJsonSource) {
- return;
- }
-
- updatedPlaylist = _this3.initialMedia_;
- }
-
- _this3.handleUpdatedMediaPlaylist(updatedPlaylist);
- });
- this.masterPlaylistLoader_.on('error', function () {
- _this3.blacklistCurrentPlaylist(_this3.masterPlaylistLoader_.error);
- });
- this.masterPlaylistLoader_.on('mediachanging', function () {
- _this3.mainSegmentLoader_.abort();
-
- _this3.mainSegmentLoader_.pause();
- });
- this.masterPlaylistLoader_.on('mediachange', function () {
- var media = _this3.masterPlaylistLoader_.media();
-
- var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
- // timeout the request.
-
- if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
- _this3.requestOptions_.timeout = 0;
- } else {
- _this3.requestOptions_.timeout = requestTimeout;
- } // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `loadedplaylist`
-
-
- _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
-
- _this3.mainSegmentLoader_.load();
-
- _this3.tech_.trigger({
- type: 'mediachange',
- bubbles: true
- });
- });
- this.masterPlaylistLoader_.on('playlistunchanged', function () {
- var updatedPlaylist = _this3.masterPlaylistLoader_.media(); // ignore unchanged playlists that have already been
- // excluded for not-changing. We likely just have a really slowly updating
- // playlist.
-
-
- if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
- return;
- }
-
- var playlistOutdated = _this3.stuckAtPlaylistEnd_(updatedPlaylist);
-
- if (playlistOutdated) {
- // Playlist has stopped updating and we're stuck at its end. Try to
- // blacklist it and switch to another playlist in the hope that that
- // one is updating (and give the player a chance to re-adjust to the
- // safe live point).
- _this3.blacklistCurrentPlaylist({
- message: 'Playlist no longer updating.',
- reason: 'playlist-unchanged'
- }); // useful for monitoring QoS
-
-
- _this3.tech_.trigger('playliststuck');
- }
- });
- this.masterPlaylistLoader_.on('renditiondisabled', function () {
- _this3.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-disabled'
- });
-
- _this3.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-disabled'
- });
- });
- this.masterPlaylistLoader_.on('renditionenabled', function () {
- _this3.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-enabled'
- });
-
- _this3.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-enabled'
- });
- });
- }
- /**
- * Given an updated media playlist (whether it was loaded for the first time, or
- * refreshed for live playlists), update any relevant properties and state to reflect
- * changes in the media that should be accounted for (e.g., cues and duration).
- *
- * @param {Object} updatedPlaylist the updated media playlist object
- *
- * @private
- */
- ;
-
- _proto.handleUpdatedMediaPlaylist = function handleUpdatedMediaPlaylist(updatedPlaylist) {
- if (this.useCueTags_) {
- this.updateAdCues_(updatedPlaylist);
- } // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `mediachange`
-
-
- this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
- this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
- // as it is possible that it was temporarily stopped while waiting for
- // a playlist (e.g., in case the playlist errored and we re-requested it).
-
- if (!this.tech_.paused()) {
- this.mainSegmentLoader_.load();
-
- if (this.audioSegmentLoader_) {
- this.audioSegmentLoader_.load();
- }
- }
- }
- /**
- * A helper function for triggerring presence usage events once per source
- *
- * @private
- */
- ;
-
- _proto.triggerPresenceUsage_ = function triggerPresenceUsage_(master, media) {
- var mediaGroups = master.mediaGroups || {};
- var defaultDemuxed = true;
- var audioGroupKeys = Object.keys(mediaGroups.AUDIO);
-
- for (var mediaGroup in mediaGroups.AUDIO) {
- for (var label in mediaGroups.AUDIO[mediaGroup]) {
- var properties = mediaGroups.AUDIO[mediaGroup][label];
-
- if (!properties.uri) {
- defaultDemuxed = false;
- }
- }
- }
-
- if (defaultDemuxed) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-demuxed'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-demuxed'
- });
- }
-
- if (Object.keys(mediaGroups.SUBTITLES).length) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-webvtt'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-webvtt'
- });
- }
-
- if (Vhs$1.Playlist.isAes(media)) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-aes'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-aes'
- });
- }
-
- if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-alternate-audio'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-alternate-audio'
- });
- }
-
- if (this.useCueTags_) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-playlist-cue-tags'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-playlist-cue-tags'
- });
- }
- };
-
- _proto.shouldSwitchToMedia_ = function shouldSwitchToMedia_(nextPlaylist) {
- var currentPlaylist = this.masterPlaylistLoader_.media();
- var buffered = this.tech_.buffered();
- var forwardBuffer = buffered.length ? buffered.end(buffered.length - 1) - this.tech_.currentTime() : 0;
- var bufferLowWaterLine = this.bufferLowWaterLine();
- var bufferHighWaterLine = this.bufferHighWaterLine();
- return shouldSwitchToMedia({
- currentPlaylist: currentPlaylist,
- nextPlaylist: nextPlaylist,
- forwardBuffer: forwardBuffer,
- bufferLowWaterLine: bufferLowWaterLine,
- bufferHighWaterLine: bufferHighWaterLine,
- duration: this.duration(),
- experimentalBufferBasedABR: this.experimentalBufferBasedABR,
- log: this.logger_
- });
- }
- /**
- * Register event handlers on the segment loaders. A helper function
- * for construction time.
- *
- * @private
- */
- ;
-
- _proto.setupSegmentLoaderListeners_ = function setupSegmentLoaderListeners_() {
- var _this4 = this;
-
- if (!this.experimentalBufferBasedABR) {
- this.mainSegmentLoader_.on('bandwidthupdate', function () {
- var nextPlaylist = _this4.selectPlaylist();
-
- if (_this4.shouldSwitchToMedia_(nextPlaylist)) {
- _this4.switchMedia_(nextPlaylist, 'bandwidthupdate');
- }
-
- _this4.tech_.trigger('bandwidthupdate');
- });
- this.mainSegmentLoader_.on('progress', function () {
- _this4.trigger('progress');
- });
- }
-
- this.mainSegmentLoader_.on('error', function () {
- _this4.blacklistCurrentPlaylist(_this4.mainSegmentLoader_.error());
- });
- this.mainSegmentLoader_.on('appenderror', function () {
- _this4.error = _this4.mainSegmentLoader_.error_;
-
- _this4.trigger('error');
- });
- this.mainSegmentLoader_.on('syncinfoupdate', function () {
- _this4.onSyncInfoUpdate_();
- });
- this.mainSegmentLoader_.on('timestampoffset', function () {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-timestamp-offset'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-timestamp-offset'
- });
- });
- this.audioSegmentLoader_.on('syncinfoupdate', function () {
- _this4.onSyncInfoUpdate_();
- });
- this.audioSegmentLoader_.on('appenderror', function () {
- _this4.error = _this4.audioSegmentLoader_.error_;
-
- _this4.trigger('error');
- });
- this.mainSegmentLoader_.on('ended', function () {
- _this4.logger_('main segment loader ended');
-
- _this4.onEndOfStream();
- });
- this.mainSegmentLoader_.on('earlyabort', function (event) {
- // never try to early abort with the new ABR algorithm
- if (_this4.experimentalBufferBasedABR) {
- return;
- }
-
- _this4.delegateLoaders_('all', ['abort']);
-
- _this4.blacklistCurrentPlaylist({
- message: 'Aborted early because there isn\'t enough bandwidth to complete the ' + 'request without rebuffering.'
- }, ABORT_EARLY_BLACKLIST_SECONDS);
- });
-
- var updateCodecs = function updateCodecs() {
- if (!_this4.sourceUpdater_.hasCreatedSourceBuffers()) {
- return _this4.tryToCreateSourceBuffers_();
- }
-
- var codecs = _this4.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
-
-
- if (!codecs) {
- return;
- }
-
- _this4.sourceUpdater_.addOrChangeSourceBuffers(codecs);
- };
-
- this.mainSegmentLoader_.on('trackinfo', updateCodecs);
- this.audioSegmentLoader_.on('trackinfo', updateCodecs);
- this.mainSegmentLoader_.on('fmp4', function () {
- if (!_this4.triggeredFmp4Usage) {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-fmp4'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-fmp4'
- });
-
- _this4.triggeredFmp4Usage = true;
- }
- });
- this.audioSegmentLoader_.on('fmp4', function () {
- if (!_this4.triggeredFmp4Usage) {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-fmp4'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-fmp4'
- });
-
- _this4.triggeredFmp4Usage = true;
- }
- });
- this.audioSegmentLoader_.on('ended', function () {
- _this4.logger_('audioSegmentLoader ended');
-
- _this4.onEndOfStream();
- });
- };
-
- _proto.mediaSecondsLoaded_ = function mediaSecondsLoaded_() {
- return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
- }
- /**
- * Call load on our SegmentLoaders
- */
- ;
-
- _proto.load = function load() {
- this.mainSegmentLoader_.load();
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.load();
- }
-
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.load();
- }
- }
- /**
- * Re-tune playback quality level for the current player
- * conditions without performing destructive actions, like
- * removing already buffered content
- *
- * @private
- * @deprecated
- */
- ;
-
- _proto.smoothQualityChange_ = function smoothQualityChange_(media) {
- if (media === void 0) {
- media = this.selectPlaylist();
- }
-
- this.fastQualityChange_(media);
- }
- /**
- * Re-tune playback quality level for the current player
- * conditions. This method will perform destructive actions like removing
- * already buffered content in order to readjust the currently active
- * playlist quickly. This is good for manual quality changes
- *
- * @private
- */
- ;
-
- _proto.fastQualityChange_ = function fastQualityChange_(media) {
- var _this5 = this;
-
- if (media === void 0) {
- media = this.selectPlaylist();
- }
-
- if (media === this.masterPlaylistLoader_.media()) {
- this.logger_('skipping fastQualityChange because new media is same as old');
- return;
- }
-
- this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
- // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
- // ahead is roughly the minimum that will accomplish this across a variety of content
- // in IE and Edge, but seeking in place is sufficient on all other browsers)
- // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
- // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
-
- this.mainSegmentLoader_.resetEverything(function () {
- // Since this is not a typical seek, we avoid the seekTo method which can cause segments
- // from the previously enabled rendition to load before the new playlist has finished loading
- if (videojs__default['default'].browser.IE_VERSION || videojs__default['default'].browser.IS_EDGE) {
- _this5.tech_.setCurrentTime(_this5.tech_.currentTime() + 0.04);
- } else {
- _this5.tech_.setCurrentTime(_this5.tech_.currentTime());
- }
- }); // don't need to reset audio as it is reset when media changes
- }
- /**
- * Begin playback.
- */
- ;
-
- _proto.play = function play() {
- if (this.setupFirstPlay()) {
- return;
- }
-
- if (this.tech_.ended()) {
- this.tech_.setCurrentTime(0);
- }
-
- if (this.hasPlayed_) {
- this.load();
- }
-
- var seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
- // seek forward to the live point
-
- if (this.tech_.duration() === Infinity) {
- if (this.tech_.currentTime() < seekable.start(0)) {
- return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
- }
- }
- }
- /**
- * Seek to the latest media position if this is a live video and the
- * player and video are loaded and initialized.
- */
- ;
-
- _proto.setupFirstPlay = function setupFirstPlay() {
- var _this6 = this;
-
- var media = this.masterPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
- // If 1) there is no active media
- // 2) the player is paused
- // 3) the first play has already been setup
- // then exit early
-
- if (!media || this.tech_.paused() || this.hasPlayed_) {
- return false;
- } // when the video is a live stream
-
-
- if (!media.endList) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- // without a seekable range, the player cannot seek to begin buffering at the live
- // point
- return false;
- }
-
- if (videojs__default['default'].browser.IE_VERSION && this.tech_.readyState() === 0) {
- // IE11 throws an InvalidStateError if you try to set currentTime while the
- // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
- this.tech_.one('loadedmetadata', function () {
- _this6.trigger('firstplay');
-
- _this6.tech_.setCurrentTime(seekable.end(0));
-
- _this6.hasPlayed_ = true;
- });
- return false;
- } // trigger firstplay to inform the source handler to ignore the next seek event
-
-
- this.trigger('firstplay'); // seek to the live point
-
- this.tech_.setCurrentTime(seekable.end(0));
- }
-
- this.hasPlayed_ = true; // we can begin loading now that everything is ready
-
- this.load();
- return true;
- }
- /**
- * handle the sourceopen event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleSourceOpen_ = function handleSourceOpen_() {
- // Only attempt to create the source buffer if none already exist.
- // handleSourceOpen is also called when we are "re-opening" a source buffer
- // after `endOfStream` has been called (in response to a seek for instance)
- this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
- // code in video.js but is required because play() must be invoked
- // *after* the media source has opened.
-
- if (this.tech_.autoplay()) {
- var playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
- // on browsers which return a promise
-
- if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
- playPromise.then(null, function (e) {});
- }
- }
-
- this.trigger('sourceopen');
- }
- /**
- * handle the sourceended event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleSourceEnded_ = function handleSourceEnded_() {
- if (!this.inbandTextTracks_.metadataTrack_) {
- return;
- }
-
- var cues = this.inbandTextTracks_.metadataTrack_.cues;
-
- if (!cues || !cues.length) {
- return;
- }
-
- var duration = this.duration();
- cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
- }
- /**
- * handle the durationchange event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleDurationChange_ = function handleDurationChange_() {
- this.tech_.trigger('durationchange');
- }
- /**
- * Calls endOfStream on the media source when all active stream types have called
- * endOfStream
- *
- * @param {string} streamType
- * Stream type of the segment loader that called endOfStream
- * @private
- */
- ;
-
- _proto.onEndOfStream = function onEndOfStream() {
- var isEndOfStream = this.mainSegmentLoader_.ended_;
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- // if the audio playlist loader exists, then alternate audio is active
- if (!this.mainSegmentLoader_.currentMediaInfo_ || this.mainSegmentLoader_.currentMediaInfo_.hasVideo) {
- // if we do not know if the main segment loader contains video yet or if we
- // definitively know the main segment loader contains video, then we need to wait
- // for both main and audio segment loaders to call endOfStream
- isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
- } else {
- // otherwise just rely on the audio loader
- isEndOfStream = this.audioSegmentLoader_.ended_;
- }
- }
-
- if (!isEndOfStream) {
- return;
- }
-
- this.stopABRTimer_();
- this.sourceUpdater_.endOfStream();
- }
- /**
- * Check if a playlist has stopped being updated
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist has stopped being updated or not
- */
- ;
-
- _proto.stuckAtPlaylistEnd_ = function stuckAtPlaylistEnd_(playlist) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- // playlist doesn't have enough information to determine whether we are stuck
- return false;
- }
-
- var expired = this.syncController_.getExpiredTime(playlist, this.duration());
-
- if (expired === null) {
- return false;
- } // does not use the safe live end to calculate playlist end, since we
- // don't want to say we are stuck while there is still content
-
-
- var absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
-
- if (!buffered.length) {
- // return true if the playhead reached the absolute end of the playlist
- return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
- }
-
- var bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
- // end of playlist
-
- return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
- }
- /**
- * Blacklists a playlist when an error occurs for a set amount of time
- * making it unavailable for selection by the rendition selection algorithm
- * and then forces a new playlist (rendition) selection.
- *
- * @param {Object=} error an optional error that may include the playlist
- * to blacklist
- * @param {number=} blacklistDuration an optional number of seconds to blacklist the
- * playlist
- */
- ;
-
- _proto.blacklistCurrentPlaylist = function blacklistCurrentPlaylist(error, blacklistDuration) {
- if (error === void 0) {
- error = {};
- }
-
- // If the `error` was generated by the playlist loader, it will contain
- // the playlist we were trying to load (but failed) and that should be
- // blacklisted instead of the currently selected playlist which is likely
- // out-of-date in this scenario
- var currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
- blacklistDuration = blacklistDuration || error.blacklistDuration || this.blacklistDuration; // If there is no current playlist, then an error occurred while we were
- // trying to load the master OR while we were disposing of the tech
-
- if (!currentPlaylist) {
- this.error = error;
-
- if (this.mediaSource.readyState !== 'open') {
- this.trigger('error');
- } else {
- this.sourceUpdater_.endOfStream('network');
- }
-
- return;
- }
-
- currentPlaylist.playlistErrors_++;
- var playlists = this.masterPlaylistLoader_.master.playlists;
- var enabledPlaylists = playlists.filter(isEnabled);
- var isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === currentPlaylist; // Don't blacklist the only playlist unless it was blacklisted
- // forever
-
- if (playlists.length === 1 && blacklistDuration !== Infinity) {
- videojs__default['default'].log.warn("Problem encountered with playlist " + currentPlaylist.id + ". " + 'Trying again since it is the only playlist.');
- this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
-
- return this.masterPlaylistLoader_.load(isFinalRendition);
- }
-
- if (isFinalRendition) {
- // Since we're on the final non-blacklisted playlist, and we're about to blacklist
- // it, instead of erring the player or retrying this playlist, clear out the current
- // blacklist. This allows other playlists to be attempted in case any have been
- // fixed.
- var reincluded = false;
- playlists.forEach(function (playlist) {
- // skip current playlist which is about to be blacklisted
- if (playlist === currentPlaylist) {
- return;
- }
-
- var excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
-
- if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
- reincluded = true;
- delete playlist.excludeUntil;
- }
- });
-
- if (reincluded) {
- videojs__default['default'].log.warn('Removing other playlists from the exclusion list because the last ' + 'rendition is about to be excluded.'); // Technically we are retrying a playlist, in that we are simply retrying a previous
- // playlist. This is needed for users relying on the retryplaylist event to catch a
- // case where the player might be stuck and looping through "dead" playlists.
-
- this.tech_.trigger('retryplaylist');
- }
- } // Blacklist this playlist
-
-
- var excludeUntil;
-
- if (currentPlaylist.playlistErrors_ > this.maxPlaylistRetries) {
- excludeUntil = Infinity;
- } else {
- excludeUntil = Date.now() + blacklistDuration * 1000;
- }
-
- currentPlaylist.excludeUntil = excludeUntil;
-
- if (error.reason) {
- currentPlaylist.lastExcludeReason_ = error.reason;
- }
-
- this.tech_.trigger('blacklistplaylist');
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-blacklisted'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-blacklisted'
- }); // TODO: should we select a new playlist if this blacklist wasn't for the currentPlaylist?
- // Would be something like media().id !=== currentPlaylist.id and we would need something
- // like `pendingMedia` in playlist loaders to check against that too. This will prevent us
- // from loading a new playlist on any blacklist.
- // Select a new playlist
-
- var nextPlaylist = this.selectPlaylist();
-
- if (!nextPlaylist) {
- this.error = 'Playback cannot continue. No available working or supported playlists.';
- this.trigger('error');
- return;
- }
-
- var logFn = error.internal ? this.logger_ : videojs__default['default'].log.warn;
- var errorMessage = error.message ? ' ' + error.message : '';
- logFn((error.internal ? 'Internal problem' : 'Problem') + " encountered with playlist " + currentPlaylist.id + "." + (errorMessage + " Switching to playlist " + nextPlaylist.id + ".")); // if audio group changed reset audio loaders
-
- if (nextPlaylist.attributes.AUDIO !== currentPlaylist.attributes.AUDIO) {
- this.delegateLoaders_('audio', ['abort', 'pause']);
- } // if subtitle group changed reset subtitle loaders
-
-
- if (nextPlaylist.attributes.SUBTITLES !== currentPlaylist.attributes.SUBTITLES) {
- this.delegateLoaders_('subtitle', ['abort', 'pause']);
- }
-
- this.delegateLoaders_('main', ['abort', 'pause']);
- var delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
- var shouldDelay = typeof nextPlaylist.lastRequest === 'number' && Date.now() - nextPlaylist.lastRequest <= delayDuration; // delay if it's a final rendition or if the last refresh is sooner than half targetDuration
-
- return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
- }
- /**
- * Pause all segment/playlist loaders
- */
- ;
-
- _proto.pauseLoading = function pauseLoading() {
- this.delegateLoaders_('all', ['abort', 'pause']);
- this.stopABRTimer_();
- }
- /**
- * Call a set of functions in order on playlist loaders, segment loaders,
- * or both types of loaders.
- *
- * @param {string} filter
- * Filter loaders that should call fnNames using a string. Can be:
- * * all - run on all loaders
- * * audio - run on all audio loaders
- * * subtitle - run on all subtitle loaders
- * * main - run on the main/master loaders
- *
- * @param {Array|string} fnNames
- * A string or array of function names to call.
- */
- ;
-
- _proto.delegateLoaders_ = function delegateLoaders_(filter, fnNames) {
- var _this7 = this;
-
- var loaders = [];
- var dontFilterPlaylist = filter === 'all';
-
- if (dontFilterPlaylist || filter === 'main') {
- loaders.push(this.masterPlaylistLoader_);
- }
-
- var mediaTypes = [];
-
- if (dontFilterPlaylist || filter === 'audio') {
- mediaTypes.push('AUDIO');
- }
-
- if (dontFilterPlaylist || filter === 'subtitle') {
- mediaTypes.push('CLOSED-CAPTIONS');
- mediaTypes.push('SUBTITLES');
- }
-
- mediaTypes.forEach(function (mediaType) {
- var loader = _this7.mediaTypes_[mediaType] && _this7.mediaTypes_[mediaType].activePlaylistLoader;
-
- if (loader) {
- loaders.push(loader);
- }
- });
- ['main', 'audio', 'subtitle'].forEach(function (name) {
- var loader = _this7[name + "SegmentLoader_"];
-
- if (loader && (filter === name || filter === 'all')) {
- loaders.push(loader);
- }
- });
- loaders.forEach(function (loader) {
- return fnNames.forEach(function (fnName) {
- if (typeof loader[fnName] === 'function') {
- loader[fnName]();
- }
- });
- });
- }
- /**
- * set the current time on all segment loaders
- *
- * @param {TimeRange} currentTime the current time to set
- * @return {TimeRange} the current time
- */
- ;
-
- _proto.setCurrentTime = function setCurrentTime(currentTime) {
- var buffered = findRange(this.tech_.buffered(), currentTime);
-
- if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
- // return immediately if the metadata is not ready yet
- return 0;
- } // it's clearly an edge-case but don't thrown an error if asked to
- // seek within an empty playlist
-
-
- if (!this.masterPlaylistLoader_.media().segments) {
- return 0;
- } // if the seek location is already buffered, continue buffering as usual
-
-
- if (buffered && buffered.length) {
- return currentTime;
- } // cancel outstanding requests so we begin buffering at the new
- // location
-
-
- this.mainSegmentLoader_.resetEverything();
- this.mainSegmentLoader_.abort();
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.resetEverything();
- this.audioSegmentLoader_.abort();
- }
-
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.resetEverything();
- this.subtitleSegmentLoader_.abort();
- } // start segment loader loading in case they are paused
-
-
- this.load();
- }
- /**
- * get the current duration
- *
- * @return {TimeRange} the duration
- */
- ;
-
- _proto.duration = function duration() {
- if (!this.masterPlaylistLoader_) {
- return 0;
- }
-
- var media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- // no playlists loaded yet, so can't determine a duration
- return 0;
- } // Don't rely on the media source for duration in the case of a live playlist since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, just return Infinity.
-
-
- if (!media.endList) {
- return Infinity;
- } // Since this is a VOD video, it is safe to rely on the media source's duration (if
- // available). If it's not available, fall back to a playlist-calculated estimate.
-
-
- if (this.mediaSource) {
- return this.mediaSource.duration;
- }
-
- return Vhs$1.Playlist.duration(media);
- }
- /**
- * check the seekable range
- *
- * @return {TimeRange} the seekable range
- */
- ;
-
- _proto.seekable = function seekable() {
- return this.seekable_;
- };
-
- _proto.onSyncInfoUpdate_ = function onSyncInfoUpdate_() {
- var audioSeekable;
-
- if (!this.masterPlaylistLoader_) {
- return;
- }
-
- var media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- return;
- }
-
- var expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- // not enough information to update seekable
- return;
- }
-
- var master = this.masterPlaylistLoader_.master;
- var mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
-
- if (mainSeekable.length === 0) {
- return;
- }
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
- expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- return;
- }
-
- audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
-
- if (audioSeekable.length === 0) {
- return;
- }
- }
-
- var oldEnd;
- var oldStart;
-
- if (this.seekable_ && this.seekable_.length) {
- oldEnd = this.seekable_.end(0);
- oldStart = this.seekable_.start(0);
- }
-
- if (!audioSeekable) {
- // seekable has been calculated based on buffering video data so it
- // can be returned directly
- this.seekable_ = mainSeekable;
- } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
- // seekables are pretty far off, rely on main
- this.seekable_ = mainSeekable;
- } else {
- this.seekable_ = videojs__default['default'].createTimeRanges([[audioSeekable.start(0) > mainSeekable.start(0) ? audioSeekable.start(0) : mainSeekable.start(0), audioSeekable.end(0) < mainSeekable.end(0) ? audioSeekable.end(0) : mainSeekable.end(0)]]);
- } // seekable is the same as last time
-
-
- if (this.seekable_ && this.seekable_.length) {
- if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
- return;
- }
- }
-
- this.logger_("seekable updated [" + printableRange(this.seekable_) + "]");
- this.tech_.trigger('seekablechanged');
- }
- /**
- * Update the player duration
- */
- ;
-
- _proto.updateDuration = function updateDuration(isLive) {
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- this.updateDuration_ = null;
- }
-
- if (this.mediaSource.readyState !== 'open') {
- this.updateDuration_ = this.updateDuration.bind(this, isLive);
- this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
- return;
- }
-
- if (isLive) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- return;
- } // Even in the case of a live playlist, the native MediaSource's duration should not
- // be set to Infinity (even though this would be expected for a live playlist), since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, the duration should be greater than or
- // equal to the last possible seekable value.
- // MediaSource duration starts as NaN
- // It is possible (and probable) that this case will never be reached for many
- // sources, since the MediaSource reports duration as the highest value without
- // accounting for timestamp offset. For example, if the timestamp offset is -100 and
- // we buffered times 0 to 100 with real times of 100 to 200, even though current
- // time will be between 0 and 100, the native media source may report the duration
- // as 200. However, since we report duration separate from the media source (as
- // Infinity), and as long as the native media source duration value is greater than
- // our reported seekable range, seeks will work as expected. The large number as
- // duration for live is actually a strategy used by some players to work around the
- // issue of live seekable ranges cited above.
-
-
- if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
- this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
- }
-
- return;
- }
-
- var buffered = this.tech_.buffered();
- var duration = Vhs$1.Playlist.duration(this.masterPlaylistLoader_.media());
-
- if (buffered.length > 0) {
- duration = Math.max(duration, buffered.end(buffered.length - 1));
- }
-
- if (this.mediaSource.duration !== duration) {
- this.sourceUpdater_.setDuration(duration);
- }
- }
- /**
- * dispose of the MasterPlaylistController and everything
- * that it controls
- */
- ;
-
- _proto.dispose = function dispose() {
- var _this8 = this;
-
- this.trigger('dispose');
- this.decrypter_.terminate();
- this.masterPlaylistLoader_.dispose();
- this.mainSegmentLoader_.dispose();
-
- if (this.loadOnPlay_) {
- this.tech_.off('play', this.loadOnPlay_);
- }
-
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- var groups = _this8.mediaTypes_[type].groups;
-
- for (var id in groups) {
- groups[id].forEach(function (group) {
- if (group.playlistLoader) {
- group.playlistLoader.dispose();
- }
- });
- }
- });
- this.audioSegmentLoader_.dispose();
- this.subtitleSegmentLoader_.dispose();
- this.sourceUpdater_.dispose();
- this.timelineChangeController_.dispose();
- this.stopABRTimer_();
-
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- }
-
- this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
-
- this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
- this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
- this.off();
- }
- /**
- * return the master playlist object if we have one
- *
- * @return {Object} the master playlist object that we parsed
- */
- ;
-
- _proto.master = function master() {
- return this.masterPlaylistLoader_.master;
- }
- /**
- * return the currently selected playlist
- *
- * @return {Object} the currently selected playlist object that we parsed
- */
- ;
-
- _proto.media = function media() {
- // playlist loader will not return media if it has not been fully loaded
- return this.masterPlaylistLoader_.media() || this.initialMedia_;
- };
-
- _proto.areMediaTypesKnown_ = function areMediaTypesKnown_() {
- var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader; // one or both loaders has not loaded sufficently to get codecs
-
- if (!this.mainSegmentLoader_.currentMediaInfo_ || usingAudioLoader && !this.audioSegmentLoader_.currentMediaInfo_) {
- return false;
- }
-
- return true;
- };
-
- _proto.getCodecsOrExclude_ = function getCodecsOrExclude_() {
- var _this9 = this;
-
- var media = {
- main: this.mainSegmentLoader_.currentMediaInfo_ || {},
- audio: this.audioSegmentLoader_.currentMediaInfo_ || {}
- }; // set "main" media equal to video
-
- media.video = media.main;
- var playlistCodecs = codecsForPlaylist(this.master(), this.media());
- var codecs = {};
- var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
-
- if (media.main.hasVideo) {
- codecs.video = playlistCodecs.video || media.main.videoCodec || codecs_js.DEFAULT_VIDEO_CODEC;
- }
-
- if (media.main.isMuxed) {
- codecs.video += "," + (playlistCodecs.audio || media.main.audioCodec || codecs_js.DEFAULT_AUDIO_CODEC);
- }
-
- if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
- codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || codecs_js.DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
-
- media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
- } // no codecs, no playback.
-
-
- if (!codecs.audio && !codecs.video) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: 'Could not determine codecs for playlist.',
- blacklistDuration: Infinity
- });
- return;
- } // fmp4 relies on browser support, while ts relies on muxer support
-
-
- var supportFunction = function supportFunction(isFmp4, codec) {
- return isFmp4 ? codecs_js.browserSupportsCodec(codec) : codecs_js.muxerSupportsCodec(codec);
- };
-
- var unsupportedCodecs = {};
- var unsupportedAudio;
- ['video', 'audio'].forEach(function (type) {
- if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
- var supporter = media[type].isFmp4 ? 'browser' : 'muxer';
- unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
- unsupportedCodecs[supporter].push(codecs[type]);
-
- if (type === 'audio') {
- unsupportedAudio = supporter;
- }
- }
- });
-
- if (usingAudioLoader && unsupportedAudio && this.media().attributes.AUDIO) {
- var audioGroup = this.media().attributes.AUDIO;
- this.master().playlists.forEach(function (variant) {
- var variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
-
- if (variantAudioGroup === audioGroup && variant !== _this9.media()) {
- variant.excludeUntil = Infinity;
- }
- });
- this.logger_("excluding audio group " + audioGroup + " as " + unsupportedAudio + " does not support codec(s): \"" + codecs.audio + "\"");
- } // if we have any unsupported codecs blacklist this playlist.
-
-
- if (Object.keys(unsupportedCodecs).length) {
- var message = Object.keys(unsupportedCodecs).reduce(function (acc, supporter) {
- if (acc) {
- acc += ', ';
- }
-
- acc += supporter + " does not support codec(s): \"" + unsupportedCodecs[supporter].join(',') + "\"";
- return acc;
- }, '') + '.';
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- internal: true,
- message: message,
- blacklistDuration: Infinity
- });
- return;
- } // check if codec switching is happening
-
-
- if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
- var switchMessages = [];
- ['video', 'audio'].forEach(function (type) {
- var newCodec = (codecs_js.parseCodecs(_this9.sourceUpdater_.codecs[type] || '')[0] || {}).type;
- var oldCodec = (codecs_js.parseCodecs(codecs[type] || '')[0] || {}).type;
-
- if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
- switchMessages.push("\"" + _this9.sourceUpdater_.codecs[type] + "\" -> \"" + codecs[type] + "\"");
- }
- });
-
- if (switchMessages.length) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: "Codec switching not supported: " + switchMessages.join(', ') + ".",
- blacklistDuration: Infinity,
- internal: true
- });
- return;
- }
- } // TODO: when using the muxer shouldn't we just return
- // the codecs that the muxer outputs?
-
-
- return codecs;
- }
- /**
- * Create source buffers and exlude any incompatible renditions.
- *
- * @private
- */
- ;
-
- _proto.tryToCreateSourceBuffers_ = function tryToCreateSourceBuffers_() {
- // media source is not ready yet or sourceBuffers are already
- // created.
- if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
- return;
- }
-
- if (!this.areMediaTypesKnown_()) {
- return;
- }
-
- var codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
-
- if (!codecs) {
- return;
- }
-
- this.sourceUpdater_.createSourceBuffers(codecs);
- var codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
- this.excludeIncompatibleVariants_(codecString);
- }
- /**
- * Excludes playlists with codecs that are unsupported by the muxer and browser.
- */
- ;
-
- _proto.excludeUnsupportedVariants_ = function excludeUnsupportedVariants_() {
- var _this10 = this;
-
- var playlists = this.master().playlists;
- var ids = []; // TODO: why don't we have a property to loop through all
- // playlist? Why did we ever mix indexes and keys?
-
- Object.keys(playlists).forEach(function (key) {
- var variant = playlists[key]; // check if we already processed this playlist.
-
- if (ids.indexOf(variant.id) !== -1) {
- return;
- }
-
- ids.push(variant.id);
- var codecs = codecsForPlaylist(_this10.master, variant);
- var unsupported = [];
-
- if (codecs.audio && !codecs_js.muxerSupportsCodec(codecs.audio) && !codecs_js.browserSupportsCodec(codecs.audio)) {
- unsupported.push("audio codec " + codecs.audio);
- }
-
- if (codecs.video && !codecs_js.muxerSupportsCodec(codecs.video) && !codecs_js.browserSupportsCodec(codecs.video)) {
- unsupported.push("video codec " + codecs.video);
- }
-
- if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
- unsupported.push("text codec " + codecs.text);
- }
-
- if (unsupported.length) {
- variant.excludeUntil = Infinity;
-
- _this10.logger_("excluding " + variant.id + " for unsupported: " + unsupported.join(', '));
- }
- });
- }
- /**
- * Blacklist playlists that are known to be codec or
- * stream-incompatible with the SourceBuffer configuration. For
- * instance, Media Source Extensions would cause the video element to
- * stall waiting for video data if you switched from a variant with
- * video and audio to an audio-only one.
- *
- * @param {Object} media a media playlist compatible with the current
- * set of SourceBuffers. Variants in the current master playlist that
- * do not appear to have compatible codec or stream configurations
- * will be excluded from the default playlist selection algorithm
- * indefinitely.
- * @private
- */
- ;
-
- _proto.excludeIncompatibleVariants_ = function excludeIncompatibleVariants_(codecString) {
- var _this11 = this;
-
- var ids = [];
- var playlists = this.master().playlists;
- var codecs = unwrapCodecList(codecs_js.parseCodecs(codecString));
- var codecCount_ = codecCount(codecs);
- var videoDetails = codecs.video && codecs_js.parseCodecs(codecs.video)[0] || null;
- var audioDetails = codecs.audio && codecs_js.parseCodecs(codecs.audio)[0] || null;
- Object.keys(playlists).forEach(function (key) {
- var variant = playlists[key]; // check if we already processed this playlist.
- // or it if it is already excluded forever.
-
- if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
- return;
- }
-
- ids.push(variant.id);
- var blacklistReasons = []; // get codecs from the playlist for this variant
-
- var variantCodecs = codecsForPlaylist(_this11.masterPlaylistLoader_.master, variant);
- var variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
- // variant is incompatible. Wait for mux.js to probe
-
- if (!variantCodecs.audio && !variantCodecs.video) {
- return;
- } // TODO: we can support this by removing the
- // old media source and creating a new one, but it will take some work.
- // The number of streams cannot change
-
-
- if (variantCodecCount !== codecCount_) {
- blacklistReasons.push("codec count \"" + variantCodecCount + "\" !== \"" + codecCount_ + "\"");
- } // only exclude playlists by codec change, if codecs cannot switch
- // during playback.
-
-
- if (!_this11.sourceUpdater_.canChangeType()) {
- var variantVideoDetails = variantCodecs.video && codecs_js.parseCodecs(variantCodecs.video)[0] || null;
- var variantAudioDetails = variantCodecs.audio && codecs_js.parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
-
- if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
- blacklistReasons.push("video codec \"" + variantVideoDetails.type + "\" !== \"" + videoDetails.type + "\"");
- } // the audio codec cannot change
-
-
- if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
- blacklistReasons.push("audio codec \"" + variantAudioDetails.type + "\" !== \"" + audioDetails.type + "\"");
- }
- }
-
- if (blacklistReasons.length) {
- variant.excludeUntil = Infinity;
-
- _this11.logger_("blacklisting " + variant.id + ": " + blacklistReasons.join(' && '));
- }
- });
- };
-
- _proto.updateAdCues_ = function updateAdCues_(media) {
- var offset = 0;
- var seekable = this.seekable();
-
- if (seekable.length) {
- offset = seekable.start(0);
- }
-
- updateAdCues(media, this.cueTagsTrack_, offset);
- }
- /**
- * Calculates the desired forward buffer length based on current time
- *
- * @return {number} Desired forward buffer length in seconds
- */
- ;
-
- _proto.goalBufferLength = function goalBufferLength() {
- var currentTime = this.tech_.currentTime();
- var initial = Config.GOAL_BUFFER_LENGTH;
- var rate = Config.GOAL_BUFFER_LENGTH_RATE;
- var max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
- return Math.min(initial + currentTime * rate, max);
- }
- /**
- * Calculates the desired buffer low water line based on current time
- *
- * @return {number} Desired buffer low water line in seconds
- */
- ;
-
- _proto.bufferLowWaterLine = function bufferLowWaterLine() {
- var currentTime = this.tech_.currentTime();
- var initial = Config.BUFFER_LOW_WATER_LINE;
- var rate = Config.BUFFER_LOW_WATER_LINE_RATE;
- var max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
- var newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
- return Math.min(initial + currentTime * rate, this.experimentalBufferBasedABR ? newMax : max);
- };
-
- _proto.bufferHighWaterLine = function bufferHighWaterLine() {
- return Config.BUFFER_HIGH_WATER_LINE;
- };
-
- return MasterPlaylistController;
-}(videojs__default['default'].EventTarget);
-
-/**
- * Returns a function that acts as the Enable/disable playlist function.
- *
- * @param {PlaylistLoader} loader - The master playlist loader
- * @param {string} playlistID - id of the playlist
- * @param {Function} changePlaylistFn - A function to be called after a
- * playlist's enabled-state has been changed. Will NOT be called if a
- * playlist's enabled-state is unchanged
- * @param {boolean=} enable - Value to set the playlist enabled-state to
- * or if undefined returns the current enabled-state for the playlist
- * @return {Function} Function for setting/getting enabled
- */
-
-var enableFunction = function enableFunction(loader, playlistID, changePlaylistFn) {
- return function (enable) {
- var playlist = loader.master.playlists[playlistID];
- var incompatible = isIncompatible(playlist);
- var currentlyEnabled = isEnabled(playlist);
-
- if (typeof enable === 'undefined') {
- return currentlyEnabled;
- }
-
- if (enable) {
- delete playlist.disabled;
- } else {
- playlist.disabled = true;
- }
-
- if (enable !== currentlyEnabled && !incompatible) {
- // Ensure the outside world knows about our changes
- changePlaylistFn();
-
- if (enable) {
- loader.trigger('renditionenabled');
- } else {
- loader.trigger('renditiondisabled');
- }
- }
-
- return enable;
- };
-};
-/**
- * The representation object encapsulates the publicly visible information
- * in a media playlist along with a setter/getter-type function (enabled)
- * for changing the enabled-state of a particular playlist entry
- *
- * @class Representation
- */
-
-
-var Representation = function Representation(vhsHandler, playlist, id) {
- var mpc = vhsHandler.masterPlaylistController_,
- smoothQualityChange = vhsHandler.options_.smoothQualityChange; // Get a reference to a bound version of the quality change function
-
- var changeType = smoothQualityChange ? 'smooth' : 'fast';
- var qualityChangeFunction = mpc[changeType + "QualityChange_"].bind(mpc); // some playlist attributes are optional
-
- if (playlist.attributes) {
- var resolution = playlist.attributes.RESOLUTION;
- this.width = resolution && resolution.width;
- this.height = resolution && resolution.height;
- this.bandwidth = playlist.attributes.BANDWIDTH;
- }
-
- this.codecs = codecsForPlaylist(mpc.master(), playlist);
- this.playlist = playlist; // The id is simply the ordinality of the media playlist
- // within the master playlist
-
- this.id = id; // Partially-apply the enableFunction to create a playlist-
- // specific variant
-
- this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
-};
-/**
- * A mixin function that adds the `representations` api to an instance
- * of the VhsHandler class
- *
- * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
- * representation API into
- */
-
-
-var renditionSelectionMixin = function renditionSelectionMixin(vhsHandler) {
- // Add a single API-specific function to the VhsHandler instance
- vhsHandler.representations = function () {
- var master = vhsHandler.masterPlaylistController_.master();
- var playlists = isAudioOnly(master) ? vhsHandler.masterPlaylistController_.getAudioTrackPlaylists_() : master.playlists;
-
- if (!playlists) {
- return [];
- }
-
- return playlists.filter(function (media) {
- return !isIncompatible(media);
- }).map(function (e, i) {
- return new Representation(vhsHandler, e, e.id);
- });
- };
-};
-
-/**
- * @file playback-watcher.js
- *
- * Playback starts, and now my watch begins. It shall not end until my death. I shall
- * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
- * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
- * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
- * my life and honor to the Playback Watch, for this Player and all the Players to come.
- */
-
-var timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
-/**
- * Returns whether or not the current time should be considered close to buffered content,
- * taking into consideration whether there's enough buffered content for proper playback.
- *
- * @param {Object} options
- * Options object
- * @param {TimeRange} options.buffered
- * Current buffer
- * @param {number} options.targetDuration
- * The active playlist's target duration
- * @param {number} options.currentTime
- * The current time of the player
- * @return {boolean}
- * Whether the current time should be considered close to the buffer
- */
-
-var closeToBufferedContent = function closeToBufferedContent(_ref) {
- var buffered = _ref.buffered,
- targetDuration = _ref.targetDuration,
- currentTime = _ref.currentTime;
-
- if (!buffered.length) {
- return false;
- } // At least two to three segments worth of content should be buffered before there's a
- // full enough buffer to consider taking any actions.
-
-
- if (buffered.end(0) - buffered.start(0) < targetDuration * 2) {
- return false;
- } // It's possible that, on seek, a remove hasn't completed and the buffered range is
- // somewhere past the current time. In that event, don't consider the buffered content
- // close.
-
-
- if (currentTime > buffered.start(0)) {
- return false;
- } // Since target duration generally represents the max (or close to max) duration of a
- // segment, if the buffer is within a segment of the current time, the gap probably
- // won't be closed, and current time should be considered close to buffered content.
-
-
- return buffered.start(0) - currentTime < targetDuration;
-};
-/**
- * @class PlaybackWatcher
- */
-
-var PlaybackWatcher = /*#__PURE__*/function () {
- /**
- * Represents an PlaybackWatcher object.
- *
- * @class
- * @param {Object} options an object that includes the tech and settings
- */
- function PlaybackWatcher(options) {
- var _this = this;
-
- this.masterPlaylistController_ = options.masterPlaylistController;
- this.tech_ = options.tech;
- this.seekable = options.seekable;
- this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
- this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
- this.media = options.media;
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = null;
- this.timer_ = null;
- this.checkCurrentTimeTimeout_ = null;
- this.logger_ = logger('PlaybackWatcher');
- this.logger_('initialize');
-
- var playHandler = function playHandler() {
- return _this.monitorCurrentTime_();
- };
-
- var canPlayHandler = function canPlayHandler() {
- return _this.monitorCurrentTime_();
- };
-
- var waitingHandler = function waitingHandler() {
- return _this.techWaiting_();
- };
-
- var cancelTimerHandler = function cancelTimerHandler() {
- return _this.cancelTimer_();
- };
-
- var fixesBadSeeksHandler = function fixesBadSeeksHandler() {
- return _this.fixesBadSeeks_();
- };
-
- var mpc = this.masterPlaylistController_;
- var loaderTypes = ['main', 'subtitle', 'audio'];
- var loaderChecks = {};
- loaderTypes.forEach(function (type) {
- loaderChecks[type] = {
- reset: function reset() {
- return _this.resetSegmentDownloads_(type);
- },
- updateend: function updateend() {
- return _this.checkSegmentDownloads_(type);
- }
- };
- mpc[type + "SegmentLoader_"].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
- // isn't changing we want to reset. We cannot assume that the new rendition
- // will also be stalled, until after new appends.
-
- mpc[type + "SegmentLoader_"].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
- // This prevents one segment playlists (single vtt or single segment content)
- // from being detected as stalling. As the buffer will not change in those cases, since
- // the buffer is the entire video duration.
-
- _this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
- });
- this.tech_.on('seekablechanged', fixesBadSeeksHandler);
- this.tech_.on('waiting', waitingHandler);
- this.tech_.on(timerCancelEvents, cancelTimerHandler);
- this.tech_.on('canplay', canPlayHandler);
- /*
- An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
- is surfaced in one of two ways:
- 1) The `waiting` event is fired before the player has buffered content, making it impossible
- to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
- we can check if playback is stalled due to a gap, and skip the gap if necessary.
- 2) A source with a gap at the beginning of the stream is loaded programatically while the player
- is in a playing state. To catch this case, it's important that our one-time play listener is setup
- even if the player is in a playing state
- */
-
- this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
-
- this.dispose = function () {
- _this.logger_('dispose');
-
- _this.tech_.off('seekablechanged', fixesBadSeeksHandler);
-
- _this.tech_.off('waiting', waitingHandler);
-
- _this.tech_.off(timerCancelEvents, cancelTimerHandler);
-
- _this.tech_.off('canplay', canPlayHandler);
-
- _this.tech_.off('play', playHandler);
-
- loaderTypes.forEach(function (type) {
- mpc[type + "SegmentLoader_"].off('appendsdone', loaderChecks[type].updateend);
- mpc[type + "SegmentLoader_"].off('playlistupdate', loaderChecks[type].reset);
-
- _this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
- });
-
- if (_this.checkCurrentTimeTimeout_) {
- window__default['default'].clearTimeout(_this.checkCurrentTimeTimeout_);
- }
-
- _this.cancelTimer_();
- };
- }
- /**
- * Periodically check current time to see if playback stopped
- *
- * @private
- */
-
-
- var _proto = PlaybackWatcher.prototype;
-
- _proto.monitorCurrentTime_ = function monitorCurrentTime_() {
- this.checkCurrentTime_();
-
- if (this.checkCurrentTimeTimeout_) {
- window__default['default'].clearTimeout(this.checkCurrentTimeTimeout_);
- } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
-
-
- this.checkCurrentTimeTimeout_ = window__default['default'].setTimeout(this.monitorCurrentTime_.bind(this), 250);
- }
- /**
- * Reset stalled download stats for a specific type of loader
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#playlistupdate
- * @listens Tech#seeking
- * @listens Tech#seeked
- */
- ;
-
- _proto.resetSegmentDownloads_ = function resetSegmentDownloads_(type) {
- var loader = this.masterPlaylistController_[type + "SegmentLoader_"];
-
- if (this[type + "StalledDownloads_"] > 0) {
- this.logger_("resetting possible stalled download count for " + type + " loader");
- }
-
- this[type + "StalledDownloads_"] = 0;
- this[type + "Buffered_"] = loader.buffered_();
- }
- /**
- * Checks on every segment `appendsdone` to see
- * if segment appends are making progress. If they are not
- * and we are still downloading bytes. We blacklist the playlist.
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#appendsdone
- */
- ;
-
- _proto.checkSegmentDownloads_ = function checkSegmentDownloads_(type) {
- var mpc = this.masterPlaylistController_;
- var loader = mpc[type + "SegmentLoader_"];
- var buffered = loader.buffered_();
- var isBufferedDifferent = isRangeDifferent(this[type + "Buffered_"], buffered);
- this[type + "Buffered_"] = buffered; // if another watcher is going to fix the issue or
- // the buffered value for this loader changed
- // appends are working
-
- if (isBufferedDifferent) {
- this.resetSegmentDownloads_(type);
- return;
- }
-
- this[type + "StalledDownloads_"]++;
- this.logger_("found #" + this[type + "StalledDownloads_"] + " " + type + " appends that did not increase buffer (possible stalled download)", {
- playlistId: loader.playlist_ && loader.playlist_.id,
- buffered: timeRangesToArray(buffered)
- }); // after 10 possibly stalled appends with no reset, exclude
-
- if (this[type + "StalledDownloads_"] < 10) {
- return;
- }
-
- this.logger_(type + " loader stalled download exclusion");
- this.resetSegmentDownloads_(type);
- this.tech_.trigger({
- type: 'usage',
- name: "vhs-" + type + "-download-exclusion"
- });
-
- if (type === 'subtitle') {
- return;
- } // TODO: should we exclude audio tracks rather than main tracks
- // when type is audio?
-
-
- mpc.blacklistCurrentPlaylist({
- message: "Excessive " + type + " segment downloading detected."
- }, Infinity);
- }
- /**
- * The purpose of this function is to emulate the "waiting" event on
- * browsers that do not emit it when they are waiting for more
- * data to continue playback
- *
- * @private
- */
- ;
-
- _proto.checkCurrentTime_ = function checkCurrentTime_() {
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = this.tech_.currentTime();
- return;
- }
-
- if (this.tech_.paused() || this.tech_.seeking()) {
- return;
- }
-
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
-
- if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
- // If current time is at the end of the final buffered region, then any playback
- // stall is most likely caused by buffering in a low bandwidth environment. The tech
- // should fire a `waiting` event in this scenario, but due to browser and tech
- // inconsistencies. Calling `techWaiting_` here allows us to simulate
- // responding to a native `waiting` event when the tech fails to emit one.
- return this.techWaiting_();
- }
-
- if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- this.waiting_();
- } else if (currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- } else {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = currentTime;
- }
- }
- /**
- * Cancels any pending timers and resets the 'timeupdate' mechanism
- * designed to detect that we are stalled
- *
- * @private
- */
- ;
-
- _proto.cancelTimer_ = function cancelTimer_() {
- this.consecutiveUpdates = 0;
-
- if (this.timer_) {
- this.logger_('cancelTimer_');
- clearTimeout(this.timer_);
- }
-
- this.timer_ = null;
- }
- /**
- * Fixes situations where there's a bad seek
- *
- * @return {boolean} whether an action was taken to fix the seek
- * @private
- */
- ;
-
- _proto.fixesBadSeeks_ = function fixesBadSeeks_() {
- var seeking = this.tech_.seeking();
-
- if (!seeking) {
- return false;
- }
-
- var seekable = this.seekable();
- var currentTime = this.tech_.currentTime();
- var isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
- var seekTo;
-
- if (isAfterSeekableRange) {
- var seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
-
- seekTo = seekableEnd;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- var seekableStart = seekable.start(0); // sync to the beginning of the live window
- // provide a buffer of .1 seconds to handle rounding/imprecise numbers
-
- seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
- // happen in live with a 3 segment playlist), then don't use a time delta
- seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
- }
-
- if (typeof seekTo !== 'undefined') {
- this.logger_("Trying to seek outside of seekable at time " + currentTime + " with " + ("seekable range " + printableRange(seekable) + ". Seeking to ") + (seekTo + "."));
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- var buffered = this.tech_.buffered();
-
- if (closeToBufferedContent({
- buffered: buffered,
- targetDuration: this.media().targetDuration,
- currentTime: currentTime
- })) {
- seekTo = buffered.start(0) + SAFE_TIME_DELTA;
- this.logger_("Buffered region starts (" + buffered.start(0) + ") " + (" just beyond seek point (" + currentTime + "). Seeking to " + seekTo + "."));
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- return false;
- }
- /**
- * Handler for situations when we determine the player is waiting.
- *
- * @private
- */
- ;
-
- _proto.waiting_ = function waiting_() {
- if (this.techWaiting_()) {
- return;
- } // All tech waiting checks failed. Use last resort correction
-
-
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
- var currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
- // region with no indication that anything is amiss (seen in Firefox). Seeking to
- // currentTime is usually enough to kickstart the player. This checks that the player
- // is currently within a buffered region before attempting a corrective seek.
- // Chrome does not appear to continue `timeupdate` events after a `waiting` event
- // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
- // make sure there is ~3 seconds of forward buffer before taking any corrective action
- // to avoid triggering an `unknownwaiting` event when the network is slow.
-
- if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime);
- this.logger_("Stopped at " + currentTime + " while inside a buffered region " + ("[" + currentRange.start(0) + " -> " + currentRange.end(0) + "]. Attempting to resume ") + 'playback by seeking to the current time.'); // unknown waiting corrections may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-unknown-waiting'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-unknown-waiting'
- });
- return;
- }
- }
- /**
- * Handler for situations when the tech fires a `waiting` event
- *
- * @return {boolean}
- * True if an action (or none) was needed to correct the waiting. False if no
- * checks passed
- * @private
- */
- ;
-
- _proto.techWaiting_ = function techWaiting_() {
- var seekable = this.seekable();
- var currentTime = this.tech_.currentTime();
-
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- // Tech is seeking or bad seek fixed, no action needed
- return true;
- }
-
- if (this.tech_.seeking() || this.timer_ !== null) {
- // Tech is seeking or already waiting on another action, no action needed
- return true;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- var livePoint = seekable.end(seekable.length - 1);
- this.logger_("Fell out of live window at time " + currentTime + ". Seeking to " + ("live point (seekable end) " + livePoint));
- this.cancelTimer_();
- this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-live-resync'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-live-resync'
- });
- return true;
- }
-
- var sourceUpdater = this.tech_.vhs.masterPlaylistController_.sourceUpdater_;
- var buffered = this.tech_.buffered();
- var videoUnderflow = this.videoUnderflow_({
- audioBuffered: sourceUpdater.audioBuffered(),
- videoBuffered: sourceUpdater.videoBuffered(),
- currentTime: currentTime
- });
-
- if (videoUnderflow) {
- // Even though the video underflowed and was stuck in a gap, the audio overplayed
- // the gap, leading currentTime into a buffered range. Seeking to currentTime
- // allows the video to catch up to the audio position without losing any audio
- // (only suffering ~3 seconds of frozen video and a pause in audio playback).
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-video-underflow'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-video-underflow'
- });
- return true;
- }
-
- var nextRange = findNextRange(buffered, currentTime); // check for gap
-
- if (nextRange.length > 0) {
- var difference = nextRange.start(0) - currentTime;
- this.logger_("Stopped at " + currentTime + ", setting timer for " + difference + ", seeking " + ("to " + nextRange.start(0)));
- this.cancelTimer_();
- this.timer_ = setTimeout(this.skipTheGap_.bind(this), difference * 1000, currentTime);
- return true;
- } // All checks failed. Returning false to indicate failure to correct waiting
-
-
- return false;
- };
-
- _proto.afterSeekableWindow_ = function afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow) {
- if (allowSeeksWithinUnsafeLiveWindow === void 0) {
- allowSeeksWithinUnsafeLiveWindow = false;
- }
-
- if (!seekable.length) {
- // we can't make a solid case if there's no seekable, default to false
- return false;
- }
-
- var allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
- var isLive = !playlist.endList;
-
- if (isLive && allowSeeksWithinUnsafeLiveWindow) {
- allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
- }
-
- if (currentTime > allowedEnd) {
- return true;
- }
-
- return false;
- };
-
- _proto.beforeSeekableWindow_ = function beforeSeekableWindow_(seekable, currentTime) {
- if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
- seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
- return true;
- }
-
- return false;
- };
-
- _proto.videoUnderflow_ = function videoUnderflow_(_ref2) {
- var videoBuffered = _ref2.videoBuffered,
- audioBuffered = _ref2.audioBuffered,
- currentTime = _ref2.currentTime;
-
- // audio only content will not have video underflow :)
- if (!videoBuffered) {
- return;
- }
-
- var gap; // find a gap in demuxed content.
-
- if (videoBuffered.length && audioBuffered.length) {
- // in Chrome audio will continue to play for ~3s when we run out of video
- // so we have to check that the video buffer did have some buffer in the
- // past.
- var lastVideoRange = findRange(videoBuffered, currentTime - 3);
- var videoRange = findRange(videoBuffered, currentTime);
- var audioRange = findRange(audioBuffered, currentTime);
-
- if (audioRange.length && !videoRange.length && lastVideoRange.length) {
- gap = {
- start: lastVideoRange.end(0),
- end: audioRange.end(0)
- };
- } // find a gap in muxed content.
-
- } else {
- var nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
- // stuck in a gap due to video underflow.
-
- if (!nextRange.length) {
- gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
- }
- }
-
- if (gap) {
- this.logger_("Encountered a gap in video from " + gap.start + " to " + gap.end + ". " + ("Seeking to current time " + currentTime));
- return true;
- }
-
- return false;
- }
- /**
- * Timer callback. If playback still has not proceeded, then we seek
- * to the start of the next buffered region.
- *
- * @private
- */
- ;
-
- _proto.skipTheGap_ = function skipTheGap_(scheduledCurrentTime) {
- var buffered = this.tech_.buffered();
- var currentTime = this.tech_.currentTime();
- var nextRange = findNextRange(buffered, currentTime);
- this.cancelTimer_();
-
- if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
- return;
- }
-
- this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
-
- this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-gap-skip'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-gap-skip'
- });
- };
-
- _proto.gapFromVideoUnderflow_ = function gapFromVideoUnderflow_(buffered, currentTime) {
- // At least in Chrome, if there is a gap in the video buffer, the audio will continue
- // playing for ~3 seconds after the video gap starts. This is done to account for
- // video buffer underflow/underrun (note that this is not done when there is audio
- // buffer underflow/underrun -- in that case the video will stop as soon as it
- // encounters the gap, as audio stalls are more noticeable/jarring to a user than
- // video stalls). The player's time will reflect the playthrough of audio, so the
- // time will appear as if we are in a buffered region, even if we are stuck in a
- // "gap."
- //
- // Example:
- // video buffer: 0 => 10.1, 10.2 => 20
- // audio buffer: 0 => 20
- // overall buffer: 0 => 10.1, 10.2 => 20
- // current time: 13
- //
- // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
- // however, the audio continued playing until it reached ~3 seconds past the gap
- // (13 seconds), at which point it stops as well. Since current time is past the
- // gap, findNextRange will return no ranges.
- //
- // To check for this issue, we see if there is a gap that starts somewhere within
- // a 3 second range (3 seconds +/- 1 second) back from our current time.
- var gaps = findGaps(buffered);
-
- for (var i = 0; i < gaps.length; i++) {
- var start = gaps.start(i);
- var end = gaps.end(i); // gap is starts no more than 4 seconds back
-
- if (currentTime - start < 4 && currentTime - start > 2) {
- return {
- start: start,
- end: end
- };
- }
- }
-
- return null;
- };
-
- return PlaybackWatcher;
-}();
-
-var defaultOptions = {
- errorInterval: 30,
- getSource: function getSource(next) {
- var tech = this.tech({
- IWillNotUseThisInPlugins: true
- });
- var sourceObj = tech.currentSource_ || this.currentSource();
- return next(sourceObj);
- }
-};
-/**
- * Main entry point for the plugin
- *
- * @param {Player} player a reference to a videojs Player instance
- * @param {Object} [options] an object with plugin options
- * @private
- */
-
-var initPlugin = function initPlugin(player, options) {
- var lastCalled = 0;
- var seekTo = 0;
- var localOptions = videojs__default['default'].mergeOptions(defaultOptions, options);
- player.ready(function () {
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload-initialized'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload-initialized'
- });
- });
- /**
- * Player modifications to perform that must wait until `loadedmetadata`
- * has been triggered
- *
- * @private
- */
-
- var loadedMetadataHandler = function loadedMetadataHandler() {
- if (seekTo) {
- player.currentTime(seekTo);
- }
- };
- /**
- * Set the source on the player element, play, and seek if necessary
- *
- * @param {Object} sourceObj An object specifying the source url and mime-type to play
- * @private
- */
-
-
- var setSource = function setSource(sourceObj) {
- if (sourceObj === null || sourceObj === undefined) {
- return;
- }
-
- seekTo = player.duration() !== Infinity && player.currentTime() || 0;
- player.one('loadedmetadata', loadedMetadataHandler);
- player.src(sourceObj);
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload'
- });
- player.play();
- };
- /**
- * Attempt to get a source from either the built-in getSource function
- * or a custom function provided via the options
- *
- * @private
- */
-
-
- var errorHandler = function errorHandler() {
- // Do not attempt to reload the source if a source-reload occurred before
- // 'errorInterval' time has elapsed since the last source-reload
- if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload-canceled'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload-canceled'
- });
- return;
- }
-
- if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
- videojs__default['default'].log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
- return;
- }
-
- lastCalled = Date.now();
- return localOptions.getSource.call(player, setSource);
- };
- /**
- * Unbind any event handlers that were bound by the plugin
- *
- * @private
- */
-
-
- var cleanupEvents = function cleanupEvents() {
- player.off('loadedmetadata', loadedMetadataHandler);
- player.off('error', errorHandler);
- player.off('dispose', cleanupEvents);
- };
- /**
- * Cleanup before re-initializing the plugin
- *
- * @param {Object} [newOptions] an object with plugin options
- * @private
- */
-
-
- var reinitPlugin = function reinitPlugin(newOptions) {
- cleanupEvents();
- initPlugin(player, newOptions);
- };
-
- player.on('error', errorHandler);
- player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
- // initializing the plugin
-
- player.reloadSourceOnError = reinitPlugin;
-};
-/**
- * Reload the source when an error is detected as long as there
- * wasn't an error previously within the last 30 seconds
- *
- * @param {Object} [options] an object with plugin options
- */
-
-
-var reloadSourceOnError = function reloadSourceOnError(options) {
- initPlugin(this, options);
-};
-
-var version$4 = "2.9.1";
-
-var version$3 = "5.11.1";
-
-var version$2 = "0.17.0";
-
-var version$1 = "4.7.0";
-
-var version = "3.1.2";
-
-var Vhs = {
- PlaylistLoader: PlaylistLoader,
- Playlist: Playlist,
- utils: utils,
- STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
- INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
- lastBandwidthSelector: lastBandwidthSelector,
- movingAverageBandwidthSelector: movingAverageBandwidthSelector,
- comparePlaylistBandwidth: comparePlaylistBandwidth,
- comparePlaylistResolution: comparePlaylistResolution,
- xhr: xhrFactory()
-}; // Define getter/setters for config properties
-
-Object.keys(Config).forEach(function (prop) {
- Object.defineProperty(Vhs, prop, {
- get: function get() {
- videojs__default['default'].log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
- return Config[prop];
- },
- set: function set(value) {
- videojs__default['default'].log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
-
- if (typeof value !== 'number' || value < 0) {
- videojs__default['default'].log.warn("value of Vhs." + prop + " must be greater than or equal to 0");
- return;
- }
-
- Config[prop] = value;
- }
- });
-});
-var LOCAL_STORAGE_KEY = 'videojs-vhs';
-/**
- * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
- * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
- * @function handleVhsMediaChange
- */
-
-var handleVhsMediaChange = function handleVhsMediaChange(qualityLevels, playlistLoader) {
- var newPlaylist = playlistLoader.media();
- var selectedIndex = -1;
-
- for (var i = 0; i < qualityLevels.length; i++) {
- if (qualityLevels[i].id === newPlaylist.id) {
- selectedIndex = i;
- break;
- }
- }
-
- qualityLevels.selectedIndex_ = selectedIndex;
- qualityLevels.trigger({
- selectedIndex: selectedIndex,
- type: 'change'
- });
-};
-/**
- * Adds quality levels to list once playlist metadata is available
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
- * @param {Object} vhs Vhs object to listen to for media events.
- * @function handleVhsLoadedMetadata
- */
-
-
-var handleVhsLoadedMetadata = function handleVhsLoadedMetadata(qualityLevels, vhs) {
- vhs.representations().forEach(function (rep) {
- qualityLevels.addQualityLevel(rep);
- });
- handleVhsMediaChange(qualityLevels, vhs.playlists);
-}; // HLS is a source handler, not a tech. Make sure attempts to use it
-// as one do not cause exceptions.
-
-
-Vhs.canPlaySource = function () {
- return videojs__default['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
-};
-
-var emeKeySystems = function emeKeySystems(keySystemOptions, mainPlaylist, audioPlaylist) {
- if (!keySystemOptions) {
- return keySystemOptions;
- }
-
- var codecs = {};
-
- if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
- codecs = unwrapCodecList(codecs_js.parseCodecs(mainPlaylist.attributes.CODECS));
- }
-
- if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
- codecs.audio = audioPlaylist.attributes.CODECS;
- }
-
- var videoContentType = codecs_js.getMimeForCodec(codecs.video);
- var audioContentType = codecs_js.getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
-
- var keySystemContentTypes = {};
-
- for (var keySystem in keySystemOptions) {
- keySystemContentTypes[keySystem] = {};
-
- if (audioContentType) {
- keySystemContentTypes[keySystem].audioContentType = audioContentType;
- }
-
- if (videoContentType) {
- keySystemContentTypes[keySystem].videoContentType = videoContentType;
- } // Default to using the video playlist's PSSH even though they may be different, as
- // videojs-contrib-eme will only accept one in the options.
- //
- // This shouldn't be an issue for most cases as early intialization will handle all
- // unique PSSH values, and if they aren't, then encrypted events should have the
- // specific information needed for the unique license.
-
-
- if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
- keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
- } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
- // so we need to prevent overwriting the URL entirely
-
-
- if (typeof keySystemOptions[keySystem] === 'string') {
- keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
- }
- }
-
- return videojs__default['default'].mergeOptions(keySystemOptions, keySystemContentTypes);
-};
-/**
- * @typedef {Object} KeySystems
- *
- * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
- * Note: not all options are listed here.
- *
- * @property {Uint8Array} [pssh]
- * Protection System Specific Header
- */
-
-/**
- * Goes through all the playlists and collects an array of KeySystems options objects
- * containing each playlist's keySystems and their pssh values, if available.
- *
- * @param {Object[]} playlists
- * The playlists to look through
- * @param {string[]} keySystems
- * The keySystems to collect pssh values for
- *
- * @return {KeySystems[]}
- * An array of KeySystems objects containing available key systems and their
- * pssh values
- */
-
-
-var getAllPsshKeySystemsOptions = function getAllPsshKeySystemsOptions(playlists, keySystems) {
- return playlists.reduce(function (keySystemsArr, playlist) {
- if (!playlist.contentProtection) {
- return keySystemsArr;
- }
-
- var keySystemsOptions = keySystems.reduce(function (keySystemsObj, keySystem) {
- var keySystemOptions = playlist.contentProtection[keySystem];
-
- if (keySystemOptions && keySystemOptions.pssh) {
- keySystemsObj[keySystem] = {
- pssh: keySystemOptions.pssh
- };
- }
-
- return keySystemsObj;
- }, {});
-
- if (Object.keys(keySystemsOptions).length) {
- keySystemsArr.push(keySystemsOptions);
- }
-
- return keySystemsArr;
- }, []);
-};
-/**
- * Returns a promise that waits for the
- * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
- *
- * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
- * browsers.
- *
- * As per the above ticket, this is particularly important for Chrome, where, if
- * unencrypted content is appended before encrypted content and the key session has not
- * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
- * during playback.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- * @param {Object[]} mainPlaylists
- * The playlists found on the master playlist object
- *
- * @return {Object}
- * Promise that resolves when the key session has been created
- */
-
-
-var waitForKeySessionCreation = function waitForKeySessionCreation(_ref) {
- var player = _ref.player,
- sourceKeySystems = _ref.sourceKeySystems,
- audioMedia = _ref.audioMedia,
- mainPlaylists = _ref.mainPlaylists;
-
- if (!player.eme.initializeMediaKeys) {
- return Promise.resolve();
- } // TODO should all audio PSSH values be initialized for DRM?
- //
- // All unique video rendition pssh values are initialized for DRM, but here only
- // the initial audio playlist license is initialized. In theory, an encrypted
- // event should be fired if the user switches to an alternative audio playlist
- // where a license is required, but this case hasn't yet been tested. In addition, there
- // may be many alternate audio playlists unlikely to be used (e.g., multiple different
- // languages).
-
-
- var playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
- var keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
- var initializationFinishedPromises = [];
- var keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
- // only place where it should not be deduped is for ms-prefixed APIs, but the early
- // return for IE11 above, and the existence of modern EME APIs in addition to
- // ms-prefixed APIs on Edge should prevent this from being a concern.
- // initializeMediaKeys also won't use the webkit-prefixed APIs.
-
- keySystemsOptionsArr.forEach(function (keySystemsOptions) {
- keySessionCreatedPromises.push(new Promise(function (resolve, reject) {
- player.tech_.one('keysessioncreated', resolve);
- }));
- initializationFinishedPromises.push(new Promise(function (resolve, reject) {
- player.eme.initializeMediaKeys({
- keySystems: keySystemsOptions
- }, function (err) {
- if (err) {
- reject(err);
- return;
- }
-
- resolve();
- });
- }));
- }); // The reasons Promise.race is chosen over Promise.any:
- //
- // * Promise.any is only available in Safari 14+.
- // * None of these promises are expected to reject. If they do reject, it might be
- // better here for the race to surface the rejection, rather than mask it by using
- // Promise.any.
-
- return Promise.race([// If a session was previously created, these will all finish resolving without
- // creating a new session, otherwise it will take until the end of all license
- // requests, which is why the key session check is used (to make setup much faster).
- Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
- Promise.race(keySessionCreatedPromises)]);
-};
-/**
- * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
- * there are keySystems on the source, sets up source options to prepare the source for
- * eme.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} media
- * The active media playlist
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- *
- * @return {boolean}
- * Whether or not options were configured and EME is available
- */
-
-var setupEmeOptions = function setupEmeOptions(_ref2) {
- var player = _ref2.player,
- sourceKeySystems = _ref2.sourceKeySystems,
- media = _ref2.media,
- audioMedia = _ref2.audioMedia;
- var sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
-
- if (!sourceOptions) {
- return false;
- }
-
- player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
- // do nothing.
-
- if (sourceOptions && !player.eme) {
- videojs__default['default'].log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
- return false;
- }
-
- return true;
-};
-
-var getVhsLocalStorage = function getVhsLocalStorage() {
- if (!window__default['default'].localStorage) {
- return null;
- }
-
- var storedObject = window__default['default'].localStorage.getItem(LOCAL_STORAGE_KEY);
-
- if (!storedObject) {
- return null;
- }
-
- try {
- return JSON.parse(storedObject);
- } catch (e) {
- // someone may have tampered with the value
- return null;
- }
-};
-
-var updateVhsLocalStorage = function updateVhsLocalStorage(options) {
- if (!window__default['default'].localStorage) {
- return false;
- }
-
- var objectToStore = getVhsLocalStorage();
- objectToStore = objectToStore ? videojs__default['default'].mergeOptions(objectToStore, options) : options;
-
- try {
- window__default['default'].localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
- } catch (e) {
- // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
- // storage is set to 0).
- // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
- // No need to perform any operation.
- return false;
- }
-
- return objectToStore;
-};
-/**
- * Parses VHS-supported media types from data URIs. See
- * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
- * for information on data URIs.
- *
- * @param {string} dataUri
- * The data URI
- *
- * @return {string|Object}
- * The parsed object/string, or the original string if no supported media type
- * was found
- */
-
-
-var expandDataUri = function expandDataUri(dataUri) {
- if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
- return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
- } // no known case for this data URI, return the string as-is
-
-
- return dataUri;
-};
-/**
- * Whether the browser has built-in HLS support.
- */
-
-
-Vhs.supportsNativeHls = function () {
- if (!document__default['default'] || !document__default['default'].createElement) {
- return false;
- }
-
- var video = document__default['default'].createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
-
- if (!videojs__default['default'].getTech('Html5').isSupported()) {
- return false;
- } // HLS manifests can go by many mime-types
-
-
- var canPlay = [// Apple santioned
- 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
- 'audio/mpegurl', // Very common
- 'audio/x-mpegurl', // Very common
- 'application/x-mpegurl', // Included for completeness
- 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
- return canPlay.some(function (canItPlay) {
- return /maybe|probably/i.test(video.canPlayType(canItPlay));
- });
-}();
-
-Vhs.supportsNativeDash = function () {
- if (!document__default['default'] || !document__default['default'].createElement || !videojs__default['default'].getTech('Html5').isSupported()) {
- return false;
- }
-
- return /maybe|probably/i.test(document__default['default'].createElement('video').canPlayType('application/dash+xml'));
-}();
-
-Vhs.supportsTypeNatively = function (type) {
- if (type === 'hls') {
- return Vhs.supportsNativeHls;
- }
-
- if (type === 'dash') {
- return Vhs.supportsNativeDash;
- }
-
- return false;
-};
-/**
- * HLS is a source handler, not a tech. Make sure attempts to use it
- * as one do not cause exceptions.
- */
-
-
-Vhs.isSupported = function () {
- return videojs__default['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
-};
-
-var Component = videojs__default['default'].getComponent('Component');
-/**
- * The Vhs Handler object, where we orchestrate all of the parts
- * of HLS to interact with video.js
- *
- * @class VhsHandler
- * @extends videojs.Component
- * @param {Object} source the soruce object
- * @param {Tech} tech the parent tech object
- * @param {Object} options optional and required options
- */
-
-var VhsHandler = /*#__PURE__*/function (_Component) {
- _inheritsLoose__default['default'](VhsHandler, _Component);
-
- function VhsHandler(source, tech, options) {
- var _this;
-
- _this = _Component.call(this, tech, videojs__default['default'].mergeOptions(options.hls, options.vhs)) || this;
-
- if (options.hls && Object.keys(options.hls).length) {
- videojs__default['default'].log.warn('Using hls options is deprecated. Use vhs instead.');
- } // if a tech level `initialBandwidth` option was passed
- // use that over the VHS level `bandwidth` option
-
-
- if (typeof options.initialBandwidth === 'number') {
- _this.options_.bandwidth = options.initialBandwidth;
- }
-
- _this.logger_ = logger('VhsHandler'); // tech.player() is deprecated but setup a reference to HLS for
- // backwards-compatibility
-
- if (tech.options_ && tech.options_.playerId) {
- var _player = videojs__default['default'](tech.options_.playerId);
-
- if (!_player.hasOwnProperty('hls')) {
- Object.defineProperty(_player, 'hls', {
- get: function get() {
- videojs__default['default'].log.warn('player.hls is deprecated. Use player.tech().vhs instead.');
- tech.trigger({
- type: 'usage',
- name: 'hls-player-access'
- });
- return _assertThisInitialized__default['default'](_this);
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('vhs')) {
- Object.defineProperty(_player, 'vhs', {
- get: function get() {
- videojs__default['default'].log.warn('player.vhs is deprecated. Use player.tech().vhs instead.');
- tech.trigger({
- type: 'usage',
- name: 'vhs-player-access'
- });
- return _assertThisInitialized__default['default'](_this);
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('dash')) {
- Object.defineProperty(_player, 'dash', {
- get: function get() {
- videojs__default['default'].log.warn('player.dash is deprecated. Use player.tech().vhs instead.');
- return _assertThisInitialized__default['default'](_this);
- },
- configurable: true
- });
- }
-
- _this.player_ = _player;
- }
-
- _this.tech_ = tech;
- _this.source_ = source;
- _this.stats = {};
- _this.ignoreNextSeekingEvent_ = false;
-
- _this.setOptions_();
-
- if (_this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
- tech.overrideNativeAudioTracks(true);
- tech.overrideNativeVideoTracks(true);
- } else if (_this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
- // overriding native HLS only works if audio tracks have been emulated
- // error early if we're misconfigured
- throw new Error('Overriding native HLS requires emulated tracks. ' + 'See https://git.io/vMpjB');
- } // listen for fullscreenchange events for this player so that we
- // can adjust our quality selection quickly
-
-
- _this.on(document__default['default'], ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
- var fullscreenElement = document__default['default'].fullscreenElement || document__default['default'].webkitFullscreenElement || document__default['default'].mozFullScreenElement || document__default['default'].msFullscreenElement;
-
- if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
- _this.masterPlaylistController_.fastQualityChange_();
- } else {
- // When leaving fullscreen, since the in page pixel dimensions should be smaller
- // than full screen, see if there should be a rendition switch down to preserve
- // bandwidth.
- _this.masterPlaylistController_.checkABR_();
- }
- });
-
- _this.on(_this.tech_, 'seeking', function () {
- if (this.ignoreNextSeekingEvent_) {
- this.ignoreNextSeekingEvent_ = false;
- return;
- }
-
- this.setCurrentTime(this.tech_.currentTime());
- });
-
- _this.on(_this.tech_, 'error', function () {
- // verify that the error was real and we are loaded
- // enough to have mpc loaded.
- if (this.tech_.error() && this.masterPlaylistController_) {
- this.masterPlaylistController_.pauseLoading();
- }
- });
-
- _this.on(_this.tech_, 'play', _this.play);
-
- return _this;
- }
-
- var _proto = VhsHandler.prototype;
-
- _proto.setOptions_ = function setOptions_() {
- var _this2 = this;
-
- // defaults
- this.options_.withCredentials = this.options_.withCredentials || false;
- this.options_.handleManifestRedirects = this.options_.handleManifestRedirects === false ? false : true;
- this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
- this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
- this.options_.smoothQualityChange = this.options_.smoothQualityChange || false;
- this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
- this.options_.customTagParsers = this.options_.customTagParsers || [];
- this.options_.customTagMappers = this.options_.customTagMappers || [];
- this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
-
- if (typeof this.options_.blacklistDuration !== 'number') {
- this.options_.blacklistDuration = 5 * 60;
- }
-
- if (typeof this.options_.bandwidth !== 'number') {
- if (this.options_.useBandwidthFromLocalStorage) {
- var storedObject = getVhsLocalStorage();
-
- if (storedObject && storedObject.bandwidth) {
- this.options_.bandwidth = storedObject.bandwidth;
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-bandwidth-from-local-storage'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-bandwidth-from-local-storage'
- });
- }
-
- if (storedObject && storedObject.throughput) {
- this.options_.throughput = storedObject.throughput;
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-throughput-from-local-storage'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-throughput-from-local-storage'
- });
- }
- }
- } // if bandwidth was not set by options or pulled from local storage, start playlist
- // selection at a reasonable bandwidth
-
-
- if (typeof this.options_.bandwidth !== 'number') {
- this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
- } // If the bandwidth number is unchanged from the initial setting
- // then this takes precedence over the enableLowInitialPlaylist option
-
-
- this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
-
- ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'smoothQualityChange', 'customTagParsers', 'customTagMappers', 'handleManifestRedirects', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'experimentalBufferBasedABR', 'liveRangeSafeTimeDelta', 'experimentalLLHLS'].forEach(function (option) {
- if (typeof _this2.source_[option] !== 'undefined') {
- _this2.options_[option] = _this2.source_[option];
- }
- });
- this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
- this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
- }
- /**
- * called when player.src gets called, handle a new source
- *
- * @param {Object} src the source object to handle
- */
- ;
-
- _proto.src = function src(_src, type) {
- var _this3 = this;
-
- // do nothing if the src is falsey
- if (!_src) {
- return;
- }
-
- this.setOptions_(); // add master playlist controller options
-
- this.options_.src = expandDataUri(this.source_.src);
- this.options_.tech = this.tech_;
- this.options_.externVhs = Vhs;
- this.options_.sourceType = mediaTypes_js.simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
-
- this.options_.seekTo = function (time) {
- _this3.tech_.setCurrentTime(time);
- };
-
- if (this.options_.smoothQualityChange) {
- videojs__default['default'].log.warn('smoothQualityChange is deprecated and will be removed in the next major version');
- }
-
- this.masterPlaylistController_ = new MasterPlaylistController(this.options_);
- var playbackWatcherOptions = videojs__default['default'].mergeOptions({
- liveRangeSafeTimeDelta: SAFE_TIME_DELTA
- }, this.options_, {
- seekable: function seekable() {
- return _this3.seekable();
- },
- media: function media() {
- return _this3.masterPlaylistController_.media();
- },
- masterPlaylistController: this.masterPlaylistController_
- });
- this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
- this.masterPlaylistController_.on('error', function () {
- var player = videojs__default['default'].players[_this3.tech_.options_.playerId];
- var error = _this3.masterPlaylistController_.error;
-
- if (typeof error === 'object' && !error.code) {
- error.code = 3;
- } else if (typeof error === 'string') {
- error = {
- message: error,
- code: 3
- };
- }
-
- player.error(error);
- });
- var defaultSelector = this.options_.experimentalBufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
- // compatibility with < v2
-
- this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
- this.masterPlaylistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
-
- this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
- this.mediaSource = this.masterPlaylistController_.mediaSource; // Proxy assignment of some properties to the master playlist
- // controller. Using a custom property for backwards compatibility
- // with < v2
-
- Object.defineProperties(this, {
- selectPlaylist: {
- get: function get() {
- return this.masterPlaylistController_.selectPlaylist;
- },
- set: function set(selectPlaylist) {
- this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
- }
- },
- throughput: {
- get: function get() {
- return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
- },
- set: function set(throughput) {
- this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
- // for the cumulative average
-
- this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
- }
- },
- bandwidth: {
- get: function get() {
- return this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
- },
- set: function set(bandwidth) {
- this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
- // `count` is set to zero that current value of `rate` isn't included
- // in the cumulative average
-
- this.masterPlaylistController_.mainSegmentLoader_.throughput = {
- rate: 0,
- count: 0
- };
- }
- },
-
- /**
- * `systemBandwidth` is a combination of two serial processes bit-rates. The first
- * is the network bitrate provided by `bandwidth` and the second is the bitrate of
- * the entire process after that - decryption, transmuxing, and appending - provided
- * by `throughput`.
- *
- * Since the two process are serial, the overall system bandwidth is given by:
- * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
- */
- systemBandwidth: {
- get: function get() {
- var invBandwidth = 1 / (this.bandwidth || 1);
- var invThroughput;
-
- if (this.throughput > 0) {
- invThroughput = 1 / this.throughput;
- } else {
- invThroughput = 0;
- }
-
- var systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
- return systemBitrate;
- },
- set: function set() {
- videojs__default['default'].log.error('The "systemBandwidth" property is read-only');
- }
- }
- });
-
- if (this.options_.bandwidth) {
- this.bandwidth = this.options_.bandwidth;
- }
-
- if (this.options_.throughput) {
- this.throughput = this.options_.throughput;
- }
-
- Object.defineProperties(this.stats, {
- bandwidth: {
- get: function get() {
- return _this3.bandwidth || 0;
- },
- enumerable: true
- },
- mediaRequests: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequests_() || 0;
- },
- enumerable: true
- },
- mediaRequestsAborted: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsAborted_() || 0;
- },
- enumerable: true
- },
- mediaRequestsTimedout: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsTimedout_() || 0;
- },
- enumerable: true
- },
- mediaRequestsErrored: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsErrored_() || 0;
- },
- enumerable: true
- },
- mediaTransferDuration: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaTransferDuration_() || 0;
- },
- enumerable: true
- },
- mediaBytesTransferred: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaBytesTransferred_() || 0;
- },
- enumerable: true
- },
- mediaSecondsLoaded: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaSecondsLoaded_() || 0;
- },
- enumerable: true
- },
- mediaAppends: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaAppends_() || 0;
- },
- enumerable: true
- },
- mainAppendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.mainAppendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- audioAppendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.audioAppendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- appendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.appendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- timeToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.timeToLoadedData_() || 0;
- },
- enumerable: true
- },
- buffered: {
- get: function get() {
- return timeRangesToArray(_this3.tech_.buffered());
- },
- enumerable: true
- },
- currentTime: {
- get: function get() {
- return _this3.tech_.currentTime();
- },
- enumerable: true
- },
- currentSource: {
- get: function get() {
- return _this3.tech_.currentSource_;
- },
- enumerable: true
- },
- currentTech: {
- get: function get() {
- return _this3.tech_.name_;
- },
- enumerable: true
- },
- duration: {
- get: function get() {
- return _this3.tech_.duration();
- },
- enumerable: true
- },
- master: {
- get: function get() {
- return _this3.playlists.master;
- },
- enumerable: true
- },
- playerDimensions: {
- get: function get() {
- return _this3.tech_.currentDimensions();
- },
- enumerable: true
- },
- seekable: {
- get: function get() {
- return timeRangesToArray(_this3.tech_.seekable());
- },
- enumerable: true
- },
- timestamp: {
- get: function get() {
- return Date.now();
- },
- enumerable: true
- },
- videoPlaybackQuality: {
- get: function get() {
- return _this3.tech_.getVideoPlaybackQuality();
- },
- enumerable: true
- }
- });
- this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
- this.tech_.on('bandwidthupdate', function () {
- if (_this3.options_.useBandwidthFromLocalStorage) {
- updateVhsLocalStorage({
- bandwidth: _this3.bandwidth,
- throughput: Math.round(_this3.throughput)
- });
- }
- });
- this.masterPlaylistController_.on('selectedinitialmedia', function () {
- // Add the manual rendition mix-in to VhsHandler
- renditionSelectionMixin(_this3);
- });
- this.masterPlaylistController_.sourceUpdater_.on('createdsourcebuffers', function () {
- _this3.setupEme_();
- }); // the bandwidth of the primary segment loader is our best
- // estimate of overall bandwidth
-
- this.on(this.masterPlaylistController_, 'progress', function () {
- this.tech_.trigger('progress');
- }); // In the live case, we need to ignore the very first `seeking` event since
- // that will be the result of the seek-to-live behavior
-
- this.on(this.masterPlaylistController_, 'firstplay', function () {
- this.ignoreNextSeekingEvent_ = true;
- });
- this.setupQualityLevels_(); // do nothing if the tech has been disposed already
- // this can occur if someone sets the src in player.ready(), for instance
-
- if (!this.tech_.el()) {
- return;
- }
-
- this.mediaSourceUrl_ = window__default['default'].URL.createObjectURL(this.masterPlaylistController_.mediaSource);
- this.tech_.src(this.mediaSourceUrl_);
- }
- /**
- * If necessary and EME is available, sets up EME options and waits for key session
- * creation.
- *
- * This function also updates the source updater so taht it can be used, as for some
- * browsers, EME must be configured before content is appended (if appending unencrypted
- * content before encrypted content).
- */
- ;
-
- _proto.setupEme_ = function setupEme_() {
- var _this4 = this;
-
- var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
- var didSetupEmeOptions = setupEmeOptions({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- media: this.playlists.media(),
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
- }); // In IE11 this is too early to initialize media keys, and IE11 does not support
- // promises.
-
- if (videojs__default['default'].browser.IE_VERSION === 11 || !didSetupEmeOptions) {
- // If EME options were not set up, we've done all we could to initialize EME.
- this.masterPlaylistController_.sourceUpdater_.initializedEme();
- return;
- }
-
- this.logger_('waiting for EME key session creation');
- waitForKeySessionCreation({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
- mainPlaylists: this.playlists.master.playlists
- }).then(function () {
- _this4.logger_('created EME key session');
-
- _this4.masterPlaylistController_.sourceUpdater_.initializedEme();
- }).catch(function (err) {
- _this4.logger_('error while creating EME key session', err);
-
- _this4.player_.error({
- message: 'Failed to initialize media keys for EME',
- code: 3
- });
- });
- }
- /**
- * Initializes the quality levels and sets listeners to update them.
- *
- * @method setupQualityLevels_
- * @private
- */
- ;
-
- _proto.setupQualityLevels_ = function setupQualityLevels_() {
- var _this5 = this;
-
- var player = videojs__default['default'].players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
- // or qualityLevels_ listeners have already been setup, do nothing.
-
- if (!player || !player.qualityLevels || this.qualityLevels_) {
- return;
- }
-
- this.qualityLevels_ = player.qualityLevels();
- this.masterPlaylistController_.on('selectedinitialmedia', function () {
- handleVhsLoadedMetadata(_this5.qualityLevels_, _this5);
- });
- this.playlists.on('mediachange', function () {
- handleVhsMediaChange(_this5.qualityLevels_, _this5.playlists);
- });
- }
- /**
- * return the version
- */
- ;
-
- VhsHandler.version = function version$5() {
- return {
- '@videojs/http-streaming': version$4,
- 'mux.js': version$3,
- 'mpd-parser': version$2,
- 'm3u8-parser': version$1,
- 'aes-decrypter': version
- };
- }
- /**
- * return the version
- */
- ;
-
- _proto.version = function version() {
- return this.constructor.version();
- };
-
- _proto.canChangeType = function canChangeType() {
- return SourceUpdater.canChangeType();
- }
- /**
- * Begin playing the video.
- */
- ;
-
- _proto.play = function play() {
- this.masterPlaylistController_.play();
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.setCurrentTime = function setCurrentTime(currentTime) {
- this.masterPlaylistController_.setCurrentTime(currentTime);
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.duration = function duration() {
- return this.masterPlaylistController_.duration();
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.seekable = function seekable() {
- return this.masterPlaylistController_.seekable();
- }
- /**
- * Abort all outstanding work and cleanup.
- */
- ;
-
- _proto.dispose = function dispose() {
- if (this.playbackWatcher_) {
- this.playbackWatcher_.dispose();
- }
-
- if (this.masterPlaylistController_) {
- this.masterPlaylistController_.dispose();
- }
-
- if (this.qualityLevels_) {
- this.qualityLevels_.dispose();
- }
-
- if (this.player_) {
- delete this.player_.vhs;
- delete this.player_.dash;
- delete this.player_.hls;
- }
-
- if (this.tech_ && this.tech_.vhs) {
- delete this.tech_.vhs;
- } // don't check this.tech_.hls as it will log a deprecated warning
-
-
- if (this.tech_) {
- delete this.tech_.hls;
- }
-
- if (this.mediaSourceUrl_ && window__default['default'].URL.revokeObjectURL) {
- window__default['default'].URL.revokeObjectURL(this.mediaSourceUrl_);
- this.mediaSourceUrl_ = null;
- }
-
- _Component.prototype.dispose.call(this);
- };
-
- _proto.convertToProgramTime = function convertToProgramTime(time, callback) {
- return getProgramTime({
- playlist: this.masterPlaylistController_.media(),
- time: time,
- callback: callback
- });
- } // the player must be playing before calling this
- ;
-
- _proto.seekToProgramTime = function seekToProgramTime$1(programTime, callback, pauseAfterSeek, retryCount) {
- if (pauseAfterSeek === void 0) {
- pauseAfterSeek = true;
- }
-
- if (retryCount === void 0) {
- retryCount = 2;
- }
-
- return seekToProgramTime({
- programTime: programTime,
- playlist: this.masterPlaylistController_.media(),
- retryCount: retryCount,
- pauseAfterSeek: pauseAfterSeek,
- seekTo: this.options_.seekTo,
- tech: this.options_.tech,
- callback: callback
- });
- };
-
- return VhsHandler;
-}(Component);
-/**
- * The Source Handler object, which informs video.js what additional
- * MIME types are supported and sets up playback. It is registered
- * automatically to the appropriate tech based on the capabilities of
- * the browser it is running in. It is not necessary to use or modify
- * this object in normal usage.
- */
-
-
-var VhsSourceHandler = {
- name: 'videojs-http-streaming',
- VERSION: version$4,
- canHandleSource: function canHandleSource(srcObj, options) {
- if (options === void 0) {
- options = {};
- }
-
- var localOptions = videojs__default['default'].mergeOptions(videojs__default['default'].options, options);
- return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
- },
- handleSource: function handleSource(source, tech, options) {
- if (options === void 0) {
- options = {};
- }
-
- var localOptions = videojs__default['default'].mergeOptions(videojs__default['default'].options, options);
- tech.vhs = new VhsHandler(source, tech, localOptions);
-
- if (!videojs__default['default'].hasOwnProperty('hls')) {
- Object.defineProperty(tech, 'hls', {
- get: function get() {
- videojs__default['default'].log.warn('player.tech().hls is deprecated. Use player.tech().vhs instead.');
- return tech.vhs;
- },
- configurable: true
- });
- }
-
- tech.vhs.xhr = xhrFactory();
- tech.vhs.src(source.src, source.type);
- return tech.vhs;
- },
- canPlayType: function canPlayType(type, options) {
- if (options === void 0) {
- options = {};
- }
-
- var _videojs$mergeOptions = videojs__default['default'].mergeOptions(videojs__default['default'].options, options),
- _videojs$mergeOptions2 = _videojs$mergeOptions.vhs.overrideNative,
- overrideNative = _videojs$mergeOptions2 === void 0 ? !videojs__default['default'].browser.IS_ANY_SAFARI : _videojs$mergeOptions2;
-
- var supportedType = mediaTypes_js.simpleTypeFromSourceType(type);
- var canUseMsePlayback = supportedType && (!Vhs.supportsTypeNatively(supportedType) || overrideNative);
- return canUseMsePlayback ? 'maybe' : '';
- }
-};
-/**
- * Check to see if the native MediaSource object exists and supports
- * an MP4 container with both H.264 video and AAC-LC audio.
- *
- * @return {boolean} if native media sources are supported
- */
-
-var supportsNativeMediaSources = function supportsNativeMediaSources() {
- return codecs_js.browserSupportsCodec('avc1.4d400d,mp4a.40.2');
-}; // register source handlers with the appropriate techs
-
-
-if (supportsNativeMediaSources()) {
- videojs__default['default'].getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
-}
-
-videojs__default['default'].VhsHandler = VhsHandler;
-Object.defineProperty(videojs__default['default'], 'HlsHandler', {
- get: function get() {
- videojs__default['default'].log.warn('videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.');
- return VhsHandler;
- },
- configurable: true
-});
-videojs__default['default'].VhsSourceHandler = VhsSourceHandler;
-Object.defineProperty(videojs__default['default'], 'HlsSourceHandler', {
- get: function get() {
- videojs__default['default'].log.warn('videojs.HlsSourceHandler is deprecated. ' + 'Use videojs.VhsSourceHandler instead.');
- return VhsSourceHandler;
- },
- configurable: true
-});
-videojs__default['default'].Vhs = Vhs;
-Object.defineProperty(videojs__default['default'], 'Hls', {
- get: function get() {
- videojs__default['default'].log.warn('videojs.Hls is deprecated. Use videojs.Vhs instead.');
- return Vhs;
- },
- configurable: true
-});
-
-if (!videojs__default['default'].use) {
- videojs__default['default'].registerComponent('Hls', Vhs);
- videojs__default['default'].registerComponent('Vhs', Vhs);
-}
-
-videojs__default['default'].options.vhs = videojs__default['default'].options.vhs || {};
-videojs__default['default'].options.hls = videojs__default['default'].options.hls || {};
-
-if (videojs__default['default'].registerPlugin) {
- videojs__default['default'].registerPlugin('reloadSourceOnError', reloadSourceOnError);
-} else {
- videojs__default['default'].plugin('reloadSourceOnError', reloadSourceOnError);
-}
-
-Object.defineProperty(exports, 'simpleTypeFromSourceType', {
- enumerable: true,
- get: function () {
- return mediaTypes_js.simpleTypeFromSourceType;
- }
-});
-exports.LOCAL_STORAGE_KEY = LOCAL_STORAGE_KEY;
-exports.Vhs = Vhs;
-exports.VhsHandler = VhsHandler;
-exports.VhsSourceHandler = VhsSourceHandler;
-exports.emeKeySystems = emeKeySystems;
-exports.expandDataUri = expandDataUri;
-exports.getAllPsshKeySystemsOptions = getAllPsshKeySystemsOptions;
-exports.setupEmeOptions = setupEmeOptions;
-exports.waitForKeySessionCreation = waitForKeySessionCreation;
diff --git a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.es.js b/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.es.js
deleted file mode 100644
index e2dde0b..0000000
--- a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.es.js
+++ /dev/null
@@ -1,25692 +0,0 @@
-/*! @name @videojs/http-streaming @version 2.9.1 @license Apache-2.0 */
-import _assertThisInitialized from '@babel/runtime/helpers/assertThisInitialized';
-import _inheritsLoose from '@babel/runtime/helpers/inheritsLoose';
-import document from 'global/document';
-import window from 'global/window';
-import _resolveUrl from '@videojs/vhs-utils/es/resolve-url.js';
-import videojs from 'video.js';
-import _extends from '@babel/runtime/helpers/extends';
-import { Parser } from 'm3u8-parser';
-import { isAudioCodec, translateLegacyCodec, codecsFromDefault, parseCodecs, getMimeForCodec, DEFAULT_VIDEO_CODEC, DEFAULT_AUDIO_CODEC, browserSupportsCodec, muxerSupportsCodec } from '@videojs/vhs-utils/es/codecs.js';
-import { simpleTypeFromSourceType } from '@videojs/vhs-utils/es/media-types.js';
-export { simpleTypeFromSourceType } from '@videojs/vhs-utils/es/media-types.js';
-import { generateSidxKey, parseUTCTiming, parse, addSidxSegmentsToPlaylist } from 'mpd-parser';
-import parseSidx from 'mux.js/lib/tools/parse-sidx';
-import { getId3Offset } from '@videojs/vhs-utils/es/id3-helpers';
-import { detectContainerForBytes, isLikelyFmp4MediaSegment } from '@videojs/vhs-utils/es/containers';
-import { concatTypedArrays, stringToBytes, toUint8 } from '@videojs/vhs-utils/es/byte-helpers';
-import { ONE_SECOND_IN_TS } from 'mux.js/lib/utils/clock';
-
-/**
- * @file resolve-url.js - Handling how URLs are resolved and manipulated
- */
-var resolveUrl = _resolveUrl;
-/**
- * Checks whether xhr request was redirected and returns correct url depending
- * on `handleManifestRedirects` option
- *
- * @api private
- *
- * @param {string} url - an url being requested
- * @param {XMLHttpRequest} req - xhr request result
- *
- * @return {string}
- */
-
-var resolveManifestRedirect = function resolveManifestRedirect(handleManifestRedirect, url, req) {
- // To understand how the responseURL below is set and generated:
- // - https://fetch.spec.whatwg.org/#concept-response-url
- // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
- if (handleManifestRedirect && req && req.responseURL && url !== req.responseURL) {
- return req.responseURL;
- }
-
- return url;
-};
-
-var logger = function logger(source) {
- if (videojs.log.debug) {
- return videojs.log.debug.bind(videojs, 'VHS:', source + " >");
- }
-
- return function () {};
-};
-
-/**
- * ranges
- *
- * Utilities for working with TimeRanges.
- *
- */
-
-var TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
-// can be misleading because of precision differences or when the current media has poorly
-// aligned audio and video, which can cause values to be slightly off from what you would
-// expect. This value is what we consider to be safe to use in such comparisons to account
-// for these scenarios.
-
-var SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
-
-var filterRanges = function filterRanges(timeRanges, predicate) {
- var results = [];
- var i;
-
- if (timeRanges && timeRanges.length) {
- // Search for ranges that match the predicate
- for (i = 0; i < timeRanges.length; i++) {
- if (predicate(timeRanges.start(i), timeRanges.end(i))) {
- results.push([timeRanges.start(i), timeRanges.end(i)]);
- }
- }
- }
-
- return videojs.createTimeRanges(results);
-};
-/**
- * Attempts to find the buffered TimeRange that contains the specified
- * time.
- *
- * @param {TimeRanges} buffered - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object
- */
-
-
-var findRange = function findRange(buffered, time) {
- return filterRanges(buffered, function (start, end) {
- return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
- });
-};
-/**
- * Returns the TimeRanges that begin later than the specified time.
- *
- * @param {TimeRanges} timeRanges - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object.
- */
-
-var findNextRange = function findNextRange(timeRanges, time) {
- return filterRanges(timeRanges, function (start) {
- return start - TIME_FUDGE_FACTOR >= time;
- });
-};
-/**
- * Returns gaps within a list of TimeRanges
- *
- * @param {TimeRanges} buffered - the TimeRanges object
- * @return {TimeRanges} a TimeRanges object of gaps
- */
-
-var findGaps = function findGaps(buffered) {
- if (buffered.length < 2) {
- return videojs.createTimeRanges();
- }
-
- var ranges = [];
-
- for (var i = 1; i < buffered.length; i++) {
- var start = buffered.end(i - 1);
- var end = buffered.start(i);
- ranges.push([start, end]);
- }
-
- return videojs.createTimeRanges(ranges);
-};
-/**
- * Calculate the intersection of two TimeRanges
- *
- * @param {TimeRanges} bufferA
- * @param {TimeRanges} bufferB
- * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
- */
-
-var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
- var start = null;
- var end = null;
- var arity = 0;
- var extents = [];
- var ranges = [];
-
- if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
- return videojs.createTimeRange();
- } // Handle the case where we have both buffers and create an
- // intersection of the two
-
-
- var count = bufferA.length; // A) Gather up all start and end times
-
- while (count--) {
- extents.push({
- time: bufferA.start(count),
- type: 'start'
- });
- extents.push({
- time: bufferA.end(count),
- type: 'end'
- });
- }
-
- count = bufferB.length;
-
- while (count--) {
- extents.push({
- time: bufferB.start(count),
- type: 'start'
- });
- extents.push({
- time: bufferB.end(count),
- type: 'end'
- });
- } // B) Sort them by time
-
-
- extents.sort(function (a, b) {
- return a.time - b.time;
- }); // C) Go along one by one incrementing arity for start and decrementing
- // arity for ends
-
- for (count = 0; count < extents.length; count++) {
- if (extents[count].type === 'start') {
- arity++; // D) If arity is ever incremented to 2 we are entering an
- // overlapping range
-
- if (arity === 2) {
- start = extents[count].time;
- }
- } else if (extents[count].type === 'end') {
- arity--; // E) If arity is ever decremented to 1 we leaving an
- // overlapping range
-
- if (arity === 1) {
- end = extents[count].time;
- }
- } // F) Record overlapping ranges
-
-
- if (start !== null && end !== null) {
- ranges.push([start, end]);
- start = null;
- end = null;
- }
- }
-
- return videojs.createTimeRanges(ranges);
-};
-/**
- * Gets a human readable string for a TimeRange
- *
- * @param {TimeRange} range
- * @return {string} a human readable string
- */
-
-var printableRange = function printableRange(range) {
- var strArr = [];
-
- if (!range || !range.length) {
- return '';
- }
-
- for (var i = 0; i < range.length; i++) {
- strArr.push(range.start(i) + ' => ' + range.end(i));
- }
-
- return strArr.join(', ');
-};
-/**
- * Calculates the amount of time left in seconds until the player hits the end of the
- * buffer and causes a rebuffer
- *
- * @param {TimeRange} buffered
- * The state of the buffer
- * @param {Numnber} currentTime
- * The current time of the player
- * @param {number} playbackRate
- * The current playback rate of the player. Defaults to 1.
- * @return {number}
- * Time until the player has to start rebuffering in seconds.
- * @function timeUntilRebuffer
- */
-
-var timeUntilRebuffer = function timeUntilRebuffer(buffered, currentTime, playbackRate) {
- if (playbackRate === void 0) {
- playbackRate = 1;
- }
-
- var bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
- return (bufferedEnd - currentTime) / playbackRate;
-};
-/**
- * Converts a TimeRanges object into an array representation
- *
- * @param {TimeRanges} timeRanges
- * @return {Array}
- */
-
-var timeRangesToArray = function timeRangesToArray(timeRanges) {
- var timeRangesList = [];
-
- for (var i = 0; i < timeRanges.length; i++) {
- timeRangesList.push({
- start: timeRanges.start(i),
- end: timeRanges.end(i)
- });
- }
-
- return timeRangesList;
-};
-/**
- * Determines if two time range objects are different.
- *
- * @param {TimeRange} a
- * the first time range object to check
- *
- * @param {TimeRange} b
- * the second time range object to check
- *
- * @return {Boolean}
- * Whether the time range objects differ
- */
-
-var isRangeDifferent = function isRangeDifferent(a, b) {
- // same object
- if (a === b) {
- return false;
- } // one or the other is undefined
-
-
- if (!a && b || !b && a) {
- return true;
- } // length is different
-
-
- if (a.length !== b.length) {
- return true;
- } // see if any start/end pair is different
-
-
- for (var i = 0; i < a.length; i++) {
- if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
- return true;
- }
- } // if the length and every pair is the same
- // this is the same time range
-
-
- return false;
-};
-var lastBufferedEnd = function lastBufferedEnd(a) {
- if (!a || !a.length || !a.end) {
- return;
- }
-
- return a.end(a.length - 1);
-};
-
-/**
- * @file playlist.js
- *
- * Playlist related utilities.
- */
-var createTimeRange = videojs.createTimeRange;
-/**
- * A function to get a combined list of parts and segments with durations
- * and indexes.
- *
- * @param {Playlist} playlist the playlist to get the list for.
- *
- * @return {Array} The part/segment list.
- */
-
-var getPartsAndSegments = function getPartsAndSegments(playlist) {
- return (playlist.segments || []).reduce(function (acc, segment, si) {
- if (segment.parts) {
- segment.parts.forEach(function (part, pi) {
- acc.push({
- duration: part.duration,
- segmentIndex: si,
- partIndex: pi,
- part: part,
- segment: segment
- });
- });
- } else {
- acc.push({
- duration: segment.duration,
- segmentIndex: si,
- partIndex: null,
- segment: segment,
- part: null
- });
- }
-
- return acc;
- }, []);
-};
-var getLastParts = function getLastParts(media) {
- var lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
- return lastSegment && lastSegment.parts || [];
-};
-var getKnownPartCount = function getKnownPartCount(_ref) {
- var preloadSegment = _ref.preloadSegment;
-
- if (!preloadSegment) {
- return;
- }
-
- var parts = preloadSegment.parts,
- preloadHints = preloadSegment.preloadHints;
- var partCount = (preloadHints || []).reduce(function (count, hint) {
- return count + (hint.type === 'PART' ? 1 : 0);
- }, 0);
- partCount += parts && parts.length ? parts.length : 0;
- return partCount;
-};
-/**
- * Get the number of seconds to delay from the end of a
- * live playlist.
- *
- * @param {Playlist} master the master playlist
- * @param {Playlist} media the media playlist
- * @return {number} the hold back in seconds.
- */
-
-var liveEdgeDelay = function liveEdgeDelay(master, media) {
- if (media.endList) {
- return 0;
- } // dash suggestedPresentationDelay trumps everything
-
-
- if (master && master.suggestedPresentationDelay) {
- return master.suggestedPresentationDelay;
- }
-
- var hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
-
- if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
- return media.serverControl.partHoldBack;
- } else if (hasParts && media.partTargetDuration) {
- return media.partTargetDuration * 3; // finally look for full segment delays
- } else if (media.serverControl && media.serverControl.holdBack) {
- return media.serverControl.holdBack;
- } else if (media.targetDuration) {
- return media.targetDuration * 3;
- }
-
- return 0;
-};
-/**
- * walk backward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {Number} endSequence the mediaSequence to stop walking on
- */
-
-var backwardDuration = function backwardDuration(playlist, endSequence) {
- var result = 0;
- var i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
- // the interval, use it
-
- var segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
- // information that is earlier than endSequence
-
- if (segment) {
- if (typeof segment.start !== 'undefined') {
- return {
- result: segment.start,
- precise: true
- };
- }
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - segment.duration,
- precise: true
- };
- }
- }
-
- while (i--) {
- segment = playlist.segments[i];
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: result + segment.end,
- precise: true
- };
- }
-
- result += segment.duration;
-
- if (typeof segment.start !== 'undefined') {
- return {
- result: result + segment.start,
- precise: true
- };
- }
- }
-
- return {
- result: result,
- precise: false
- };
-};
-/**
- * walk forward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {number} endSequence the mediaSequence to stop walking on
- */
-
-
-var forwardDuration = function forwardDuration(playlist, endSequence) {
- var result = 0;
- var segment;
- var i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
- // information
-
- for (; i < playlist.segments.length; i++) {
- segment = playlist.segments[i];
-
- if (typeof segment.start !== 'undefined') {
- return {
- result: segment.start - result,
- precise: true
- };
- }
-
- result += segment.duration;
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - result,
- precise: true
- };
- }
- } // indicate we didn't find a useful duration estimate
-
-
- return {
- result: -1,
- precise: false
- };
-};
-/**
- * Calculate the media duration from the segments associated with a
- * playlist. The duration of a subinterval of the available segments
- * may be calculated by specifying an end index.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper boundary
- * for the playlist. Defaults to playlist length.
- * @param {number} expired the amount of time that has dropped
- * off the front of the playlist in a live scenario
- * @return {number} the duration between the first available segment
- * and end index.
- */
-
-
-var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
- if (typeof endSequence === 'undefined') {
- endSequence = playlist.mediaSequence + playlist.segments.length;
- }
-
- if (endSequence < playlist.mediaSequence) {
- return 0;
- } // do a backward walk to estimate the duration
-
-
- var backward = backwardDuration(playlist, endSequence);
-
- if (backward.precise) {
- // if we were able to base our duration estimate on timing
- // information provided directly from the Media Source, return
- // it
- return backward.result;
- } // walk forward to see if a precise duration estimate can be made
- // that way
-
-
- var forward = forwardDuration(playlist, endSequence);
-
- if (forward.precise) {
- // we found a segment that has been buffered and so it's
- // position is known precisely
- return forward.result;
- } // return the less-precise, playlist-based duration estimate
-
-
- return backward.result + expired;
-};
-/**
- * Calculates the duration of a playlist. If a start and end index
- * are specified, the duration will be for the subset of the media
- * timeline between those two indices. The total duration for live
- * playlists is always Infinity.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper
- * boundary for the playlist. Defaults to the playlist media
- * sequence number plus its length.
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @return {number} the duration between the start index and end
- * index.
- */
-
-
-var duration = function duration(playlist, endSequence, expired) {
- if (!playlist) {
- return 0;
- }
-
- if (typeof expired !== 'number') {
- expired = 0;
- } // if a slice of the total duration is not requested, use
- // playlist-level duration indicators when they're present
-
-
- if (typeof endSequence === 'undefined') {
- // if present, use the duration specified in the playlist
- if (playlist.totalDuration) {
- return playlist.totalDuration;
- } // duration should be Infinity for live playlists
-
-
- if (!playlist.endList) {
- return window.Infinity;
- }
- } // calculate the total duration based on the segment durations
-
-
- return intervalDuration(playlist, endSequence, expired);
-};
-/**
- * Calculate the time between two indexes in the current playlist
- * neight the start- nor the end-index need to be within the current
- * playlist in which case, the targetDuration of the playlist is used
- * to approximate the durations of the segments
- *
- * @param {Array} options.durationList list to iterate over for durations.
- * @param {number} options.defaultDuration duration to use for elements before or after the durationList
- * @param {number} options.startIndex partsAndSegments index to start
- * @param {number} options.endIndex partsAndSegments index to end.
- * @return {number} the number of seconds between startIndex and endIndex
- */
-
-var sumDurations = function sumDurations(_ref2) {
- var defaultDuration = _ref2.defaultDuration,
- durationList = _ref2.durationList,
- startIndex = _ref2.startIndex,
- endIndex = _ref2.endIndex;
- var durations = 0;
-
- if (startIndex > endIndex) {
- var _ref3 = [endIndex, startIndex];
- startIndex = _ref3[0];
- endIndex = _ref3[1];
- }
-
- if (startIndex < 0) {
- for (var i = startIndex; i < Math.min(0, endIndex); i++) {
- durations += defaultDuration;
- }
-
- startIndex = 0;
- }
-
- for (var _i = startIndex; _i < endIndex; _i++) {
- durations += durationList[_i].duration;
- }
-
- return durations;
-};
-/**
- * Calculates the playlist end time
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
- * playlist end calculation should consider the safe live end
- * (truncate the playlist end by three segments). This is normally
- * used for calculating the end of the playlist's seekable range.
- * This takes into account the value of liveEdgePadding.
- * Setting liveEdgePadding to 0 is equivalent to setting this to false.
- * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
- * If this is provided, it is used in the safe live end calculation.
- * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {number} the end time of playlist
- * @function playlistEnd
- */
-
-var playlistEnd = function playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding) {
- if (!playlist || !playlist.segments) {
- return null;
- }
-
- if (playlist.endList) {
- return duration(playlist);
- }
-
- if (expired === null) {
- return null;
- }
-
- expired = expired || 0;
- var lastSegmentTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
-
- if (useSafeLiveEnd) {
- liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
- lastSegmentTime -= liveEdgePadding;
- } // don't return a time less than zero
-
-
- return Math.max(0, lastSegmentTime);
-};
-/**
- * Calculates the interval of time that is currently seekable in a
- * playlist. The returned time ranges are relative to the earliest
- * moment in the specified playlist that is still available. A full
- * seekable implementation for live streams would need to offset
- * these values by the duration of content that has expired from the
- * stream.
- *
- * @param {Object} playlist a media playlist object
- * dropped off the front of the playlist in a live scenario
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {TimeRanges} the periods of time that are valid targets
- * for seeking
- */
-
-var seekable = function seekable(playlist, expired, liveEdgePadding) {
- var useSafeLiveEnd = true;
- var seekableStart = expired || 0;
- var seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
-
- if (seekableEnd === null) {
- return createTimeRange();
- }
-
- return createTimeRange(seekableStart, seekableEnd);
-};
-/**
- * Determine the index and estimated starting time of the segment that
- * contains a specified playback position in a media playlist.
- *
- * @param {Object} options.playlist the media playlist to query
- * @param {number} options.currentTime The number of seconds since the earliest
- * possible position to determine the containing segment for
- * @param {number} options.startTime the time when the segment/part starts
- * @param {number} options.startingSegmentIndex the segment index to start looking at.
- * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
- *
- * @return {Object} an object with partIndex, segmentIndex, and startTime.
- */
-
-var getMediaInfoForTime = function getMediaInfoForTime(_ref4) {
- var playlist = _ref4.playlist,
- currentTime = _ref4.currentTime,
- startingSegmentIndex = _ref4.startingSegmentIndex,
- startingPartIndex = _ref4.startingPartIndex,
- startTime = _ref4.startTime;
- var time = currentTime - startTime;
- var partsAndSegments = getPartsAndSegments(playlist);
- var startIndex = 0;
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- var partAndSegment = partsAndSegments[i];
-
- if (startingSegmentIndex !== partAndSegment.segmentIndex) {
- continue;
- } // skip this if part index does not match.
-
-
- if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
- continue;
- }
-
- startIndex = i;
- break;
- }
-
- if (time < 0) {
- // Walk backward from startIndex in the playlist, adding durations
- // until we find a segment that contains `time` and return it
- if (startIndex > 0) {
- for (var _i2 = startIndex - 1; _i2 >= 0; _i2--) {
- var _partAndSegment = partsAndSegments[_i2];
- time += _partAndSegment.duration; // TODO: consider not using TIME_FUDGE_FACTOR at all here
-
- if (time + TIME_FUDGE_FACTOR > 0) {
- return {
- partIndex: _partAndSegment.partIndex,
- segmentIndex: _partAndSegment.segmentIndex,
- startTime: startTime - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex: startIndex,
- endIndex: _i2
- })
- };
- }
- }
- } // We were unable to find a good segment within the playlist
- // so select the first segment
-
-
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- } // When startIndex is negative, we first walk forward to first segment
- // adding target durations. If we "run out of time" before getting to
- // the first segment, return the first segment
-
-
- if (startIndex < 0) {
- for (var _i3 = startIndex; _i3 < 0; _i3++) {
- time -= playlist.targetDuration;
-
- if (time < 0) {
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- }
- }
-
- startIndex = 0;
- } // Walk forward from startIndex in the playlist, subtracting durations
- // until we find a segment that contains `time` and return it
-
-
- for (var _i4 = startIndex; _i4 < partsAndSegments.length; _i4++) {
- var _partAndSegment2 = partsAndSegments[_i4];
- time -= _partAndSegment2.duration; // TODO: consider not using TIME_FUDGE_FACTOR at all here
-
- if (time - TIME_FUDGE_FACTOR < 0) {
- return {
- partIndex: _partAndSegment2.partIndex,
- segmentIndex: _partAndSegment2.segmentIndex,
- startTime: startTime + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex: startIndex,
- endIndex: _i4
- })
- };
- }
- } // We are out of possible candidates so load the last one...
-
-
- return {
- segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
- partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
- startTime: currentTime
- };
-};
-/**
- * Check whether the playlist is blacklisted or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is blacklisted or not
- * @function isBlacklisted
- */
-
-var isBlacklisted = function isBlacklisted(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil > Date.now();
-};
-/**
- * Check whether the playlist is compatible with current playback configuration or has
- * been blacklisted permanently for being incompatible.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is incompatible or not
- * @function isIncompatible
- */
-
-var isIncompatible = function isIncompatible(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil === Infinity;
-};
-/**
- * Check whether the playlist is enabled or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is enabled or not
- * @function isEnabled
- */
-
-var isEnabled = function isEnabled(playlist) {
- var blacklisted = isBlacklisted(playlist);
- return !playlist.disabled && !blacklisted;
-};
-/**
- * Check whether the playlist has been manually disabled through the representations api.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is disabled manually or not
- * @function isDisabled
- */
-
-var isDisabled = function isDisabled(playlist) {
- return playlist.disabled;
-};
-/**
- * Returns whether the current playlist is an AES encrypted HLS stream
- *
- * @return {boolean} true if it's an AES encrypted HLS stream
- */
-
-var isAes = function isAes(media) {
- for (var i = 0; i < media.segments.length; i++) {
- if (media.segments[i].key) {
- return true;
- }
- }
-
- return false;
-};
-/**
- * Checks if the playlist has a value for the specified attribute
- *
- * @param {string} attr
- * Attribute to check for
- * @param {Object} playlist
- * The media playlist object
- * @return {boolean}
- * Whether the playlist contains a value for the attribute or not
- * @function hasAttribute
- */
-
-var hasAttribute = function hasAttribute(attr, playlist) {
- return playlist.attributes && playlist.attributes[attr];
-};
-/**
- * Estimates the time required to complete a segment download from the specified playlist
- *
- * @param {number} segmentDuration
- * Duration of requested segment
- * @param {number} bandwidth
- * Current measured bandwidth of the player
- * @param {Object} playlist
- * The media playlist object
- * @param {number=} bytesReceived
- * Number of bytes already received for the request. Defaults to 0
- * @return {number|NaN}
- * The estimated time to request the segment. NaN if bandwidth information for
- * the given playlist is unavailable
- * @function estimateSegmentRequestTime
- */
-
-var estimateSegmentRequestTime = function estimateSegmentRequestTime(segmentDuration, bandwidth, playlist, bytesReceived) {
- if (bytesReceived === void 0) {
- bytesReceived = 0;
- }
-
- if (!hasAttribute('BANDWIDTH', playlist)) {
- return NaN;
- }
-
- var size = segmentDuration * playlist.attributes.BANDWIDTH;
- return (size - bytesReceived * 8) / bandwidth;
-};
-/*
- * Returns whether the current playlist is the lowest rendition
- *
- * @return {Boolean} true if on lowest rendition
- */
-
-var isLowestEnabledRendition = function isLowestEnabledRendition(master, media) {
- if (master.playlists.length === 1) {
- return true;
- }
-
- var currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
- return master.playlists.filter(function (playlist) {
- if (!isEnabled(playlist)) {
- return false;
- }
-
- return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
- }).length === 0;
-};
-var playlistMatch = function playlistMatch(a, b) {
- // both playlits are null
- // or only one playlist is non-null
- // no match
- if (!a && !b || !a && b || a && !b) {
- return false;
- } // playlist objects are the same, match
-
-
- if (a === b) {
- return true;
- } // first try to use id as it should be the most
- // accurate
-
-
- if (a.id && b.id && a.id === b.id) {
- return true;
- } // next try to use reslovedUri as it should be the
- // second most accurate.
-
-
- if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
- return true;
- } // finally try to use uri as it should be accurate
- // but might miss a few cases for relative uris
-
-
- if (a.uri && b.uri && a.uri === b.uri) {
- return true;
- }
-
- return false;
-};
-
-var someAudioVariant = function someAudioVariant(master, callback) {
- var AUDIO = master && master.mediaGroups && master.mediaGroups.AUDIO || {};
- var found = false;
-
- for (var groupName in AUDIO) {
- for (var label in AUDIO[groupName]) {
- found = callback(AUDIO[groupName][label]);
-
- if (found) {
- break;
- }
- }
-
- if (found) {
- break;
- }
- }
-
- return !!found;
-};
-
-var isAudioOnly = function isAudioOnly(master) {
- // we are audio only if we have no main playlists but do
- // have media group playlists.
- if (!master || !master.playlists || !master.playlists.length) {
- // without audio variants or playlists this
- // is not an audio only master.
- var found = someAudioVariant(master, function (variant) {
- return variant.playlists && variant.playlists.length || variant.uri;
- });
- return found;
- } // if every playlist has only an audio codec it is audio only
-
-
- var _loop = function _loop(i) {
- var playlist = master.playlists[i];
- var CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
-
- if (CODECS && CODECS.split(',').every(function (c) {
- return isAudioCodec(c);
- })) {
- return "continue";
- } // playlist is in an audio group it is audio only
-
-
- var found = someAudioVariant(master, function (variant) {
- return playlistMatch(playlist, variant);
- });
-
- if (found) {
- return "continue";
- } // if we make it here this playlist isn't audio and we
- // are not audio only
-
-
- return {
- v: false
- };
- };
-
- for (var i = 0; i < master.playlists.length; i++) {
- var _ret = _loop(i);
-
- if (_ret === "continue") continue;
- if (typeof _ret === "object") return _ret.v;
- } // if we make it past every playlist without returning, then
- // this is an audio only playlist.
-
-
- return true;
-}; // exports
-
-var Playlist = {
- liveEdgeDelay: liveEdgeDelay,
- duration: duration,
- seekable: seekable,
- getMediaInfoForTime: getMediaInfoForTime,
- isEnabled: isEnabled,
- isDisabled: isDisabled,
- isBlacklisted: isBlacklisted,
- isIncompatible: isIncompatible,
- playlistEnd: playlistEnd,
- isAes: isAes,
- hasAttribute: hasAttribute,
- estimateSegmentRequestTime: estimateSegmentRequestTime,
- isLowestEnabledRendition: isLowestEnabledRendition,
- isAudioOnly: isAudioOnly,
- playlistMatch: playlistMatch
-};
-
-var log = videojs.log;
-var createPlaylistID = function createPlaylistID(index, uri) {
- return index + "-" + uri;
-};
-/**
- * Parses a given m3u8 playlist
- *
- * @param {Function} [onwarn]
- * a function to call when the parser triggers a warning event.
- * @param {Function} [oninfo]
- * a function to call when the parser triggers an info event.
- * @param {string} manifestString
- * The downloaded manifest string
- * @param {Object[]} [customTagParsers]
- * An array of custom tag parsers for the m3u8-parser instance
- * @param {Object[]} [customTagMappers]
- * An array of custom tag mappers for the m3u8-parser instance
- * @param {boolean} [experimentalLLHLS=false]
- * Whether to keep ll-hls features in the manifest after parsing.
- * @return {Object}
- * The manifest object
- */
-
-var parseManifest = function parseManifest(_ref) {
- var onwarn = _ref.onwarn,
- oninfo = _ref.oninfo,
- manifestString = _ref.manifestString,
- _ref$customTagParsers = _ref.customTagParsers,
- customTagParsers = _ref$customTagParsers === void 0 ? [] : _ref$customTagParsers,
- _ref$customTagMappers = _ref.customTagMappers,
- customTagMappers = _ref$customTagMappers === void 0 ? [] : _ref$customTagMappers,
- experimentalLLHLS = _ref.experimentalLLHLS;
- var parser = new Parser();
-
- if (onwarn) {
- parser.on('warn', onwarn);
- }
-
- if (oninfo) {
- parser.on('info', oninfo);
- }
-
- customTagParsers.forEach(function (customParser) {
- return parser.addParser(customParser);
- });
- customTagMappers.forEach(function (mapper) {
- return parser.addTagMapper(mapper);
- });
- parser.push(manifestString);
- parser.end();
- var manifest = parser.manifest; // remove llhls features from the parsed manifest
- // if we don't want llhls support.
-
- if (!experimentalLLHLS) {
- ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
- if (manifest.hasOwnProperty(k)) {
- delete manifest[k];
- }
- });
-
- if (manifest.segments) {
- manifest.segments.forEach(function (segment) {
- ['parts', 'preloadHints'].forEach(function (k) {
- if (segment.hasOwnProperty(k)) {
- delete segment[k];
- }
- });
- });
- }
- }
-
- if (!manifest.targetDuration) {
- var targetDuration = 10;
-
- if (manifest.segments && manifest.segments.length) {
- targetDuration = manifest.segments.reduce(function (acc, s) {
- return Math.max(acc, s.duration);
- }, 0);
- }
-
- if (onwarn) {
- onwarn("manifest has no targetDuration defaulting to " + targetDuration);
- }
-
- manifest.targetDuration = targetDuration;
- }
-
- var parts = getLastParts(manifest);
-
- if (parts.length && !manifest.partTargetDuration) {
- var partTargetDuration = parts.reduce(function (acc, p) {
- return Math.max(acc, p.duration);
- }, 0);
-
- if (onwarn) {
- onwarn("manifest has no partTargetDuration defaulting to " + partTargetDuration);
- log.error('LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.');
- }
-
- manifest.partTargetDuration = partTargetDuration;
- }
-
- return manifest;
-};
-/**
- * Loops through all supported media groups in master and calls the provided
- * callback for each group
- *
- * @param {Object} master
- * The parsed master manifest object
- * @param {Function} callback
- * Callback to call for each media group
- */
-
-var forEachMediaGroup = function forEachMediaGroup(master, callback) {
- if (!master.mediaGroups) {
- return;
- }
-
- ['AUDIO', 'SUBTITLES'].forEach(function (mediaType) {
- if (!master.mediaGroups[mediaType]) {
- return;
- }
-
- for (var groupKey in master.mediaGroups[mediaType]) {
- for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
- var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
- callback(mediaProperties, mediaType, groupKey, labelKey);
- }
- }
- });
-};
-/**
- * Adds properties and attributes to the playlist to keep consistent functionality for
- * playlists throughout VHS.
- *
- * @param {Object} config
- * Arguments object
- * @param {Object} config.playlist
- * The media playlist
- * @param {string} [config.uri]
- * The uri to the media playlist (if media playlist is not from within a master
- * playlist)
- * @param {string} id
- * ID to use for the playlist
- */
-
-var setupMediaPlaylist = function setupMediaPlaylist(_ref2) {
- var playlist = _ref2.playlist,
- uri = _ref2.uri,
- id = _ref2.id;
- playlist.id = id;
- playlist.playlistErrors_ = 0;
-
- if (uri) {
- // For media playlists, m3u8-parser does not have access to a URI, as HLS media
- // playlists do not contain their own source URI, but one is needed for consistency in
- // VHS.
- playlist.uri = uri;
- } // For HLS master playlists, even though certain attributes MUST be defined, the
- // stream may still be played without them.
- // For HLS media playlists, m3u8-parser does not attach an attributes object to the
- // manifest.
- //
- // To avoid undefined reference errors through the project, and make the code easier
- // to write/read, add an empty attributes object for these cases.
-
-
- playlist.attributes = playlist.attributes || {};
-};
-/**
- * Adds ID, resolvedUri, and attributes properties to each playlist of the master, where
- * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
- * playlist references to the playlists array.
- *
- * @param {Object} master
- * The master playlist
- */
-
-var setupMediaPlaylists = function setupMediaPlaylists(master) {
- var i = master.playlists.length;
-
- while (i--) {
- var playlist = master.playlists[i];
- setupMediaPlaylist({
- playlist: playlist,
- id: createPlaylistID(i, playlist.uri)
- });
- playlist.resolvedUri = resolveUrl(master.uri, playlist.uri);
- master.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
-
- master.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
- // the stream can be played without it. Although an attributes property may have been
- // added to the playlist to prevent undefined references, issue a warning to fix the
- // manifest.
-
- if (!playlist.attributes.BANDWIDTH) {
- log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
- }
- }
-};
-/**
- * Adds resolvedUri properties to each media group.
- *
- * @param {Object} master
- * The master playlist
- */
-
-var resolveMediaGroupUris = function resolveMediaGroupUris(master) {
- forEachMediaGroup(master, function (properties) {
- if (properties.uri) {
- properties.resolvedUri = resolveUrl(master.uri, properties.uri);
- }
- });
-};
-/**
- * Creates a master playlist wrapper to insert a sole media playlist into.
- *
- * @param {Object} media
- * Media playlist
- * @param {string} uri
- * The media URI
- *
- * @return {Object}
- * Master playlist
- */
-
-var masterForMedia = function masterForMedia(media, uri) {
- var id = createPlaylistID(0, uri);
- var master = {
- mediaGroups: {
- 'AUDIO': {},
- 'VIDEO': {},
- 'CLOSED-CAPTIONS': {},
- 'SUBTITLES': {}
- },
- uri: window.location.href,
- resolvedUri: window.location.href,
- playlists: [{
- uri: uri,
- id: id,
- resolvedUri: uri,
- // m3u8-parser does not attach an attributes property to media playlists so make
- // sure that the property is attached to avoid undefined reference errors
- attributes: {}
- }]
- }; // set up ID reference
-
- master.playlists[id] = master.playlists[0]; // URI reference added for backwards compatibility
-
- master.playlists[uri] = master.playlists[0];
- return master;
-};
-/**
- * Does an in-place update of the master manifest to add updated playlist URI references
- * as well as other properties needed by VHS that aren't included by the parser.
- *
- * @param {Object} master
- * Master manifest object
- * @param {string} uri
- * The source URI
- */
-
-var addPropertiesToMaster = function addPropertiesToMaster(master, uri) {
- master.uri = uri;
-
- for (var i = 0; i < master.playlists.length; i++) {
- if (!master.playlists[i].uri) {
- // Set up phony URIs for the playlists since playlists are referenced by their URIs
- // throughout VHS, but some formats (e.g., DASH) don't have external URIs
- // TODO: consider adding dummy URIs in mpd-parser
- var phonyUri = "placeholder-uri-" + i;
- master.playlists[i].uri = phonyUri;
- }
- }
-
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- var groupId = "placeholder-uri-" + mediaType + "-" + groupKey + "-" + labelKey;
-
- if (!properties.playlists || !properties.playlists.length) {
- properties.playlists = [_extends({}, properties)];
- }
-
- properties.playlists.forEach(function (p, i) {
- var id = createPlaylistID(i, groupId);
-
- if (p.uri) {
- p.resolvedUri = p.resolvedUri || resolveUrl(master.uri, p.uri);
- } else {
- // DEPRECATED, this has been added to prevent a breaking change.
- // previously we only ever had a single media group playlist, so
- // we mark the first playlist uri without prepending the index as we used to
- // ideally we would do all of the playlists the same way.
- p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
- // the placeholder again
-
- p.resolvedUri = p.uri;
- }
-
- p.id = p.id || id; // add an empty attributes object, all playlists are
- // expected to have this.
-
- p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
-
- master.playlists[p.id] = p;
- master.playlists[p.uri] = p;
- });
- });
- setupMediaPlaylists(master);
- resolveMediaGroupUris(master);
-};
-
-var mergeOptions$2 = videojs.mergeOptions,
- EventTarget$1 = videojs.EventTarget;
-
-var addLLHLSQueryDirectives = function addLLHLSQueryDirectives(uri, media) {
- if (media.endList) {
- return uri;
- }
-
- var query = [];
-
- if (media.serverControl && media.serverControl.canBlockReload) {
- var preloadSegment = media.preloadSegment; // next msn is a zero based value, length is not.
-
- var nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
- // that we are going to request a part of that preload segment.
- // the logic below is used to determine that.
-
- if (preloadSegment) {
- var parts = preloadSegment.parts || []; // _HLS_part is a zero based index
-
- var nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
- // length of parts, then we know we had part preload hints
- // and we need to add the _HLS_part= query
-
- if (nextPart > -1 && nextPart !== parts.length - 1) {
- // add existing parts to our preload hints
- query.push("_HLS_part=" + nextPart);
- } // this if statement makes sure that we request the msn
- // of the preload segment if:
- // 1. the preload segment had parts (and was not yet a full segment)
- // but was added to our segments array
- // 2. the preload segment had preload hints for parts that are not in
- // the manifest yet.
- // in all other cases we want the segment after the preload segment
- // which will be given by using media.segments.length because it is 1 based
- // rather than 0 based.
-
-
- if (nextPart > -1 || parts.length) {
- nextMSN--;
- }
- } // add _HLS_msn= in front of any _HLS_part query
-
-
- query.unshift("_HLS_msn=" + nextMSN);
- }
-
- if (media.serverControl && media.serverControl.canSkipUntil) {
- // add _HLS_skip= infront of all other queries.
- query.unshift('_HLS_skip=' + (media.serverControl.canSkipDateranges ? 'v2' : 'YES'));
- }
-
- query.forEach(function (str, i) {
- var symbol = i === 0 ? '?' : '&';
- uri += "" + symbol + str;
- });
- return uri;
-};
-/**
- * Returns a new segment object with properties and
- * the parts array merged.
- *
- * @param {Object} a the old segment
- * @param {Object} b the new segment
- *
- * @return {Object} the merged segment
- */
-
-
-var updateSegment = function updateSegment(a, b) {
- if (!a) {
- return b;
- }
-
- var result = mergeOptions$2(a, b); // if only the old segment has preload hints
- // and the new one does not, remove preload hints.
-
- if (a.preloadHints && !b.preloadHints) {
- delete result.preloadHints;
- } // if only the old segment has parts
- // then the parts are no longer valid
-
-
- if (a.parts && !b.parts) {
- delete result.parts; // if both segments have parts
- // copy part propeties from the old segment
- // to the new one.
- } else if (a.parts && b.parts) {
- for (var i = 0; i < b.parts.length; i++) {
- if (a.parts && a.parts[i]) {
- result.parts[i] = mergeOptions$2(a.parts[i], b.parts[i]);
- }
- }
- } // set skipped to false for segments that have
- // have had information merged from the old segment.
-
-
- if (!a.skipped && b.skipped) {
- result.skipped = false;
- } // set preload to false for segments that have
- // had information added in the new segment.
-
-
- if (a.preload && !b.preload) {
- result.preload = false;
- }
-
- return result;
-};
-/**
- * Returns a new array of segments that is the result of merging
- * properties from an older list of segments onto an updated
- * list. No properties on the updated playlist will be ovewritten.
- *
- * @param {Array} original the outdated list of segments
- * @param {Array} update the updated list of segments
- * @param {number=} offset the index of the first update
- * segment in the original segment list. For non-live playlists,
- * this should always be zero and does not need to be
- * specified. For live playlists, it should be the difference
- * between the media sequence numbers in the original and updated
- * playlists.
- * @return {Array} a list of merged segment objects
- */
-
-var updateSegments = function updateSegments(original, update, offset) {
- var oldSegments = original.slice();
- var newSegments = update.slice();
- offset = offset || 0;
- var result = [];
- var currentMap;
-
- for (var newIndex = 0; newIndex < newSegments.length; newIndex++) {
- var oldSegment = oldSegments[newIndex + offset];
- var newSegment = newSegments[newIndex];
-
- if (oldSegment) {
- currentMap = oldSegment.map || currentMap;
- result.push(updateSegment(oldSegment, newSegment));
- } else {
- // carry over map to new segment if it is missing
- if (currentMap && !newSegment.map) {
- newSegment.map = currentMap;
- }
-
- result.push(newSegment);
- }
- }
-
- return result;
-};
-var resolveSegmentUris = function resolveSegmentUris(segment, baseUri) {
- // preloadSegment will not have a uri at all
- // as the segment isn't actually in the manifest yet, only parts
- if (!segment.resolvedUri && segment.uri) {
- segment.resolvedUri = resolveUrl(baseUri, segment.uri);
- }
-
- if (segment.key && !segment.key.resolvedUri) {
- segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
- }
-
- if (segment.map && !segment.map.resolvedUri) {
- segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
- }
-
- if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
- segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
- }
-
- if (segment.parts && segment.parts.length) {
- segment.parts.forEach(function (p) {
- if (p.resolvedUri) {
- return;
- }
-
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
-
- if (segment.preloadHints && segment.preloadHints.length) {
- segment.preloadHints.forEach(function (p) {
- if (p.resolvedUri) {
- return;
- }
-
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
-};
-
-var getAllSegments = function getAllSegments(media) {
- var segments = media.segments || [];
- var preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
- // a usable segment, only include a preloadSegment that has
- // parts.
-
- if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
- // if preloadHints has a MAP that means that the
- // init segment is going to change. We cannot use any of the parts
- // from this preload segment.
- if (preloadSegment.preloadHints) {
- for (var i = 0; i < preloadSegment.preloadHints.length; i++) {
- if (preloadSegment.preloadHints[i].type === 'MAP') {
- return segments;
- }
- }
- } // set the duration for our preload segment to target duration.
-
-
- preloadSegment.duration = media.targetDuration;
- preloadSegment.preload = true;
- segments.push(preloadSegment);
- }
-
- return segments;
-}; // consider the playlist unchanged if the playlist object is the same or
-// the number of segments is equal, the media sequence number is unchanged,
-// and this playlist hasn't become the end of the playlist
-
-
-var isPlaylistUnchanged = function isPlaylistUnchanged(a, b) {
- return a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence;
-};
-/**
- * Returns a new master playlist that is the result of merging an
- * updated media playlist into the original version. If the
- * updated media playlist does not match any of the playlist
- * entries in the original master playlist, null is returned.
- *
- * @param {Object} master a parsed master M3U8 object
- * @param {Object} media a parsed media M3U8 object
- * @return {Object} a new object that represents the original
- * master playlist with the updated media playlist merged in, or
- * null if the merge produced no change.
- */
-
-var updateMaster$1 = function updateMaster(master, newMedia, unchangedCheck) {
- if (unchangedCheck === void 0) {
- unchangedCheck = isPlaylistUnchanged;
- }
-
- var result = mergeOptions$2(master, {});
- var oldMedia = result.playlists[newMedia.id];
-
- if (!oldMedia) {
- return null;
- }
-
- if (unchangedCheck(oldMedia, newMedia)) {
- return null;
- }
-
- newMedia.segments = getAllSegments(newMedia);
- var mergedPlaylist = mergeOptions$2(oldMedia, newMedia); // always use the new media's preload segment
-
- if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
- delete mergedPlaylist.preloadSegment;
- } // if the update could overlap existing segment information, merge the two segment lists
-
-
- if (oldMedia.segments) {
- if (newMedia.skip) {
- newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
- // old properties into the new segments
-
- for (var i = 0; i < newMedia.skip.skippedSegments; i++) {
- newMedia.segments.unshift({
- skipped: true
- });
- }
- }
-
- mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
- } // resolve any segment URIs to prevent us from having to do it later
-
-
- mergedPlaylist.segments.forEach(function (segment) {
- resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
- }); // TODO Right now in the playlists array there are two references to each playlist, one
- // that is referenced by index, and one by URI. The index reference may no longer be
- // necessary.
-
- for (var _i = 0; _i < result.playlists.length; _i++) {
- if (result.playlists[_i].id === newMedia.id) {
- result.playlists[_i] = mergedPlaylist;
- }
- }
-
- result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
-
- result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
-
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- if (!properties.playlists) {
- return;
- }
-
- for (var _i2 = 0; _i2 < properties.playlists.length; _i2++) {
- if (newMedia.id === properties.playlists[_i2].id) {
- properties.playlists[_i2] = newMedia;
- }
- }
- });
- return result;
-};
-/**
- * Calculates the time to wait before refreshing a live playlist
- *
- * @param {Object} media
- * The current media
- * @param {boolean} update
- * True if there were any updates from the last refresh, false otherwise
- * @return {number}
- * The time in ms to wait before refreshing the live playlist
- */
-
-var refreshDelay = function refreshDelay(media, update) {
- var lastSegment = media.segments[media.segments.length - 1];
- var lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
- var lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
-
- if (update && lastDuration) {
- return lastDuration * 1000;
- } // if the playlist is unchanged since the last reload or last segment duration
- // cannot be determined, try again after half the target duration
-
-
- return (media.partTargetDuration || media.targetDuration || 10) * 500;
-};
-/**
- * Load a playlist from a remote location
- *
- * @class PlaylistLoader
- * @extends Stream
- * @param {string|Object} src url or object of manifest
- * @param {boolean} withCredentials the withCredentials xhr option
- * @class
- */
-
-var PlaylistLoader = /*#__PURE__*/function (_EventTarget) {
- _inheritsLoose(PlaylistLoader, _EventTarget);
-
- function PlaylistLoader(src, vhs, options) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _EventTarget.call(this) || this;
-
- if (!src) {
- throw new Error('A non-empty playlist URL or object is required');
- }
-
- _this.logger_ = logger('PlaylistLoader');
- var _options = options,
- _options$withCredenti = _options.withCredentials,
- withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
- _options$handleManife = _options.handleManifestRedirects,
- handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
- _this.src = src;
- _this.vhs_ = vhs;
- _this.withCredentials = withCredentials;
- _this.handleManifestRedirects = handleManifestRedirects;
- var vhsOptions = vhs.options_;
- _this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
- _this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
- _this.experimentalLLHLS = vhsOptions && vhsOptions.experimentalLLHLS || false; // initialize the loader state
-
- _this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
-
- _this.handleMediaupdatetimeout_ = _this.handleMediaupdatetimeout_.bind(_assertThisInitialized(_this));
-
- _this.on('mediaupdatetimeout', _this.handleMediaupdatetimeout_);
-
- return _this;
- }
-
- var _proto = PlaylistLoader.prototype;
-
- _proto.handleMediaupdatetimeout_ = function handleMediaupdatetimeout_() {
- var _this2 = this;
-
- if (this.state !== 'HAVE_METADATA') {
- // only refresh the media playlist if no other activity is going on
- return;
- }
-
- var media = this.media();
- var uri = resolveUrl(this.master.uri, media.uri);
-
- if (this.experimentalLLHLS) {
- uri = addLLHLSQueryDirectives(uri, media);
- }
-
- this.state = 'HAVE_CURRENT_METADATA';
- this.request = this.vhs_.xhr({
- uri: uri,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this2.request) {
- return;
- }
-
- if (error) {
- return _this2.playlistRequestError(_this2.request, _this2.media(), 'HAVE_METADATA');
- }
-
- _this2.haveMetadata({
- playlistString: _this2.request.responseText,
- url: _this2.media().uri,
- id: _this2.media().id
- });
- });
- };
-
- _proto.playlistRequestError = function playlistRequestError(xhr, playlist, startingState) {
- var uri = playlist.uri,
- id = playlist.id; // any in-flight request is now finished
-
- this.request = null;
-
- if (startingState) {
- this.state = startingState;
- }
-
- this.error = {
- playlist: this.master.playlists[id],
- status: xhr.status,
- message: "HLS playlist request error at URL: " + uri + ".",
- responseText: xhr.responseText,
- code: xhr.status >= 500 ? 4 : 2
- };
- this.trigger('error');
- };
-
- _proto.parseManifest_ = function parseManifest_(_ref) {
- var _this3 = this;
-
- var url = _ref.url,
- manifestString = _ref.manifestString;
- return parseManifest({
- onwarn: function onwarn(_ref2) {
- var message = _ref2.message;
- return _this3.logger_("m3u8-parser warn for " + url + ": " + message);
- },
- oninfo: function oninfo(_ref3) {
- var message = _ref3.message;
- return _this3.logger_("m3u8-parser info for " + url + ": " + message);
- },
- manifestString: manifestString,
- customTagParsers: this.customTagParsers,
- customTagMappers: this.customTagMappers,
- experimentalLLHLS: this.experimentalLLHLS
- });
- }
- /**
- * Update the playlist loader's state in response to a new or updated playlist.
- *
- * @param {string} [playlistString]
- * Playlist string (if playlistObject is not provided)
- * @param {Object} [playlistObject]
- * Playlist object (if playlistString is not provided)
- * @param {string} url
- * URL of playlist
- * @param {string} id
- * ID to use for playlist
- */
- ;
-
- _proto.haveMetadata = function haveMetadata(_ref4) {
- var _this4 = this;
-
- var playlistString = _ref4.playlistString,
- playlistObject = _ref4.playlistObject,
- url = _ref4.url,
- id = _ref4.id;
- // any in-flight request is now finished
- this.request = null;
- this.state = 'HAVE_METADATA';
- var playlist = playlistObject || this.parseManifest_({
- url: url,
- manifestString: playlistString
- });
- playlist.lastRequest = Date.now();
- setupMediaPlaylist({
- playlist: playlist,
- uri: url,
- id: id
- }); // merge this playlist into the master
-
- var update = updateMaster$1(this.master, playlist);
- this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
-
- if (update) {
- this.master = update;
- this.media_ = this.master.playlists[id];
- } else {
- this.trigger('playlistunchanged');
- } // refresh live playlists after a target duration passes
-
-
- if (!this.media().endList) {
- window.clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = window.setTimeout(function () {
- _this4.trigger('mediaupdatetimeout');
- }, refreshDelay(this.media(), !!update));
- }
-
- this.trigger('loadedplaylist');
- }
- /**
- * Abort any outstanding work and clean up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.stopRequest();
- window.clearTimeout(this.mediaUpdateTimeout);
- window.clearTimeout(this.finalRenditionTimeout);
- this.off();
- };
-
- _proto.stopRequest = function stopRequest() {
- if (this.request) {
- var oldRequest = this.request;
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- }
- /**
- * When called without any arguments, returns the currently
- * active media playlist. When called with a single argument,
- * triggers the playlist loader to asynchronously switch to the
- * specified media playlist. Calling this method while the
- * loader is in the HAVE_NOTHING causes an error to be emitted
- * but otherwise has no effect.
- *
- * @param {Object=} playlist the parsed media playlist
- * object to switch to
- * @param {boolean=} shouldDelay whether we should delay the request by half target duration
- *
- * @return {Playlist} the current loaded media
- */
- ;
-
- _proto.media = function media(playlist, shouldDelay) {
- var _this5 = this;
-
- // getter
- if (!playlist) {
- return this.media_;
- } // setter
-
-
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- } // find the playlist object if the target playlist has been
- // specified by URI
-
-
- if (typeof playlist === 'string') {
- if (!this.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
-
- playlist = this.master.playlists[playlist];
- }
-
- window.clearTimeout(this.finalRenditionTimeout);
-
- if (shouldDelay) {
- var delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
- this.finalRenditionTimeout = window.setTimeout(this.media.bind(this, playlist, false), delay);
- return;
- }
-
- var startingState = this.state;
- var mediaChange = !this.media_ || playlist.id !== this.media_.id;
- var masterPlaylistRef = this.master.playlists[playlist.id]; // switch to fully loaded playlists immediately
-
- if (masterPlaylistRef && masterPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
- // media playlist or, for the case of demuxed audio, a resolved audio media group)
- playlist.endList && playlist.segments.length) {
- // abort outstanding playlist requests
- if (this.request) {
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- }
-
- this.state = 'HAVE_METADATA';
- this.media_ = playlist; // trigger media change if the active media has been updated
-
- if (mediaChange) {
- this.trigger('mediachanging');
-
- if (startingState === 'HAVE_MASTER') {
- // The initial playlist was a master manifest, and the first media selected was
- // also provided (in the form of a resolved playlist object) as part of the
- // source object (rather than just a URL). Therefore, since the media playlist
- // doesn't need to be requested, loadedmetadata won't trigger as part of the
- // normal flow, and needs an explicit trigger here.
- this.trigger('loadedmetadata');
- } else {
- this.trigger('mediachange');
- }
- }
-
- return;
- } // switching to the active playlist is a no-op
-
-
- if (!mediaChange) {
- return;
- }
-
- this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
-
- if (this.request) {
- if (playlist.resolvedUri === this.request.url) {
- // requesting to switch to the same playlist multiple times
- // has no effect after the first
- return;
- }
-
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- } // request the new playlist
-
-
- if (this.media_) {
- this.trigger('mediachanging');
- }
-
- this.request = this.vhs_.xhr({
- uri: playlist.resolvedUri,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this5.request) {
- return;
- }
-
- playlist.lastRequest = Date.now();
- playlist.resolvedUri = resolveManifestRedirect(_this5.handleManifestRedirects, playlist.resolvedUri, req);
-
- if (error) {
- return _this5.playlistRequestError(_this5.request, playlist, startingState);
- }
-
- _this5.haveMetadata({
- playlistString: req.responseText,
- url: playlist.uri,
- id: playlist.id
- }); // fire loadedmetadata the first time a media playlist is loaded
-
-
- if (startingState === 'HAVE_MASTER') {
- _this5.trigger('loadedmetadata');
- } else {
- _this5.trigger('mediachange');
- }
- });
- }
- /**
- * pause loading of the playlist
- */
- ;
-
- _proto.pause = function pause() {
- this.stopRequest();
- window.clearTimeout(this.mediaUpdateTimeout);
-
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- } // Need to restore state now that no activity is happening
-
-
- if (this.state === 'SWITCHING_MEDIA') {
- // if the loader was in the process of switching media, it should either return to
- // HAVE_MASTER or HAVE_METADATA depending on if the loader has loaded a media
- // playlist yet. This is determined by the existence of loader.media_
- if (this.media_) {
- this.state = 'HAVE_METADATA';
- } else {
- this.state = 'HAVE_MASTER';
- }
- } else if (this.state === 'HAVE_CURRENT_METADATA') {
- this.state = 'HAVE_METADATA';
- }
- }
- /**
- * start loading of the playlist
- */
- ;
-
- _proto.load = function load(shouldDelay) {
- var _this6 = this;
-
- window.clearTimeout(this.mediaUpdateTimeout);
- var media = this.media();
-
- if (shouldDelay) {
- var delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
- this.mediaUpdateTimeout = window.setTimeout(function () {
- return _this6.load();
- }, delay);
- return;
- }
-
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- }
- /**
- * start loading of the playlist
- */
- ;
-
- _proto.start = function start() {
- var _this7 = this;
-
- this.started = true;
-
- if (typeof this.src === 'object') {
- // in the case of an entirely constructed manifest object (meaning there's no actual
- // manifest on a server), default the uri to the page's href
- if (!this.src.uri) {
- this.src.uri = window.location.href;
- } // resolvedUri is added on internally after the initial request. Since there's no
- // request for pre-resolved manifests, add on resolvedUri here.
-
-
- this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
- // request can be skipped (since the top level of the manifest, at a minimum, is
- // already available as a parsed manifest object). However, if the manifest object
- // represents a master playlist, some media playlists may need to be resolved before
- // the starting segment list is available. Therefore, go directly to setup of the
- // initial playlist, and let the normal flow continue from there.
- //
- // Note that the call to setup is asynchronous, as other sections of VHS may assume
- // that the first request is asynchronous.
-
- setTimeout(function () {
- _this7.setupInitialPlaylist(_this7.src);
- }, 0);
- return;
- } // request the specified URL
-
-
- this.request = this.vhs_.xhr({
- uri: this.src,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this7.request) {
- return;
- } // clear the loader's request reference
-
-
- _this7.request = null;
-
- if (error) {
- _this7.error = {
- status: req.status,
- message: "HLS playlist request error at URL: " + _this7.src + ".",
- responseText: req.responseText,
- // MEDIA_ERR_NETWORK
- code: 2
- };
-
- if (_this7.state === 'HAVE_NOTHING') {
- _this7.started = false;
- }
-
- return _this7.trigger('error');
- }
-
- _this7.src = resolveManifestRedirect(_this7.handleManifestRedirects, _this7.src, req);
-
- var manifest = _this7.parseManifest_({
- manifestString: req.responseText,
- url: _this7.src
- });
-
- _this7.setupInitialPlaylist(manifest);
- });
- };
-
- _proto.srcUri = function srcUri() {
- return typeof this.src === 'string' ? this.src : this.src.uri;
- }
- /**
- * Given a manifest object that's either a master or media playlist, trigger the proper
- * events and set the state of the playlist loader.
- *
- * If the manifest object represents a master playlist, `loadedplaylist` will be
- * triggered to allow listeners to select a playlist. If none is selected, the loader
- * will default to the first one in the playlists array.
- *
- * If the manifest object represents a media playlist, `loadedplaylist` will be
- * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
- *
- * In the case of a media playlist, a master playlist object wrapper with one playlist
- * will be created so that all logic can handle playlists in the same fashion (as an
- * assumed manifest object schema).
- *
- * @param {Object} manifest
- * The parsed manifest object
- */
- ;
-
- _proto.setupInitialPlaylist = function setupInitialPlaylist(manifest) {
- this.state = 'HAVE_MASTER';
-
- if (manifest.playlists) {
- this.master = manifest;
- addPropertiesToMaster(this.master, this.srcUri()); // If the initial master playlist has playlists wtih segments already resolved,
- // then resolve URIs in advance, as they are usually done after a playlist request,
- // which may not happen if the playlist is resolved.
-
- manifest.playlists.forEach(function (playlist) {
- playlist.segments = getAllSegments(playlist);
- playlist.segments.forEach(function (segment) {
- resolveSegmentUris(segment, playlist.resolvedUri);
- });
- });
- this.trigger('loadedplaylist');
-
- if (!this.request) {
- // no media playlist was specifically selected so start
- // from the first listed one
- this.media(this.master.playlists[0]);
- }
-
- return;
- } // In order to support media playlists passed in as vhs-json, the case where the uri
- // is not provided as part of the manifest should be considered, and an appropriate
- // default used.
-
-
- var uri = this.srcUri() || window.location.href;
- this.master = masterForMedia(manifest, uri);
- this.haveMetadata({
- playlistObject: manifest,
- url: uri,
- id: this.master.playlists[0].id
- });
- this.trigger('loadedmetadata');
- };
-
- return PlaylistLoader;
-}(EventTarget$1);
-
-/**
- * @file xhr.js
- */
-var videojsXHR = videojs.xhr,
- mergeOptions$1 = videojs.mergeOptions;
-
-var callbackWrapper = function callbackWrapper(request, error, response, callback) {
- var reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
-
- if (!error && reqResponse) {
- request.responseTime = Date.now();
- request.roundTripTime = request.responseTime - request.requestTime;
- request.bytesReceived = reqResponse.byteLength || reqResponse.length;
-
- if (!request.bandwidth) {
- request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
- }
- }
-
- if (response.headers) {
- request.responseHeaders = response.headers;
- } // videojs.xhr now uses a specific code on the error
- // object to signal that a request has timed out instead
- // of setting a boolean on the request object
-
-
- if (error && error.code === 'ETIMEDOUT') {
- request.timedout = true;
- } // videojs.xhr no longer considers status codes outside of 200 and 0
- // (for file uris) to be errors, but the old XHR did, so emulate that
- // behavior. Status 206 may be used in response to byterange requests.
-
-
- if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
- error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
- }
-
- callback(error, request);
-};
-
-var xhrFactory = function xhrFactory() {
- var xhr = function XhrFunction(options, callback) {
- // Add a default timeout
- options = mergeOptions$1({
- timeout: 45e3
- }, options); // Allow an optional user-specified function to modify the option
- // object before we construct the xhr request
-
- var beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
-
- if (beforeRequest && typeof beforeRequest === 'function') {
- var newOptions = beforeRequest(options);
-
- if (newOptions) {
- options = newOptions;
- }
- } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
- // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
-
-
- var xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
- var request = xhrMethod(options, function (error, response) {
- return callbackWrapper(request, error, response, callback);
- });
- var originalAbort = request.abort;
-
- request.abort = function () {
- request.aborted = true;
- return originalAbort.apply(request, arguments);
- };
-
- request.uri = options.uri;
- request.requestTime = Date.now();
- return request;
- };
-
- xhr.original = true;
- return xhr;
-};
-/**
- * Turns segment byterange into a string suitable for use in
- * HTTP Range requests
- *
- * @param {Object} byterange - an object with two values defining the start and end
- * of a byte-range
- */
-
-
-var byterangeStr = function byterangeStr(byterange) {
- // `byterangeEnd` is one less than `offset + length` because the HTTP range
- // header uses inclusive ranges
- var byterangeEnd = byterange.offset + byterange.length - 1;
- var byterangeStart = byterange.offset;
- return 'bytes=' + byterangeStart + '-' + byterangeEnd;
-};
-/**
- * Defines headers for use in the xhr request for a particular segment.
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- */
-
-
-var segmentXhrHeaders = function segmentXhrHeaders(segment) {
- var headers = {};
-
- if (segment.byterange) {
- headers.Range = byterangeStr(segment.byterange);
- }
-
- return headers;
-};
-
-/**
- * @file bin-utils.js
- */
-
-/**
- * convert a TimeRange to text
- *
- * @param {TimeRange} range the timerange to use for conversion
- * @param {number} i the iterator on the range to convert
- * @return {string} the range in string format
- */
-var textRange = function textRange(range, i) {
- return range.start(i) + '-' + range.end(i);
-};
-/**
- * format a number as hex string
- *
- * @param {number} e The number
- * @param {number} i the iterator
- * @return {string} the hex formatted number as a string
- */
-
-
-var formatHexString = function formatHexString(e, i) {
- var value = e.toString(16);
- return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
-};
-
-var formatAsciiString = function formatAsciiString(e) {
- if (e >= 0x20 && e < 0x7e) {
- return String.fromCharCode(e);
- }
-
- return '.';
-};
-/**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-
-
-var createTransferableMessage = function createTransferableMessage(message) {
- var transferable = {};
- Object.keys(message).forEach(function (key) {
- var value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
- return transferable;
-};
-/**
- * Returns a unique string identifier for a media initialization
- * segment.
- *
- * @param {Object} initSegment
- * the init segment object.
- *
- * @return {string} the generated init segment id
- */
-
-var initSegmentId = function initSegmentId(initSegment) {
- var byterange = initSegment.byterange || {
- length: Infinity,
- offset: 0
- };
- return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
-};
-/**
- * Returns a unique string identifier for a media segment key.
- *
- * @param {Object} key the encryption key
- * @return {string} the unique id for the media segment key.
- */
-
-var segmentKeyId = function segmentKeyId(key) {
- return key.resolvedUri;
-};
-/**
- * utils to help dump binary data to the console
- *
- * @param {Array|TypedArray} data
- * data to dump to a string
- *
- * @return {string} the data as a hex string.
- */
-
-var hexDump = function hexDump(data) {
- var bytes = Array.prototype.slice.call(data);
- var step = 16;
- var result = '';
- var hex;
- var ascii;
-
- for (var j = 0; j < bytes.length / step; j++) {
- hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
- ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
- result += hex + ' ' + ascii + '\n';
- }
-
- return result;
-};
-var tagDump = function tagDump(_ref) {
- var bytes = _ref.bytes;
- return hexDump(bytes);
-};
-var textRanges = function textRanges(ranges) {
- var result = '';
- var i;
-
- for (i = 0; i < ranges.length; i++) {
- result += textRange(ranges, i) + ' ';
- }
-
- return result;
-};
-
-var utils = /*#__PURE__*/Object.freeze({
- __proto__: null,
- createTransferableMessage: createTransferableMessage,
- initSegmentId: initSegmentId,
- segmentKeyId: segmentKeyId,
- hexDump: hexDump,
- tagDump: tagDump,
- textRanges: textRanges
-});
-
-// TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
-// 25% was arbitrarily chosen, and may need to be refined over time.
-
-var SEGMENT_END_FUDGE_PERCENT = 0.25;
-/**
- * Converts a player time (any time that can be gotten/set from player.currentTime(),
- * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
- * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
- *
- * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
- * point" (a point where we have a mapping from program time to player time, with player
- * time being the post transmux start of the segment).
- *
- * For more details, see [this doc](../../docs/program-time-from-player-time.md).
- *
- * @param {number} playerTime the player time
- * @param {Object} segment the segment which contains the player time
- * @return {Date} program time
- */
-
-var playerTimeToProgramTime = function playerTimeToProgramTime(playerTime, segment) {
- if (!segment.dateTimeObject) {
- // Can't convert without an "anchor point" for the program time (i.e., a time that can
- // be used to map the start of a segment with a real world time).
- return null;
- }
-
- var transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
- var transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
-
- var startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
- var offsetFromSegmentStart = playerTime - startOfSegment;
- return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
-};
-var originalSegmentVideoDuration = function originalSegmentVideoDuration(videoTimingInfo) {
- return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
-};
-/**
- * Finds a segment that contains the time requested given as an ISO-8601 string. The
- * returned segment might be an estimate or an accurate match.
- *
- * @param {string} programTime The ISO-8601 programTime to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-
-var findSegmentForProgramTime = function findSegmentForProgramTime(programTime, playlist) {
- // Assumptions:
- // - verifyProgramDateTimeTags has already been run
- // - live streams have been started
- var dateTimeObject;
-
- try {
- dateTimeObject = new Date(programTime);
- } catch (e) {
- return null;
- }
-
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- var segment = playlist.segments[0];
-
- if (dateTimeObject < segment.dateTimeObject) {
- // Requested time is before stream start.
- return null;
- }
-
- for (var i = 0; i < playlist.segments.length - 1; i++) {
- segment = playlist.segments[i];
- var nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
-
- if (dateTimeObject < nextSegmentStart) {
- break;
- }
- }
-
- var lastSegment = playlist.segments[playlist.segments.length - 1];
- var lastSegmentStart = lastSegment.dateTimeObject;
- var lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
- var lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
-
- if (dateTimeObject > lastSegmentEnd) {
- // Beyond the end of the stream, or our best guess of the end of the stream.
- return null;
- }
-
- if (dateTimeObject > lastSegmentStart) {
- segment = lastSegment;
- }
-
- return {
- segment: segment,
- estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
- // Although, given that all segments have accurate date time objects, the segment
- // selected should be accurate, unless the video has been transmuxed at some point
- // (determined by the presence of the videoTimingInfo object), the segment's "player
- // time" (the start time in the player) can't be considered accurate.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
-};
-/**
- * Finds a segment that contains the given player time(in seconds).
- *
- * @param {number} time The player time to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-
-var findSegmentForPlayerTime = function findSegmentForPlayerTime(time, playlist) {
- // Assumptions:
- // - there will always be a segment.duration
- // - we can start from zero
- // - segments are in time order
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- var segmentEnd = 0;
- var segment;
-
- for (var i = 0; i < playlist.segments.length; i++) {
- segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
- // should contain the most accurate values we have for the segment's player times.
- //
- // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
- // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
- // calculate an end value.
-
- segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
-
- if (time <= segmentEnd) {
- break;
- }
- }
-
- var lastSegment = playlist.segments[playlist.segments.length - 1];
-
- if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
- // The time requested is beyond the stream end.
- return null;
- }
-
- if (time > segmentEnd) {
- // The time is within or beyond the last segment.
- //
- // Check to see if the time is beyond a reasonable guess of the end of the stream.
- if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
- // Technically, because the duration value is only an estimate, the time may still
- // exist in the last segment, however, there isn't enough information to make even
- // a reasonable estimate.
- return null;
- }
-
- segment = lastSegment;
- }
-
- return {
- segment: segment,
- estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
- // Because videoTimingInfo is only set after transmux, it is the only way to get
- // accurate timing values.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
-};
-/**
- * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
- * If the offset returned is positive, the programTime occurs after the
- * comparisonTimestamp.
- * If the offset is negative, the programTime occurs before the comparisonTimestamp.
- *
- * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
- * @param {string} programTime The programTime as an ISO-8601 string
- * @return {number} offset
- */
-
-var getOffsetFromTimestamp = function getOffsetFromTimestamp(comparisonTimeStamp, programTime) {
- var segmentDateTime;
- var programDateTime;
-
- try {
- segmentDateTime = new Date(comparisonTimeStamp);
- programDateTime = new Date(programTime);
- } catch (e) {// TODO handle error
- }
-
- var segmentTimeEpoch = segmentDateTime.getTime();
- var programTimeEpoch = programDateTime.getTime();
- return (programTimeEpoch - segmentTimeEpoch) / 1000;
-};
-/**
- * Checks that all segments in this playlist have programDateTime tags.
- *
- * @param {Object} playlist A playlist object
- */
-
-var verifyProgramDateTimeTags = function verifyProgramDateTimeTags(playlist) {
- if (!playlist.segments || playlist.segments.length === 0) {
- return false;
- }
-
- for (var i = 0; i < playlist.segments.length; i++) {
- var segment = playlist.segments[i];
-
- if (!segment.dateTimeObject) {
- return false;
- }
- }
-
- return true;
-};
-/**
- * Returns the programTime of the media given a playlist and a playerTime.
- * The playlist must have programDateTime tags for a programDateTime tag to be returned.
- * If the segments containing the time requested have not been buffered yet, an estimate
- * may be returned to the callback.
- *
- * @param {Object} args
- * @param {Object} args.playlist A playlist object to search within
- * @param {number} time A playerTime in seconds
- * @param {Function} callback(err, programTime)
- * @return {string} err.message A detailed error message
- * @return {Object} programTime
- * @return {number} programTime.mediaSeconds The streamTime in seconds
- * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
- */
-
-var getProgramTime = function getProgramTime(_ref) {
- var playlist = _ref.playlist,
- _ref$time = _ref.time,
- time = _ref$time === void 0 ? undefined : _ref$time,
- callback = _ref.callback;
-
- if (!callback) {
- throw new Error('getProgramTime: callback must be provided');
- }
-
- if (!playlist || time === undefined) {
- return callback({
- message: 'getProgramTime: playlist and time must be provided'
- });
- }
-
- var matchedSegment = findSegmentForPlayerTime(time, playlist);
-
- if (!matchedSegment) {
- return callback({
- message: 'valid programTime was not found'
- });
- }
-
- if (matchedSegment.type === 'estimate') {
- return callback({
- message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
- seekTime: matchedSegment.estimatedStart
- });
- }
-
- var programTimeObject = {
- mediaSeconds: time
- };
- var programTime = playerTimeToProgramTime(time, matchedSegment.segment);
-
- if (programTime) {
- programTimeObject.programDateTime = programTime.toISOString();
- }
-
- return callback(null, programTimeObject);
-};
-/**
- * Seeks in the player to a time that matches the given programTime ISO-8601 string.
- *
- * @param {Object} args
- * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
- * @param {Object} args.playlist A playlist to look within
- * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
- * @param {Function} args.seekTo A method to perform a seek
- * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
- * @param {Object} args.tech The tech to seek on
- * @param {Function} args.callback(err, newTime) A callback to return the new time to
- * @return {string} err.message A detailed error message
- * @return {number} newTime The exact time that was seeked to in seconds
- */
-
-var seekToProgramTime = function seekToProgramTime(_ref2) {
- var programTime = _ref2.programTime,
- playlist = _ref2.playlist,
- _ref2$retryCount = _ref2.retryCount,
- retryCount = _ref2$retryCount === void 0 ? 2 : _ref2$retryCount,
- seekTo = _ref2.seekTo,
- _ref2$pauseAfterSeek = _ref2.pauseAfterSeek,
- pauseAfterSeek = _ref2$pauseAfterSeek === void 0 ? true : _ref2$pauseAfterSeek,
- tech = _ref2.tech,
- callback = _ref2.callback;
-
- if (!callback) {
- throw new Error('seekToProgramTime: callback must be provided');
- }
-
- if (typeof programTime === 'undefined' || !playlist || !seekTo) {
- return callback({
- message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
- });
- }
-
- if (!playlist.endList && !tech.hasStarted_) {
- return callback({
- message: 'player must be playing a live stream to start buffering'
- });
- }
-
- if (!verifyProgramDateTimeTags(playlist)) {
- return callback({
- message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
- });
- }
-
- var matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
-
- if (!matchedSegment) {
- return callback({
- message: programTime + " was not found in the stream"
- });
- }
-
- var segment = matchedSegment.segment;
- var mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
-
- if (matchedSegment.type === 'estimate') {
- // we've run out of retries
- if (retryCount === 0) {
- return callback({
- message: programTime + " is not buffered yet. Try again"
- });
- }
-
- seekTo(matchedSegment.estimatedStart + mediaOffset);
- tech.one('seeked', function () {
- seekToProgramTime({
- programTime: programTime,
- playlist: playlist,
- retryCount: retryCount - 1,
- seekTo: seekTo,
- pauseAfterSeek: pauseAfterSeek,
- tech: tech,
- callback: callback
- });
- });
- return;
- } // Since the segment.start value is determined from the buffered end or ending time
- // of the prior segment, the seekToTime doesn't need to account for any transmuxer
- // modifications.
-
-
- var seekToTime = segment.start + mediaOffset;
-
- var seekedCallback = function seekedCallback() {
- return callback(null, tech.currentTime());
- }; // listen for seeked event
-
-
- tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
-
- if (pauseAfterSeek) {
- tech.pause();
- }
-
- seekTo(seekToTime);
-};
-
-// which will only happen if the request is complete.
-
-var callbackOnCompleted = function callbackOnCompleted(request, cb) {
- if (request.readyState === 4) {
- return cb();
- }
-
- return;
-};
-
-var containerRequest = function containerRequest(uri, xhr, cb) {
- var bytes = [];
- var id3Offset;
- var finished = false;
-
- var endRequestAndCallback = function endRequestAndCallback(err, req, type, _bytes) {
- req.abort();
- finished = true;
- return cb(err, req, type, _bytes);
- };
-
- var progressListener = function progressListener(error, request) {
- if (finished) {
- return;
- }
-
- if (error) {
- return endRequestAndCallback(error, request, '', bytes);
- } // grap the new part of content that was just downloaded
-
-
- var newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
-
- bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
- id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
- // or we need at least two bytes after an id3Offset
-
- if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- }
-
- var type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
- // to see the second sync byte, wait until we have enough data
- // before declaring it ts
-
- if (type === 'ts' && bytes.length < 188) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- } // this may be an unsynced ts segment
- // wait for 376 bytes before detecting no container
-
-
- if (!type && bytes.length < 376) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- }
-
- return endRequestAndCallback(null, request, type, bytes);
- };
-
- var options = {
- uri: uri,
- beforeSend: function beforeSend(request) {
- // this forces the browser to pass the bytes to us unprocessed
- request.overrideMimeType('text/plain; charset=x-user-defined');
- request.addEventListener('progress', function (_ref) {
- _ref.total;
- _ref.loaded;
- return callbackWrapper(request, null, {
- statusCode: request.status
- }, progressListener);
- });
- }
- };
- var request = xhr(options, function (error, response) {
- return callbackWrapper(request, error, response, progressListener);
- });
- return request;
-};
-
-var EventTarget = videojs.EventTarget,
- mergeOptions = videojs.mergeOptions;
-
-var dashPlaylistUnchanged = function dashPlaylistUnchanged(a, b) {
- if (!isPlaylistUnchanged(a, b)) {
- return false;
- } // for dash the above check will often return true in scenarios where
- // the playlist actually has changed because mediaSequence isn't a
- // dash thing, and we often set it to 1. So if the playlists have the same amount
- // of segments we return true.
- // So for dash we need to make sure that the underlying segments are different.
- // if sidx changed then the playlists are different.
-
-
- if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
- return false;
- } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
- return false;
- } // one or the other does not have segments
- // there was a change.
-
-
- if (a.segments && !b.segments || !a.segments && b.segments) {
- return false;
- } // neither has segments nothing changed
-
-
- if (!a.segments && !b.segments) {
- return true;
- } // check segments themselves
-
-
- for (var i = 0; i < a.segments.length; i++) {
- var aSegment = a.segments[i];
- var bSegment = b.segments[i]; // if uris are different between segments there was a change
-
- if (aSegment.uri !== bSegment.uri) {
- return false;
- } // neither segment has a byterange, there will be no byterange change.
-
-
- if (!aSegment.byterange && !bSegment.byterange) {
- continue;
- }
-
- var aByterange = aSegment.byterange;
- var bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
-
- if (aByterange && !bByterange || !aByterange && bByterange) {
- return false;
- } // if both segments have byterange with different offsets, there was a change.
-
-
- if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
- return false;
- }
- } // if everything was the same with segments, this is the same playlist.
-
-
- return true;
-};
-/**
- * Parses the master XML string and updates playlist URI references.
- *
- * @param {Object} config
- * Object of arguments
- * @param {string} config.masterXml
- * The mpd XML
- * @param {string} config.srcUrl
- * The mpd URL
- * @param {Date} config.clientOffset
- * A time difference between server and client
- * @param {Object} config.sidxMapping
- * SIDX mappings for moof/mdat URIs and byte ranges
- * @return {Object}
- * The parsed mpd manifest object
- */
-
-
-var parseMasterXml = function parseMasterXml(_ref) {
- var masterXml = _ref.masterXml,
- srcUrl = _ref.srcUrl,
- clientOffset = _ref.clientOffset,
- sidxMapping = _ref.sidxMapping;
- var master = parse(masterXml, {
- manifestUri: srcUrl,
- clientOffset: clientOffset,
- sidxMapping: sidxMapping
- });
- addPropertiesToMaster(master, srcUrl);
- return master;
-};
-/**
- * Returns a new master manifest that is the result of merging an updated master manifest
- * into the original version.
- *
- * @param {Object} oldMaster
- * The old parsed mpd object
- * @param {Object} newMaster
- * The updated parsed mpd object
- * @return {Object}
- * A new object representing the original master manifest with the updated media
- * playlists merged in
- */
-
-var updateMaster = function updateMaster(oldMaster, newMaster, sidxMapping) {
- var noChanges = true;
- var update = mergeOptions(oldMaster, {
- // These are top level properties that can be updated
- duration: newMaster.duration,
- minimumUpdatePeriod: newMaster.minimumUpdatePeriod
- }); // First update the playlists in playlist list
-
- for (var i = 0; i < newMaster.playlists.length; i++) {
- var playlist = newMaster.playlists[i];
-
- if (playlist.sidx) {
- var sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
-
- if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
- addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
- }
- }
-
- var playlistUpdate = updateMaster$1(update, playlist, dashPlaylistUnchanged);
-
- if (playlistUpdate) {
- update = playlistUpdate;
- noChanges = false;
- }
- } // Then update media group playlists
-
-
- forEachMediaGroup(newMaster, function (properties, type, group, label) {
- if (properties.playlists && properties.playlists.length) {
- var id = properties.playlists[0].id;
-
- var _playlistUpdate = updateMaster$1(update, properties.playlists[0], dashPlaylistUnchanged);
-
- if (_playlistUpdate) {
- update = _playlistUpdate; // update the playlist reference within media groups
-
- update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
- noChanges = false;
- }
- }
- });
-
- if (newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
- noChanges = false;
- }
-
- if (noChanges) {
- return null;
- }
-
- return update;
-}; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
-// If the SIDXs have maps, the two maps should match,
-// both `a` and `b` missing SIDXs is considered matching.
-// If `a` or `b` but not both have a map, they aren't matching.
-
-var equivalentSidx = function equivalentSidx(a, b) {
- var neitherMap = Boolean(!a.map && !b.map);
- var equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
- return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
-}; // exported for testing
-
-
-var compareSidxEntry = function compareSidxEntry(playlists, oldSidxMapping) {
- var newSidxMapping = {};
-
- for (var id in playlists) {
- var playlist = playlists[id];
- var currentSidxInfo = playlist.sidx;
-
- if (currentSidxInfo) {
- var key = generateSidxKey(currentSidxInfo);
-
- if (!oldSidxMapping[key]) {
- break;
- }
-
- var savedSidxInfo = oldSidxMapping[key].sidxInfo;
-
- if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
- newSidxMapping[key] = oldSidxMapping[key];
- }
- }
- }
-
- return newSidxMapping;
-};
-/**
- * A function that filters out changed items as they need to be requested separately.
- *
- * The method is exported for testing
- *
- * @param {Object} master the parsed mpd XML returned via mpd-parser
- * @param {Object} oldSidxMapping the SIDX to compare against
- */
-
-var filterChangedSidxMappings = function filterChangedSidxMappings(master, oldSidxMapping) {
- var videoSidx = compareSidxEntry(master.playlists, oldSidxMapping);
- var mediaGroupSidx = videoSidx;
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- if (properties.playlists && properties.playlists.length) {
- var playlists = properties.playlists;
- mediaGroupSidx = mergeOptions(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
- }
- });
- return mediaGroupSidx;
-};
-
-var DashPlaylistLoader = /*#__PURE__*/function (_EventTarget) {
- _inheritsLoose(DashPlaylistLoader, _EventTarget);
-
- // DashPlaylistLoader must accept either a src url or a playlist because subsequent
- // playlist loader setups from media groups will expect to be able to pass a playlist
- // (since there aren't external URLs to media playlists with DASH)
- function DashPlaylistLoader(srcUrlOrPlaylist, vhs, options, masterPlaylistLoader) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _EventTarget.call(this) || this;
- _this.masterPlaylistLoader_ = masterPlaylistLoader || _assertThisInitialized(_this);
-
- if (!masterPlaylistLoader) {
- _this.isMaster_ = true;
- }
-
- var _options = options,
- _options$withCredenti = _options.withCredentials,
- withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
- _options$handleManife = _options.handleManifestRedirects,
- handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
- _this.vhs_ = vhs;
- _this.withCredentials = withCredentials;
- _this.handleManifestRedirects = handleManifestRedirects;
-
- if (!srcUrlOrPlaylist) {
- throw new Error('A non-empty playlist URL or object is required');
- } // event naming?
-
-
- _this.on('minimumUpdatePeriod', function () {
- _this.refreshXml_();
- }); // live playlist staleness timeout
-
-
- _this.on('mediaupdatetimeout', function () {
- _this.refreshMedia_(_this.media().id);
- });
-
- _this.state = 'HAVE_NOTHING';
- _this.loadedPlaylists_ = {};
- _this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
- // The masterPlaylistLoader will be created with a string
-
- if (_this.isMaster_) {
- _this.masterPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
- // once multi-period is refactored
-
- _this.masterPlaylistLoader_.sidxMapping_ = {};
- } else {
- _this.childPlaylist_ = srcUrlOrPlaylist;
- }
-
- return _this;
- }
-
- var _proto = DashPlaylistLoader.prototype;
-
- _proto.requestErrored_ = function requestErrored_(err, request, startingState) {
- // disposed
- if (!this.request) {
- return true;
- } // pending request is cleared
-
-
- this.request = null;
-
- if (err) {
- // use the provided error object or create one
- // based on the request/response
- this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
- status: request.status,
- message: 'DASH request error at URL: ' + request.uri,
- response: request.response,
- // MEDIA_ERR_NETWORK
- code: 2
- };
-
- if (startingState) {
- this.state = startingState;
- }
-
- this.trigger('error');
- return true;
- }
- }
- /**
- * Verify that the container of the sidx segment can be parsed
- * and if it can, get and parse that segment.
- */
- ;
-
- _proto.addSidxSegments_ = function addSidxSegments_(playlist, startingState, cb) {
- var _this2 = this;
-
- var sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
-
- if (!playlist.sidx || !sidxKey || this.masterPlaylistLoader_.sidxMapping_[sidxKey]) {
- // keep this function async
- this.mediaRequest_ = window.setTimeout(function () {
- return cb(false);
- }, 0);
- return;
- } // resolve the segment URL relative to the playlist
-
-
- var uri = resolveManifestRedirect(this.handleManifestRedirects, playlist.sidx.resolvedUri);
-
- var fin = function fin(err, request) {
- if (_this2.requestErrored_(err, request, startingState)) {
- return;
- }
-
- var sidxMapping = _this2.masterPlaylistLoader_.sidxMapping_;
- var sidx;
-
- try {
- sidx = parseSidx(toUint8(request.response).subarray(8));
- } catch (e) {
- // sidx parsing failed.
- _this2.requestErrored_(e, request, startingState);
-
- return;
- }
-
- sidxMapping[sidxKey] = {
- sidxInfo: playlist.sidx,
- sidx: sidx
- };
- addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
- return cb(true);
- };
-
- this.request = containerRequest(uri, this.vhs_.xhr, function (err, request, container, bytes) {
- if (err) {
- return fin(err, request);
- }
-
- if (!container || container !== 'mp4') {
- return fin({
- status: request.status,
- message: "Unsupported " + (container || 'unknown') + " container type for sidx segment at URL: " + uri,
- // response is just bytes in this case
- // but we really don't want to return that.
- response: '',
- playlist: playlist,
- internal: true,
- blacklistDuration: Infinity,
- // MEDIA_ERR_NETWORK
- code: 2
- }, request);
- } // if we already downloaded the sidx bytes in the container request, use them
-
-
- var _playlist$sidx$bytera = playlist.sidx.byterange,
- offset = _playlist$sidx$bytera.offset,
- length = _playlist$sidx$bytera.length;
-
- if (bytes.length >= length + offset) {
- return fin(err, {
- response: bytes.subarray(offset, offset + length),
- status: request.status,
- uri: request.uri
- });
- } // otherwise request sidx bytes
-
-
- _this2.request = _this2.vhs_.xhr({
- uri: uri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders({
- byterange: playlist.sidx.byterange
- })
- }, fin);
- });
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.stopRequest();
- this.loadedPlaylists_ = {};
- window.clearTimeout(this.minimumUpdatePeriodTimeout_);
- window.clearTimeout(this.mediaRequest_);
- window.clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- this.mediaRequest_ = null;
- this.minimumUpdatePeriodTimeout_ = null;
-
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
-
- this.off();
- };
-
- _proto.hasPendingRequest = function hasPendingRequest() {
- return this.request || this.mediaRequest_;
- };
-
- _proto.stopRequest = function stopRequest() {
- if (this.request) {
- var oldRequest = this.request;
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- };
-
- _proto.media = function media(playlist) {
- var _this3 = this;
-
- // getter
- if (!playlist) {
- return this.media_;
- } // setter
-
-
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- }
-
- var startingState = this.state; // find the playlist object if the target playlist has been specified by URI
-
- if (typeof playlist === 'string') {
- if (!this.masterPlaylistLoader_.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
-
- playlist = this.masterPlaylistLoader_.master.playlists[playlist];
- }
-
- var mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
-
- if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
- this.state = 'HAVE_METADATA';
- this.media_ = playlist; // trigger media change if the active media has been updated
-
- if (mediaChange) {
- this.trigger('mediachanging');
- this.trigger('mediachange');
- }
-
- return;
- } // switching to the active playlist is a no-op
-
-
- if (!mediaChange) {
- return;
- } // switching from an already loaded playlist
-
-
- if (this.media_) {
- this.trigger('mediachanging');
- }
-
- this.addSidxSegments_(playlist, startingState, function (sidxChanged) {
- // everything is ready just continue to haveMetadata
- _this3.haveMetadata({
- startingState: startingState,
- playlist: playlist
- });
- });
- };
-
- _proto.haveMetadata = function haveMetadata(_ref2) {
- var startingState = _ref2.startingState,
- playlist = _ref2.playlist;
- this.state = 'HAVE_METADATA';
- this.loadedPlaylists_[playlist.id] = playlist;
- this.mediaRequest_ = null; // This will trigger loadedplaylist
-
- this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
- // to resolve setup of media groups
-
- if (startingState === 'HAVE_MASTER') {
- this.trigger('loadedmetadata');
- } else {
- // trigger media change if the active media has been updated
- this.trigger('mediachange');
- }
- };
-
- _proto.pause = function pause() {
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
-
- this.stopRequest();
- window.clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
-
- if (this.isMaster_) {
- window.clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_);
- this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
- }
-
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- }
- };
-
- _proto.load = function load(isFinalRendition) {
- var _this4 = this;
-
- window.clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- var media = this.media();
-
- if (isFinalRendition) {
- var delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
- this.mediaUpdateTimeout = window.setTimeout(function () {
- return _this4.load();
- }, delay);
- return;
- } // because the playlists are internal to the manifest, load should either load the
- // main manifest, or do nothing but trigger an event
-
-
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- // Check to see if this is the master loader and the MUP was cleared (this happens
- // when the loader was paused). `media` should be set at this point since one is always
- // set during `start()`.
- if (this.isMaster_ && !this.minimumUpdatePeriodTimeout_) {
- // Trigger minimumUpdatePeriod to refresh the master manifest
- this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
-
- this.updateMinimumUpdatePeriodTimeout_();
- }
-
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- };
-
- _proto.start = function start() {
- var _this5 = this;
-
- this.started = true; // We don't need to request the master manifest again
- // Call this asynchronously to match the xhr request behavior below
-
- if (!this.isMaster_) {
- this.mediaRequest_ = window.setTimeout(function () {
- return _this5.haveMaster_();
- }, 0);
- return;
- }
-
- this.requestMaster_(function (req, masterChanged) {
- _this5.haveMaster_();
-
- if (!_this5.hasPendingRequest() && !_this5.media_) {
- _this5.media(_this5.masterPlaylistLoader_.master.playlists[0]);
- }
- });
- };
-
- _proto.requestMaster_ = function requestMaster_(cb) {
- var _this6 = this;
-
- this.request = this.vhs_.xhr({
- uri: this.masterPlaylistLoader_.srcUrl,
- withCredentials: this.withCredentials
- }, function (error, req) {
- if (_this6.requestErrored_(error, req)) {
- if (_this6.state === 'HAVE_NOTHING') {
- _this6.started = false;
- }
-
- return;
- }
-
- var masterChanged = req.responseText !== _this6.masterPlaylistLoader_.masterXml_;
- _this6.masterPlaylistLoader_.masterXml_ = req.responseText;
-
- if (req.responseHeaders && req.responseHeaders.date) {
- _this6.masterLoaded_ = Date.parse(req.responseHeaders.date);
- } else {
- _this6.masterLoaded_ = Date.now();
- }
-
- _this6.masterPlaylistLoader_.srcUrl = resolveManifestRedirect(_this6.handleManifestRedirects, _this6.masterPlaylistLoader_.srcUrl, req);
-
- if (masterChanged) {
- _this6.handleMaster_();
-
- _this6.syncClientServerClock_(function () {
- return cb(req, masterChanged);
- });
-
- return;
- }
-
- return cb(req, masterChanged);
- });
- }
- /**
- * Parses the master xml for UTCTiming node to sync the client clock to the server
- * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
- *
- * @param {Function} done
- * Function to call when clock sync has completed
- */
- ;
-
- _proto.syncClientServerClock_ = function syncClientServerClock_(done) {
- var _this7 = this;
-
- var utcTiming = parseUTCTiming(this.masterPlaylistLoader_.masterXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
- // server clock
-
- if (utcTiming === null) {
- this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
- return done();
- }
-
- if (utcTiming.method === 'DIRECT') {
- this.masterPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
- return done();
- }
-
- this.request = this.vhs_.xhr({
- uri: resolveUrl(this.masterPlaylistLoader_.srcUrl, utcTiming.value),
- method: utcTiming.method,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this7.request) {
- return;
- }
-
- if (error) {
- // sync request failed, fall back to using date header from mpd
- // TODO: log warning
- _this7.masterPlaylistLoader_.clientOffset_ = _this7.masterLoaded_ - Date.now();
- return done();
- }
-
- var serverTime;
-
- if (utcTiming.method === 'HEAD') {
- if (!req.responseHeaders || !req.responseHeaders.date) {
- // expected date header not preset, fall back to using date header from mpd
- // TODO: log warning
- serverTime = _this7.masterLoaded_;
- } else {
- serverTime = Date.parse(req.responseHeaders.date);
- }
- } else {
- serverTime = Date.parse(req.responseText);
- }
-
- _this7.masterPlaylistLoader_.clientOffset_ = serverTime - Date.now();
- done();
- });
- };
-
- _proto.haveMaster_ = function haveMaster_() {
- this.state = 'HAVE_MASTER';
-
- if (this.isMaster_) {
- // We have the master playlist at this point, so
- // trigger this to allow MasterPlaylistController
- // to make an initial playlist selection
- this.trigger('loadedplaylist');
- } else if (!this.media_) {
- // no media playlist was specifically selected so select
- // the one the child playlist loader was created with
- this.media(this.childPlaylist_);
- }
- };
-
- _proto.handleMaster_ = function handleMaster_() {
- // clear media request
- this.mediaRequest_ = null;
- var newMaster = parseMasterXml({
- masterXml: this.masterPlaylistLoader_.masterXml_,
- srcUrl: this.masterPlaylistLoader_.srcUrl,
- clientOffset: this.masterPlaylistLoader_.clientOffset_,
- sidxMapping: this.masterPlaylistLoader_.sidxMapping_
- });
- var oldMaster = this.masterPlaylistLoader_.master; // if we have an old master to compare the new master against
-
- if (oldMaster) {
- newMaster = updateMaster(oldMaster, newMaster, this.masterPlaylistLoader_.sidxMapping_);
- } // only update master if we have a new master
-
-
- this.masterPlaylistLoader_.master = newMaster ? newMaster : oldMaster;
- var location = this.masterPlaylistLoader_.master.locations && this.masterPlaylistLoader_.master.locations[0];
-
- if (location && location !== this.masterPlaylistLoader_.srcUrl) {
- this.masterPlaylistLoader_.srcUrl = location;
- }
-
- if (!oldMaster || newMaster && newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
- this.updateMinimumUpdatePeriodTimeout_();
- }
-
- return Boolean(newMaster);
- };
-
- _proto.updateMinimumUpdatePeriodTimeout_ = function updateMinimumUpdatePeriodTimeout_() {
- var mpl = this.masterPlaylistLoader_; // cancel any pending creation of mup on media
- // a new one will be added if needed.
-
- if (mpl.createMupOnMedia_) {
- mpl.off('loadedmetadata', mpl.createMupOnMedia_);
- mpl.createMupOnMedia_ = null;
- } // clear any pending timeouts
-
-
- if (mpl.minimumUpdatePeriodTimeout_) {
- window.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
- mpl.minimumUpdatePeriodTimeout_ = null;
- }
-
- var mup = mpl.master && mpl.master.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
- // MPD has no future validity, so a new one will need to be acquired when new
- // media segments are to be made available. Thus, we use the target duration
- // in this case
-
- if (mup === 0) {
- if (mpl.media()) {
- mup = mpl.media().targetDuration * 1000;
- } else {
- mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
- mpl.one('loadedmetadata', mpl.createMupOnMedia_);
- }
- } // if minimumUpdatePeriod is invalid or <= zero, which
- // can happen when a live video becomes VOD. skip timeout
- // creation.
-
-
- if (typeof mup !== 'number' || mup <= 0) {
- if (mup < 0) {
- this.logger_("found invalid minimumUpdatePeriod of " + mup + ", not setting a timeout");
- }
-
- return;
- }
-
- this.createMUPTimeout_(mup);
- };
-
- _proto.createMUPTimeout_ = function createMUPTimeout_(mup) {
- var mpl = this.masterPlaylistLoader_;
- mpl.minimumUpdatePeriodTimeout_ = window.setTimeout(function () {
- mpl.minimumUpdatePeriodTimeout_ = null;
- mpl.trigger('minimumUpdatePeriod');
- mpl.createMUPTimeout_(mup);
- }, mup);
- }
- /**
- * Sends request to refresh the master xml and updates the parsed master manifest
- */
- ;
-
- _proto.refreshXml_ = function refreshXml_() {
- var _this8 = this;
-
- this.requestMaster_(function (req, masterChanged) {
- if (!masterChanged) {
- return;
- }
-
- if (_this8.media_) {
- _this8.media_ = _this8.masterPlaylistLoader_.master.playlists[_this8.media_.id];
- } // This will filter out updated sidx info from the mapping
-
-
- _this8.masterPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(_this8.masterPlaylistLoader_.master, _this8.masterPlaylistLoader_.sidxMapping_);
-
- _this8.addSidxSegments_(_this8.media(), _this8.state, function (sidxChanged) {
- // TODO: do we need to reload the current playlist?
- _this8.refreshMedia_(_this8.media().id);
- });
- });
- }
- /**
- * Refreshes the media playlist by re-parsing the master xml and updating playlist
- * references. If this is an alternate loader, the updated parsed manifest is retrieved
- * from the master loader.
- */
- ;
-
- _proto.refreshMedia_ = function refreshMedia_(mediaID) {
- var _this9 = this;
-
- if (!mediaID) {
- throw new Error('refreshMedia_ must take a media id');
- } // for master we have to reparse the master xml
- // to re-create segments based on current timing values
- // which may change media. We only skip updating master
- // if this is the first time this.media_ is being set.
- // as master was just parsed in that case.
-
-
- if (this.media_ && this.isMaster_) {
- this.handleMaster_();
- }
-
- var playlists = this.masterPlaylistLoader_.master.playlists;
- var mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
-
- if (mediaChanged) {
- this.media_ = playlists[mediaID];
- } else {
- this.trigger('playlistunchanged');
- }
-
- if (!this.mediaUpdateTimeout) {
- var createMediaUpdateTimeout = function createMediaUpdateTimeout() {
- if (_this9.media().endList) {
- return;
- }
-
- _this9.mediaUpdateTimeout = window.setTimeout(function () {
- _this9.trigger('mediaupdatetimeout');
-
- createMediaUpdateTimeout();
- }, refreshDelay(_this9.media(), Boolean(mediaChanged)));
- };
-
- createMediaUpdateTimeout();
- }
-
- this.trigger('loadedplaylist');
- };
-
- return DashPlaylistLoader;
-}(EventTarget);
-
-var Config = {
- GOAL_BUFFER_LENGTH: 30,
- MAX_GOAL_BUFFER_LENGTH: 60,
- BACK_BUFFER_LENGTH: 30,
- GOAL_BUFFER_LENGTH_RATE: 1,
- // 0.5 MB/s
- INITIAL_BANDWIDTH: 4194304,
- // A fudge factor to apply to advertised playlist bitrates to account for
- // temporary flucations in client bandwidth
- BANDWIDTH_VARIANCE: 1.2,
- // How much of the buffer must be filled before we consider upswitching
- BUFFER_LOW_WATER_LINE: 0,
- MAX_BUFFER_LOW_WATER_LINE: 30,
- // TODO: Remove this when experimentalBufferBasedABR is removed
- EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
- BUFFER_LOW_WATER_LINE_RATE: 1,
- // If the buffer is greater than the high water line, we won't switch down
- BUFFER_HIGH_WATER_LINE: 30
-};
-
-var stringToArrayBuffer = function stringToArrayBuffer(string) {
- var view = new Uint8Array(new ArrayBuffer(string.length));
-
- for (var i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view.buffer;
-};
-
-/* global Blob, BlobBuilder, Worker */
-// unify worker interface
-var browserWorkerPolyFill = function browserWorkerPolyFill(workerObj) {
- // node only supports on/off
- workerObj.on = workerObj.addEventListener;
- workerObj.off = workerObj.removeEventListener;
- return workerObj;
-};
-
-var createObjectURL = function createObjectURL(str) {
- try {
- return URL.createObjectURL(new Blob([str], {
- type: 'application/javascript'
- }));
- } catch (e) {
- var blob = new BlobBuilder();
- blob.append(str);
- return URL.createObjectURL(blob.getBlob());
- }
-};
-
-var factory = function factory(code) {
- return function () {
- var objectUrl = createObjectURL(code);
- var worker = browserWorkerPolyFill(new Worker(objectUrl));
- worker.objURL = objectUrl;
- var terminate = worker.terminate;
- worker.on = worker.addEventListener;
- worker.off = worker.removeEventListener;
-
- worker.terminate = function () {
- URL.revokeObjectURL(objectUrl);
- return terminate.call(this);
- };
-
- return worker;
- };
-};
-var transform = function transform(code) {
- return "var browserWorkerPolyFill = " + browserWorkerPolyFill.toString() + ";\n" + 'browserWorkerPolyFill(self);\n' + code;
-};
-
-var getWorkerString = function getWorkerString(fn) {
- return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
-};
-
-/* rollup-plugin-worker-factory start for worker!/Users/gkatsevman/p/http-streaming-release/src/transmuxer-worker.js */
-var workerCode$1 = transform(getWorkerString(function () {
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * A lightweight readable stream implemention that handles event dispatching.
- * Objects that inherit from streams should call init in their constructors.
- */
-
- var Stream = function Stream() {
- this.init = function () {
- var listeners = {};
- /**
- * Add a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} the callback to be invoked when an event of
- * the specified type occurs
- */
-
- this.on = function (type, listener) {
- if (!listeners[type]) {
- listeners[type] = [];
- }
-
- listeners[type] = listeners[type].concat(listener);
- };
- /**
- * Remove a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} a function previously registered for this
- * type of event through `on`
- */
-
-
- this.off = function (type, listener) {
- var index;
-
- if (!listeners[type]) {
- return false;
- }
-
- index = listeners[type].indexOf(listener);
- listeners[type] = listeners[type].slice();
- listeners[type].splice(index, 1);
- return index > -1;
- };
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- * @param type {string} the event name
- */
-
-
- this.trigger = function (type) {
- var callbacks, i, length, args;
- callbacks = listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- args = [];
- i = arguments.length;
-
- for (i = 1; i < arguments.length; ++i) {
- args.push(arguments[i]);
- }
-
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].apply(this, args);
- }
- }
- };
- /**
- * Destroys the stream and cleans up.
- */
-
-
- this.dispose = function () {
- listeners = {};
- };
- };
- };
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- * @param destination {stream} the stream that will receive all `data` events
- * @param autoFlush {boolean} if false, we will not call `flush` on the destination
- * when the current stream emits a 'done' event
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
-
-
- Stream.prototype.pipe = function (destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- this.on('done', function (flushSource) {
- destination.flush(flushSource);
- });
- this.on('partialdone', function (flushSource) {
- destination.partialFlush(flushSource);
- });
- this.on('endedtimeline', function (flushSource) {
- destination.endTimeline(flushSource);
- });
- this.on('reset', function (flushSource) {
- destination.reset(flushSource);
- });
- return destination;
- }; // Default stream functions that are expected to be overridden to perform
- // actual work. These are provided by the prototype as a sort of no-op
- // implementation so that we don't have to check for their existence in the
- // `pipe` function above.
-
-
- Stream.prototype.push = function (data) {
- this.trigger('data', data);
- };
-
- Stream.prototype.flush = function (flushSource) {
- this.trigger('done', flushSource);
- };
-
- Stream.prototype.partialFlush = function (flushSource) {
- this.trigger('partialdone', flushSource);
- };
-
- Stream.prototype.endTimeline = function (flushSource) {
- this.trigger('endedtimeline', flushSource);
- };
-
- Stream.prototype.reset = function (flushSource) {
- this.trigger('reset', flushSource);
- };
-
- var stream = Stream;
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Functions that generate fragmented MP4s suitable for use with Media
- * Source Extensions.
- */
-
- var UINT32_MAX = Math.pow(2, 32) - 1;
- var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants
-
- (function () {
- var i;
- types = {
- avc1: [],
- // codingname
- avcC: [],
- btrt: [],
- dinf: [],
- dref: [],
- esds: [],
- ftyp: [],
- hdlr: [],
- mdat: [],
- mdhd: [],
- mdia: [],
- mfhd: [],
- minf: [],
- moof: [],
- moov: [],
- mp4a: [],
- // codingname
- mvex: [],
- mvhd: [],
- pasp: [],
- sdtp: [],
- smhd: [],
- stbl: [],
- stco: [],
- stsc: [],
- stsd: [],
- stsz: [],
- stts: [],
- styp: [],
- tfdt: [],
- tfhd: [],
- traf: [],
- trak: [],
- trun: [],
- trex: [],
- tkhd: [],
- vmhd: []
- }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
- // don't throw an error
-
- if (typeof Uint8Array === 'undefined') {
- return;
- }
-
- for (i in types) {
- if (types.hasOwnProperty(i)) {
- types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
- }
- }
-
- MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
- AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
- MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
- VIDEO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
- ]);
- AUDIO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
- ]);
- HDLR_TYPES = {
- video: VIDEO_HDLR,
- audio: AUDIO_HDLR
- };
- DREF = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // entry_count
- 0x00, 0x00, 0x00, 0x0c, // entry_size
- 0x75, 0x72, 0x6c, 0x20, // 'url' type
- 0x00, // version 0
- 0x00, 0x00, 0x01 // entry_flags
- ]);
- SMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, // balance, 0 means centered
- 0x00, 0x00 // reserved
- ]);
- STCO = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00 // entry_count
- ]);
- STSC = STCO;
- STSZ = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // sample_size
- 0x00, 0x00, 0x00, 0x00 // sample_count
- ]);
- STTS = STCO;
- VMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x01, // flags
- 0x00, 0x00, // graphicsmode
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
- ]);
- })();
-
- box = function box(type) {
- var payload = [],
- size = 0,
- i,
- result,
- view;
-
- for (i = 1; i < arguments.length; i++) {
- payload.push(arguments[i]);
- }
-
- i = payload.length; // calculate the total size we need to allocate
-
- while (i--) {
- size += payload[i].byteLength;
- }
-
- result = new Uint8Array(size + 8);
- view = new DataView(result.buffer, result.byteOffset, result.byteLength);
- view.setUint32(0, result.byteLength);
- result.set(type, 4); // copy the payload into the result
-
- for (i = 0, size = 8; i < payload.length; i++) {
- result.set(payload[i], size);
- size += payload[i].byteLength;
- }
-
- return result;
- };
-
- dinf = function dinf() {
- return box(types.dinf, box(types.dref, DREF));
- };
-
- esds = function esds(track) {
- return box(types.esds, new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- // ES_Descriptor
- 0x03, // tag, ES_DescrTag
- 0x19, // length
- 0x00, 0x00, // ES_ID
- 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
- // DecoderConfigDescriptor
- 0x04, // tag, DecoderConfigDescrTag
- 0x11, // length
- 0x40, // object type
- 0x15, // streamType
- 0x00, 0x06, 0x00, // bufferSizeDB
- 0x00, 0x00, 0xda, 0xc0, // maxBitrate
- 0x00, 0x00, 0xda, 0xc0, // avgBitrate
- // DecoderSpecificInfo
- 0x05, // tag, DecoderSpecificInfoTag
- 0x02, // length
- // ISO/IEC 14496-3, AudioSpecificConfig
- // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
- track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
- ]));
- };
-
- ftyp = function ftyp() {
- return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
- };
-
- hdlr = function hdlr(type) {
- return box(types.hdlr, HDLR_TYPES[type]);
- };
-
- mdat = function mdat(data) {
- return box(types.mdat, data);
- };
-
- mdhd = function mdhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x02, // creation_time
- 0x00, 0x00, 0x00, 0x03, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
- 0x55, 0xc4, // 'und' language (undetermined)
- 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
- // defined. The sample rate can be parsed out of an ADTS header, for
- // instance.
-
- if (track.samplerate) {
- result[12] = track.samplerate >>> 24 & 0xFF;
- result[13] = track.samplerate >>> 16 & 0xFF;
- result[14] = track.samplerate >>> 8 & 0xFF;
- result[15] = track.samplerate & 0xFF;
- }
-
- return box(types.mdhd, result);
- };
-
- mdia = function mdia(track) {
- return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
- };
-
- mfhd = function mfhd(sequenceNumber) {
- return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
- (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
- ]));
- };
-
- minf = function minf(track) {
- return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
- };
-
- moof = function moof(sequenceNumber, tracks) {
- var trackFragments = [],
- i = tracks.length; // build traf boxes for each track fragment
-
- while (i--) {
- trackFragments[i] = traf(tracks[i]);
- }
-
- return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
- };
- /**
- * Returns a movie box.
- * @param tracks {array} the tracks associated with this movie
- * @see ISO/IEC 14496-12:2012(E), section 8.2.1
- */
-
-
- moov = function moov(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trak(tracks[i]);
- }
-
- return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
- };
-
- mvex = function mvex(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trex(tracks[i]);
- }
-
- return box.apply(null, [types.mvex].concat(boxes));
- };
-
- mvhd = function mvhd(duration) {
- var bytes = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // creation_time
- 0x00, 0x00, 0x00, 0x02, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
- 0x00, 0x01, 0x00, 0x00, // 1.0 rate
- 0x01, 0x00, // 1.0 volume
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0xff, 0xff, 0xff, 0xff // next_track_ID
- ]);
- return box(types.mvhd, bytes);
- };
-
- sdtp = function sdtp(track) {
- var samples = track.samples || [],
- bytes = new Uint8Array(4 + samples.length),
- flags,
- i; // leave the full box header (4 bytes) all zero
- // write the sample table
-
- for (i = 0; i < samples.length; i++) {
- flags = samples[i].flags;
- bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
- }
-
- return box(types.sdtp, bytes);
- };
-
- stbl = function stbl(track) {
- return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
- };
-
- (function () {
- var videoSample, audioSample;
-
- stsd = function stsd(track) {
- return box(types.stsd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
- };
-
- videoSample = function videoSample(track) {
- var sps = track.sps || [],
- pps = track.pps || [],
- sequenceParameterSets = [],
- pictureParameterSets = [],
- i,
- avc1Box; // assemble the SPSs
-
- for (i = 0; i < sps.length; i++) {
- sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
- sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
-
- sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
- } // assemble the PPSs
-
-
- for (i = 0; i < pps.length; i++) {
- pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
- pictureParameterSets.push(pps[i].byteLength & 0xFF);
- pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
- }
-
- avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- (track.width & 0xff00) >> 8, track.width & 0xff, // width
- (track.height & 0xff00) >> 8, track.height & 0xff, // height
- 0x00, 0x48, 0x00, 0x00, // horizresolution
- 0x00, 0x48, 0x00, 0x00, // vertresolution
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // frame_count
- 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
- 0x00, 0x18, // depth = 24
- 0x11, 0x11 // pre_defined = -1
- ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
- track.profileIdc, // AVCProfileIndication
- track.profileCompatibility, // profile_compatibility
- track.levelIdc, // AVCLevelIndication
- 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
- ].concat([sps.length], // numOfSequenceParameterSets
- sequenceParameterSets, // "SPS"
- [pps.length], // numOfPictureParameterSets
- pictureParameterSets // "PPS"
- ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
- 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
- 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
- ]))];
-
- if (track.sarRatio) {
- var hSpacing = track.sarRatio[0],
- vSpacing = track.sarRatio[1];
- avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 0xFF000000) >> 24, (hSpacing & 0xFF0000) >> 16, (hSpacing & 0xFF00) >> 8, hSpacing & 0xFF, (vSpacing & 0xFF000000) >> 24, (vSpacing & 0xFF0000) >> 16, (vSpacing & 0xFF00) >> 8, vSpacing & 0xFF])));
- }
-
- return box.apply(null, avc1Box);
- };
-
- audioSample = function audioSample(track) {
- return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- // AudioSampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
- (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
- // MP4AudioSampleEntry, ISO/IEC 14496-14
- ]), esds(track));
- };
- })();
-
- tkhd = function tkhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x07, // flags
- 0x00, 0x00, 0x00, 0x00, // creation_time
- 0x00, 0x00, 0x00, 0x00, // modification_time
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, // layer
- 0x00, 0x00, // alternate_group
- 0x01, 0x00, // non-audio track volume
- 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
- (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
- ]);
- return box(types.tkhd, result);
- };
- /**
- * Generate a track fragment (traf) box. A traf box collects metadata
- * about tracks in a movie fragment (moof) box.
- */
-
-
- traf = function traf(track) {
- var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
- trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x3a, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x00, 0x00, 0x00 // default_sample_flags
- ]));
- upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
- lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));
- trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
- 0x00, 0x00, 0x00, // flags
- // baseMediaDecodeTime
- upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])); // the data offset specifies the number of bytes from the start of
- // the containing moof to the first payload byte of the associated
- // mdat
-
- dataOffset = 32 + // tfhd
- 20 + // tfdt
- 8 + // traf header
- 16 + // mfhd
- 8 + // moof header
- 8; // mdat header
- // audio tracks require less metadata
-
- if (track.type === 'audio') {
- trackFragmentRun = trun$1(track, dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
- } // video tracks should contain an independent and disposable samples
- // box (sdtp)
- // generate one and adjust offsets to match
-
-
- sampleDependencyTable = sdtp(track);
- trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
- };
- /**
- * Generate a track box.
- * @param track {object} a track definition
- * @return {Uint8Array} the track box
- */
-
-
- trak = function trak(track) {
- track.duration = track.duration || 0xffffffff;
- return box(types.trak, tkhd(track), mdia(track));
- };
-
- trex = function trex(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x01, 0x00, 0x01 // default_sample_flags
- ]); // the last two bytes of default_sample_flags is the sample
- // degradation priority, a hint about the importance of this sample
- // relative to others. Lower the degradation priority for all sample
- // types other than video.
-
- if (track.type !== 'video') {
- result[result.length - 1] = 0x00;
- }
-
- return box(types.trex, result);
- };
-
- (function () {
- var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
- // duration is present for the first sample, it will be present for
- // all subsequent samples.
- // see ISO/IEC 14496-12:2012, Section 8.8.8.1
-
- trunHeader = function trunHeader(samples, offset) {
- var durationPresent = 0,
- sizePresent = 0,
- flagsPresent = 0,
- compositionTimeOffset = 0; // trun flag constants
-
- if (samples.length) {
- if (samples[0].duration !== undefined) {
- durationPresent = 0x1;
- }
-
- if (samples[0].size !== undefined) {
- sizePresent = 0x2;
- }
-
- if (samples[0].flags !== undefined) {
- flagsPresent = 0x4;
- }
-
- if (samples[0].compositionTimeOffset !== undefined) {
- compositionTimeOffset = 0x8;
- }
- }
-
- return [0x00, // version 0
- 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
- (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
- (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
- ];
- };
-
- videoTrun = function videoTrun(track, offset) {
- var bytesOffest, bytes, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 16 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 16);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
-
- bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
- bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
-
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
- }
-
- return box(types.trun, bytes);
- };
-
- audioTrun = function audioTrun(track, offset) {
- var bytes, bytesOffest, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 8 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 8);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
- }
-
- return box(types.trun, bytes);
- };
-
- trun$1 = function trun(track, offset) {
- if (track.type === 'audio') {
- return audioTrun(track, offset);
- }
-
- return videoTrun(track, offset);
- };
- })();
-
- var mp4Generator = {
- ftyp: ftyp,
- mdat: mdat,
- moof: moof,
- moov: moov,
- initSegment: function initSegment(tracks) {
- var fileType = ftyp(),
- movie = moov(tracks),
- result;
- result = new Uint8Array(fileType.byteLength + movie.byteLength);
- result.set(fileType);
- result.set(movie, fileType.byteLength);
- return result;
- }
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- // Convert an array of nal units into an array of frames with each frame being
- // composed of the nal units that make up that frame
- // Also keep track of cummulative data about the frame from the nal units such
- // as the frame duration, starting pts, etc.
-
- var groupNalsIntoFrames = function groupNalsIntoFrames(nalUnits) {
- var i,
- currentNal,
- currentFrame = [],
- frames = []; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength = 0;
- frames.nalCount = 0;
- frames.duration = 0;
- currentFrame.byteLength = 0;
-
- for (i = 0; i < nalUnits.length; i++) {
- currentNal = nalUnits[i]; // Split on 'aud'-type nal units
-
- if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
- // Since the very first nal unit is expected to be an AUD
- // only push to the frames array when currentFrame is not empty
- if (currentFrame.length) {
- currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- }
-
- currentFrame = [currentNal];
- currentFrame.byteLength = currentNal.data.byteLength;
- currentFrame.pts = currentNal.pts;
- currentFrame.dts = currentNal.dts;
- } else {
- // Specifically flag key frames for ease of use later
- if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
- currentFrame.keyFrame = true;
- }
-
- currentFrame.duration = currentNal.dts - currentFrame.dts;
- currentFrame.byteLength += currentNal.data.byteLength;
- currentFrame.push(currentNal);
- }
- } // For the last frame, use the duration of the previous frame if we
- // have nothing better to go on
-
-
- if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
- currentFrame.duration = frames[frames.length - 1].duration;
- } // Push the final frame
- // TODO added for LHLS, make sure this is OK
-
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- return frames;
- }; // Convert an array of frames into an array of Gop with each Gop being composed
- // of the frames that make up that Gop
- // Also keep track of cummulative data about the Gop from the frames such as the
- // Gop duration, starting pts, etc.
-
-
- var groupFramesIntoGops = function groupFramesIntoGops(frames) {
- var i,
- currentFrame,
- currentGop = [],
- gops = []; // We must pre-set some of the values on the Gop since we
- // keep running totals of these values
-
- currentGop.byteLength = 0;
- currentGop.nalCount = 0;
- currentGop.duration = 0;
- currentGop.pts = frames[0].pts;
- currentGop.dts = frames[0].dts; // store some metadata about all the Gops
-
- gops.byteLength = 0;
- gops.nalCount = 0;
- gops.duration = 0;
- gops.pts = frames[0].pts;
- gops.dts = frames[0].dts;
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
-
- if (currentFrame.keyFrame) {
- // Since the very first frame is expected to be an keyframe
- // only push to the gops array when currentGop is not empty
- if (currentGop.length) {
- gops.push(currentGop);
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration;
- }
-
- currentGop = [currentFrame];
- currentGop.nalCount = currentFrame.length;
- currentGop.byteLength = currentFrame.byteLength;
- currentGop.pts = currentFrame.pts;
- currentGop.dts = currentFrame.dts;
- currentGop.duration = currentFrame.duration;
- } else {
- currentGop.duration += currentFrame.duration;
- currentGop.nalCount += currentFrame.length;
- currentGop.byteLength += currentFrame.byteLength;
- currentGop.push(currentFrame);
- }
- }
-
- if (gops.length && currentGop.duration <= 0) {
- currentGop.duration = gops[gops.length - 1].duration;
- }
-
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration; // push the final Gop
-
- gops.push(currentGop);
- return gops;
- };
- /*
- * Search for the first keyframe in the GOPs and throw away all frames
- * until that keyframe. Then extend the duration of the pulled keyframe
- * and pull the PTS and DTS of the keyframe so that it covers the time
- * range of the frames that were disposed.
- *
- * @param {Array} gops video GOPs
- * @returns {Array} modified video GOPs
- */
-
-
- var extendFirstKeyFrame = function extendFirstKeyFrame(gops) {
- var currentGop;
-
- if (!gops[0][0].keyFrame && gops.length > 1) {
- // Remove the first GOP
- currentGop = gops.shift();
- gops.byteLength -= currentGop.byteLength;
- gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
- // first gop to cover the time period of the
- // frames we just removed
-
- gops[0][0].dts = currentGop.dts;
- gops[0][0].pts = currentGop.pts;
- gops[0][0].duration += currentGop.duration;
- }
-
- return gops;
- };
- /**
- * Default sample object
- * see ISO/IEC 14496-12:2012, section 8.6.4.3
- */
-
-
- var createDefaultSample = function createDefaultSample() {
- return {
- size: 0,
- flags: {
- isLeading: 0,
- dependsOn: 1,
- isDependedOn: 0,
- hasRedundancy: 0,
- degradationPriority: 0,
- isNonSyncSample: 1
- }
- };
- };
- /*
- * Collates information from a video frame into an object for eventual
- * entry into an MP4 sample table.
- *
- * @param {Object} frame the video frame
- * @param {Number} dataOffset the byte offset to position the sample
- * @return {Object} object containing sample table info for a frame
- */
-
-
- var sampleForFrame = function sampleForFrame(frame, dataOffset) {
- var sample = createDefaultSample();
- sample.dataOffset = dataOffset;
- sample.compositionTimeOffset = frame.pts - frame.dts;
- sample.duration = frame.duration;
- sample.size = 4 * frame.length; // Space for nal unit size
-
- sample.size += frame.byteLength;
-
- if (frame.keyFrame) {
- sample.flags.dependsOn = 2;
- sample.flags.isNonSyncSample = 0;
- }
-
- return sample;
- }; // generate the track's sample table from an array of gops
-
-
- var generateSampleTable$1 = function generateSampleTable(gops, baseDataOffset) {
- var h,
- i,
- sample,
- currentGop,
- currentFrame,
- dataOffset = baseDataOffset || 0,
- samples = [];
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h];
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i];
- sample = sampleForFrame(currentFrame, dataOffset);
- dataOffset += sample.size;
- samples.push(sample);
- }
- }
-
- return samples;
- }; // generate the track's raw mdat data from an array of gops
-
-
- var concatenateNalData = function concatenateNalData(gops) {
- var h,
- i,
- j,
- currentGop,
- currentFrame,
- currentNal,
- dataOffset = 0,
- nalsByteLength = gops.byteLength,
- numberOfNals = gops.nalCount,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each Gop..
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h]; // For each Frame..
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i]; // For each NAL..
-
- for (j = 0; j < currentFrame.length; j++) {
- currentNal = currentFrame[j];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
- }
- }
-
- return data;
- }; // generate the track's sample table from a frame
-
-
- var generateSampleTableForFrame = function generateSampleTableForFrame(frame, baseDataOffset) {
- var sample,
- dataOffset = baseDataOffset || 0,
- samples = [];
- sample = sampleForFrame(frame, dataOffset);
- samples.push(sample);
- return samples;
- }; // generate the track's raw mdat data from a frame
-
-
- var concatenateNalDataForFrame = function concatenateNalDataForFrame(frame) {
- var i,
- currentNal,
- dataOffset = 0,
- nalsByteLength = frame.byteLength,
- numberOfNals = frame.length,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each NAL..
-
- for (i = 0; i < frame.length; i++) {
- currentNal = frame[i];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
-
- return data;
- };
-
- var frameUtils = {
- groupNalsIntoFrames: groupNalsIntoFrames,
- groupFramesIntoGops: groupFramesIntoGops,
- extendFirstKeyFrame: extendFirstKeyFrame,
- generateSampleTable: generateSampleTable$1,
- concatenateNalData: concatenateNalData,
- generateSampleTableForFrame: generateSampleTableForFrame,
- concatenateNalDataForFrame: concatenateNalDataForFrame
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var highPrefix = [33, 16, 5, 32, 164, 27];
- var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
-
- var zeroFill = function zeroFill(count) {
- var a = [];
-
- while (count--) {
- a.push(0);
- }
-
- return a;
- };
-
- var makeTable = function makeTable(metaTable) {
- return Object.keys(metaTable).reduce(function (obj, key) {
- obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
- return arr.concat(part);
- }, []));
- return obj;
- }, {});
- };
-
- var silence;
-
- var silence_1 = function silence_1() {
- if (!silence) {
- // Frames-of-silence to use for filling in missing AAC frames
- var coneOfSilence = {
- 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
- 88200: [highPrefix, [231], zeroFill(170), [56]],
- 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
- 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
- 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
- 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
- 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
- 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
- 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
- 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
- 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
- };
- silence = makeTable(coneOfSilence);
- }
-
- return silence;
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
-
- var ONE_SECOND_IN_TS$4 = 90000,
- // 90kHz clock
- secondsToVideoTs,
- secondsToAudioTs,
- videoTsToSeconds,
- audioTsToSeconds,
- audioTsToVideoTs,
- videoTsToAudioTs,
- metadataTsToSeconds;
-
- secondsToVideoTs = function secondsToVideoTs(seconds) {
- return seconds * ONE_SECOND_IN_TS$4;
- };
-
- secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
- return seconds * sampleRate;
- };
-
- videoTsToSeconds = function videoTsToSeconds(timestamp) {
- return timestamp / ONE_SECOND_IN_TS$4;
- };
-
- audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
- return timestamp / sampleRate;
- };
-
- audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
- return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
- };
-
- videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
- return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
- };
- /**
- * Adjust ID3 tag or caption timing information by the timeline pts values
- * (if keepOriginalTimestamps is false) and convert to seconds
- */
-
-
- metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
- return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
- };
-
- var clock = {
- ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
- secondsToVideoTs: secondsToVideoTs,
- secondsToAudioTs: secondsToAudioTs,
- videoTsToSeconds: videoTsToSeconds,
- audioTsToSeconds: audioTsToSeconds,
- audioTsToVideoTs: audioTsToVideoTs,
- videoTsToAudioTs: videoTsToAudioTs,
- metadataTsToSeconds: metadataTsToSeconds
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- /**
- * Sum the `byteLength` properties of the data in each AAC frame
- */
-
- var sumFrameByteLengths = function sumFrameByteLengths(array) {
- var i,
- currentObj,
- sum = 0; // sum the byteLength's all each nal unit in the frame
-
- for (i = 0; i < array.length; i++) {
- currentObj = array[i];
- sum += currentObj.data.byteLength;
- }
-
- return sum;
- }; // Possibly pad (prefix) the audio track with silence if appending this track
- // would lead to the introduction of a gap in the audio buffer
-
-
- var prefixWithSilence = function prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
- var baseMediaDecodeTimeTs,
- frameDuration = 0,
- audioGapDuration = 0,
- audioFillFrameCount = 0,
- audioFillDuration = 0,
- silentFrame,
- i,
- firstFrame;
-
- if (!frames.length) {
- return;
- }
-
- baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
-
- frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
-
- if (audioAppendStartTs && videoBaseMediaDecodeTime) {
- // insert the shortest possible amount (audio gap or audio to video gap)
- audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
-
- audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
- audioFillDuration = audioFillFrameCount * frameDuration;
- } // don't attempt to fill gaps smaller than a single frame or larger
- // than a half second
-
-
- if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
- return;
- }
-
- silentFrame = silence_1()[track.samplerate];
-
- if (!silentFrame) {
- // we don't have a silent frame pregenerated for the sample rate, so use a frame
- // from the content instead
- silentFrame = frames[0].data;
- }
-
- for (i = 0; i < audioFillFrameCount; i++) {
- firstFrame = frames[0];
- frames.splice(0, 0, {
- data: silentFrame,
- dts: firstFrame.dts - frameDuration,
- pts: firstFrame.pts - frameDuration
- });
- }
-
- track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
- return audioFillDuration;
- }; // If the audio segment extends before the earliest allowed dts
- // value, remove AAC frames until starts at or after the earliest
- // allowed DTS so that we don't end up with a negative baseMedia-
- // DecodeTime for the audio track
-
-
- var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts) {
- if (track.minSegmentDts >= earliestAllowedDts) {
- return adtsFrames;
- } // We will need to recalculate the earliest segment Dts
-
-
- track.minSegmentDts = Infinity;
- return adtsFrames.filter(function (currentFrame) {
- // If this is an allowed frame, keep it and record it's Dts
- if (currentFrame.dts >= earliestAllowedDts) {
- track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
- track.minSegmentPts = track.minSegmentDts;
- return true;
- } // Otherwise, discard it
-
-
- return false;
- });
- }; // generate the track's raw mdat data from an array of frames
-
-
- var generateSampleTable = function generateSampleTable(frames) {
- var i,
- currentFrame,
- samples = [];
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- samples.push({
- size: currentFrame.data.byteLength,
- duration: 1024 // For AAC audio, all samples contain 1024 samples
-
- });
- }
-
- return samples;
- }; // generate the track's sample table from an array of frames
-
-
- var concatenateFrameData = function concatenateFrameData(frames) {
- var i,
- currentFrame,
- dataOffset = 0,
- data = new Uint8Array(sumFrameByteLengths(frames));
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- data.set(currentFrame.data, dataOffset);
- dataOffset += currentFrame.data.byteLength;
- }
-
- return data;
- };
-
- var audioFrameUtils = {
- prefixWithSilence: prefixWithSilence,
- trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
- generateSampleTable: generateSampleTable,
- concatenateFrameData: concatenateFrameData
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ONE_SECOND_IN_TS$3 = clock.ONE_SECOND_IN_TS;
- /**
- * Store information about the start and end of the track and the
- * duration for each frame/sample we process in order to calculate
- * the baseMediaDecodeTime
- */
-
- var collectDtsInfo = function collectDtsInfo(track, data) {
- if (typeof data.pts === 'number') {
- if (track.timelineStartInfo.pts === undefined) {
- track.timelineStartInfo.pts = data.pts;
- }
-
- if (track.minSegmentPts === undefined) {
- track.minSegmentPts = data.pts;
- } else {
- track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
- }
-
- if (track.maxSegmentPts === undefined) {
- track.maxSegmentPts = data.pts;
- } else {
- track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
- }
- }
-
- if (typeof data.dts === 'number') {
- if (track.timelineStartInfo.dts === undefined) {
- track.timelineStartInfo.dts = data.dts;
- }
-
- if (track.minSegmentDts === undefined) {
- track.minSegmentDts = data.dts;
- } else {
- track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
- }
-
- if (track.maxSegmentDts === undefined) {
- track.maxSegmentDts = data.dts;
- } else {
- track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
- }
- }
- };
- /**
- * Clear values used to calculate the baseMediaDecodeTime between
- * tracks
- */
-
-
- var clearDtsInfo = function clearDtsInfo(track) {
- delete track.minSegmentDts;
- delete track.maxSegmentDts;
- delete track.minSegmentPts;
- delete track.maxSegmentPts;
- };
- /**
- * Calculate the track's baseMediaDecodeTime based on the earliest
- * DTS the transmuxer has ever seen and the minimum DTS for the
- * current track
- * @param track {object} track metadata configuration
- * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime(track, keepOriginalTimestamps) {
- var baseMediaDecodeTime,
- scale,
- minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
-
- if (!keepOriginalTimestamps) {
- minSegmentDts -= track.timelineStartInfo.dts;
- } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
- // we want the start of the first segment to be placed
-
-
- baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
-
- baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
-
- baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
-
- if (track.type === 'audio') {
- // Audio has a different clock equal to the sampling_rate so we need to
- // scale the PTS values into the clock rate of the track
- scale = track.samplerate / ONE_SECOND_IN_TS$3;
- baseMediaDecodeTime *= scale;
- baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
- }
-
- return baseMediaDecodeTime;
- };
-
- var trackDecodeInfo = {
- clearDtsInfo: clearDtsInfo,
- calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
- collectDtsInfo: collectDtsInfo
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Reads in-band caption information from a video elementary
- * stream. Captions must follow the CEA-708 standard for injection
- * into an MPEG-2 transport streams.
- * @see https://en.wikipedia.org/wiki/CEA-708
- * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
- */
- // payload type field to indicate how they are to be
- // interpreted. CEAS-708 caption content is always transmitted with
- // payload type 0x04.
-
- var USER_DATA_REGISTERED_ITU_T_T35 = 4,
- RBSP_TRAILING_BITS = 128;
- /**
- * Parse a supplemental enhancement information (SEI) NAL unit.
- * Stops parsing once a message of type ITU T T35 has been found.
- *
- * @param bytes {Uint8Array} the bytes of a SEI NAL unit
- * @return {object} the parsed SEI payload
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- */
-
- var parseSei = function parseSei(bytes) {
- var i = 0,
- result = {
- payloadType: -1,
- payloadSize: 0
- },
- payloadType = 0,
- payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
-
- while (i < bytes.byteLength) {
- // stop once we have hit the end of the sei_rbsp
- if (bytes[i] === RBSP_TRAILING_BITS) {
- break;
- } // Parse payload type
-
-
- while (bytes[i] === 0xFF) {
- payloadType += 255;
- i++;
- }
-
- payloadType += bytes[i++]; // Parse payload size
-
- while (bytes[i] === 0xFF) {
- payloadSize += 255;
- i++;
- }
-
- payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
- // there can only ever be one caption message in a frame's sei
-
- if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
- var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
-
- if (userIdentifier === 'GA94') {
- result.payloadType = payloadType;
- result.payloadSize = payloadSize;
- result.payload = bytes.subarray(i, i + payloadSize);
- break;
- } else {
- result.payload = void 0;
- }
- } // skip the payload and parse the next message
-
-
- i += payloadSize;
- payloadType = 0;
- payloadSize = 0;
- }
-
- return result;
- }; // see ANSI/SCTE 128-1 (2013), section 8.1
-
-
- var parseUserData = function parseUserData(sei) {
- // itu_t_t35_contry_code must be 181 (United States) for
- // captions
- if (sei.payload[0] !== 181) {
- return null;
- } // itu_t_t35_provider_code should be 49 (ATSC) for captions
-
-
- if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
- return null;
- } // the user_identifier should be "GA94" to indicate ATSC1 data
-
-
- if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
- return null;
- } // finally, user_data_type_code should be 0x03 for caption data
-
-
- if (sei.payload[7] !== 0x03) {
- return null;
- } // return the user_data_type_structure and strip the trailing
- // marker bits
-
-
- return sei.payload.subarray(8, sei.payload.length - 1);
- }; // see CEA-708-D, section 4.4
-
-
- var parseCaptionPackets = function parseCaptionPackets(pts, userData) {
- var results = [],
- i,
- count,
- offset,
- data; // if this is just filler, return immediately
-
- if (!(userData[0] & 0x40)) {
- return results;
- } // parse out the cc_data_1 and cc_data_2 fields
-
-
- count = userData[0] & 0x1f;
-
- for (i = 0; i < count; i++) {
- offset = i * 3;
- data = {
- type: userData[offset + 2] & 0x03,
- pts: pts
- }; // capture cc data when cc_valid is 1
-
- if (userData[offset + 2] & 0x04) {
- data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
- results.push(data);
- }
- }
-
- return results;
- };
-
- var discardEmulationPreventionBytes$1 = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- }; // exports
-
-
- var captionPacketParser = {
- parseSei: parseSei,
- parseUserData: parseUserData,
- parseCaptionPackets: parseCaptionPackets,
- discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
- USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
- }; // Link To Transport
- // -----------------
-
- var CaptionStream$1 = function CaptionStream(options) {
- options = options || {};
- CaptionStream.prototype.init.call(this); // parse708captions flag, default to true
-
- this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
- this.captionPackets_ = [];
- this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
- ];
-
- if (this.parse708captions_) {
- this.cc708Stream_ = new Cea708Stream(); // eslint-disable-line no-use-before-define
- }
-
- this.reset(); // forward data and done events from CCs to this CaptionStream
-
- this.ccStreams_.forEach(function (cc) {
- cc.on('data', this.trigger.bind(this, 'data'));
- cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
- cc.on('done', this.trigger.bind(this, 'done'));
- }, this);
-
- if (this.parse708captions_) {
- this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
- this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
- this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
- }
- };
-
- CaptionStream$1.prototype = new stream();
-
- CaptionStream$1.prototype.push = function (event) {
- var sei, userData, newCaptionPackets; // only examine SEI NALs
-
- if (event.nalUnitType !== 'sei_rbsp') {
- return;
- } // parse the sei
-
-
- sei = captionPacketParser.parseSei(event.escapedRBSP); // no payload data, skip
-
- if (!sei.payload) {
- return;
- } // ignore everything but user_data_registered_itu_t_t35
-
-
- if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
- return;
- } // parse out the user data payload
-
-
- userData = captionPacketParser.parseUserData(sei); // ignore unrecognized userData
-
- if (!userData) {
- return;
- } // Sometimes, the same segment # will be downloaded twice. To stop the
- // caption data from being processed twice, we track the latest dts we've
- // received and ignore everything with a dts before that. However, since
- // data for a specific dts can be split across packets on either side of
- // a segment boundary, we need to make sure we *don't* ignore the packets
- // from the *next* segment that have dts === this.latestDts_. By constantly
- // tracking the number of packets received with dts === this.latestDts_, we
- // know how many should be ignored once we start receiving duplicates.
-
-
- if (event.dts < this.latestDts_) {
- // We've started getting older data, so set the flag.
- this.ignoreNextEqualDts_ = true;
- return;
- } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
- this.numSameDts_--;
-
- if (!this.numSameDts_) {
- // We've received the last duplicate packet, time to start processing again
- this.ignoreNextEqualDts_ = false;
- }
-
- return;
- } // parse out CC data packets and save them for later
-
-
- newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
- this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
-
- if (this.latestDts_ !== event.dts) {
- this.numSameDts_ = 0;
- }
-
- this.numSameDts_++;
- this.latestDts_ = event.dts;
- };
-
- CaptionStream$1.prototype.flushCCStreams = function (flushType) {
- this.ccStreams_.forEach(function (cc) {
- return flushType === 'flush' ? cc.flush() : cc.partialFlush();
- }, this);
- };
-
- CaptionStream$1.prototype.flushStream = function (flushType) {
- // make sure we actually parsed captions before proceeding
- if (!this.captionPackets_.length) {
- this.flushCCStreams(flushType);
- return;
- } // In Chrome, the Array#sort function is not stable so add a
- // presortIndex that we can use to ensure we get a stable-sort
-
-
- this.captionPackets_.forEach(function (elem, idx) {
- elem.presortIndex = idx;
- }); // sort caption byte-pairs based on their PTS values
-
- this.captionPackets_.sort(function (a, b) {
- if (a.pts === b.pts) {
- return a.presortIndex - b.presortIndex;
- }
-
- return a.pts - b.pts;
- });
- this.captionPackets_.forEach(function (packet) {
- if (packet.type < 2) {
- // Dispatch packet to the right Cea608Stream
- this.dispatchCea608Packet(packet);
- } else {
- // Dispatch packet to the Cea708Stream
- this.dispatchCea708Packet(packet);
- }
- }, this);
- this.captionPackets_.length = 0;
- this.flushCCStreams(flushType);
- };
-
- CaptionStream$1.prototype.flush = function () {
- return this.flushStream('flush');
- }; // Only called if handling partial data
-
-
- CaptionStream$1.prototype.partialFlush = function () {
- return this.flushStream('partialFlush');
- };
-
- CaptionStream$1.prototype.reset = function () {
- this.latestDts_ = null;
- this.ignoreNextEqualDts_ = false;
- this.numSameDts_ = 0;
- this.activeCea608Channel_ = [null, null];
- this.ccStreams_.forEach(function (ccStream) {
- ccStream.reset();
- });
- }; // From the CEA-608 spec:
-
- /*
- * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
- * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
- * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
- * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
- * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
- * to switch to captioning or Text.
- */
- // With that in mind, we ignore any data between an XDS control code and a
- // subsequent closed-captioning control code.
-
-
- CaptionStream$1.prototype.dispatchCea608Packet = function (packet) {
- // NOTE: packet.type is the CEA608 field
- if (this.setsTextOrXDSActive(packet)) {
- this.activeCea608Channel_[packet.type] = null;
- } else if (this.setsChannel1Active(packet)) {
- this.activeCea608Channel_[packet.type] = 0;
- } else if (this.setsChannel2Active(packet)) {
- this.activeCea608Channel_[packet.type] = 1;
- }
-
- if (this.activeCea608Channel_[packet.type] === null) {
- // If we haven't received anything to set the active channel, or the
- // packets are Text/XDS data, discard the data; we don't want jumbled
- // captions
- return;
- }
-
- this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
- };
-
- CaptionStream$1.prototype.setsChannel1Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1000;
- };
-
- CaptionStream$1.prototype.setsChannel2Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1800;
- };
-
- CaptionStream$1.prototype.setsTextOrXDSActive = function (packet) {
- return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
- };
-
- CaptionStream$1.prototype.dispatchCea708Packet = function (packet) {
- if (this.parse708captions_) {
- this.cc708Stream_.push(packet);
- }
- }; // ----------------------
- // Session to Application
- // ----------------------
- // This hash maps special and extended character codes to their
- // proper Unicode equivalent. The first one-byte key is just a
- // non-standard character code. The two-byte keys that follow are
- // the extended CEA708 character codes, along with the preceding
- // 0x10 extended character byte to distinguish these codes from
- // non-extended character codes. Every CEA708 character code that
- // is not in this object maps directly to a standard unicode
- // character code.
- // The transparent space and non-breaking transparent space are
- // technically not fully supported since there is no code to
- // make them transparent, so they have normal non-transparent
- // stand-ins.
- // The special closed caption (CC) character isn't a standard
- // unicode character, so a fairly similar unicode character was
- // chosen in it's place.
-
-
- var CHARACTER_TRANSLATION_708 = {
- 0x7f: 0x266a,
- // ♪
- 0x1020: 0x20,
- // Transparent Space
- 0x1021: 0xa0,
- // Nob-breaking Transparent Space
- 0x1025: 0x2026,
- // …
- 0x102a: 0x0160,
- // Š
- 0x102c: 0x0152,
- // Œ
- 0x1030: 0x2588,
- // █
- 0x1031: 0x2018,
- // ‘
- 0x1032: 0x2019,
- // ’
- 0x1033: 0x201c,
- // “
- 0x1034: 0x201d,
- // ”
- 0x1035: 0x2022,
- // •
- 0x1039: 0x2122,
- // ™
- 0x103a: 0x0161,
- // š
- 0x103c: 0x0153,
- // œ
- 0x103d: 0x2120,
- // ℠
- 0x103f: 0x0178,
- // Ÿ
- 0x1076: 0x215b,
- // ⅛
- 0x1077: 0x215c,
- // ⅜
- 0x1078: 0x215d,
- // ⅝
- 0x1079: 0x215e,
- // ⅞
- 0x107a: 0x23d0,
- // ⏐
- 0x107b: 0x23a4,
- // ⎤
- 0x107c: 0x23a3,
- // ⎣
- 0x107d: 0x23af,
- // ⎯
- 0x107e: 0x23a6,
- // ⎦
- 0x107f: 0x23a1,
- // ⎡
- 0x10a0: 0x3138 // ㄸ (CC char)
-
- };
-
- var get708CharFromCode = function get708CharFromCode(code) {
- var newCode = CHARACTER_TRANSLATION_708[code] || code;
-
- if (code & 0x1000 && code === newCode) {
- // Invalid extended code
- return '';
- }
-
- return String.fromCharCode(newCode);
- };
-
- var within708TextBlock = function within708TextBlock(b) {
- return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
- };
-
- var Cea708Window = function Cea708Window(windowNum) {
- this.windowNum = windowNum;
- this.reset();
- };
-
- Cea708Window.prototype.reset = function () {
- this.clearText();
- this.pendingNewLine = false;
- this.winAttr = {};
- this.penAttr = {};
- this.penLoc = {};
- this.penColor = {}; // These default values are arbitrary,
- // defineWindow will usually override them
-
- this.visible = 0;
- this.rowLock = 0;
- this.columnLock = 0;
- this.priority = 0;
- this.relativePositioning = 0;
- this.anchorVertical = 0;
- this.anchorHorizontal = 0;
- this.anchorPoint = 0;
- this.rowCount = 1;
- this.virtualRowCount = this.rowCount + 1;
- this.columnCount = 41;
- this.windowStyle = 0;
- this.penStyle = 0;
- };
-
- Cea708Window.prototype.getText = function () {
- return this.rows.join('\n');
- };
-
- Cea708Window.prototype.clearText = function () {
- this.rows = [''];
- this.rowIdx = 0;
- };
-
- Cea708Window.prototype.newLine = function (pts) {
- if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
- this.beforeRowOverflow(pts);
- }
-
- if (this.rows.length > 0) {
- this.rows.push('');
- this.rowIdx++;
- } // Show all virtual rows since there's no visible scrolling
-
-
- while (this.rows.length > this.virtualRowCount) {
- this.rows.shift();
- this.rowIdx--;
- }
- };
-
- Cea708Window.prototype.isEmpty = function () {
- if (this.rows.length === 0) {
- return true;
- } else if (this.rows.length === 1) {
- return this.rows[0] === '';
- }
-
- return false;
- };
-
- Cea708Window.prototype.addText = function (text) {
- this.rows[this.rowIdx] += text;
- };
-
- Cea708Window.prototype.backspace = function () {
- if (!this.isEmpty()) {
- var row = this.rows[this.rowIdx];
- this.rows[this.rowIdx] = row.substr(0, row.length - 1);
- }
- };
-
- var Cea708Service = function Cea708Service(serviceNum) {
- this.serviceNum = serviceNum;
- this.text = '';
- this.currentWindow = new Cea708Window(-1);
- this.windows = [];
- };
- /**
- * Initialize service windows
- * Must be run before service use
- *
- * @param {Integer} pts PTS value
- * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
- */
-
-
- Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
- this.startPts = pts;
-
- for (var win = 0; win < 8; win++) {
- this.windows[win] = new Cea708Window(win);
-
- if (typeof beforeRowOverflow === 'function') {
- this.windows[win].beforeRowOverflow = beforeRowOverflow;
- }
- }
- };
- /**
- * Set current window of service to be affected by commands
- *
- * @param {Integer} windowNum Window number
- */
-
-
- Cea708Service.prototype.setCurrentWindow = function (windowNum) {
- this.currentWindow = this.windows[windowNum];
- };
-
- var Cea708Stream = function Cea708Stream() {
- Cea708Stream.prototype.init.call(this);
- var self = this;
- this.current708Packet = null;
- this.services = {};
-
- this.push = function (packet) {
- if (packet.type === 3) {
- // 708 packet start
- self.new708Packet();
- self.add708Bytes(packet);
- } else {
- if (self.current708Packet === null) {
- // This should only happen at the start of a file if there's no packet start.
- self.new708Packet();
- }
-
- self.add708Bytes(packet);
- }
- };
- };
-
- Cea708Stream.prototype = new stream();
- /**
- * Push current 708 packet, create new 708 packet.
- */
-
- Cea708Stream.prototype.new708Packet = function () {
- if (this.current708Packet !== null) {
- this.push708Packet();
- }
-
- this.current708Packet = {
- data: [],
- ptsVals: []
- };
- };
- /**
- * Add pts and both bytes from packet into current 708 packet.
- */
-
-
- Cea708Stream.prototype.add708Bytes = function (packet) {
- var data = packet.ccData;
- var byte0 = data >>> 8;
- var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
- // that service blocks will always line up with byte pairs.
-
- this.current708Packet.ptsVals.push(packet.pts);
- this.current708Packet.data.push(byte0);
- this.current708Packet.data.push(byte1);
- };
- /**
- * Parse completed 708 packet into service blocks and push each service block.
- */
-
-
- Cea708Stream.prototype.push708Packet = function () {
- var packet708 = this.current708Packet;
- var packetData = packet708.data;
- var serviceNum = null;
- var blockSize = null;
- var i = 0;
- var b = packetData[i++];
- packet708.seq = b >> 6;
- packet708.sizeCode = b & 0x3f; // 0b00111111;
-
- for (; i < packetData.length; i++) {
- b = packetData[i++];
- serviceNum = b >> 5;
- blockSize = b & 0x1f; // 0b00011111
-
- if (serviceNum === 7 && blockSize > 0) {
- // Extended service num
- b = packetData[i++];
- serviceNum = b;
- }
-
- this.pushServiceBlock(serviceNum, i, blockSize);
-
- if (blockSize > 0) {
- i += blockSize - 1;
- }
- }
- };
- /**
- * Parse service block, execute commands, read text.
- *
- * Note: While many of these commands serve important purposes,
- * many others just parse out the parameters or attributes, but
- * nothing is done with them because this is not a full and complete
- * implementation of the entire 708 spec.
- *
- * @param {Integer} serviceNum Service number
- * @param {Integer} start Start index of the 708 packet data
- * @param {Integer} size Block size
- */
-
-
- Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
- var b;
- var i = start;
- var packetData = this.current708Packet.data;
- var service = this.services[serviceNum];
-
- if (!service) {
- service = this.initService(serviceNum, i);
- }
-
- for (; i < start + size && i < packetData.length; i++) {
- b = packetData[i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service);
- } else if (b === 0x10) {
- i = this.extendedCommands(i, service);
- } else if (0x80 <= b && b <= 0x87) {
- i = this.setCurrentWindow(i, service);
- } else if (0x98 <= b && b <= 0x9f) {
- i = this.defineWindow(i, service);
- } else if (b === 0x88) {
- i = this.clearWindows(i, service);
- } else if (b === 0x8c) {
- i = this.deleteWindows(i, service);
- } else if (b === 0x89) {
- i = this.displayWindows(i, service);
- } else if (b === 0x8a) {
- i = this.hideWindows(i, service);
- } else if (b === 0x8b) {
- i = this.toggleWindows(i, service);
- } else if (b === 0x97) {
- i = this.setWindowAttributes(i, service);
- } else if (b === 0x90) {
- i = this.setPenAttributes(i, service);
- } else if (b === 0x91) {
- i = this.setPenColor(i, service);
- } else if (b === 0x92) {
- i = this.setPenLocation(i, service);
- } else if (b === 0x8f) {
- service = this.reset(i, service);
- } else if (b === 0x08) {
- // BS: Backspace
- service.currentWindow.backspace();
- } else if (b === 0x0c) {
- // FF: Form feed
- service.currentWindow.clearText();
- } else if (b === 0x0d) {
- // CR: Carriage return
- service.currentWindow.pendingNewLine = true;
- } else if (b === 0x0e) {
- // HCR: Horizontal carriage return
- service.currentWindow.clearText();
- } else if (b === 0x8d) {
- // DLY: Delay, nothing to do
- i++;
- } else ;
- }
- };
- /**
- * Execute an extended command
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.extendedCommands = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service, true);
- }
-
- return i;
- };
- /**
- * Get PTS value of a given byte index
- *
- * @param {Integer} byteIndex Index of the byte
- * @return {Integer} PTS
- */
-
-
- Cea708Stream.prototype.getPts = function (byteIndex) {
- // There's 1 pts value per 2 bytes
- return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
- };
- /**
- * Initializes a service
- *
- * @param {Integer} serviceNum Service number
- * @return {Service} Initialized service object
- */
-
-
- Cea708Stream.prototype.initService = function (serviceNum, i) {
- var self = this;
- this.services[serviceNum] = new Cea708Service(serviceNum);
- this.services[serviceNum].init(this.getPts(i), function (pts) {
- self.flushDisplayed(pts, self.services[serviceNum]);
- });
- return this.services[serviceNum];
- };
- /**
- * Execute text writing to current window
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.handleText = function (i, service, isExtended) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var extended = isExtended ? 0x1000 : 0x0000;
- var char = get708CharFromCode(extended | b);
- var win = service.currentWindow;
-
- if (win.pendingNewLine && !win.isEmpty()) {
- win.newLine(this.getPts(i));
- }
-
- win.pendingNewLine = false;
- win.addText(char);
- return i;
- };
- /**
- * Parse and execute the CW# command.
- *
- * Set the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setCurrentWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- return i;
- };
- /**
- * Parse and execute the DF# command.
- *
- * Define a window and set it as the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.defineWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- var win = service.currentWindow;
- b = packetData[++i];
- win.visible = (b & 0x20) >> 5; // v
-
- win.rowLock = (b & 0x10) >> 4; // rl
-
- win.columnLock = (b & 0x08) >> 3; // cl
-
- win.priority = b & 0x07; // p
-
- b = packetData[++i];
- win.relativePositioning = (b & 0x80) >> 7; // rp
-
- win.anchorVertical = b & 0x7f; // av
-
- b = packetData[++i];
- win.anchorHorizontal = b; // ah
-
- b = packetData[++i];
- win.anchorPoint = (b & 0xf0) >> 4; // ap
-
- win.rowCount = b & 0x0f; // rc
-
- b = packetData[++i];
- win.columnCount = b & 0x3f; // cc
-
- b = packetData[++i];
- win.windowStyle = (b & 0x38) >> 3; // ws
-
- win.penStyle = b & 0x07; // ps
- // The spec says there are (rowCount+1) "virtual rows"
-
- win.virtualRowCount = win.rowCount + 1;
- return i;
- };
- /**
- * Parse and execute the SWA command.
- *
- * Set attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setWindowAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var winAttr = service.currentWindow.winAttr;
- b = packetData[++i];
- winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
-
- winAttr.fillRed = (b & 0x30) >> 4; // fr
-
- winAttr.fillGreen = (b & 0x0c) >> 2; // fg
-
- winAttr.fillBlue = b & 0x03; // fb
-
- b = packetData[++i];
- winAttr.borderType = (b & 0xc0) >> 6; // bt
-
- winAttr.borderRed = (b & 0x30) >> 4; // br
-
- winAttr.borderGreen = (b & 0x0c) >> 2; // bg
-
- winAttr.borderBlue = b & 0x03; // bb
-
- b = packetData[++i];
- winAttr.borderType += (b & 0x80) >> 5; // bt
-
- winAttr.wordWrap = (b & 0x40) >> 6; // ww
-
- winAttr.printDirection = (b & 0x30) >> 4; // pd
-
- winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
-
- winAttr.justify = b & 0x03; // j
-
- b = packetData[++i];
- winAttr.effectSpeed = (b & 0xf0) >> 4; // es
-
- winAttr.effectDirection = (b & 0x0c) >> 2; // ed
-
- winAttr.displayEffect = b & 0x03; // de
-
- return i;
- };
- /**
- * Gather text from all displayed windows and push a caption to output.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.flushDisplayed = function (pts, service) {
- var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
- // display text in the correct order, but sample files so far have not shown any issue.
-
- for (var winId = 0; winId < 8; winId++) {
- if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
- displayedText.push(service.windows[winId].getText());
- }
- }
-
- service.endPts = pts;
- service.text = displayedText.join('\n\n');
- this.pushCaption(service);
- service.startPts = pts;
- };
- /**
- * Push a caption to output if the caption contains text.
- *
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.pushCaption = function (service) {
- if (service.text !== '') {
- this.trigger('data', {
- startPts: service.startPts,
- endPts: service.endPts,
- text: service.text,
- stream: 'cc708_' + service.serviceNum
- });
- service.text = '';
- service.startPts = service.endPts;
- }
- };
- /**
- * Parse and execute the DSW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.displayWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the HDW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.hideWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 0;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the TGW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.toggleWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible ^= 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the CLW command.
- *
- * Clear text of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.clearWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].clearText();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the DLW command.
- *
- * Re-initialize windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.deleteWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].reset();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the SPA command.
- *
- * Set pen attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penAttr = service.currentWindow.penAttr;
- b = packetData[++i];
- penAttr.textTag = (b & 0xf0) >> 4; // tt
-
- penAttr.offset = (b & 0x0c) >> 2; // o
-
- penAttr.penSize = b & 0x03; // s
-
- b = packetData[++i];
- penAttr.italics = (b & 0x80) >> 7; // i
-
- penAttr.underline = (b & 0x40) >> 6; // u
-
- penAttr.edgeType = (b & 0x38) >> 3; // et
-
- penAttr.fontStyle = b & 0x07; // fs
-
- return i;
- };
- /**
- * Parse and execute the SPC command.
- *
- * Set pen color of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenColor = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penColor = service.currentWindow.penColor;
- b = packetData[++i];
- penColor.fgOpacity = (b & 0xc0) >> 6; // fo
-
- penColor.fgRed = (b & 0x30) >> 4; // fr
-
- penColor.fgGreen = (b & 0x0c) >> 2; // fg
-
- penColor.fgBlue = b & 0x03; // fb
-
- b = packetData[++i];
- penColor.bgOpacity = (b & 0xc0) >> 6; // bo
-
- penColor.bgRed = (b & 0x30) >> 4; // br
-
- penColor.bgGreen = (b & 0x0c) >> 2; // bg
-
- penColor.bgBlue = b & 0x03; // bb
-
- b = packetData[++i];
- penColor.edgeRed = (b & 0x30) >> 4; // er
-
- penColor.edgeGreen = (b & 0x0c) >> 2; // eg
-
- penColor.edgeBlue = b & 0x03; // eb
-
- return i;
- };
- /**
- * Parse and execute the SPL command.
- *
- * Set pen location of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenLocation = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
-
- service.currentWindow.pendingNewLine = true;
- b = packetData[++i];
- penLoc.row = b & 0x0f; // r
-
- b = packetData[++i];
- penLoc.column = b & 0x3f; // c
-
- return i;
- };
- /**
- * Execute the RST command.
- *
- * Reset service to a clean slate. Re-initialize.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Service} Re-initialized service
- */
-
-
- Cea708Stream.prototype.reset = function (i, service) {
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
- return this.initService(service.serviceNum, i);
- }; // This hash maps non-ASCII, special, and extended character codes to their
- // proper Unicode equivalent. The first keys that are only a single byte
- // are the non-standard ASCII characters, which simply map the CEA608 byte
- // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
- // character codes, but have their MSB bitmasked with 0x03 so that a lookup
- // can be performed regardless of the field and data channel on which the
- // character code was received.
-
-
- var CHARACTER_TRANSLATION = {
- 0x2a: 0xe1,
- // á
- 0x5c: 0xe9,
- // é
- 0x5e: 0xed,
- // í
- 0x5f: 0xf3,
- // ó
- 0x60: 0xfa,
- // ú
- 0x7b: 0xe7,
- // ç
- 0x7c: 0xf7,
- // ÷
- 0x7d: 0xd1,
- // Ñ
- 0x7e: 0xf1,
- // ñ
- 0x7f: 0x2588,
- // █
- 0x0130: 0xae,
- // ®
- 0x0131: 0xb0,
- // °
- 0x0132: 0xbd,
- // ½
- 0x0133: 0xbf,
- // ¿
- 0x0134: 0x2122,
- // ™
- 0x0135: 0xa2,
- // ¢
- 0x0136: 0xa3,
- // £
- 0x0137: 0x266a,
- // ♪
- 0x0138: 0xe0,
- // à
- 0x0139: 0xa0,
- //
- 0x013a: 0xe8,
- // è
- 0x013b: 0xe2,
- // â
- 0x013c: 0xea,
- // ê
- 0x013d: 0xee,
- // î
- 0x013e: 0xf4,
- // ô
- 0x013f: 0xfb,
- // û
- 0x0220: 0xc1,
- // Á
- 0x0221: 0xc9,
- // É
- 0x0222: 0xd3,
- // Ó
- 0x0223: 0xda,
- // Ú
- 0x0224: 0xdc,
- // Ü
- 0x0225: 0xfc,
- // ü
- 0x0226: 0x2018,
- // ‘
- 0x0227: 0xa1,
- // ¡
- 0x0228: 0x2a,
- // *
- 0x0229: 0x27,
- // '
- 0x022a: 0x2014,
- // —
- 0x022b: 0xa9,
- // ©
- 0x022c: 0x2120,
- // ℠
- 0x022d: 0x2022,
- // •
- 0x022e: 0x201c,
- // “
- 0x022f: 0x201d,
- // ”
- 0x0230: 0xc0,
- // À
- 0x0231: 0xc2,
- // Â
- 0x0232: 0xc7,
- // Ç
- 0x0233: 0xc8,
- // È
- 0x0234: 0xca,
- // Ê
- 0x0235: 0xcb,
- // Ë
- 0x0236: 0xeb,
- // ë
- 0x0237: 0xce,
- // Î
- 0x0238: 0xcf,
- // Ï
- 0x0239: 0xef,
- // ï
- 0x023a: 0xd4,
- // Ô
- 0x023b: 0xd9,
- // Ù
- 0x023c: 0xf9,
- // ù
- 0x023d: 0xdb,
- // Û
- 0x023e: 0xab,
- // «
- 0x023f: 0xbb,
- // »
- 0x0320: 0xc3,
- // Ã
- 0x0321: 0xe3,
- // ã
- 0x0322: 0xcd,
- // Í
- 0x0323: 0xcc,
- // Ì
- 0x0324: 0xec,
- // ì
- 0x0325: 0xd2,
- // Ò
- 0x0326: 0xf2,
- // ò
- 0x0327: 0xd5,
- // Õ
- 0x0328: 0xf5,
- // õ
- 0x0329: 0x7b,
- // {
- 0x032a: 0x7d,
- // }
- 0x032b: 0x5c,
- // \
- 0x032c: 0x5e,
- // ^
- 0x032d: 0x5f,
- // _
- 0x032e: 0x7c,
- // |
- 0x032f: 0x7e,
- // ~
- 0x0330: 0xc4,
- // Ä
- 0x0331: 0xe4,
- // ä
- 0x0332: 0xd6,
- // Ö
- 0x0333: 0xf6,
- // ö
- 0x0334: 0xdf,
- // ß
- 0x0335: 0xa5,
- // ¥
- 0x0336: 0xa4,
- // ¤
- 0x0337: 0x2502,
- // │
- 0x0338: 0xc5,
- // Å
- 0x0339: 0xe5,
- // å
- 0x033a: 0xd8,
- // Ø
- 0x033b: 0xf8,
- // ø
- 0x033c: 0x250c,
- // ┌
- 0x033d: 0x2510,
- // ┐
- 0x033e: 0x2514,
- // └
- 0x033f: 0x2518 // ┘
-
- };
-
- var getCharFromCode = function getCharFromCode(code) {
- if (code === null) {
- return '';
- }
-
- code = CHARACTER_TRANSLATION[code] || code;
- return String.fromCharCode(code);
- }; // the index of the last row in a CEA-608 display buffer
-
-
- var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
- // getting it through bit logic.
-
- var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // CEA-608 captions are rendered onto a 34x15 matrix of character
- // cells. The "bottom" row is the last element in the outer array.
-
- var createDisplayBuffer = function createDisplayBuffer() {
- var result = [],
- i = BOTTOM_ROW + 1;
-
- while (i--) {
- result.push('');
- }
-
- return result;
- };
-
- var Cea608Stream = function Cea608Stream(field, dataChannel) {
- Cea608Stream.prototype.init.call(this);
- this.field_ = field || 0;
- this.dataChannel_ = dataChannel || 0;
- this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
- this.setConstants();
- this.reset();
-
- this.push = function (packet) {
- var data, swap, char0, char1, text; // remove the parity bits
-
- data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
-
- if (data === this.lastControlCode_) {
- this.lastControlCode_ = null;
- return;
- } // Store control codes
-
-
- if ((data & 0xf000) === 0x1000) {
- this.lastControlCode_ = data;
- } else if (data !== this.PADDING_) {
- this.lastControlCode_ = null;
- }
-
- char0 = data >>> 8;
- char1 = data & 0xff;
-
- if (data === this.PADDING_) {
- return;
- } else if (data === this.RESUME_CAPTION_LOADING_) {
- this.mode_ = 'popOn';
- } else if (data === this.END_OF_CAPTION_) {
- // If an EOC is received while in paint-on mode, the displayed caption
- // text should be swapped to non-displayed memory as if it was a pop-on
- // caption. Because of that, we should explicitly switch back to pop-on
- // mode
- this.mode_ = 'popOn';
- this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
-
- this.flushDisplayed(packet.pts); // flip memory
-
- swap = this.displayed_;
- this.displayed_ = this.nonDisplayed_;
- this.nonDisplayed_ = swap; // start measuring the time to display the caption
-
- this.startPts_ = packet.pts;
- } else if (data === this.ROLL_UP_2_ROWS_) {
- this.rollUpRows_ = 2;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_3_ROWS_) {
- this.rollUpRows_ = 3;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_4_ROWS_) {
- this.rollUpRows_ = 4;
- this.setRollUp(packet.pts);
- } else if (data === this.CARRIAGE_RETURN_) {
- this.clearFormatting(packet.pts);
- this.flushDisplayed(packet.pts);
- this.shiftRowsUp_();
- this.startPts_ = packet.pts;
- } else if (data === this.BACKSPACE_) {
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- }
- } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
- this.nonDisplayed_ = createDisplayBuffer();
- } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
- if (this.mode_ !== 'paintOn') {
- // NOTE: This should be removed when proper caption positioning is
- // implemented
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- }
-
- this.mode_ = 'paintOn';
- this.startPts_ = packet.pts; // Append special characters to caption text
- } else if (this.isSpecialCharacter(char0, char1)) {
- // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Append extended characters to caption text
- } else if (this.isExtCharacter(char0, char1)) {
- // Extended characters always follow their "non-extended" equivalents.
- // IE if a "è" is desired, you'll always receive "eè"; non-compliant
- // decoders are supposed to drop the "è", while compliant decoders
- // backspace the "e" and insert "è".
- // Delete the previous character
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- } // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
-
-
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Process mid-row codes
- } else if (this.isMidRowCode(char0, char1)) {
- // Attributes are not additive, so clear all formatting
- this.clearFormatting(packet.pts); // According to the standard, mid-row codes
- // should be replaced with spaces, so add one now
-
- this[this.mode_](packet.pts, ' ');
- this.column_++;
-
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
-
- if ((char1 & 0x1) === 0x1) {
- this.addFormatting(packet.pts, ['u']);
- } // Detect offset control codes and adjust cursor
-
- } else if (this.isOffsetControlCode(char0, char1)) {
- // Cursor position is set by indent PAC (see below) in 4-column
- // increments, with an additional offset code of 1-3 to reach any
- // of the 32 columns specified by CEA-608. So all we need to do
- // here is increment the column cursor by the given offset.
- this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
- } else if (this.isPAC(char0, char1)) {
- // There's no logic for PAC -> row mapping, so we have to just
- // find the row code in an array and use its index :(
- var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
-
- if (this.mode_ === 'rollUp') {
- // This implies that the base row is incorrectly set.
- // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
- // of roll-up rows set.
- if (row - this.rollUpRows_ + 1 < 0) {
- row = this.rollUpRows_ - 1;
- }
-
- this.setRollUp(packet.pts, row);
- }
-
- if (row !== this.row_) {
- // formatting is only persistent for current row
- this.clearFormatting(packet.pts);
- this.row_ = row;
- } // All PACs can apply underline, so detect and apply
- // (All odd-numbered second bytes set underline)
-
-
- if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
- this.addFormatting(packet.pts, ['u']);
- }
-
- if ((data & 0x10) === 0x10) {
- // We've got an indent level code. Each successive even number
- // increments the column cursor by 4, so we can get the desired
- // column position by bit-shifting to the right (to get n/2)
- // and multiplying by 4.
- this.column_ = ((data & 0xe) >> 1) * 4;
- }
-
- if (this.isColorPAC(char1)) {
- // it's a color code, though we only support white, which
- // can be either normal or italicized. white italics can be
- // either 0x4e or 0x6e depending on the row, so we just
- // bitwise-and with 0xe to see if italics should be turned on
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
- } // We have a normal character in char0, and possibly one in char1
-
- } else if (this.isNormalChar(char0)) {
- if (char1 === 0x00) {
- char1 = null;
- }
-
- text = getCharFromCode(char0);
- text += getCharFromCode(char1);
- this[this.mode_](packet.pts, text);
- this.column_ += text.length;
- } // finish data processing
-
- };
- };
-
- Cea608Stream.prototype = new stream(); // Trigger a cue point that captures the current state of the
- // display buffer
-
- Cea608Stream.prototype.flushDisplayed = function (pts) {
- var content = this.displayed_ // remove spaces from the start and end of the string
- .map(function (row) {
- try {
- return row.trim();
- } catch (e) {
- // Ordinarily, this shouldn't happen. However, caption
- // parsing errors should not throw exceptions and
- // break playback.
- // eslint-disable-next-line no-console
- console.error('Skipping malformed caption.');
- return '';
- }
- }) // combine all text rows to display in one cue
- .join('\n') // and remove blank rows from the start and end, but not the middle
- .replace(/^\n+|\n+$/g, '');
-
- if (content.length) {
- this.trigger('data', {
- startPts: this.startPts_,
- endPts: pts,
- text: content,
- stream: this.name_
- });
- }
- };
- /**
- * Zero out the data, used for startup and on seek
- */
-
-
- Cea608Stream.prototype.reset = function () {
- this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
- // actually display captions. If a caption is shifted to a row
- // with a lower index than this, it is cleared from the display
- // buffer
-
- this.topRow_ = 0;
- this.startPts_ = 0;
- this.displayed_ = createDisplayBuffer();
- this.nonDisplayed_ = createDisplayBuffer();
- this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
-
- this.column_ = 0;
- this.row_ = BOTTOM_ROW;
- this.rollUpRows_ = 2; // This variable holds currently-applied formatting
-
- this.formatting_ = [];
- };
- /**
- * Sets up control code and related constants for this instance
- */
-
-
- Cea608Stream.prototype.setConstants = function () {
- // The following attributes have these uses:
- // ext_ : char0 for mid-row codes, and the base for extended
- // chars (ext_+0, ext_+1, and ext_+2 are char0s for
- // extended codes)
- // control_: char0 for control codes, except byte-shifted to the
- // left so that we can do this.control_ | CONTROL_CODE
- // offset_: char0 for tab offset codes
- //
- // It's also worth noting that control codes, and _only_ control codes,
- // differ between field 1 and field2. Field 2 control codes are always
- // their field 1 value plus 1. That's why there's the "| field" on the
- // control value.
- if (this.dataChannel_ === 0) {
- this.BASE_ = 0x10;
- this.EXT_ = 0x11;
- this.CONTROL_ = (0x14 | this.field_) << 8;
- this.OFFSET_ = 0x17;
- } else if (this.dataChannel_ === 1) {
- this.BASE_ = 0x18;
- this.EXT_ = 0x19;
- this.CONTROL_ = (0x1c | this.field_) << 8;
- this.OFFSET_ = 0x1f;
- } // Constants for the LSByte command codes recognized by Cea608Stream. This
- // list is not exhaustive. For a more comprehensive listing and semantics see
- // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
- // Padding
-
-
- this.PADDING_ = 0x0000; // Pop-on Mode
-
- this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
- this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
-
- this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
- this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
- this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
- this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
-
- this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
-
- this.BACKSPACE_ = this.CONTROL_ | 0x21;
- this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
- this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
- };
- /**
- * Detects if the 2-byte packet data is a special character
- *
- * Special characters have a second byte in the range 0x30 to 0x3f,
- * with the first byte being 0x11 (for data channel 1) or 0x19 (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an special character
- */
-
-
- Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet data is an extended character
- *
- * Extended characters have a second byte in the range 0x20 to 0x3f,
- * with the first byte being 0x12 or 0x13 (for data channel 1) or
- * 0x1a or 0x1b (for data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an extended character
- */
-
-
- Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
- return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet is a mid-row code
- *
- * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
- * the first byte being 0x11 (for data channel 1) or 0x19 (for data
- * channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a mid-row code
- */
-
-
- Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
- };
- /**
- * Detects if the 2-byte packet is an offset control code
- *
- * Offset control codes have a second byte in the range 0x21 to 0x23,
- * with the first byte being 0x17 (for data channel 1) or 0x1f (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an offset control code
- */
-
-
- Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
- return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
- };
- /**
- * Detects if the 2-byte packet is a Preamble Address Code
- *
- * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
- * or 0x18 to 0x1f (for data channel 2), with the second byte in the
- * range 0x40 to 0x7f.
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a PAC
- */
-
-
- Cea608Stream.prototype.isPAC = function (char0, char1) {
- return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
- };
- /**
- * Detects if a packet's second byte is in the range of a PAC color code
- *
- * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
- * 0x60 to 0x6f.
- *
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the byte is a color PAC
- */
-
-
- Cea608Stream.prototype.isColorPAC = function (char1) {
- return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
- };
- /**
- * Detects if a single byte is in the range of a normal character
- *
- * Normal text bytes are in the range 0x20 to 0x7f.
- *
- * @param {Integer} char The byte
- * @return {Boolean} Whether the byte is a normal character
- */
-
-
- Cea608Stream.prototype.isNormalChar = function (char) {
- return char >= 0x20 && char <= 0x7f;
- };
- /**
- * Configures roll-up
- *
- * @param {Integer} pts Current PTS
- * @param {Integer} newBaseRow Used by PACs to slide the current window to
- * a new position
- */
-
-
- Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
- // Reset the base row to the bottom row when switching modes
- if (this.mode_ !== 'rollUp') {
- this.row_ = BOTTOM_ROW;
- this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
-
- this.flushDisplayed(pts);
- this.nonDisplayed_ = createDisplayBuffer();
- this.displayed_ = createDisplayBuffer();
- }
-
- if (newBaseRow !== undefined && newBaseRow !== this.row_) {
- // move currently displayed captions (up or down) to the new base row
- for (var i = 0; i < this.rollUpRows_; i++) {
- this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
- this.displayed_[this.row_ - i] = '';
- }
- }
-
- if (newBaseRow === undefined) {
- newBaseRow = this.row_;
- }
-
- this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
- }; // Adds the opening HTML tag for the passed character to the caption text,
- // and keeps track of it for later closing
-
-
- Cea608Stream.prototype.addFormatting = function (pts, format) {
- this.formatting_ = this.formatting_.concat(format);
- var text = format.reduce(function (text, format) {
- return text + '<' + format + '>';
- }, '');
- this[this.mode_](pts, text);
- }; // Adds HTML closing tags for current formatting to caption text and
- // clears remembered formatting
-
-
- Cea608Stream.prototype.clearFormatting = function (pts) {
- if (!this.formatting_.length) {
- return;
- }
-
- var text = this.formatting_.reverse().reduce(function (text, format) {
- return text + '' + format + '>';
- }, '');
- this.formatting_ = [];
- this[this.mode_](pts, text);
- }; // Mode Implementations
-
-
- Cea608Stream.prototype.popOn = function (pts, text) {
- var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
-
- baseRow += text;
- this.nonDisplayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.rollUp = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.shiftRowsUp_ = function () {
- var i; // clear out inactive rows
-
- for (i = 0; i < this.topRow_; i++) {
- this.displayed_[i] = '';
- }
-
- for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
- this.displayed_[i] = '';
- } // shift displayed rows up
-
-
- for (i = this.topRow_; i < this.row_; i++) {
- this.displayed_[i] = this.displayed_[i + 1];
- } // clear out the bottom row
-
-
- this.displayed_[this.row_] = '';
- };
-
- Cea608Stream.prototype.paintOn = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- }; // exports
-
-
- var captionStream = {
- CaptionStream: CaptionStream$1,
- Cea608Stream: Cea608Stream,
- Cea708Stream: Cea708Stream
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var streamTypes = {
- H264_STREAM_TYPE: 0x1B,
- ADTS_STREAM_TYPE: 0x0F,
- METADATA_STREAM_TYPE: 0x15
- };
- var MAX_TS = 8589934592;
- var RO_THRESH = 4294967296;
- var TYPE_SHARED = 'shared';
-
- var handleRollover$1 = function handleRollover(value, reference) {
- var direction = 1;
-
- if (value > reference) {
- // If the current timestamp value is greater than our reference timestamp and we detect a
- // timestamp rollover, this means the roll over is happening in the opposite direction.
- // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
- // point will be set to a small number, e.g. 1. The user then seeks backwards over the
- // rollover point. In loading this segment, the timestamp values will be very large,
- // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
- // the time stamp to be `value - 2^33`.
- direction = -1;
- } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
- // cause an incorrect adjustment.
-
-
- while (Math.abs(reference - value) > RO_THRESH) {
- value += direction * MAX_TS;
- }
-
- return value;
- };
-
- var TimestampRolloverStream$1 = function TimestampRolloverStream(type) {
- var lastDTS, referenceDTS;
- TimestampRolloverStream.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
- // video and audio. We could use `undefined` here, but having a string
- // makes debugging a little clearer.
-
- this.type_ = type || TYPE_SHARED;
-
- this.push = function (data) {
- // Any "shared" rollover streams will accept _all_ data. Otherwise,
- // streams will only accept data that matches their type.
- if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
- return;
- }
-
- if (referenceDTS === undefined) {
- referenceDTS = data.dts;
- }
-
- data.dts = handleRollover$1(data.dts, referenceDTS);
- data.pts = handleRollover$1(data.pts, referenceDTS);
- lastDTS = data.dts;
- this.trigger('data', data);
- };
-
- this.flush = function () {
- referenceDTS = lastDTS;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.discontinuity = function () {
- referenceDTS = void 0;
- lastDTS = void 0;
- };
-
- this.reset = function () {
- this.discontinuity();
- this.trigger('reset');
- };
- };
-
- TimestampRolloverStream$1.prototype = new stream();
- var timestampRolloverStream = {
- TimestampRolloverStream: TimestampRolloverStream$1,
- handleRollover: handleRollover$1
- };
-
- var percentEncode$1 = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- },
- // return the string representation of the specified byte range,
- // interpreted as UTf-8.
- parseUtf8 = function parseUtf8(bytes, start, end) {
- return decodeURIComponent(percentEncode$1(bytes, start, end));
- },
- // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
- parseIso88591$1 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
- },
- parseSyncSafeInteger$1 = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- },
- tagParsers = {
- TXXX: function TXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the text fields
- tag.description = parseUtf8(tag.data, 1, i); // do not include the null terminator in the tag value
-
- tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
- break;
- }
- }
-
- tag.data = tag.value;
- },
- WXXX: function WXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.description = parseUtf8(tag.data, 1, i);
- tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
- break;
- }
- }
- },
- PRIV: function PRIV(tag) {
- var i;
-
- for (i = 0; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.owner = parseIso88591$1(tag.data, 0, i);
- break;
- }
- }
-
- tag.privateData = tag.data.subarray(i + 1);
- tag.data = tag.privateData;
- }
- },
- _MetadataStream;
-
- _MetadataStream = function MetadataStream(options) {
- var settings = {
- debug: !!(options && options.debug),
- // the bytes of the program-level descriptor field in MP2T
- // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
- // program element descriptors"
- descriptor: options && options.descriptor
- },
- // the total size in bytes of the ID3 tag being parsed
- tagSize = 0,
- // tag data that is not complete enough to be parsed
- buffer = [],
- // the total number of bytes currently in the buffer
- bufferSize = 0,
- i;
-
- _MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
- // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
-
-
- this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
-
- if (settings.descriptor) {
- for (i = 0; i < settings.descriptor.length; i++) {
- this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
- }
- }
-
- this.push = function (chunk) {
- var tag, frameStart, frameSize, frame, i, frameHeader;
-
- if (chunk.type !== 'timed-metadata') {
- return;
- } // if data_alignment_indicator is set in the PES header,
- // we must have the start of a new ID3 tag. Assume anything
- // remaining in the buffer was malformed and throw it out
-
-
- if (chunk.dataAlignmentIndicator) {
- bufferSize = 0;
- buffer.length = 0;
- } // ignore events that don't look like ID3 data
-
-
- if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) {
- if (settings.debug) {
- // eslint-disable-next-line no-console
- console.log('Skipping unrecognized metadata packet');
- }
-
- return;
- } // add this chunk to the data we've collected so far
-
-
- buffer.push(chunk);
- bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
-
- if (buffer.length === 1) {
- // the frame size is transmitted as a 28-bit integer in the
- // last four bytes of the ID3 header.
- // The most significant bit of each byte is dropped and the
- // results concatenated to recover the actual value.
- tagSize = parseSyncSafeInteger$1(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
- // convenient for our comparisons to include it
-
- tagSize += 10;
- } // if the entire frame has not arrived, wait for more data
-
-
- if (bufferSize < tagSize) {
- return;
- } // collect the entire frame so it can be parsed
-
-
- tag = {
- data: new Uint8Array(tagSize),
- frames: [],
- pts: buffer[0].pts,
- dts: buffer[0].dts
- };
-
- for (i = 0; i < tagSize;) {
- tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
- i += buffer[0].data.byteLength;
- bufferSize -= buffer[0].data.byteLength;
- buffer.shift();
- } // find the start of the first frame and the end of the tag
-
-
- frameStart = 10;
-
- if (tag.data[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger$1(tag.data.subarray(10, 14)); // clip any padding off the end
-
- tagSize -= parseSyncSafeInteger$1(tag.data.subarray(16, 20));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger$1(tag.data.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- // eslint-disable-next-line no-console
- return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
- }
-
- frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
- frame = {
- id: frameHeader,
- data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
- };
- frame.key = frame.id;
-
- if (tagParsers[frame.id]) {
- tagParsers[frame.id](frame); // handle the special PRIV frame used to indicate the start
- // time for raw AAC data
-
- if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.data,
- size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
- // on the value of this frame
- // we couldn't have known the appropriate pts and dts before
- // parsing this ID3 tag so set those values now
-
- if (tag.pts === undefined && tag.dts === undefined) {
- tag.pts = frame.timeStamp;
- tag.dts = frame.timeStamp;
- }
-
- this.trigger('timestamp', frame);
- }
- }
-
- tag.frames.push(frame);
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < tagSize);
-
- this.trigger('data', tag);
- };
- };
-
- _MetadataStream.prototype = new stream();
- var metadataStream = _MetadataStream;
- var TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
-
- var _TransportPacketStream, _TransportParseStream, _ElementaryStream; // constants
-
-
- var MP2T_PACKET_LENGTH$1 = 188,
- // bytes
- SYNC_BYTE$1 = 0x47;
- /**
- * Splits an incoming stream of binary data into MPEG-2 Transport
- * Stream packets.
- */
-
- _TransportPacketStream = function TransportPacketStream() {
- var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
- bytesInBuffer = 0;
-
- _TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
-
- /**
- * Split a stream of data into M2TS packets
- **/
-
-
- this.push = function (bytes) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH$1,
- everything; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (bytesInBuffer) {
- everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
- everything.set(buffer.subarray(0, bytesInBuffer));
- everything.set(bytes, bytesInBuffer);
- bytesInBuffer = 0;
- } else {
- everything = bytes;
- } // While we have enough data for a packet
-
-
- while (endIndex < everything.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
- // We found a packet so emit it and jump one whole packet forward in
- // the stream
- this.trigger('data', everything.subarray(startIndex, endIndex));
- startIndex += MP2T_PACKET_LENGTH$1;
- endIndex += MP2T_PACKET_LENGTH$1;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // If there was some data left over at the end of the segment that couldn't
- // possibly be a whole packet, keep it because it might be the start of a packet
- // that continues in the next segment
-
-
- if (startIndex < everything.byteLength) {
- buffer.set(everything.subarray(startIndex), 0);
- bytesInBuffer = everything.byteLength - startIndex;
- }
- };
- /**
- * Passes identified M2TS packets to the TransportParseStream to be parsed
- **/
-
-
- this.flush = function () {
- // If the buffer contains a whole packet when we are being flushed, emit it
- // and empty the buffer. Otherwise hold onto the data because it may be
- // important for decoding the next segment
- if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
- this.trigger('data', buffer);
- bytesInBuffer = 0;
- }
-
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.reset = function () {
- bytesInBuffer = 0;
- this.trigger('reset');
- };
- };
-
- _TransportPacketStream.prototype = new stream();
- /**
- * Accepts an MP2T TransportPacketStream and emits data events with parsed
- * forms of the individual transport stream packets.
- */
-
- _TransportParseStream = function TransportParseStream() {
- var parsePsi, parsePat, parsePmt, self;
-
- _TransportParseStream.prototype.init.call(this);
-
- self = this;
- this.packetsWaitingForPmt = [];
- this.programMapTable = undefined;
-
- parsePsi = function parsePsi(payload, psi) {
- var offset = 0; // PSI packets may be split into multiple sections and those
- // sections may be split into multiple packets. If a PSI
- // section starts in this packet, the payload_unit_start_indicator
- // will be true and the first byte of the payload will indicate
- // the offset from the current position to the start of the
- // section.
-
- if (psi.payloadUnitStartIndicator) {
- offset += payload[offset] + 1;
- }
-
- if (psi.type === 'pat') {
- parsePat(payload.subarray(offset), psi);
- } else {
- parsePmt(payload.subarray(offset), psi);
- }
- };
-
- parsePat = function parsePat(payload, pat) {
- pat.section_number = payload[7]; // eslint-disable-line camelcase
-
- pat.last_section_number = payload[8]; // eslint-disable-line camelcase
- // skip the PSI header and parse the first PMT entry
-
- self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
- pat.pmtPid = self.pmtPid;
- };
- /**
- * Parse out the relevant fields of a Program Map Table (PMT).
- * @param payload {Uint8Array} the PMT-specific portion of an MP2T
- * packet. The first byte in this array should be the table_id
- * field.
- * @param pmt {object} the object that should be decorated with
- * fields parsed from the PMT.
- */
-
-
- parsePmt = function parsePmt(payload, pmt) {
- var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
- // take effect. We don't believe this should ever be the case
- // for HLS but we'll ignore "forward" PMT declarations if we see
- // them. Future PMT declarations have the current_next_indicator
- // set to zero.
-
- if (!(payload[5] & 0x01)) {
- return;
- } // overwrite any existing program map table
-
-
- self.programMapTable = {
- video: null,
- audio: null,
- 'timed-metadata': {}
- }; // the mapping table ends at the end of the current section
-
- sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
- tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
- // long the program info descriptors are
-
- programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
-
- offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- var streamType = payload[offset];
- var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
- // TODO: should this be done for metadata too? for now maintain behavior of
- // multiple metadata streams
-
- if (streamType === streamTypes.H264_STREAM_TYPE && self.programMapTable.video === null) {
- self.programMapTable.video = pid;
- } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
- self.programMapTable.audio = pid;
- } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
- // map pid to stream type for metadata streams
- self.programMapTable['timed-metadata'][pid] = streamType;
- } // move to the next table entry
- // skip past the elementary stream descriptors, if present
-
-
- offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
- } // record the map on the packet as well
-
-
- pmt.programMapTable = self.programMapTable;
- };
- /**
- * Deliver a new MP2T packet to the next stream in the pipeline.
- */
-
-
- this.push = function (packet) {
- var result = {},
- offset = 4;
- result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
-
- result.pid = packet[1] & 0x1f;
- result.pid <<= 8;
- result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
- // fifth byte of the TS packet header. The adaptation field is
- // used to add stuffing to PES packets that don't fill a complete
- // TS packet, and to specify some forms of timing and control data
- // that we do not currently use.
-
- if ((packet[3] & 0x30) >>> 4 > 0x01) {
- offset += packet[offset] + 1;
- } // parse the rest of the packet based on the type
-
-
- if (result.pid === 0) {
- result.type = 'pat';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result);
- } else if (result.pid === this.pmtPid) {
- result.type = 'pmt';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
-
- while (this.packetsWaitingForPmt.length) {
- this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
- }
- } else if (this.programMapTable === undefined) {
- // When we have not seen a PMT yet, defer further processing of
- // PES packets until one has been parsed
- this.packetsWaitingForPmt.push([packet, offset, result]);
- } else {
- this.processPes_(packet, offset, result);
- }
- };
-
- this.processPes_ = function (packet, offset, result) {
- // set the appropriate stream type
- if (result.pid === this.programMapTable.video) {
- result.streamType = streamTypes.H264_STREAM_TYPE;
- } else if (result.pid === this.programMapTable.audio) {
- result.streamType = streamTypes.ADTS_STREAM_TYPE;
- } else {
- // if not video or audio, it is timed-metadata or unknown
- // if unknown, streamType will be undefined
- result.streamType = this.programMapTable['timed-metadata'][result.pid];
- }
-
- result.type = 'pes';
- result.data = packet.subarray(offset);
- this.trigger('data', result);
- };
- };
-
- _TransportParseStream.prototype = new stream();
- _TransportParseStream.STREAM_TYPES = {
- h264: 0x1b,
- adts: 0x0f
- };
- /**
- * Reconsistutes program elementary stream (PES) packets from parsed
- * transport stream packets. That is, if you pipe an
- * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
- * events will be events which capture the bytes for individual PES
- * packets plus relevant metadata that has been extracted from the
- * container.
- */
-
- _ElementaryStream = function ElementaryStream() {
- var self = this,
- // PES packet fragments
- video = {
- data: [],
- size: 0
- },
- audio = {
- data: [],
- size: 0
- },
- timedMetadata = {
- data: [],
- size: 0
- },
- programMapTable,
- parsePes = function parsePes(payload, pes) {
- var ptsDtsFlags;
- var startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
-
- pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
- // that are frame data that is continuing from the previous fragment. This
- // is to check that the pes data is the start of a new pes payload
-
- if (startPrefix !== 1) {
- return;
- } // get the packet length, this will be 0 for video
-
-
- pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
-
- pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
- // and a DTS value. Determine what combination of values is
- // available to work with.
-
- ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
- // performs all bitwise operations on 32-bit integers but javascript
- // supports a much greater range (52-bits) of integer using standard
- // mathematical operations.
- // We construct a 31-bit value using bitwise operators over the 31
- // most significant bits and then multiply by 4 (equal to a left-shift
- // of 2) before we add the final 2 least significant bits of the
- // timestamp (equal to an OR.)
-
- if (ptsDtsFlags & 0xC0) {
- // the PTS and DTS are not written out directly. For information
- // on how they are encoded, see
- // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
- pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
- pes.pts *= 4; // Left shift by 2
-
- pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
-
- pes.dts = pes.pts;
-
- if (ptsDtsFlags & 0x40) {
- pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
- pes.dts *= 4; // Left shift by 2
-
- pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
- }
- } // the data section starts immediately after the PES header.
- // pes_header_data_length specifies the number of header bytes
- // that follow the last byte of the field.
-
-
- pes.data = payload.subarray(9 + payload[8]);
- },
-
- /**
- * Pass completely parsed PES packets to the next stream in the pipeline
- **/
- flushStream = function flushStream(stream, type, forceFlush) {
- var packetData = new Uint8Array(stream.size),
- event = {
- type: type
- },
- i = 0,
- offset = 0,
- packetFlushable = false,
- fragment; // do nothing if there is not enough buffered data for a complete
- // PES header
-
- if (!stream.data.length || stream.size < 9) {
- return;
- }
-
- event.trackId = stream.data[0].pid; // reassemble the packet
-
- for (i = 0; i < stream.data.length; i++) {
- fragment = stream.data[i];
- packetData.set(fragment.data, offset);
- offset += fragment.data.byteLength;
- } // parse assembled packet's PES header
-
-
- parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
- // check that there is enough stream data to fill the packet
-
- packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
-
- if (forceFlush || packetFlushable) {
- stream.size = 0;
- stream.data.length = 0;
- } // only emit packets that are complete. this is to avoid assembling
- // incomplete PES packets due to poor segmentation
-
-
- if (packetFlushable) {
- self.trigger('data', event);
- }
- };
-
- _ElementaryStream.prototype.init.call(this);
- /**
- * Identifies M2TS packet types and parses PES packets using metadata
- * parsed from the PMT
- **/
-
-
- this.push = function (data) {
- ({
- pat: function pat() {// we have to wait for the PMT to arrive as well before we
- // have any meaningful metadata
- },
- pes: function pes() {
- var stream, streamType;
-
- switch (data.streamType) {
- case streamTypes.H264_STREAM_TYPE:
- stream = video;
- streamType = 'video';
- break;
-
- case streamTypes.ADTS_STREAM_TYPE:
- stream = audio;
- streamType = 'audio';
- break;
-
- case streamTypes.METADATA_STREAM_TYPE:
- stream = timedMetadata;
- streamType = 'timed-metadata';
- break;
-
- default:
- // ignore unknown stream types
- return;
- } // if a new packet is starting, we can flush the completed
- // packet
-
-
- if (data.payloadUnitStartIndicator) {
- flushStream(stream, streamType, true);
- } // buffer this fragment until we are sure we've received the
- // complete payload
-
-
- stream.data.push(data);
- stream.size += data.data.byteLength;
- },
- pmt: function pmt() {
- var event = {
- type: 'metadata',
- tracks: []
- };
- programMapTable = data.programMapTable; // translate audio and video streams to tracks
-
- if (programMapTable.video !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.video,
- codec: 'avc',
- type: 'video'
- });
- }
-
- if (programMapTable.audio !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.audio,
- codec: 'adts',
- type: 'audio'
- });
- }
-
- self.trigger('data', event);
- }
- })[data.type]();
- };
-
- this.reset = function () {
- video.size = 0;
- video.data.length = 0;
- audio.size = 0;
- audio.data.length = 0;
- this.trigger('reset');
- };
- /**
- * Flush any remaining input. Video PES packets may be of variable
- * length. Normally, the start of a new video packet can trigger the
- * finalization of the previous packet. That is not possible if no
- * more video is forthcoming, however. In that case, some other
- * mechanism (like the end of the file) has to be employed. When it is
- * clear that no additional data is forthcoming, calling this method
- * will flush the buffered packets.
- */
-
-
- this.flushStreams_ = function () {
- // !!THIS ORDER IS IMPORTANT!!
- // video first then audio
- flushStream(video, 'video');
- flushStream(audio, 'audio');
- flushStream(timedMetadata, 'timed-metadata');
- };
-
- this.flush = function () {
- this.flushStreams_();
- this.trigger('done');
- };
- };
-
- _ElementaryStream.prototype = new stream();
- var m2ts = {
- PAT_PID: 0x0000,
- MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
- TransportPacketStream: _TransportPacketStream,
- TransportParseStream: _TransportParseStream,
- ElementaryStream: _ElementaryStream,
- TimestampRolloverStream: TimestampRolloverStream,
- CaptionStream: captionStream.CaptionStream,
- Cea608Stream: captionStream.Cea608Stream,
- Cea708Stream: captionStream.Cea708Stream,
- MetadataStream: metadataStream
- };
-
- for (var type in streamTypes) {
- if (streamTypes.hasOwnProperty(type)) {
- m2ts[type] = streamTypes[type];
- }
- }
-
- var m2ts_1 = m2ts;
- var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
-
- var _AdtsStream;
-
- var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
- /*
- * Accepts a ElementaryStream and emits data events with parsed
- * AAC Audio Frames of the individual packets. Input audio in ADTS
- * format is unpacked and re-emitted as AAC frames.
- *
- * @see http://wiki.multimedia.cx/index.php?title=ADTS
- * @see http://wiki.multimedia.cx/?title=Understanding_AAC
- */
-
- _AdtsStream = function AdtsStream(handlePartialSegments) {
- var buffer,
- frameNum = 0;
-
- _AdtsStream.prototype.init.call(this);
-
- this.push = function (packet) {
- var i = 0,
- frameLength,
- protectionSkipBytes,
- frameEnd,
- oldBuffer,
- sampleCount,
- adtsFrameDuration;
-
- if (!handlePartialSegments) {
- frameNum = 0;
- }
-
- if (packet.type !== 'audio') {
- // ignore non-audio data
- return;
- } // Prepend any data in the buffer to the input data so that we can parse
- // aac frames the cross a PES packet boundary
-
-
- if (buffer) {
- oldBuffer = buffer;
- buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
- buffer.set(oldBuffer);
- buffer.set(packet.data, oldBuffer.byteLength);
- } else {
- buffer = packet.data;
- } // unpack any ADTS frames which have been fully received
- // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
-
-
- while (i + 5 < buffer.length) {
- // Look for the start of an ADTS header..
- if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- } // The protection skip bit tells us if we have 2 bytes of CRC data at the
- // end of the ADTS header
-
-
- protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
- // end of the sync sequence
-
- frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
- sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
- adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2];
- frameEnd = i + frameLength; // If we don't have enough data to actually finish this ADTS frame, return
- // and wait for more data
-
- if (buffer.byteLength < frameEnd) {
- return;
- } // Otherwise, deliver the complete AAC frame
-
-
- this.trigger('data', {
- pts: packet.pts + frameNum * adtsFrameDuration,
- dts: packet.dts + frameNum * adtsFrameDuration,
- sampleCount: sampleCount,
- audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
- channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
- samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
- samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
- // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
- samplesize: 16,
- data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
- });
- frameNum++; // If the buffer is empty, clear it and return
-
- if (buffer.byteLength === frameEnd) {
- buffer = undefined;
- return;
- } // Remove the finished frame from the buffer and start the process again
-
-
- buffer = buffer.subarray(frameEnd);
- }
- };
-
- this.flush = function () {
- frameNum = 0;
- this.trigger('done');
- };
-
- this.reset = function () {
- buffer = void 0;
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- buffer = void 0;
- this.trigger('endedtimeline');
- };
- };
-
- _AdtsStream.prototype = new stream();
- var adts = _AdtsStream;
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ExpGolomb;
- /**
- * Parser for exponential Golomb codes, a variable-bitwidth number encoding
- * scheme used by h264.
- */
-
- ExpGolomb = function ExpGolomb(workingData) {
- var // the number of bytes left to examine in workingData
- workingBytesAvailable = workingData.byteLength,
- // the current word being examined
- workingWord = 0,
- // :uint
- // the number of bits left to examine in the current word
- workingBitsAvailable = 0; // :uint;
- // ():uint
-
- this.length = function () {
- return 8 * workingBytesAvailable;
- }; // ():uint
-
-
- this.bitsAvailable = function () {
- return 8 * workingBytesAvailable + workingBitsAvailable;
- }; // ():void
-
-
- this.loadWord = function () {
- var position = workingData.byteLength - workingBytesAvailable,
- workingBytes = new Uint8Array(4),
- availableBytes = Math.min(4, workingBytesAvailable);
-
- if (availableBytes === 0) {
- throw new Error('no bytes available');
- }
-
- workingBytes.set(workingData.subarray(position, position + availableBytes));
- workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
-
- workingBitsAvailable = availableBytes * 8;
- workingBytesAvailable -= availableBytes;
- }; // (count:int):void
-
-
- this.skipBits = function (count) {
- var skipBytes; // :int
-
- if (workingBitsAvailable > count) {
- workingWord <<= count;
- workingBitsAvailable -= count;
- } else {
- count -= workingBitsAvailable;
- skipBytes = Math.floor(count / 8);
- count -= skipBytes * 8;
- workingBytesAvailable -= skipBytes;
- this.loadWord();
- workingWord <<= count;
- workingBitsAvailable -= count;
- }
- }; // (size:int):uint
-
-
- this.readBits = function (size) {
- var bits = Math.min(workingBitsAvailable, size),
- // :uint
- valu = workingWord >>> 32 - bits; // :uint
- // if size > 31, handle error
-
- workingBitsAvailable -= bits;
-
- if (workingBitsAvailable > 0) {
- workingWord <<= bits;
- } else if (workingBytesAvailable > 0) {
- this.loadWord();
- }
-
- bits = size - bits;
-
- if (bits > 0) {
- return valu << bits | this.readBits(bits);
- }
-
- return valu;
- }; // ():uint
-
-
- this.skipLeadingZeros = function () {
- var leadingZeroCount; // :uint
-
- for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
- if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
- // the first bit of working word is 1
- workingWord <<= leadingZeroCount;
- workingBitsAvailable -= leadingZeroCount;
- return leadingZeroCount;
- }
- } // we exhausted workingWord and still have not found a 1
-
-
- this.loadWord();
- return leadingZeroCount + this.skipLeadingZeros();
- }; // ():void
-
-
- this.skipUnsignedExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():void
-
-
- this.skipExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():uint
-
-
- this.readUnsignedExpGolomb = function () {
- var clz = this.skipLeadingZeros(); // :uint
-
- return this.readBits(clz + 1) - 1;
- }; // ():int
-
-
- this.readExpGolomb = function () {
- var valu = this.readUnsignedExpGolomb(); // :int
-
- if (0x01 & valu) {
- // the number is odd if the low order bit is set
- return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
- }
-
- return -1 * (valu >>> 1); // divide by two then make it negative
- }; // Some convenience functions
- // :Boolean
-
-
- this.readBoolean = function () {
- return this.readBits(1) === 1;
- }; // ():int
-
-
- this.readUnsignedByte = function () {
- return this.readBits(8);
- };
-
- this.loadWord();
- };
-
- var expGolomb = ExpGolomb;
-
- var _H264Stream, _NalByteStream;
-
- var PROFILES_WITH_OPTIONAL_SPS_DATA;
- /**
- * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
- */
-
- _NalByteStream = function NalByteStream() {
- var syncPoint = 0,
- i,
- buffer;
-
- _NalByteStream.prototype.init.call(this);
- /*
- * Scans a byte stream and triggers a data event with the NAL units found.
- * @param {Object} data Event received from H264Stream
- * @param {Uint8Array} data.data The h264 byte stream to be scanned
- *
- * @see H264Stream.push
- */
-
-
- this.push = function (data) {
- var swapBuffer;
-
- if (!buffer) {
- buffer = data.data;
- } else {
- swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
- swapBuffer.set(buffer);
- swapBuffer.set(data.data, buffer.byteLength);
- buffer = swapBuffer;
- }
-
- var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
- // scan for NAL unit boundaries
- // a match looks like this:
- // 0 0 1 .. NAL .. 0 0 1
- // ^ sync point ^ i
- // or this:
- // 0 0 1 .. NAL .. 0 0 0
- // ^ sync point ^ i
- // advance the sync point to a NAL start, if necessary
-
- for (; syncPoint < len - 3; syncPoint++) {
- if (buffer[syncPoint + 2] === 1) {
- // the sync point is properly aligned
- i = syncPoint + 5;
- break;
- }
- }
-
- while (i < len) {
- // look at the current byte to determine if we've hit the end of
- // a NAL unit boundary
- switch (buffer[i]) {
- case 0:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0) {
- i += 2;
- break;
- } else if (buffer[i - 2] !== 0) {
- i++;
- break;
- } // deliver the NAL unit if it isn't empty
-
-
- if (syncPoint + 3 !== i - 2) {
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- } // drop trailing zeroes
-
-
- do {
- i++;
- } while (buffer[i] !== 1 && i < len);
-
- syncPoint = i - 2;
- i += 3;
- break;
-
- case 1:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
- i += 3;
- break;
- } // deliver the NAL unit
-
-
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- syncPoint = i - 2;
- i += 3;
- break;
-
- default:
- // the current byte isn't a one or zero, so it cannot be part
- // of a sync sequence
- i += 3;
- break;
- }
- } // filter out the NAL units that were delivered
-
-
- buffer = buffer.subarray(syncPoint);
- i -= syncPoint;
- syncPoint = 0;
- };
-
- this.reset = function () {
- buffer = null;
- syncPoint = 0;
- this.trigger('reset');
- };
-
- this.flush = function () {
- // deliver the last buffered NAL unit
- if (buffer && buffer.byteLength > 3) {
- this.trigger('data', buffer.subarray(syncPoint + 3));
- } // reset the stream state
-
-
- buffer = null;
- syncPoint = 0;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
- };
-
- _NalByteStream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the SPS
- // see Recommendation ITU-T H.264 (4/2013),
- // 7.3.2.1.1 Sequence parameter set data syntax
-
- PROFILES_WITH_OPTIONAL_SPS_DATA = {
- 100: true,
- 110: true,
- 122: true,
- 244: true,
- 44: true,
- 83: true,
- 86: true,
- 118: true,
- 128: true,
- 138: true,
- 139: true,
- 134: true
- };
- /**
- * Accepts input from a ElementaryStream and produces H.264 NAL unit data
- * events.
- */
-
- _H264Stream = function H264Stream() {
- var nalByteStream = new _NalByteStream(),
- self,
- trackId,
- currentPts,
- currentDts,
- discardEmulationPreventionBytes,
- readSequenceParameterSet,
- skipScalingList;
-
- _H264Stream.prototype.init.call(this);
-
- self = this;
- /*
- * Pushes a packet from a stream onto the NalByteStream
- *
- * @param {Object} packet - A packet received from a stream
- * @param {Uint8Array} packet.data - The raw bytes of the packet
- * @param {Number} packet.dts - Decode timestamp of the packet
- * @param {Number} packet.pts - Presentation timestamp of the packet
- * @param {Number} packet.trackId - The id of the h264 track this packet came from
- * @param {('video'|'audio')} packet.type - The type of packet
- *
- */
-
- this.push = function (packet) {
- if (packet.type !== 'video') {
- return;
- }
-
- trackId = packet.trackId;
- currentPts = packet.pts;
- currentDts = packet.dts;
- nalByteStream.push(packet);
- };
- /*
- * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
- * for the NALUs to the next stream component.
- * Also, preprocess caption and sequence parameter NALUs.
- *
- * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
- * @see NalByteStream.push
- */
-
-
- nalByteStream.on('data', function (data) {
- var event = {
- trackId: trackId,
- pts: currentPts,
- dts: currentDts,
- data: data
- };
-
- switch (data[0] & 0x1f) {
- case 0x05:
- event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
- break;
-
- case 0x06:
- event.nalUnitType = 'sei_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- break;
-
- case 0x07:
- event.nalUnitType = 'seq_parameter_set_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- event.config = readSequenceParameterSet(event.escapedRBSP);
- break;
-
- case 0x08:
- event.nalUnitType = 'pic_parameter_set_rbsp';
- break;
-
- case 0x09:
- event.nalUnitType = 'access_unit_delimiter_rbsp';
- break;
- } // This triggers data on the H264Stream
-
-
- self.trigger('data', event);
- });
- nalByteStream.on('done', function () {
- self.trigger('done');
- });
- nalByteStream.on('partialdone', function () {
- self.trigger('partialdone');
- });
- nalByteStream.on('reset', function () {
- self.trigger('reset');
- });
- nalByteStream.on('endedtimeline', function () {
- self.trigger('endedtimeline');
- });
-
- this.flush = function () {
- nalByteStream.flush();
- };
-
- this.partialFlush = function () {
- nalByteStream.partialFlush();
- };
-
- this.reset = function () {
- nalByteStream.reset();
- };
-
- this.endTimeline = function () {
- nalByteStream.endTimeline();
- };
- /**
- * Advance the ExpGolomb decoder past a scaling list. The scaling
- * list is optionally transmitted as part of a sequence parameter
- * set and is not relevant to transmuxing.
- * @param count {number} the number of entries in this scaling list
- * @param expGolombDecoder {object} an ExpGolomb pointed to the
- * start of a scaling list
- * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
- */
-
-
- skipScalingList = function skipScalingList(count, expGolombDecoder) {
- var lastScale = 8,
- nextScale = 8,
- j,
- deltaScale;
-
- for (j = 0; j < count; j++) {
- if (nextScale !== 0) {
- deltaScale = expGolombDecoder.readExpGolomb();
- nextScale = (lastScale + deltaScale + 256) % 256;
- }
-
- lastScale = nextScale === 0 ? lastScale : nextScale;
- }
- };
- /**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
-
- discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- };
- /**
- * Read a sequence parameter set and return some interesting video
- * properties. A sequence parameter set is the H264 metadata that
- * describes the properties of upcoming video frames.
- * @param data {Uint8Array} the bytes of a sequence parameter set
- * @return {object} an object with configuration parsed from the
- * sequence parameter set, including the dimensions of the
- * associated video frames.
- */
-
-
- readSequenceParameterSet = function readSequenceParameterSet(data) {
- var frameCropLeftOffset = 0,
- frameCropRightOffset = 0,
- frameCropTopOffset = 0,
- frameCropBottomOffset = 0,
- sarScale = 1,
- expGolombDecoder,
- profileIdc,
- levelIdc,
- profileCompatibility,
- chromaFormatIdc,
- picOrderCntType,
- numRefFramesInPicOrderCntCycle,
- picWidthInMbsMinus1,
- picHeightInMapUnitsMinus1,
- frameMbsOnlyFlag,
- scalingListCount,
- sarRatio,
- aspectRatioIdc,
- i;
- expGolombDecoder = new expGolomb(data);
- profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
-
- profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
-
- levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
-
- expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
- // some profiles have more optional data we don't need
-
- if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
- chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
-
- if (chromaFormatIdc === 3) {
- expGolombDecoder.skipBits(1); // separate_colour_plane_flag
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
-
- expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
-
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_matrix_present_flag
- scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
-
- for (i = 0; i < scalingListCount; i++) {
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_list_present_flag[ i ]
- if (i < 6) {
- skipScalingList(16, expGolombDecoder);
- } else {
- skipScalingList(64, expGolombDecoder);
- }
- }
- }
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
-
- picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
-
- if (picOrderCntType === 0) {
- expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
- } else if (picOrderCntType === 1) {
- expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
-
- expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
-
- expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
-
- numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
-
- for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
- expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
-
- expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
-
- picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- frameMbsOnlyFlag = expGolombDecoder.readBits(1);
-
- if (frameMbsOnlyFlag === 0) {
- expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
- }
-
- expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
-
- if (expGolombDecoder.readBoolean()) {
- // frame_cropping_flag
- frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
- }
-
- if (expGolombDecoder.readBoolean()) {
- // vui_parameters_present_flag
- if (expGolombDecoder.readBoolean()) {
- // aspect_ratio_info_present_flag
- aspectRatioIdc = expGolombDecoder.readUnsignedByte();
-
- switch (aspectRatioIdc) {
- case 1:
- sarRatio = [1, 1];
- break;
-
- case 2:
- sarRatio = [12, 11];
- break;
-
- case 3:
- sarRatio = [10, 11];
- break;
-
- case 4:
- sarRatio = [16, 11];
- break;
-
- case 5:
- sarRatio = [40, 33];
- break;
-
- case 6:
- sarRatio = [24, 11];
- break;
-
- case 7:
- sarRatio = [20, 11];
- break;
-
- case 8:
- sarRatio = [32, 11];
- break;
-
- case 9:
- sarRatio = [80, 33];
- break;
-
- case 10:
- sarRatio = [18, 11];
- break;
-
- case 11:
- sarRatio = [15, 11];
- break;
-
- case 12:
- sarRatio = [64, 33];
- break;
-
- case 13:
- sarRatio = [160, 99];
- break;
-
- case 14:
- sarRatio = [4, 3];
- break;
-
- case 15:
- sarRatio = [3, 2];
- break;
-
- case 16:
- sarRatio = [2, 1];
- break;
-
- case 255:
- {
- sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
- break;
- }
- }
-
- if (sarRatio) {
- sarScale = sarRatio[0] / sarRatio[1];
- }
- }
- }
-
- return {
- profileIdc: profileIdc,
- levelIdc: levelIdc,
- profileCompatibility: profileCompatibility,
- width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
- height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
- sarRatio: sarRatio
- };
- };
- };
-
- _H264Stream.prototype = new stream();
- var h264 = {
- H264Stream: _H264Stream,
- NalByteStream: _NalByteStream
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Utilities to detect basic properties and metadata about Aac data.
- */
-
- var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
-
- var parseId3TagSize = function parseId3TagSize(header, byteIndex) {
- var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
- flags = header[byteIndex + 5],
- footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
-
- returnSize = returnSize >= 0 ? returnSize : 0;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
- };
-
- var getId3Offset = function getId3Offset(data, offset) {
- if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
- return offset;
- }
-
- offset += parseId3TagSize(data, offset);
- return getId3Offset(data, offset);
- }; // TODO: use vhs-utils
-
-
- var isLikelyAacData$1 = function isLikelyAacData(data) {
- var offset = getId3Offset(data, 0);
- return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
- // is not mp3 data but aac data.
- (data[offset + 1] & 0x16) === 0x10;
- };
-
- var parseSyncSafeInteger = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- }; // return a percent-encoded representation of the specified byte range
- // @see http://en.wikipedia.org/wiki/Percent-encoding
-
-
- var percentEncode = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- }; // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
-
-
- var parseIso88591 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
- };
-
- var parseAdtsSize = function parseAdtsSize(header, byteIndex) {
- var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
- middle = header[byteIndex + 4] << 3,
- highTwo = header[byteIndex + 3] & 0x3 << 11;
- return highTwo | middle | lowThree;
- };
-
- var parseType$2 = function parseType(header, byteIndex) {
- if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
- return 'timed-metadata';
- } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
- return 'audio';
- }
-
- return null;
- };
-
- var parseSampleRate = function parseSampleRate(packet) {
- var i = 0;
-
- while (i + 5 < packet.length) {
- if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- }
-
- return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
- }
-
- return null;
- };
-
- var parseAacTimestamp = function parseAacTimestamp(packet) {
- var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
-
- frameStart = 10;
-
- if (packet[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- return null;
- }
-
- frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
-
- if (frameHeader === 'PRIV') {
- frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
-
- for (var i = 0; i < frame.byteLength; i++) {
- if (frame[i] === 0) {
- var owner = parseIso88591(frame, 0, i);
-
- if (owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.subarray(i + 1);
- var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- return size;
- }
-
- break;
- }
- }
- }
-
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < packet.byteLength);
-
- return null;
- };
-
- var utils = {
- isLikelyAacData: isLikelyAacData$1,
- parseId3TagSize: parseId3TagSize,
- parseAdtsSize: parseAdtsSize,
- parseType: parseType$2,
- parseSampleRate: parseSampleRate,
- parseAacTimestamp: parseAacTimestamp
- };
-
- var _AacStream;
- /**
- * Splits an incoming stream of binary data into ADTS and ID3 Frames.
- */
-
-
- _AacStream = function AacStream() {
- var everything = new Uint8Array(),
- timeStamp = 0;
-
- _AacStream.prototype.init.call(this);
-
- this.setTimestamp = function (timestamp) {
- timeStamp = timestamp;
- };
-
- this.push = function (bytes) {
- var frameSize = 0,
- byteIndex = 0,
- bytesLeft,
- chunk,
- packet,
- tempLength; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (everything.length) {
- tempLength = everything.length;
- everything = new Uint8Array(bytes.byteLength + tempLength);
- everything.set(everything.subarray(0, tempLength));
- everything.set(bytes, tempLength);
- } else {
- everything = bytes;
- }
-
- while (everything.length - byteIndex >= 3) {
- if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
- // Exit early because we don't have enough to parse
- // the ID3 tag header
- if (everything.length - byteIndex < 10) {
- break;
- } // check framesize
-
-
- frameSize = utils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
- // Add to byteIndex to support multiple ID3 tags in sequence
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- chunk = {
- type: 'timed-metadata',
- data: everything.subarray(byteIndex, byteIndex + frameSize)
- };
- this.trigger('data', chunk);
- byteIndex += frameSize;
- continue;
- } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
- // Exit early because we don't have enough to parse
- // the ADTS frame header
- if (everything.length - byteIndex < 7) {
- break;
- }
-
- frameSize = utils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- packet = {
- type: 'audio',
- data: everything.subarray(byteIndex, byteIndex + frameSize),
- pts: timeStamp,
- dts: timeStamp
- };
- this.trigger('data', packet);
- byteIndex += frameSize;
- continue;
- }
-
- byteIndex++;
- }
-
- bytesLeft = everything.length - byteIndex;
-
- if (bytesLeft > 0) {
- everything = everything.subarray(byteIndex);
- } else {
- everything = new Uint8Array();
- }
- };
-
- this.reset = function () {
- everything = new Uint8Array();
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- everything = new Uint8Array();
- this.trigger('endedtimeline');
- };
- };
-
- _AacStream.prototype = new stream();
- var aac = _AacStream; // constants
-
- var AUDIO_PROPERTIES = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
- var audioProperties = AUDIO_PROPERTIES;
- var VIDEO_PROPERTIES = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
- var videoProperties = VIDEO_PROPERTIES;
- var H264Stream = h264.H264Stream;
- var isLikelyAacData = utils.isLikelyAacData;
- var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS; // object types
-
- var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
- /**
- * Compare two arrays (even typed) for same-ness
- */
-
-
- var arrayEquals = function arrayEquals(a, b) {
- var i;
-
- if (a.length !== b.length) {
- return false;
- } // compare the value of each element in the array
-
-
- for (i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) {
- return false;
- }
- }
-
- return true;
- };
-
- var generateSegmentTimingInfo = function generateSegmentTimingInfo(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
- var ptsOffsetFromDts = startPts - startDts,
- decodeDuration = endDts - startDts,
- presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
- // however, the player time values will reflect a start from the baseMediaDecodeTime.
- // In order to provide relevant values for the player times, base timing info on the
- // baseMediaDecodeTime and the DTS and PTS durations of the segment.
-
- return {
- start: {
- dts: baseMediaDecodeTime,
- pts: baseMediaDecodeTime + ptsOffsetFromDts
- },
- end: {
- dts: baseMediaDecodeTime + decodeDuration,
- pts: baseMediaDecodeTime + presentationDuration
- },
- prependedContentDuration: prependedContentDuration,
- baseMediaDecodeTime: baseMediaDecodeTime
- };
- };
- /**
- * Constructs a single-track, ISO BMFF media segment from AAC data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- _AudioSegmentStream = function AudioSegmentStream(track, options) {
- var adtsFrames = [],
- sequenceNumber = 0,
- earliestAllowedDts = 0,
- audioAppendStartTs = 0,
- videoBaseMediaDecodeTime = Infinity;
- options = options || {};
-
- _AudioSegmentStream.prototype.init.call(this);
-
- this.push = function (data) {
- trackDecodeInfo.collectDtsInfo(track, data);
-
- if (track) {
- audioProperties.forEach(function (prop) {
- track[prop] = data[prop];
- });
- } // buffer audio data until end() is called
-
-
- adtsFrames.push(data);
- };
-
- this.setEarliestDts = function (earliestDts) {
- earliestAllowedDts = earliestDts;
- };
-
- this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- videoBaseMediaDecodeTime = baseMediaDecodeTime;
- };
-
- this.setAudioAppendStart = function (timestamp) {
- audioAppendStartTs = timestamp;
- };
-
- this.flush = function () {
- var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
-
- if (adtsFrames.length === 0) {
- this.trigger('done', 'AudioSegmentStream');
- return;
- }
-
- frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
-
- videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
- // samples (that is, adts frames) in the audio data
-
- track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
-
- mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
- adtsFrames = [];
- moof = mp4Generator.moof(sequenceNumber, [track]);
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- trackDecodeInfo.clearDtsInfo(track);
- frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
- // tests) on adding the timingInfo event. However, it seems unlikely that there's a
- // valid use-case where an init segment/data should be triggered without associated
- // frames. Leaving for now, but should be looked into.
-
- if (frames.length) {
- segmentDuration = frames.length * frameDuration;
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
- // frame info is in video clock cycles. Convert to match expectation of
- // listeners (that all timestamps will be based on video clock cycles).
- clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
- frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
- this.trigger('timingInfo', {
- start: frames[0].pts,
- end: frames[0].pts + segmentDuration
- });
- }
-
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.trigger('done', 'AudioSegmentStream');
- };
-
- this.reset = function () {
- trackDecodeInfo.clearDtsInfo(track);
- adtsFrames = [];
- this.trigger('reset');
- };
- };
-
- _AudioSegmentStream.prototype = new stream();
- /**
- * Constructs a single-track, ISO BMFF media segment from H264 data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
- * gopsToAlignWith list when attempting to align gop pts
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
- _VideoSegmentStream = function VideoSegmentStream(track, options) {
- var sequenceNumber = 0,
- nalUnits = [],
- gopsToAlignWith = [],
- config,
- pps;
- options = options || {};
-
- _VideoSegmentStream.prototype.init.call(this);
-
- delete track.minPTS;
- this.gopCache_ = [];
- /**
- * Constructs a ISO BMFF segment given H264 nalUnits
- * @param {Object} nalUnit A data event representing a nalUnit
- * @param {String} nalUnit.nalUnitType
- * @param {Object} nalUnit.config Properties for a mp4 track
- * @param {Uint8Array} nalUnit.data The nalUnit bytes
- * @see lib/codecs/h264.js
- **/
-
- this.push = function (nalUnit) {
- trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
-
- if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
- config = nalUnit.config;
- track.sps = [nalUnit.data];
- videoProperties.forEach(function (prop) {
- track[prop] = config[prop];
- }, this);
- }
-
- if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
- pps = nalUnit.data;
- track.pps = [nalUnit.data];
- } // buffer video until flush() is called
-
-
- nalUnits.push(nalUnit);
- };
- /**
- * Pass constructed ISO BMFF track and boxes on to the
- * next stream in the pipeline
- **/
-
-
- this.flush = function () {
- var frames,
- gopForFusion,
- gops,
- moof,
- mdat,
- boxes,
- prependedContentDuration = 0,
- firstGop,
- lastGop; // Throw away nalUnits at the start of the byte stream until
- // we find the first AUD
-
- while (nalUnits.length) {
- if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
- break;
- }
-
- nalUnits.shift();
- } // Return early if no video data has been observed
-
-
- if (nalUnits.length === 0) {
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Organize the raw nal-units into arrays that represent
- // higher-level constructs such as frames and gops
- // (group-of-pictures)
-
-
- frames = frameUtils.groupNalsIntoFrames(nalUnits);
- gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
- // a problem since MSE (on Chrome) requires a leading keyframe.
- //
- // We have two approaches to repairing this situation:
- // 1) GOP-FUSION:
- // This is where we keep track of the GOPS (group-of-pictures)
- // from previous fragments and attempt to find one that we can
- // prepend to the current fragment in order to create a valid
- // fragment.
- // 2) KEYFRAME-PULLING:
- // Here we search for the first keyframe in the fragment and
- // throw away all the frames between the start of the fragment
- // and that keyframe. We then extend the duration and pull the
- // PTS of the keyframe forward so that it covers the time range
- // of the frames that were disposed of.
- //
- // #1 is far prefereable over #2 which can cause "stuttering" but
- // requires more things to be just right.
-
- if (!gops[0][0].keyFrame) {
- // Search for a gop for fusion from our gopCache
- gopForFusion = this.getGopForFusion_(nalUnits[0], track);
-
- if (gopForFusion) {
- // in order to provide more accurate timing information about the segment, save
- // the number of seconds prepended to the original segment due to GOP fusion
- prependedContentDuration = gopForFusion.duration;
- gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
- // new gop at the beginning
-
- gops.byteLength += gopForFusion.byteLength;
- gops.nalCount += gopForFusion.nalCount;
- gops.pts = gopForFusion.pts;
- gops.dts = gopForFusion.dts;
- gops.duration += gopForFusion.duration;
- } else {
- // If we didn't find a candidate gop fall back to keyframe-pulling
- gops = frameUtils.extendFirstKeyFrame(gops);
- }
- } // Trim gops to align with gopsToAlignWith
-
-
- if (gopsToAlignWith.length) {
- var alignedGops;
-
- if (options.alignGopsAtEnd) {
- alignedGops = this.alignGopsAtEnd_(gops);
- } else {
- alignedGops = this.alignGopsAtStart_(gops);
- }
-
- if (!alignedGops) {
- // save all the nals in the last GOP into the gop cache
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
-
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
- // when recalculated before sending off to CoalesceStream
-
-
- trackDecodeInfo.clearDtsInfo(track);
- gops = alignedGops;
- }
-
- trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
- // samples (that is, frames) in the video data
-
- track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
-
- mdat = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
- this.trigger('processedGopsInfo', gops.map(function (gop) {
- return {
- pts: gop.pts,
- dts: gop.dts,
- byteLength: gop.byteLength
- };
- }));
- firstGop = gops[0];
- lastGop = gops[gops.length - 1];
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
- this.trigger('timingInfo', {
- start: gops[0].pts,
- end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
- }); // save all the nals in the last GOP into the gop cache
-
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = [];
- this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
- this.trigger('timelineStartInfo', track.timelineStartInfo);
- moof = mp4Generator.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
- // throwing away hundreds of media segment fragments
-
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.resetStream_(); // Continue with the flush process now
-
- this.trigger('done', 'VideoSegmentStream');
- };
-
- this.reset = function () {
- this.resetStream_();
- nalUnits = [];
- this.gopCache_.length = 0;
- gopsToAlignWith.length = 0;
- this.trigger('reset');
- };
-
- this.resetStream_ = function () {
- trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
- // for instance, when we are rendition switching
-
- config = undefined;
- pps = undefined;
- }; // Search for a candidate Gop for gop-fusion from the gop cache and
- // return it or return null if no good candidate was found
-
-
- this.getGopForFusion_ = function (nalUnit) {
- var halfSecond = 45000,
- // Half-a-second in a 90khz clock
- allowableOverlap = 10000,
- // About 3 frames @ 30fps
- nearestDistance = Infinity,
- dtsDistance,
- nearestGopObj,
- currentGop,
- currentGopObj,
- i; // Search for the GOP nearest to the beginning of this nal unit
-
- for (i = 0; i < this.gopCache_.length; i++) {
- currentGopObj = this.gopCache_[i];
- currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
-
- if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
- continue;
- } // Reject Gops that would require a negative baseMediaDecodeTime
-
-
- if (currentGop.dts < track.timelineStartInfo.dts) {
- continue;
- } // The distance between the end of the gop and the start of the nalUnit
-
-
- dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
- // a half-second of the nal unit
-
- if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
- // Always use the closest GOP we found if there is more than
- // one candidate
- if (!nearestGopObj || nearestDistance > dtsDistance) {
- nearestGopObj = currentGopObj;
- nearestDistance = dtsDistance;
- }
- }
- }
-
- if (nearestGopObj) {
- return nearestGopObj.gop;
- }
-
- return null;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the START of the list
-
-
- this.alignGopsAtStart_ = function (gops) {
- var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
- byteLength = gops.byteLength;
- nalCount = gops.nalCount;
- duration = gops.duration;
- alignIndex = gopIndex = 0;
-
- while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- break;
- }
-
- if (gop.pts > align.pts) {
- // this current gop starts after the current gop we want to align on, so increment
- // align index
- alignIndex++;
- continue;
- } // current gop starts before the current gop we want to align on. so increment gop
- // index
-
-
- gopIndex++;
- byteLength -= gop.byteLength;
- nalCount -= gop.nalCount;
- duration -= gop.duration;
- }
-
- if (gopIndex === 0) {
- // no gops to trim
- return gops;
- }
-
- if (gopIndex === gops.length) {
- // all gops trimmed, skip appending all gops
- return null;
- }
-
- alignedGops = gops.slice(gopIndex);
- alignedGops.byteLength = byteLength;
- alignedGops.duration = duration;
- alignedGops.nalCount = nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the END of the list
-
-
- this.alignGopsAtEnd_ = function (gops) {
- var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
- alignIndex = gopsToAlignWith.length - 1;
- gopIndex = gops.length - 1;
- alignEndIndex = null;
- matchFound = false;
-
- while (alignIndex >= 0 && gopIndex >= 0) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- matchFound = true;
- break;
- }
-
- if (align.pts > gop.pts) {
- alignIndex--;
- continue;
- }
-
- if (alignIndex === gopsToAlignWith.length - 1) {
- // gop.pts is greater than the last alignment candidate. If no match is found
- // by the end of this loop, we still want to append gops that come after this
- // point
- alignEndIndex = gopIndex;
- }
-
- gopIndex--;
- }
-
- if (!matchFound && alignEndIndex === null) {
- return null;
- }
-
- var trimIndex;
-
- if (matchFound) {
- trimIndex = gopIndex;
- } else {
- trimIndex = alignEndIndex;
- }
-
- if (trimIndex === 0) {
- return gops;
- }
-
- var alignedGops = gops.slice(trimIndex);
- var metadata = alignedGops.reduce(function (total, gop) {
- total.byteLength += gop.byteLength;
- total.duration += gop.duration;
- total.nalCount += gop.nalCount;
- return total;
- }, {
- byteLength: 0,
- duration: 0,
- nalCount: 0
- });
- alignedGops.byteLength = metadata.byteLength;
- alignedGops.duration = metadata.duration;
- alignedGops.nalCount = metadata.nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- };
-
- this.alignGopsWith = function (newGopsToAlignWith) {
- gopsToAlignWith = newGopsToAlignWith;
- };
- };
-
- _VideoSegmentStream.prototype = new stream();
- /**
- * A Stream that can combine multiple streams (ie. audio & video)
- * into a single output segment for MSE. Also supports audio-only
- * and video-only streams.
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at media timeline start.
- */
-
- _CoalesceStream = function CoalesceStream(options, metadataStream) {
- // Number of Tracks per output segment
- // If greater than 1, we combine multiple
- // tracks into a single segment
- this.numberOfTracks = 0;
- this.metadataStream = metadataStream;
- options = options || {};
-
- if (typeof options.remux !== 'undefined') {
- this.remuxTracks = !!options.remux;
- } else {
- this.remuxTracks = true;
- }
-
- if (typeof options.keepOriginalTimestamps === 'boolean') {
- this.keepOriginalTimestamps = options.keepOriginalTimestamps;
- } else {
- this.keepOriginalTimestamps = false;
- }
-
- this.pendingTracks = [];
- this.videoTrack = null;
- this.pendingBoxes = [];
- this.pendingCaptions = [];
- this.pendingMetadata = [];
- this.pendingBytes = 0;
- this.emittedTracks = 0;
-
- _CoalesceStream.prototype.init.call(this); // Take output from multiple
-
-
- this.push = function (output) {
- // buffer incoming captions until the associated video segment
- // finishes
- if (output.text) {
- return this.pendingCaptions.push(output);
- } // buffer incoming id3 tags until the final flush
-
-
- if (output.frames) {
- return this.pendingMetadata.push(output);
- } // Add this track to the list of pending tracks and store
- // important information required for the construction of
- // the final segment
-
-
- this.pendingTracks.push(output.track);
- this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
- // We unshift audio and push video because
- // as of Chrome 75 when switching from
- // one init segment to another if the video
- // mdat does not appear after the audio mdat
- // only audio will play for the duration of our transmux.
-
- if (output.track.type === 'video') {
- this.videoTrack = output.track;
- this.pendingBoxes.push(output.boxes);
- }
-
- if (output.track.type === 'audio') {
- this.audioTrack = output.track;
- this.pendingBoxes.unshift(output.boxes);
- }
- };
- };
-
- _CoalesceStream.prototype = new stream();
-
- _CoalesceStream.prototype.flush = function (flushSource) {
- var offset = 0,
- event = {
- captions: [],
- captionStreams: {},
- metadata: [],
- info: {}
- },
- caption,
- id3,
- initSegment,
- timelineStartPts = 0,
- i;
-
- if (this.pendingTracks.length < this.numberOfTracks) {
- if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
- // Return because we haven't received a flush from a data-generating
- // portion of the segment (meaning that we have only recieved meta-data
- // or captions.)
- return;
- } else if (this.remuxTracks) {
- // Return until we have enough tracks from the pipeline to remux (if we
- // are remuxing audio and video into a single MP4)
- return;
- } else if (this.pendingTracks.length === 0) {
- // In the case where we receive a flush without any data having been
- // received we consider it an emitted track for the purposes of coalescing
- // `done` events.
- // We do this for the case where there is an audio and video track in the
- // segment but no audio data. (seen in several playlists with alternate
- // audio tracks and no audio present in the main TS segments.)
- this.emittedTracks++;
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
-
- return;
- }
- }
-
- if (this.videoTrack) {
- timelineStartPts = this.videoTrack.timelineStartInfo.pts;
- videoProperties.forEach(function (prop) {
- event.info[prop] = this.videoTrack[prop];
- }, this);
- } else if (this.audioTrack) {
- timelineStartPts = this.audioTrack.timelineStartInfo.pts;
- audioProperties.forEach(function (prop) {
- event.info[prop] = this.audioTrack[prop];
- }, this);
- }
-
- if (this.videoTrack || this.audioTrack) {
- if (this.pendingTracks.length === 1) {
- event.type = this.pendingTracks[0].type;
- } else {
- event.type = 'combined';
- }
-
- this.emittedTracks += this.pendingTracks.length;
- initSegment = mp4Generator.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
-
- event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
- // and track definitions
-
- event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
-
- event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
-
- for (i = 0; i < this.pendingBoxes.length; i++) {
- event.data.set(this.pendingBoxes[i], offset);
- offset += this.pendingBoxes[i].byteLength;
- } // Translate caption PTS times into second offsets to match the
- // video timeline for the segment, and add track info
-
-
- for (i = 0; i < this.pendingCaptions.length; i++) {
- caption = this.pendingCaptions[i];
- caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
- caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
- event.captionStreams[caption.stream] = true;
- event.captions.push(caption);
- } // Translate ID3 frame PTS times into second offsets to match the
- // video timeline for the segment
-
-
- for (i = 0; i < this.pendingMetadata.length; i++) {
- id3 = this.pendingMetadata[i];
- id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
- event.metadata.push(id3);
- } // We add this to every single emitted segment even though we only need
- // it for the first
-
-
- event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
-
- this.pendingTracks.length = 0;
- this.videoTrack = null;
- this.pendingBoxes.length = 0;
- this.pendingCaptions.length = 0;
- this.pendingBytes = 0;
- this.pendingMetadata.length = 0; // Emit the built segment
- // We include captions and ID3 tags for backwards compatibility,
- // ideally we should send only video and audio in the data event
-
- this.trigger('data', event); // Emit each caption to the outside world
- // Ideally, this would happen immediately on parsing captions,
- // but we need to ensure that video data is sent back first
- // so that caption timing can be adjusted to match video timing
-
- for (i = 0; i < event.captions.length; i++) {
- caption = event.captions[i];
- this.trigger('caption', caption);
- } // Emit each id3 tag to the outside world
- // Ideally, this would happen immediately on parsing the tag,
- // but we need to ensure that video data is sent back first
- // so that ID3 frame timing can be adjusted to match video timing
-
-
- for (i = 0; i < event.metadata.length; i++) {
- id3 = event.metadata[i];
- this.trigger('id3Frame', id3);
- }
- } // Only emit `done` if all tracks have been flushed and emitted
-
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
- };
-
- _CoalesceStream.prototype.setRemux = function (val) {
- this.remuxTracks = val;
- };
- /**
- * A Stream that expects MP2T binary data as input and produces
- * corresponding media segments, suitable for use with Media Source
- * Extension (MSE) implementations that support the ISO BMFF byte
- * stream format, like Chrome.
- */
-
-
- _Transmuxer = function Transmuxer(options) {
- var self = this,
- hasFlushed = true,
- videoTrack,
- audioTrack;
-
- _Transmuxer.prototype.init.call(this);
-
- options = options || {};
- this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
- this.transmuxPipeline_ = {};
-
- this.setupAacPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'aac';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.aacStream = new aac();
- pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('audio');
- pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('timed-metadata');
- pipeline.adtsStream = new adts();
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.aacStream;
- pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
- pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
- pipeline.metadataStream.on('timestamp', function (frame) {
- pipeline.aacStream.setTimestamp(frame.timeStamp);
- });
- pipeline.aacStream.on('data', function (data) {
- if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
- return;
- }
-
- audioTrack = audioTrack || {
- timelineStartInfo: {
- baseMediaDecodeTime: self.baseMediaDecodeTime
- },
- codec: 'adts',
- type: 'audio'
- }; // hook up the audio segment stream to the first track with aac data
-
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- };
-
- this.setupTsPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'ts';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.packetStream = new m2ts_1.TransportPacketStream();
- pipeline.parseStream = new m2ts_1.TransportParseStream();
- pipeline.elementaryStream = new m2ts_1.ElementaryStream();
- pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
- pipeline.adtsStream = new adts();
- pipeline.h264Stream = new H264Stream();
- pipeline.captionStream = new m2ts_1.CaptionStream(options);
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
-
- pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
- // demux the streams
-
- pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
- pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
- pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
-
- pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
- pipeline.elementaryStream.on('data', function (data) {
- var i;
-
- if (data.type === 'metadata') {
- i = data.tracks.length; // scan the tracks listed in the metadata
-
- while (i--) {
- if (!videoTrack && data.tracks[i].type === 'video') {
- videoTrack = data.tracks[i];
- videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- } else if (!audioTrack && data.tracks[i].type === 'audio') {
- audioTrack = data.tracks[i];
- audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- }
- } // hook up the video segment stream to the first track with h264 data
-
-
- if (videoTrack && !pipeline.videoSegmentStream) {
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
- pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
- // When video emits timelineStartInfo data after a flush, we forward that
- // info to the AudioSegmentStream, if it exists, because video timeline
- // data takes precedence. Do not do this if keepOriginalTimestamps is set,
- // because this is a particularly subtle form of timestamp alteration.
- if (audioTrack && !options.keepOriginalTimestamps) {
- audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
- // very earliest DTS we have seen in video because Chrome will
- // interpret any video track with a baseMediaDecodeTime that is
- // non-zero as a gap.
-
- pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
- pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
- pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
- if (audioTrack) {
- pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
-
- pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
- }
-
- if (audioTrack && !pipeline.audioSegmentStream) {
- // hook up the audio segment stream to the first track with aac data
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
- pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
- } // emit pmt info
-
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
- pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
- id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
- self.trigger('id3Frame', id3Frame);
- });
- pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- }; // hook up the segment streams once track metadata is delivered
-
-
- this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- var pipeline = this.transmuxPipeline_;
-
- if (!options.keepOriginalTimestamps) {
- this.baseMediaDecodeTime = baseMediaDecodeTime;
- }
-
- if (audioTrack) {
- audioTrack.timelineStartInfo.dts = undefined;
- audioTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(audioTrack);
-
- if (pipeline.audioTimestampRolloverStream) {
- pipeline.audioTimestampRolloverStream.discontinuity();
- }
- }
-
- if (videoTrack) {
- if (pipeline.videoSegmentStream) {
- pipeline.videoSegmentStream.gopCache_ = [];
- }
-
- videoTrack.timelineStartInfo.dts = undefined;
- videoTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(videoTrack);
- pipeline.captionStream.reset();
- }
-
- if (pipeline.timestampRolloverStream) {
- pipeline.timestampRolloverStream.discontinuity();
- }
- };
-
- this.setAudioAppendStart = function (timestamp) {
- if (audioTrack) {
- this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
- }
- };
-
- this.setRemux = function (val) {
- var pipeline = this.transmuxPipeline_;
- options.remux = val;
-
- if (pipeline && pipeline.coalesceStream) {
- pipeline.coalesceStream.setRemux(val);
- }
- };
-
- this.alignGopsWith = function (gopsToAlignWith) {
- if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
- this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
- }
- }; // feed incoming data to the front of the parsing pipeline
-
-
- this.push = function (data) {
- if (hasFlushed) {
- var isAac = isLikelyAacData(data);
-
- if (isAac && this.transmuxPipeline_.type !== 'aac') {
- this.setupAacPipeline();
- } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
- this.setupTsPipeline();
- }
-
- hasFlushed = false;
- }
-
- this.transmuxPipeline_.headOfPipeline.push(data);
- }; // flush any buffered data
-
-
- this.flush = function () {
- hasFlushed = true; // Start at the top of the pipeline and flush all pending work
-
- this.transmuxPipeline_.headOfPipeline.flush();
- };
-
- this.endTimeline = function () {
- this.transmuxPipeline_.headOfPipeline.endTimeline();
- };
-
- this.reset = function () {
- if (this.transmuxPipeline_.headOfPipeline) {
- this.transmuxPipeline_.headOfPipeline.reset();
- }
- }; // Caption data has to be reset when seeking outside buffered range
-
-
- this.resetCaptions = function () {
- if (this.transmuxPipeline_.captionStream) {
- this.transmuxPipeline_.captionStream.reset();
- }
- };
- };
-
- _Transmuxer.prototype = new stream();
- var transmuxer = {
- Transmuxer: _Transmuxer,
- VideoSegmentStream: _VideoSegmentStream,
- AudioSegmentStream: _AudioSegmentStream,
- AUDIO_PROPERTIES: audioProperties,
- VIDEO_PROPERTIES: videoProperties,
- // exported for testing
- generateSegmentTimingInfo: generateSegmentTimingInfo
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var toUnsigned$3 = function toUnsigned(value) {
- return value >>> 0;
- };
-
- var toHexString$1 = function toHexString(value) {
- return ('00' + value.toString(16)).slice(-2);
- };
-
- var bin = {
- toUnsigned: toUnsigned$3,
- toHexString: toHexString$1
- };
-
- var parseType$1 = function parseType(buffer) {
- var result = '';
- result += String.fromCharCode(buffer[0]);
- result += String.fromCharCode(buffer[1]);
- result += String.fromCharCode(buffer[2]);
- result += String.fromCharCode(buffer[3]);
- return result;
- };
-
- var parseType_1 = parseType$1;
- var toUnsigned$2 = bin.toUnsigned;
-
- var findBox = function findBox(data, path) {
- var results = [],
- i,
- size,
- type,
- end,
- subresults;
-
- if (!path.length) {
- // short-circuit the search for empty paths
- return null;
- }
-
- for (i = 0; i < data.byteLength;) {
- size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
- type = parseType_1(data.subarray(i + 4, i + 8));
- end = size > 1 ? i + size : data.byteLength;
-
- if (type === path[0]) {
- if (path.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data.subarray(i + 8, end));
- } else {
- // recursively search for the next box along the path
- subresults = findBox(data.subarray(i + 8, end), path.slice(1));
-
- if (subresults.length) {
- results = results.concat(subresults);
- }
- }
- }
-
- i = end;
- } // we've finished searching all of data
-
-
- return results;
- };
-
- var findBox_1 = findBox;
- var toUnsigned$1 = bin.toUnsigned;
-
- var tfdt = function tfdt(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- baseMediaDecodeTime: toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7])
- };
-
- if (result.version === 1) {
- result.baseMediaDecodeTime *= Math.pow(2, 32);
- result.baseMediaDecodeTime += toUnsigned$1(data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11]);
- }
-
- return result;
- };
-
- var parseTfdt = tfdt;
-
- var parseSampleFlags = function parseSampleFlags(flags) {
- return {
- isLeading: (flags[0] & 0x0c) >>> 2,
- dependsOn: flags[0] & 0x03,
- isDependedOn: (flags[1] & 0xc0) >>> 6,
- hasRedundancy: (flags[1] & 0x30) >>> 4,
- paddingValue: (flags[1] & 0x0e) >>> 1,
- isNonSyncSample: flags[1] & 0x01,
- degradationPriority: flags[2] << 8 | flags[3]
- };
- };
-
- var parseSampleFlags_1 = parseSampleFlags;
-
- var trun = function trun(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- samples: []
- },
- view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- // Flag interpretation
- dataOffsetPresent = result.flags[2] & 0x01,
- // compare with 2nd byte of 0x1
- firstSampleFlagsPresent = result.flags[2] & 0x04,
- // compare with 2nd byte of 0x4
- sampleDurationPresent = result.flags[1] & 0x01,
- // compare with 2nd byte of 0x100
- sampleSizePresent = result.flags[1] & 0x02,
- // compare with 2nd byte of 0x200
- sampleFlagsPresent = result.flags[1] & 0x04,
- // compare with 2nd byte of 0x400
- sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
- // compare with 2nd byte of 0x800
- sampleCount = view.getUint32(4),
- offset = 8,
- sample;
-
- if (dataOffsetPresent) {
- // 32 bit signed integer
- result.dataOffset = view.getInt32(offset);
- offset += 4;
- } // Overrides the flags for the first sample only. The order of
- // optional values will be: duration, size, compositionTimeOffset
-
-
- if (firstSampleFlagsPresent && sampleCount) {
- sample = {
- flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
- };
- offset += 4;
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- sampleCount--;
- }
-
- while (sampleCount--) {
- sample = {};
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleFlagsPresent) {
- sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- }
-
- return result;
- };
-
- var parseTrun = trun;
-
- var tfhd = function tfhd(data) {
- var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- trackId: view.getUint32(4)
- },
- baseDataOffsetPresent = result.flags[2] & 0x01,
- sampleDescriptionIndexPresent = result.flags[2] & 0x02,
- defaultSampleDurationPresent = result.flags[2] & 0x08,
- defaultSampleSizePresent = result.flags[2] & 0x10,
- defaultSampleFlagsPresent = result.flags[2] & 0x20,
- durationIsEmpty = result.flags[0] & 0x010000,
- defaultBaseIsMoof = result.flags[0] & 0x020000,
- i;
- i = 8;
-
- if (baseDataOffsetPresent) {
- i += 4; // truncate top 4 bytes
- // FIXME: should we read the full 64 bits?
-
- result.baseDataOffset = view.getUint32(12);
- i += 4;
- }
-
- if (sampleDescriptionIndexPresent) {
- result.sampleDescriptionIndex = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleDurationPresent) {
- result.defaultSampleDuration = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleSizePresent) {
- result.defaultSampleSize = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleFlagsPresent) {
- result.defaultSampleFlags = view.getUint32(i);
- }
-
- if (durationIsEmpty) {
- result.durationIsEmpty = true;
- }
-
- if (!baseDataOffsetPresent && defaultBaseIsMoof) {
- result.baseDataOffsetIsMoof = true;
- }
-
- return result;
- };
-
- var parseTfhd = tfhd;
- var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
- var CaptionStream = captionStream.CaptionStream;
- /**
- * Maps an offset in the mdat to a sample based on the the size of the samples.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Number} offset - The offset into the mdat
- * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
- * @return {?Object} The matching sample, or null if no match was found.
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
- var mapToSample = function mapToSample(offset, samples) {
- var approximateOffset = offset;
-
- for (var i = 0; i < samples.length; i++) {
- var sample = samples[i];
-
- if (approximateOffset < sample.size) {
- return sample;
- }
-
- approximateOffset -= sample.size;
- }
-
- return null;
- };
- /**
- * Finds SEI nal units contained in a Media Data Box.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Uint8Array} avcStream - The bytes of the mdat
- * @param {Object[]} samples - The samples parsed out by `parseSamples`
- * @param {Number} trackId - The trackId of this video track
- * @return {Object[]} seiNals - the parsed SEI NALUs found.
- * The contents of the seiNal should match what is expected by
- * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
- *
- * @see ISO-BMFF-12/2015, Section 8.1.1
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- **/
-
-
- var findSeiNals = function findSeiNals(avcStream, samples, trackId) {
- var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
- result = [],
- seiNal,
- i,
- length,
- lastMatchedSample;
-
- for (i = 0; i + 4 < avcStream.length; i += length) {
- length = avcView.getUint32(i);
- i += 4; // Bail if this doesn't appear to be an H264 stream
-
- if (length <= 0) {
- continue;
- }
-
- switch (avcStream[i] & 0x1F) {
- case 0x06:
- var data = avcStream.subarray(i + 1, i + 1 + length);
- var matchingSample = mapToSample(i, samples);
- seiNal = {
- nalUnitType: 'sei_rbsp',
- size: length,
- data: data,
- escapedRBSP: discardEmulationPreventionBytes(data),
- trackId: trackId
- };
-
- if (matchingSample) {
- seiNal.pts = matchingSample.pts;
- seiNal.dts = matchingSample.dts;
- lastMatchedSample = matchingSample;
- } else if (lastMatchedSample) {
- // If a matching sample cannot be found, use the last
- // sample's values as they should be as close as possible
- seiNal.pts = lastMatchedSample.pts;
- seiNal.dts = lastMatchedSample.dts;
- } else {
- // eslint-disable-next-line no-console
- console.log("We've encountered a nal unit without data. See mux.js#233.");
- break;
- }
-
- result.push(seiNal);
- break;
- }
- }
-
- return result;
- };
- /**
- * Parses sample information out of Track Run Boxes and calculates
- * the absolute presentation and decode timestamps of each sample.
- *
- * @param {Array} truns - The Trun Run boxes to be parsed
- * @param {Number} baseMediaDecodeTime - base media decode time from tfdt
- @see ISO-BMFF-12/2015, Section 8.8.12
- * @param {Object} tfhd - The parsed Track Fragment Header
- * @see inspect.parseTfhd
- * @return {Object[]} the parsed samples
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
-
- var parseSamples = function parseSamples(truns, baseMediaDecodeTime, tfhd) {
- var currentDts = baseMediaDecodeTime;
- var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
- var defaultSampleSize = tfhd.defaultSampleSize || 0;
- var trackId = tfhd.trackId;
- var allSamples = [];
- truns.forEach(function (trun) {
- // Note: We currently do not parse the sample table as well
- // as the trun. It's possible some sources will require this.
- // moov > trak > mdia > minf > stbl
- var trackRun = parseTrun(trun);
- var samples = trackRun.samples;
- samples.forEach(function (sample) {
- if (sample.duration === undefined) {
- sample.duration = defaultSampleDuration;
- }
-
- if (sample.size === undefined) {
- sample.size = defaultSampleSize;
- }
-
- sample.trackId = trackId;
- sample.dts = currentDts;
-
- if (sample.compositionTimeOffset === undefined) {
- sample.compositionTimeOffset = 0;
- }
-
- sample.pts = currentDts + sample.compositionTimeOffset;
- currentDts += sample.duration;
- });
- allSamples = allSamples.concat(samples);
- });
- return allSamples;
- };
- /**
- * Parses out caption nals from an FMP4 segment's video tracks.
- *
- * @param {Uint8Array} segment - The bytes of a single segment
- * @param {Number} videoTrackId - The trackId of a video track in the segment
- * @return {Object.} A mapping of video trackId to
- * a list of seiNals found in that track
- **/
-
-
- var parseCaptionNals = function parseCaptionNals(segment, videoTrackId) {
- // To get the samples
- var trafs = findBox_1(segment, ['moof', 'traf']); // To get SEI NAL units
-
- var mdats = findBox_1(segment, ['mdat']);
- var captionNals = {};
- var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
-
- mdats.forEach(function (mdat, index) {
- var matchingTraf = trafs[index];
- mdatTrafPairs.push({
- mdat: mdat,
- traf: matchingTraf
- });
- });
- mdatTrafPairs.forEach(function (pair) {
- var mdat = pair.mdat;
- var traf = pair.traf;
- var tfhd = findBox_1(traf, ['tfhd']); // Exactly 1 tfhd per traf
-
- var headerInfo = parseTfhd(tfhd[0]);
- var trackId = headerInfo.trackId;
- var tfdt = findBox_1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
-
- var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
- var truns = findBox_1(traf, ['trun']);
- var samples;
- var seiNals; // Only parse video data for the chosen video track
-
- if (videoTrackId === trackId && truns.length > 0) {
- samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
- seiNals = findSeiNals(mdat, samples, trackId);
-
- if (!captionNals[trackId]) {
- captionNals[trackId] = [];
- }
-
- captionNals[trackId] = captionNals[trackId].concat(seiNals);
- }
- });
- return captionNals;
- };
- /**
- * Parses out inband captions from an MP4 container and returns
- * caption objects that can be used by WebVTT and the TextTrack API.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
- * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
- * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number} trackId - The id of the video track to parse
- * @param {Number} timescale - The timescale for the video track from the init segment
- *
- * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
- * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
- * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
- * @return {String} parsedCaptions[].text - The visible content of the caption
- **/
-
-
- var parseEmbeddedCaptions = function parseEmbeddedCaptions(segment, trackId, timescale) {
- var seiNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
-
- if (trackId === null) {
- return null;
- }
-
- seiNals = parseCaptionNals(segment, trackId);
- return {
- seiNals: seiNals[trackId],
- timescale: timescale
- };
- };
- /**
- * Converts SEI NALUs into captions that can be used by video.js
- **/
-
-
- var CaptionParser = function CaptionParser() {
- var isInitialized = false;
- var captionStream; // Stores segments seen before trackId and timescale are set
-
- var segmentCache; // Stores video track ID of the track being parsed
-
- var trackId; // Stores the timescale of the track being parsed
-
- var timescale; // Stores captions parsed so far
-
- var parsedCaptions; // Stores whether we are receiving partial data or not
-
- var parsingPartial;
- /**
- * A method to indicate whether a CaptionParser has been initalized
- * @returns {Boolean}
- **/
-
- this.isInitialized = function () {
- return isInitialized;
- };
- /**
- * Initializes the underlying CaptionStream, SEI NAL parsing
- * and management, and caption collection
- **/
-
-
- this.init = function (options) {
- captionStream = new CaptionStream();
- isInitialized = true;
- parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
-
- captionStream.on('data', function (event) {
- // Convert to seconds in the source's timescale
- event.startTime = event.startPts / timescale;
- event.endTime = event.endPts / timescale;
- parsedCaptions.captions.push(event);
- parsedCaptions.captionStreams[event.stream] = true;
- });
- };
- /**
- * Determines if a new video track will be selected
- * or if the timescale changed
- * @return {Boolean}
- **/
-
-
- this.isNewInit = function (videoTrackIds, timescales) {
- if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
- return false;
- }
-
- return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
- };
- /**
- * Parses out SEI captions and interacts with underlying
- * CaptionStream to return dispatched captions
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
- * @param {Object.} timescales - The timescales found in the init segment
- * @see parseEmbeddedCaptions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.parse = function (segment, videoTrackIds, timescales) {
- var parsedData;
-
- if (!this.isInitialized()) {
- return null; // This is not likely to be a video segment
- } else if (!videoTrackIds || !timescales) {
- return null;
- } else if (this.isNewInit(videoTrackIds, timescales)) {
- // Use the first video track only as there is no
- // mechanism to switch to other video tracks
- trackId = videoTrackIds[0];
- timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
- // data until we have one.
- // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
- } else if (trackId === null || !timescale) {
- segmentCache.push(segment);
- return null;
- } // Now that a timescale and trackId is set, parse cached segments
-
-
- while (segmentCache.length > 0) {
- var cachedSegment = segmentCache.shift();
- this.parse(cachedSegment, videoTrackIds, timescales);
- }
-
- parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
-
- if (parsedData === null || !parsedData.seiNals) {
- return null;
- }
-
- this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
-
- this.flushStream();
- return parsedCaptions;
- };
- /**
- * Pushes SEI NALUs onto CaptionStream
- * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
- * Assumes that `parseCaptionNals` has been called first
- * @see m2ts/caption-stream.js
- **/
-
-
- this.pushNals = function (nals) {
- if (!this.isInitialized() || !nals || nals.length === 0) {
- return null;
- }
-
- nals.forEach(function (nal) {
- captionStream.push(nal);
- });
- };
- /**
- * Flushes underlying CaptionStream to dispatch processed, displayable captions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.flushStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- if (!parsingPartial) {
- captionStream.flush();
- } else {
- captionStream.partialFlush();
- }
- };
- /**
- * Reset caption buckets for new data
- **/
-
-
- this.clearParsedCaptions = function () {
- parsedCaptions.captions = [];
- parsedCaptions.captionStreams = {};
- };
- /**
- * Resets underlying CaptionStream
- * @see m2ts/caption-stream.js
- **/
-
-
- this.resetCaptionStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- captionStream.reset();
- };
- /**
- * Convenience method to clear all captions flushed from the
- * CaptionStream and still being parsed
- * @see m2ts/caption-stream.js
- **/
-
-
- this.clearAllCaptions = function () {
- this.clearParsedCaptions();
- this.resetCaptionStream();
- };
- /**
- * Reset caption parser
- **/
-
-
- this.reset = function () {
- segmentCache = [];
- trackId = null;
- timescale = null;
-
- if (!parsedCaptions) {
- parsedCaptions = {
- captions: [],
- // CC1, CC2, CC3, CC4
- captionStreams: {}
- };
- } else {
- this.clearParsedCaptions();
- }
-
- this.resetCaptionStream();
- };
-
- this.reset();
- };
-
- var captionParser = CaptionParser;
- var toUnsigned = bin.toUnsigned;
- var toHexString = bin.toHexString;
- var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader;
- /**
- * Parses an MP4 initialization segment and extracts the timescale
- * values for any declared tracks. Timescale values indicate the
- * number of clock ticks per second to assume for time-based values
- * elsewhere in the MP4.
- *
- * To determine the start time of an MP4, you need two pieces of
- * information: the timescale unit and the earliest base media decode
- * time. Multiple timescales can be specified within an MP4 but the
- * base media decode time is always expressed in the timescale from
- * the media header box for the track:
- * ```
- * moov > trak > mdia > mdhd.timescale
- * ```
- * @param init {Uint8Array} the bytes of the init segment
- * @return {object} a hash of track ids to timescale values or null if
- * the init segment is malformed.
- */
-
- timescale = function timescale(init) {
- var result = {},
- traks = findBox_1(init, ['moov', 'trak']); // mdhd timescale
-
- return traks.reduce(function (result, trak) {
- var tkhd, version, index, id, mdhd;
- tkhd = findBox_1(trak, ['tkhd'])[0];
-
- if (!tkhd) {
- return null;
- }
-
- version = tkhd[0];
- index = version === 0 ? 12 : 20;
- id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
- mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
-
- if (!mdhd) {
- return null;
- }
-
- version = mdhd[0];
- index = version === 0 ? 12 : 20;
- result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
- return result;
- }, result);
- };
- /**
- * Determine the base media decode start time, in seconds, for an MP4
- * fragment. If multiple fragments are specified, the earliest time is
- * returned.
- *
- * The base media decode time can be parsed from track fragment
- * metadata:
- * ```
- * moof > traf > tfdt.baseMediaDecodeTime
- * ```
- * It requires the timescale value from the mdhd to interpret.
- *
- * @param timescale {object} a hash of track ids to timescale values.
- * @return {number} the earliest base media decode start time for the
- * fragment, in seconds
- */
-
-
- startTime = function startTime(timescale, fragment) {
- var trafs, baseTimes, result; // we need info from two childrend of each track fragment box
-
- trafs = findBox_1(fragment, ['moof', 'traf']); // determine the start times for each track
-
- baseTimes = [].concat.apply([], trafs.map(function (traf) {
- return findBox_1(traf, ['tfhd']).map(function (tfhd) {
- var id, scale, baseTime; // get the track id from the tfhd
-
- id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
-
- scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
-
- baseTime = findBox_1(traf, ['tfdt']).map(function (tfdt) {
- var version, result;
- version = tfdt[0];
- result = toUnsigned(tfdt[4] << 24 | tfdt[5] << 16 | tfdt[6] << 8 | tfdt[7]);
-
- if (version === 1) {
- result *= Math.pow(2, 32);
- result += toUnsigned(tfdt[8] << 24 | tfdt[9] << 16 | tfdt[10] << 8 | tfdt[11]);
- }
-
- return result;
- })[0];
- baseTime = typeof baseTime === 'number' && !isNaN(baseTime) ? baseTime : Infinity; // convert base time to seconds
-
- return baseTime / scale;
- });
- })); // return the minimum
-
- result = Math.min.apply(null, baseTimes);
- return isFinite(result) ? result : 0;
- };
- /**
- * Determine the composition start, in seconds, for an MP4
- * fragment.
- *
- * The composition start time of a fragment can be calculated using the base
- * media decode time, composition time offset, and timescale, as follows:
- *
- * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
- *
- * All of the aforementioned information is contained within a media fragment's
- * `traf` box, except for timescale info, which comes from the initialization
- * segment, so a track id (also contained within a `traf`) is also necessary to
- * associate it with a timescale
- *
- *
- * @param timescales {object} - a hash of track ids to timescale values.
- * @param fragment {Unit8Array} - the bytes of a media segment
- * @return {number} the composition start time for the fragment, in seconds
- **/
-
-
- compositionStartTime = function compositionStartTime(timescales, fragment) {
- var trafBoxes = findBox_1(fragment, ['moof', 'traf']);
- var baseMediaDecodeTime = 0;
- var compositionTimeOffset = 0;
- var trackId;
-
- if (trafBoxes && trafBoxes.length) {
- // The spec states that track run samples contained within a `traf` box are contiguous, but
- // it does not explicitly state whether the `traf` boxes themselves are contiguous.
- // We will assume that they are, so we only need the first to calculate start time.
- var tfhd = findBox_1(trafBoxes[0], ['tfhd'])[0];
- var trun = findBox_1(trafBoxes[0], ['trun'])[0];
- var tfdt = findBox_1(trafBoxes[0], ['tfdt'])[0];
-
- if (tfhd) {
- var parsedTfhd = parseTfhd(tfhd);
- trackId = parsedTfhd.trackId;
- }
-
- if (tfdt) {
- var parsedTfdt = parseTfdt(tfdt);
- baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
- }
-
- if (trun) {
- var parsedTrun = parseTrun(trun);
-
- if (parsedTrun.samples && parsedTrun.samples.length) {
- compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
- }
- }
- } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
- // specified.
-
-
- var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
-
- return (baseMediaDecodeTime + compositionTimeOffset) / timescale;
- };
- /**
- * Find the trackIds of the video tracks in this source.
- * Found by parsing the Handler Reference and Track Header Boxes:
- * moov > trak > mdia > hdlr
- * moov > trak > tkhd
- *
- * @param {Uint8Array} init - The bytes of the init segment for this source
- * @return {Number[]} A list of trackIds
- *
- * @see ISO-BMFF-12/2015, Section 8.4.3
- **/
-
-
- getVideoTrackIds = function getVideoTrackIds(init) {
- var traks = findBox_1(init, ['moov', 'trak']);
- var videoTrackIds = [];
- traks.forEach(function (trak) {
- var hdlrs = findBox_1(trak, ['mdia', 'hdlr']);
- var tkhds = findBox_1(trak, ['tkhd']);
- hdlrs.forEach(function (hdlr, index) {
- var handlerType = parseType_1(hdlr.subarray(8, 12));
- var tkhd = tkhds[index];
- var view;
- var version;
- var trackId;
-
- if (handlerType === 'vide') {
- view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- version = view.getUint8(0);
- trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
- videoTrackIds.push(trackId);
- }
- });
- });
- return videoTrackIds;
- };
-
- getTimescaleFromMediaHeader = function getTimescaleFromMediaHeader(mdhd) {
- // mdhd is a FullBox, meaning it will have its own version as the first byte
- var version = mdhd[0];
- var index = version === 0 ? 12 : 20;
- return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
- };
- /**
- * Get all the video, audio, and hint tracks from a non fragmented
- * mp4 segment
- */
-
-
- getTracks = function getTracks(init) {
- var traks = findBox_1(init, ['moov', 'trak']);
- var tracks = [];
- traks.forEach(function (trak) {
- var track = {};
- var tkhd = findBox_1(trak, ['tkhd'])[0];
- var view, tkhdVersion; // id
-
- if (tkhd) {
- view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- tkhdVersion = view.getUint8(0);
- track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
- }
-
- var hdlr = findBox_1(trak, ['mdia', 'hdlr'])[0]; // type
-
- if (hdlr) {
- var type = parseType_1(hdlr.subarray(8, 12));
-
- if (type === 'vide') {
- track.type = 'video';
- } else if (type === 'soun') {
- track.type = 'audio';
- } else {
- track.type = type;
- }
- } // codec
-
-
- var stsd = findBox_1(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
-
- if (stsd) {
- var sampleDescriptions = stsd.subarray(8); // gives the codec type string
-
- track.codec = parseType_1(sampleDescriptions.subarray(4, 8));
- var codecBox = findBox_1(sampleDescriptions, [track.codec])[0];
- var codecConfig, codecConfigType;
-
- if (codecBox) {
- // https://tools.ietf.org/html/rfc6381#section-3.3
- if (/^[a-z]vc[1-9]$/i.test(track.codec)) {
- // we don't need anything but the "config" parameter of the
- // avc1 codecBox
- codecConfig = codecBox.subarray(78);
- codecConfigType = parseType_1(codecConfig.subarray(4, 8));
-
- if (codecConfigType === 'avcC' && codecConfig.length > 11) {
- track.codec += '.'; // left padded with zeroes for single digit hex
- // profile idc
-
- track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
-
- track.codec += toHexString(codecConfig[10]); // level idc
-
- track.codec += toHexString(codecConfig[11]);
- } else {
- // TODO: show a warning that we couldn't parse the codec
- // and are using the default
- track.codec = 'avc1.4d400d';
- }
- } else if (/^mp4[a,v]$/i.test(track.codec)) {
- // we do not need anything but the streamDescriptor of the mp4a codecBox
- codecConfig = codecBox.subarray(28);
- codecConfigType = parseType_1(codecConfig.subarray(4, 8));
-
- if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
- track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
-
- track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
- } else {
- // TODO: show a warning that we couldn't parse the codec
- // and are using the default
- track.codec = 'mp4a.40.2';
- }
- } else {
- // flac, opus, etc
- track.codec = track.codec.toLowerCase();
- }
- }
- }
-
- var mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
-
- if (mdhd) {
- track.timescale = getTimescaleFromMediaHeader(mdhd);
- }
-
- tracks.push(track);
- });
- return tracks;
- };
-
- var probe$2 = {
- // export mp4 inspector's findBox and parseType for backwards compatibility
- findBox: findBox_1,
- parseType: parseType_1,
- timescale: timescale,
- startTime: startTime,
- compositionStartTime: compositionStartTime,
- videoTrackIds: getVideoTrackIds,
- tracks: getTracks,
- getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
- };
-
- var parsePid = function parsePid(packet) {
- var pid = packet[1] & 0x1f;
- pid <<= 8;
- pid |= packet[2];
- return pid;
- };
-
- var parsePayloadUnitStartIndicator = function parsePayloadUnitStartIndicator(packet) {
- return !!(packet[1] & 0x40);
- };
-
- var parseAdaptionField = function parseAdaptionField(packet) {
- var offset = 0; // if an adaption field is present, its length is specified by the
- // fifth byte of the TS packet header. The adaptation field is
- // used to add stuffing to PES packets that don't fill a complete
- // TS packet, and to specify some forms of timing and control data
- // that we do not currently use.
-
- if ((packet[3] & 0x30) >>> 4 > 0x01) {
- offset += packet[4] + 1;
- }
-
- return offset;
- };
-
- var parseType = function parseType(packet, pmtPid) {
- var pid = parsePid(packet);
-
- if (pid === 0) {
- return 'pat';
- } else if (pid === pmtPid) {
- return 'pmt';
- } else if (pmtPid) {
- return 'pes';
- }
-
- return null;
- };
-
- var parsePat = function parsePat(packet) {
- var pusi = parsePayloadUnitStartIndicator(packet);
- var offset = 4 + parseAdaptionField(packet);
-
- if (pusi) {
- offset += packet[offset] + 1;
- }
-
- return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
- };
-
- var parsePmt = function parsePmt(packet) {
- var programMapTable = {};
- var pusi = parsePayloadUnitStartIndicator(packet);
- var payloadOffset = 4 + parseAdaptionField(packet);
-
- if (pusi) {
- payloadOffset += packet[payloadOffset] + 1;
- } // PMTs can be sent ahead of the time when they should actually
- // take effect. We don't believe this should ever be the case
- // for HLS but we'll ignore "forward" PMT declarations if we see
- // them. Future PMT declarations have the current_next_indicator
- // set to zero.
-
-
- if (!(packet[payloadOffset + 5] & 0x01)) {
- return;
- }
-
- var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
-
- sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
- tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
- // long the program info descriptors are
-
- programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
-
- var offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
-
- programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
- // skip past the elementary stream descriptors, if present
-
- offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
- }
-
- return programMapTable;
- };
-
- var parsePesType = function parsePesType(packet, programMapTable) {
- var pid = parsePid(packet);
- var type = programMapTable[pid];
-
- switch (type) {
- case streamTypes.H264_STREAM_TYPE:
- return 'video';
-
- case streamTypes.ADTS_STREAM_TYPE:
- return 'audio';
-
- case streamTypes.METADATA_STREAM_TYPE:
- return 'timed-metadata';
-
- default:
- return null;
- }
- };
-
- var parsePesTime = function parsePesTime(packet) {
- var pusi = parsePayloadUnitStartIndicator(packet);
-
- if (!pusi) {
- return null;
- }
-
- var offset = 4 + parseAdaptionField(packet);
-
- if (offset >= packet.byteLength) {
- // From the H 222.0 MPEG-TS spec
- // "For transport stream packets carrying PES packets, stuffing is needed when there
- // is insufficient PES packet data to completely fill the transport stream packet
- // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
- // the sum of the lengths of the data elements in it, so that the payload bytes
- // remaining after the adaptation field exactly accommodates the available PES packet
- // data."
- //
- // If the offset is >= the length of the packet, then the packet contains no data
- // and instead is just adaption field stuffing bytes
- return null;
- }
-
- var pes = null;
- var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
- // and a DTS value. Determine what combination of values is
- // available to work with.
-
- ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
- // performs all bitwise operations on 32-bit integers but javascript
- // supports a much greater range (52-bits) of integer using standard
- // mathematical operations.
- // We construct a 31-bit value using bitwise operators over the 31
- // most significant bits and then multiply by 4 (equal to a left-shift
- // of 2) before we add the final 2 least significant bits of the
- // timestamp (equal to an OR.)
-
- if (ptsDtsFlags & 0xC0) {
- pes = {}; // the PTS and DTS are not written out directly. For information
- // on how they are encoded, see
- // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
-
- pes.pts = (packet[offset + 9] & 0x0E) << 27 | (packet[offset + 10] & 0xFF) << 20 | (packet[offset + 11] & 0xFE) << 12 | (packet[offset + 12] & 0xFF) << 5 | (packet[offset + 13] & 0xFE) >>> 3;
- pes.pts *= 4; // Left shift by 2
-
- pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
-
- pes.dts = pes.pts;
-
- if (ptsDtsFlags & 0x40) {
- pes.dts = (packet[offset + 14] & 0x0E) << 27 | (packet[offset + 15] & 0xFF) << 20 | (packet[offset + 16] & 0xFE) << 12 | (packet[offset + 17] & 0xFF) << 5 | (packet[offset + 18] & 0xFE) >>> 3;
- pes.dts *= 4; // Left shift by 2
-
- pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
- }
- }
-
- return pes;
- };
-
- var parseNalUnitType = function parseNalUnitType(type) {
- switch (type) {
- case 0x05:
- return 'slice_layer_without_partitioning_rbsp_idr';
-
- case 0x06:
- return 'sei_rbsp';
-
- case 0x07:
- return 'seq_parameter_set_rbsp';
-
- case 0x08:
- return 'pic_parameter_set_rbsp';
-
- case 0x09:
- return 'access_unit_delimiter_rbsp';
-
- default:
- return null;
- }
- };
-
- var videoPacketContainsKeyFrame = function videoPacketContainsKeyFrame(packet) {
- var offset = 4 + parseAdaptionField(packet);
- var frameBuffer = packet.subarray(offset);
- var frameI = 0;
- var frameSyncPoint = 0;
- var foundKeyFrame = false;
- var nalType; // advance the sync point to a NAL start, if necessary
-
- for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
- if (frameBuffer[frameSyncPoint + 2] === 1) {
- // the sync point is properly aligned
- frameI = frameSyncPoint + 5;
- break;
- }
- }
-
- while (frameI < frameBuffer.byteLength) {
- // look at the current byte to determine if we've hit the end of
- // a NAL unit boundary
- switch (frameBuffer[frameI]) {
- case 0:
- // skip past non-sync sequences
- if (frameBuffer[frameI - 1] !== 0) {
- frameI += 2;
- break;
- } else if (frameBuffer[frameI - 2] !== 0) {
- frameI++;
- break;
- }
-
- if (frameSyncPoint + 3 !== frameI - 2) {
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
- } // drop trailing zeroes
-
-
- do {
- frameI++;
- } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
-
- frameSyncPoint = frameI - 2;
- frameI += 3;
- break;
-
- case 1:
- // skip past non-sync sequences
- if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
- frameI += 3;
- break;
- }
-
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
-
- frameSyncPoint = frameI - 2;
- frameI += 3;
- break;
-
- default:
- // the current byte isn't a one or zero, so it cannot be part
- // of a sync sequence
- frameI += 3;
- break;
- }
- }
-
- frameBuffer = frameBuffer.subarray(frameSyncPoint);
- frameI -= frameSyncPoint;
- frameSyncPoint = 0; // parse the final nal
-
- if (frameBuffer && frameBuffer.byteLength > 3) {
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
- }
-
- return foundKeyFrame;
- };
-
- var probe$1 = {
- parseType: parseType,
- parsePat: parsePat,
- parsePmt: parsePmt,
- parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
- parsePesType: parsePesType,
- parsePesTime: parsePesTime,
- videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
- };
- var handleRollover = timestampRolloverStream.handleRollover;
- var probe = {};
- probe.ts = probe$1;
- probe.aac = utils;
- var ONE_SECOND_IN_TS = clock.ONE_SECOND_IN_TS;
- var MP2T_PACKET_LENGTH = 188,
- // bytes
- SYNC_BYTE = 0x47;
- /**
- * walks through segment data looking for pat and pmt packets to parse out
- * program map table information
- */
-
- var parsePsi_ = function parsePsi_(bytes, pmt) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type;
-
- while (endIndex < bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pat':
- pmt.pid = probe.ts.parsePat(packet);
- break;
-
- case 'pmt':
- var table = probe.ts.parsePmt(packet);
- pmt.table = pmt.table || {};
- Object.keys(table).forEach(function (key) {
- pmt.table[key] = table[key];
- });
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- }
- };
- /**
- * walks through the segment data from the start and end to get timing information
- * for the first and last audio pes packets
- */
-
-
- var parseAudioPes_ = function parseAudioPes_(bytes, pmt, result) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type,
- pesType,
- pusi,
- parsed;
- var endLoop = false; // Start walking from start of segment to get first audio packet
-
- while (endIndex <= bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'audio' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'audio';
- result.audio.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // Start walking from end of segment to get last audio packet
-
-
- endIndex = bytes.byteLength;
- startIndex = endIndex - MP2T_PACKET_LENGTH;
- endLoop = false;
-
- while (startIndex >= 0) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'audio' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'audio';
- result.audio.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex -= MP2T_PACKET_LENGTH;
- endIndex -= MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex--;
- endIndex--;
- }
- };
- /**
- * walks through the segment data from the start and end to get timing information
- * for the first and last video pes packets as well as timing information for the first
- * key frame.
- */
-
-
- var parseVideoPes_ = function parseVideoPes_(bytes, pmt, result) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type,
- pesType,
- pusi,
- parsed,
- frame,
- i,
- pes;
- var endLoop = false;
- var currentFrame = {
- data: [],
- size: 0
- }; // Start walking from start of segment to get first video packet
-
- while (endIndex < bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'video') {
- if (pusi && !endLoop) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'video';
- result.video.push(parsed);
- endLoop = true;
- }
- }
-
- if (!result.firstKeyFrame) {
- if (pusi) {
- if (currentFrame.size !== 0) {
- frame = new Uint8Array(currentFrame.size);
- i = 0;
-
- while (currentFrame.data.length) {
- pes = currentFrame.data.shift();
- frame.set(pes, i);
- i += pes.byteLength;
- }
-
- if (probe.ts.videoPacketContainsKeyFrame(frame)) {
- var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
- // the keyframe seems to work fine with HLS playback
- // and definitely preferable to a crash with TypeError...
-
- if (firstKeyFrame) {
- result.firstKeyFrame = firstKeyFrame;
- result.firstKeyFrame.type = 'video';
- } else {
- // eslint-disable-next-line
- console.warn('Failed to extract PTS/DTS from PES at first keyframe. ' + 'This could be an unusual TS segment, or else mux.js did not ' + 'parse your TS segment correctly. If you know your TS ' + 'segments do contain PTS/DTS on keyframes please file a bug ' + 'report! You can try ffprobe to double check for yourself.');
- }
- }
-
- currentFrame.size = 0;
- }
- }
-
- currentFrame.data.push(packet);
- currentFrame.size += packet.byteLength;
- }
- }
-
- break;
- }
-
- if (endLoop && result.firstKeyFrame) {
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // Start walking from end of segment to get last video packet
-
-
- endIndex = bytes.byteLength;
- startIndex = endIndex - MP2T_PACKET_LENGTH;
- endLoop = false;
-
- while (startIndex >= 0) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'video' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'video';
- result.video.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex -= MP2T_PACKET_LENGTH;
- endIndex -= MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex--;
- endIndex--;
- }
- };
- /**
- * Adjusts the timestamp information for the segment to account for
- * rollover and convert to seconds based on pes packet timescale (90khz clock)
- */
-
-
- var adjustTimestamp_ = function adjustTimestamp_(segmentInfo, baseTimestamp) {
- if (segmentInfo.audio && segmentInfo.audio.length) {
- var audioBaseTimestamp = baseTimestamp;
-
- if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
- audioBaseTimestamp = segmentInfo.audio[0].dts;
- }
-
- segmentInfo.audio.forEach(function (info) {
- info.dts = handleRollover(info.dts, audioBaseTimestamp);
- info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
-
- info.dtsTime = info.dts / ONE_SECOND_IN_TS;
- info.ptsTime = info.pts / ONE_SECOND_IN_TS;
- });
- }
-
- if (segmentInfo.video && segmentInfo.video.length) {
- var videoBaseTimestamp = baseTimestamp;
-
- if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
- videoBaseTimestamp = segmentInfo.video[0].dts;
- }
-
- segmentInfo.video.forEach(function (info) {
- info.dts = handleRollover(info.dts, videoBaseTimestamp);
- info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
-
- info.dtsTime = info.dts / ONE_SECOND_IN_TS;
- info.ptsTime = info.pts / ONE_SECOND_IN_TS;
- });
-
- if (segmentInfo.firstKeyFrame) {
- var frame = segmentInfo.firstKeyFrame;
- frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
- frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
-
- frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
- frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
- }
- }
- };
- /**
- * inspects the aac data stream for start and end time information
- */
-
-
- var inspectAac_ = function inspectAac_(bytes) {
- var endLoop = false,
- audioCount = 0,
- sampleRate = null,
- timestamp = null,
- frameSize = 0,
- byteIndex = 0,
- packet;
-
- while (bytes.length - byteIndex >= 3) {
- var type = probe.aac.parseType(bytes, byteIndex);
-
- switch (type) {
- case 'timed-metadata':
- // Exit early because we don't have enough to parse
- // the ID3 tag header
- if (bytes.length - byteIndex < 10) {
- endLoop = true;
- break;
- }
-
- frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (frameSize > bytes.length) {
- endLoop = true;
- break;
- }
-
- if (timestamp === null) {
- packet = bytes.subarray(byteIndex, byteIndex + frameSize);
- timestamp = probe.aac.parseAacTimestamp(packet);
- }
-
- byteIndex += frameSize;
- break;
-
- case 'audio':
- // Exit early because we don't have enough to parse
- // the ADTS frame header
- if (bytes.length - byteIndex < 7) {
- endLoop = true;
- break;
- }
-
- frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (frameSize > bytes.length) {
- endLoop = true;
- break;
- }
-
- if (sampleRate === null) {
- packet = bytes.subarray(byteIndex, byteIndex + frameSize);
- sampleRate = probe.aac.parseSampleRate(packet);
- }
-
- audioCount++;
- byteIndex += frameSize;
- break;
-
- default:
- byteIndex++;
- break;
- }
-
- if (endLoop) {
- return null;
- }
- }
-
- if (sampleRate === null || timestamp === null) {
- return null;
- }
-
- var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
- var result = {
- audio: [{
- type: 'audio',
- dts: timestamp,
- pts: timestamp
- }, {
- type: 'audio',
- dts: timestamp + audioCount * 1024 * audioTimescale,
- pts: timestamp + audioCount * 1024 * audioTimescale
- }]
- };
- return result;
- };
- /**
- * inspects the transport stream segment data for start and end time information
- * of the audio and video tracks (when present) as well as the first key frame's
- * start time.
- */
-
-
- var inspectTs_ = function inspectTs_(bytes) {
- var pmt = {
- pid: null,
- table: null
- };
- var result = {};
- parsePsi_(bytes, pmt);
-
- for (var pid in pmt.table) {
- if (pmt.table.hasOwnProperty(pid)) {
- var type = pmt.table[pid];
-
- switch (type) {
- case streamTypes.H264_STREAM_TYPE:
- result.video = [];
- parseVideoPes_(bytes, pmt, result);
-
- if (result.video.length === 0) {
- delete result.video;
- }
-
- break;
-
- case streamTypes.ADTS_STREAM_TYPE:
- result.audio = [];
- parseAudioPes_(bytes, pmt, result);
-
- if (result.audio.length === 0) {
- delete result.audio;
- }
-
- break;
- }
- }
- }
-
- return result;
- };
- /**
- * Inspects segment byte data and returns an object with start and end timing information
- *
- * @param {Uint8Array} bytes The segment byte data
- * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
- * timestamps for rollover. This value must be in 90khz clock.
- * @return {Object} Object containing start and end frame timing info of segment.
- */
-
-
- var inspect = function inspect(bytes, baseTimestamp) {
- var isAacData = probe.aac.isLikelyAacData(bytes);
- var result;
-
- if (isAacData) {
- result = inspectAac_(bytes);
- } else {
- result = inspectTs_(bytes);
- }
-
- if (!result || !result.audio && !result.video) {
- return null;
- }
-
- adjustTimestamp_(result, baseTimestamp);
- return result;
- };
-
- var tsInspector = {
- inspect: inspect,
- parseAudioPes_: parseAudioPes_
- };
- /* global self */
-
- /**
- * Re-emits transmuxer events by converting them into messages to the
- * world outside the worker.
- *
- * @param {Object} transmuxer the transmuxer to wire events on
- * @private
- */
-
- var wireTransmuxerEvents = function wireTransmuxerEvents(self, transmuxer) {
- transmuxer.on('data', function (segment) {
- // transfer ownership of the underlying ArrayBuffer
- // instead of doing a copy to save memory
- // ArrayBuffers are transferable but generic TypedArrays are not
- // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
- var initArray = segment.initSegment;
- segment.initSegment = {
- data: initArray.buffer,
- byteOffset: initArray.byteOffset,
- byteLength: initArray.byteLength
- };
- var typedArray = segment.data;
- segment.data = typedArray.buffer;
- self.postMessage({
- action: 'data',
- segment: segment,
- byteOffset: typedArray.byteOffset,
- byteLength: typedArray.byteLength
- }, [segment.data]);
- });
- transmuxer.on('done', function (data) {
- self.postMessage({
- action: 'done'
- });
- });
- transmuxer.on('gopInfo', function (gopInfo) {
- self.postMessage({
- action: 'gopInfo',
- gopInfo: gopInfo
- });
- });
- transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
- var videoSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- videoSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'videoSegmentTimingInfo',
- videoSegmentTimingInfo: videoSegmentTimingInfo
- });
- });
- transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
- // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
- var audioSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- audioSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'audioSegmentTimingInfo',
- audioSegmentTimingInfo: audioSegmentTimingInfo
- });
- });
- transmuxer.on('id3Frame', function (id3Frame) {
- self.postMessage({
- action: 'id3Frame',
- id3Frame: id3Frame
- });
- });
- transmuxer.on('caption', function (caption) {
- self.postMessage({
- action: 'caption',
- caption: caption
- });
- });
- transmuxer.on('trackinfo', function (trackInfo) {
- self.postMessage({
- action: 'trackinfo',
- trackInfo: trackInfo
- });
- });
- transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
- // convert to video TS since we prioritize video time over audio
- self.postMessage({
- action: 'audioTimingInfo',
- audioTimingInfo: {
- start: clock.videoTsToSeconds(audioTimingInfo.start),
- end: clock.videoTsToSeconds(audioTimingInfo.end)
- }
- });
- });
- transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
- self.postMessage({
- action: 'videoTimingInfo',
- videoTimingInfo: {
- start: clock.videoTsToSeconds(videoTimingInfo.start),
- end: clock.videoTsToSeconds(videoTimingInfo.end)
- }
- });
- });
- };
- /**
- * All incoming messages route through this hash. If no function exists
- * to handle an incoming message, then we ignore the message.
- *
- * @class MessageHandlers
- * @param {Object} options the options to initialize with
- */
-
-
- var MessageHandlers = /*#__PURE__*/function () {
- function MessageHandlers(self, options) {
- this.options = options || {};
- this.self = self;
- this.init();
- }
- /**
- * initialize our web worker and wire all the events.
- */
-
-
- var _proto = MessageHandlers.prototype;
-
- _proto.init = function init() {
- if (this.transmuxer) {
- this.transmuxer.dispose();
- }
-
- this.transmuxer = new transmuxer.Transmuxer(this.options);
- wireTransmuxerEvents(this.self, this.transmuxer);
- };
-
- _proto.pushMp4Captions = function pushMp4Captions(data) {
- if (!this.captionParser) {
- this.captionParser = new captionParser();
- this.captionParser.init();
- }
-
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- var parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
- this.self.postMessage({
- action: 'mp4Captions',
- captions: parsed && parsed.captions || [],
- data: segment.buffer
- }, [segment.buffer]);
- };
-
- _proto.probeMp4StartTime = function probeMp4StartTime(_ref) {
- var timescales = _ref.timescales,
- data = _ref.data;
- var startTime = probe$2.startTime(timescales, data);
- this.self.postMessage({
- action: 'probeMp4StartTime',
- startTime: startTime,
- data: data
- }, [data.buffer]);
- };
-
- _proto.probeMp4Tracks = function probeMp4Tracks(_ref2) {
- var data = _ref2.data;
- var tracks = probe$2.tracks(data);
- this.self.postMessage({
- action: 'probeMp4Tracks',
- tracks: tracks,
- data: data
- }, [data.buffer]);
- }
- /**
- * Probe an mpeg2-ts segment to determine the start time of the segment in it's
- * internal "media time," as well as whether it contains video and/or audio.
- *
- * @private
- * @param {Uint8Array} bytes - segment bytes
- * @param {number} baseStartTime
- * Relative reference timestamp used when adjusting frame timestamps for rollover.
- * This value should be in seconds, as it's converted to a 90khz clock within the
- * function body.
- * @return {Object} The start time of the current segment in "media time" as well as
- * whether it contains video and/or audio
- */
- ;
-
- _proto.probeTs = function probeTs(_ref3) {
- var data = _ref3.data,
- baseStartTime = _ref3.baseStartTime;
- var tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock.ONE_SECOND_IN_TS : void 0;
- var timeInfo = tsInspector.inspect(data, tsStartTime);
- var result = null;
-
- if (timeInfo) {
- result = {
- // each type's time info comes back as an array of 2 times, start and end
- hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
- hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
- };
-
- if (result.hasVideo) {
- result.videoStart = timeInfo.video[0].ptsTime;
- }
-
- if (result.hasAudio) {
- result.audioStart = timeInfo.audio[0].ptsTime;
- }
- }
-
- this.self.postMessage({
- action: 'probeTs',
- result: result,
- data: data
- }, [data.buffer]);
- };
-
- _proto.clearAllMp4Captions = function clearAllMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearAllCaptions();
- }
- };
-
- _proto.clearParsedMp4Captions = function clearParsedMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearParsedCaptions();
- }
- }
- /**
- * Adds data (a ts segment) to the start of the transmuxer pipeline for
- * processing.
- *
- * @param {ArrayBuffer} data data to push into the muxer
- */
- ;
-
- _proto.push = function push(data) {
- // Cast array buffer to correct type for transmuxer
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- this.transmuxer.push(segment);
- }
- /**
- * Recreate the transmuxer so that the next segment added via `push`
- * start with a fresh transmuxer.
- */
- ;
-
- _proto.reset = function reset() {
- this.transmuxer.reset();
- }
- /**
- * Set the value that will be used as the `baseMediaDecodeTime` time for the
- * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
- * set relative to the first based on the PTS values.
- *
- * @param {Object} data used to set the timestamp offset in the muxer
- */
- ;
-
- _proto.setTimestampOffset = function setTimestampOffset(data) {
- var timestampOffset = data.timestampOffset || 0;
- this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset)));
- };
-
- _proto.setAudioAppendStart = function setAudioAppendStart(data) {
- this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));
- };
-
- _proto.setRemux = function setRemux(data) {
- this.transmuxer.setRemux(data.remux);
- }
- /**
- * Forces the pipeline to finish processing the last segment and emit it's
- * results.
- *
- * @param {Object} data event data, not really used
- */
- ;
-
- _proto.flush = function flush(data) {
- this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
-
- self.postMessage({
- action: 'done',
- type: 'transmuxed'
- });
- };
-
- _proto.endTimeline = function endTimeline() {
- this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
- // timelines
-
- self.postMessage({
- action: 'endedtimeline',
- type: 'transmuxed'
- });
- };
-
- _proto.alignGopsWith = function alignGopsWith(data) {
- this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
- };
-
- return MessageHandlers;
- }();
- /**
- * Our web worker interface so that things can talk to mux.js
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- *
- * @param {Object} self the scope for the web worker
- */
-
-
- self.onmessage = function (event) {
- if (event.data.action === 'init' && event.data.options) {
- this.messageHandlers = new MessageHandlers(self, event.data.options);
- return;
- }
-
- if (!this.messageHandlers) {
- this.messageHandlers = new MessageHandlers(self);
- }
-
- if (event.data && event.data.action && event.data.action !== 'init') {
- if (this.messageHandlers[event.data.action]) {
- this.messageHandlers[event.data.action](event.data);
- }
- }
- };
-}));
-var TransmuxWorker = factory(workerCode$1);
-/* rollup-plugin-worker-factory end for worker!/Users/gkatsevman/p/http-streaming-release/src/transmuxer-worker.js */
-
-var handleData_ = function handleData_(event, transmuxedData, callback) {
- var _event$data$segment = event.data.segment,
- type = _event$data$segment.type,
- initSegment = _event$data$segment.initSegment,
- captions = _event$data$segment.captions,
- captionStreams = _event$data$segment.captionStreams,
- metadata = _event$data$segment.metadata,
- videoFrameDtsTime = _event$data$segment.videoFrameDtsTime,
- videoFramePtsTime = _event$data$segment.videoFramePtsTime;
- transmuxedData.buffer.push({
- captions: captions,
- captionStreams: captionStreams,
- metadata: metadata
- });
- var boxes = event.data.segment.boxes || {
- data: event.data.segment.data
- };
- var result = {
- type: type,
- // cast ArrayBuffer to TypedArray
- data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
- initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
- };
-
- if (typeof videoFrameDtsTime !== 'undefined') {
- result.videoFrameDtsTime = videoFrameDtsTime;
- }
-
- if (typeof videoFramePtsTime !== 'undefined') {
- result.videoFramePtsTime = videoFramePtsTime;
- }
-
- callback(result);
-};
-var handleDone_ = function handleDone_(_ref) {
- var transmuxedData = _ref.transmuxedData,
- callback = _ref.callback;
- // Previously we only returned data on data events,
- // not on done events. Clear out the buffer to keep that consistent.
- transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
- // have received
-
- callback(transmuxedData);
-};
-var handleGopInfo_ = function handleGopInfo_(event, transmuxedData) {
- transmuxedData.gopInfo = event.data.gopInfo;
-};
-var processTransmux = function processTransmux(options) {
- var transmuxer = options.transmuxer,
- bytes = options.bytes,
- audioAppendStart = options.audioAppendStart,
- gopsToAlignWith = options.gopsToAlignWith,
- remux = options.remux,
- onData = options.onData,
- onTrackInfo = options.onTrackInfo,
- onAudioTimingInfo = options.onAudioTimingInfo,
- onVideoTimingInfo = options.onVideoTimingInfo,
- onVideoSegmentTimingInfo = options.onVideoSegmentTimingInfo,
- onAudioSegmentTimingInfo = options.onAudioSegmentTimingInfo,
- onId3 = options.onId3,
- onCaptions = options.onCaptions,
- onDone = options.onDone,
- onEndedTimeline = options.onEndedTimeline,
- isEndOfTimeline = options.isEndOfTimeline;
- var transmuxedData = {
- buffer: []
- };
- var waitForEndedTimelineEvent = isEndOfTimeline;
-
- var handleMessage = function handleMessage(event) {
- if (transmuxer.currentTransmux !== options) {
- // disposed
- return;
- }
-
- if (event.data.action === 'data') {
- handleData_(event, transmuxedData, onData);
- }
-
- if (event.data.action === 'trackinfo') {
- onTrackInfo(event.data.trackInfo);
- }
-
- if (event.data.action === 'gopInfo') {
- handleGopInfo_(event, transmuxedData);
- }
-
- if (event.data.action === 'audioTimingInfo') {
- onAudioTimingInfo(event.data.audioTimingInfo);
- }
-
- if (event.data.action === 'videoTimingInfo') {
- onVideoTimingInfo(event.data.videoTimingInfo);
- }
-
- if (event.data.action === 'videoSegmentTimingInfo') {
- onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
- }
-
- if (event.data.action === 'audioSegmentTimingInfo') {
- onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
- }
-
- if (event.data.action === 'id3Frame') {
- onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
- }
-
- if (event.data.action === 'caption') {
- onCaptions(event.data.caption);
- }
-
- if (event.data.action === 'endedtimeline') {
- waitForEndedTimelineEvent = false;
- onEndedTimeline();
- } // wait for the transmuxed event since we may have audio and video
-
-
- if (event.data.type !== 'transmuxed') {
- return;
- } // If the "endedtimeline" event has not yet fired, and this segment represents the end
- // of a timeline, that means there may still be data events before the segment
- // processing can be considerred complete. In that case, the final event should be
- // an "endedtimeline" event with the type "transmuxed."
-
-
- if (waitForEndedTimelineEvent) {
- return;
- }
-
- transmuxer.onmessage = null;
- handleDone_({
- transmuxedData: transmuxedData,
- callback: onDone
- });
- /* eslint-disable no-use-before-define */
-
- dequeue(transmuxer);
- /* eslint-enable */
- };
-
- transmuxer.onmessage = handleMessage;
-
- if (audioAppendStart) {
- transmuxer.postMessage({
- action: 'setAudioAppendStart',
- appendStart: audioAppendStart
- });
- } // allow empty arrays to be passed to clear out GOPs
-
-
- if (Array.isArray(gopsToAlignWith)) {
- transmuxer.postMessage({
- action: 'alignGopsWith',
- gopsToAlignWith: gopsToAlignWith
- });
- }
-
- if (typeof remux !== 'undefined') {
- transmuxer.postMessage({
- action: 'setRemux',
- remux: remux
- });
- }
-
- if (bytes.byteLength) {
- var buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
- var byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
- transmuxer.postMessage({
- action: 'push',
- // Send the typed-array of data as an ArrayBuffer so that
- // it can be sent as a "Transferable" and avoid the costly
- // memory copy
- data: buffer,
- // To recreate the original typed-array, we need information
- // about what portion of the ArrayBuffer it was a view into
- byteOffset: byteOffset,
- byteLength: bytes.byteLength
- }, [buffer]);
- }
-
- if (isEndOfTimeline) {
- transmuxer.postMessage({
- action: 'endTimeline'
- });
- } // even if we didn't push any bytes, we have to make sure we flush in case we reached
- // the end of the segment
-
-
- transmuxer.postMessage({
- action: 'flush'
- });
-};
-var dequeue = function dequeue(transmuxer) {
- transmuxer.currentTransmux = null;
-
- if (transmuxer.transmuxQueue.length) {
- transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
-
- if (typeof transmuxer.currentTransmux === 'function') {
- transmuxer.currentTransmux();
- } else {
- processTransmux(transmuxer.currentTransmux);
- }
- }
-};
-var processAction = function processAction(transmuxer, action) {
- transmuxer.postMessage({
- action: action
- });
- dequeue(transmuxer);
-};
-var enqueueAction = function enqueueAction(action, transmuxer) {
- if (!transmuxer.currentTransmux) {
- transmuxer.currentTransmux = action;
- processAction(transmuxer, action);
- return;
- }
-
- transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
-};
-var reset = function reset(transmuxer) {
- enqueueAction('reset', transmuxer);
-};
-var endTimeline = function endTimeline(transmuxer) {
- enqueueAction('endTimeline', transmuxer);
-};
-var transmux = function transmux(options) {
- if (!options.transmuxer.currentTransmux) {
- options.transmuxer.currentTransmux = options;
- processTransmux(options);
- return;
- }
-
- options.transmuxer.transmuxQueue.push(options);
-};
-var createTransmuxer = function createTransmuxer(options) {
- var transmuxer = new TransmuxWorker();
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue = [];
- var term = transmuxer.terminate;
-
- transmuxer.terminate = function () {
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue.length = 0;
- return term.call(transmuxer);
- };
-
- transmuxer.postMessage({
- action: 'init',
- options: options
- });
- return transmuxer;
-};
-var segmentTransmuxer = {
- reset: reset,
- endTimeline: endTimeline,
- transmux: transmux,
- createTransmuxer: createTransmuxer
-};
-
-var workerCallback = function workerCallback(options) {
- var transmuxer = options.transmuxer;
- var endAction = options.endAction || options.action;
- var callback = options.callback;
-
- var message = _extends({}, options, {
- endAction: null,
- transmuxer: null,
- callback: null
- });
-
- var listenForEndEvent = function listenForEndEvent(event) {
- if (event.data.action !== endAction) {
- return;
- }
-
- transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
-
- if (event.data.data) {
- event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
-
- if (options.data) {
- options.data = event.data.data;
- }
- }
-
- callback(event.data);
- };
-
- transmuxer.addEventListener('message', listenForEndEvent);
-
- if (options.data) {
- var isArrayBuffer = options.data instanceof ArrayBuffer;
- message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
- message.byteLength = options.data.byteLength;
- var transfers = [isArrayBuffer ? options.data : options.data.buffer];
- transmuxer.postMessage(message, transfers);
- } else {
- transmuxer.postMessage(message);
- }
-};
-
-var REQUEST_ERRORS = {
- FAILURE: 2,
- TIMEOUT: -101,
- ABORTED: -102
-};
-/**
- * Abort all requests
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- */
-
-var abortAll = function abortAll(activeXhrs) {
- activeXhrs.forEach(function (xhr) {
- xhr.abort();
- });
-};
-/**
- * Gather important bandwidth stats once a request has completed
- *
- * @param {Object} request - the XHR request from which to gather stats
- */
-
-
-var getRequestStats = function getRequestStats(request) {
- return {
- bandwidth: request.bandwidth,
- bytesReceived: request.bytesReceived || 0,
- roundTripTime: request.roundTripTime || 0
- };
-};
-/**
- * If possible gather bandwidth stats as a request is in
- * progress
- *
- * @param {Event} progressEvent - an event object from an XHR's progress event
- */
-
-
-var getProgressStats = function getProgressStats(progressEvent) {
- var request = progressEvent.target;
- var roundTripTime = Date.now() - request.requestTime;
- var stats = {
- bandwidth: Infinity,
- bytesReceived: 0,
- roundTripTime: roundTripTime || 0
- };
- stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
- // because we should only use bandwidth stats on progress to determine when
- // abort a request early due to insufficient bandwidth
-
- stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
- return stats;
-};
-/**
- * Handle all error conditions in one place and return an object
- * with all the information
- *
- * @param {Error|null} error - if non-null signals an error occured with the XHR
- * @param {Object} request - the XHR request that possibly generated the error
- */
-
-
-var handleErrors = function handleErrors(error, request) {
- if (request.timedout) {
- return {
- status: request.status,
- message: 'HLS request timed-out at URL: ' + request.uri,
- code: REQUEST_ERRORS.TIMEOUT,
- xhr: request
- };
- }
-
- if (request.aborted) {
- return {
- status: request.status,
- message: 'HLS request aborted at URL: ' + request.uri,
- code: REQUEST_ERRORS.ABORTED,
- xhr: request
- };
- }
-
- if (error) {
- return {
- status: request.status,
- message: 'HLS request errored at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
- return {
- status: request.status,
- message: 'Empty HLS response at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- return null;
-};
-/**
- * Handle responses for key data and convert the key data to the correct format
- * for the decryption step later
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Array} objects - objects to add the key bytes to.
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
-var handleKeyResponse = function handleKeyResponse(segment, objects, finishProcessingFn) {
- return function (error, request) {
- var response = request.response;
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- if (response.byteLength !== 16) {
- return finishProcessingFn({
- status: request.status,
- message: 'Invalid HLS key at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- }, segment);
- }
-
- var view = new DataView(response);
- var bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
-
- for (var i = 0; i < objects.length; i++) {
- objects[i].bytes = bytes;
- }
-
- return finishProcessingFn(null, segment);
- };
-};
-
-var parseInitSegment = function parseInitSegment(segment, _callback) {
- var type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
- // only know how to parse mp4 init segments at the moment
-
- if (type !== 'mp4') {
- var uri = segment.map.resolvedUri || segment.map.uri;
- return _callback({
- internal: true,
- message: "Found unsupported " + (type || 'unknown') + " container for initialization segment at URL: " + uri,
- code: REQUEST_ERRORS.FAILURE
- });
- }
-
- workerCallback({
- action: 'probeMp4Tracks',
- data: segment.map.bytes,
- transmuxer: segment.transmuxer,
- callback: function callback(_ref) {
- var tracks = _ref.tracks,
- data = _ref.data;
- // transfer bytes back to us
- segment.map.bytes = data;
- tracks.forEach(function (track) {
- segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
-
- if (segment.map.tracks[track.type]) {
- return;
- }
-
- segment.map.tracks[track.type] = track;
-
- if (typeof track.id === 'number' && track.timescale) {
- segment.map.timescales = segment.map.timescales || {};
- segment.map.timescales[track.id] = track.timescale;
- }
- });
- return _callback(null);
- }
- });
-};
-/**
- * Handle init-segment responses
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
-var handleInitSegmentResponse = function handleInitSegmentResponse(_ref2) {
- var segment = _ref2.segment,
- finishProcessingFn = _ref2.finishProcessingFn;
- return function (error, request) {
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- var bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
- // until the key request is done to decrypt.
-
- if (segment.map.key) {
- segment.map.encryptedBytes = bytes;
- return finishProcessingFn(null, segment);
- }
-
- segment.map.bytes = bytes;
- parseInitSegment(segment, function (parseError) {
- if (parseError) {
- parseError.xhr = request;
- parseError.status = request.status;
- return finishProcessingFn(parseError, segment);
- }
-
- finishProcessingFn(null, segment);
- });
- };
-};
-/**
- * Response handler for segment-requests being sure to set the correct
- * property depending on whether the segment is encryped or not
- * Also records and keeps track of stats that are used for ABR purposes
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
-var handleSegmentResponse = function handleSegmentResponse(_ref3) {
- var segment = _ref3.segment,
- finishProcessingFn = _ref3.finishProcessingFn,
- responseType = _ref3.responseType;
- return function (error, request) {
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- var newBytes = // although responseText "should" exist, this guard serves to prevent an error being
- // thrown for two primary cases:
- // 1. the mime type override stops working, or is not implemented for a specific
- // browser
- // 2. when using mock XHR libraries like sinon that do not allow the override behavior
- responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
- segment.stats = getRequestStats(request);
-
- if (segment.key) {
- segment.encryptedBytes = new Uint8Array(newBytes);
- } else {
- segment.bytes = new Uint8Array(newBytes);
- }
-
- return finishProcessingFn(null, segment);
- };
-};
-
-var transmuxAndNotify = function transmuxAndNotify(_ref4) {
- var segment = _ref4.segment,
- bytes = _ref4.bytes,
- trackInfoFn = _ref4.trackInfoFn,
- timingInfoFn = _ref4.timingInfoFn,
- videoSegmentTimingInfoFn = _ref4.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref4.audioSegmentTimingInfoFn,
- id3Fn = _ref4.id3Fn,
- captionsFn = _ref4.captionsFn,
- isEndOfTimeline = _ref4.isEndOfTimeline,
- endedTimelineFn = _ref4.endedTimelineFn,
- dataFn = _ref4.dataFn,
- doneFn = _ref4.doneFn;
- var fmp4Tracks = segment.map && segment.map.tracks || {};
- var isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
- // One reason for this is that in the case of full segments, we want to trust start
- // times from the probe, rather than the transmuxer.
-
- var audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
- var audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
- var videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
- var videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
-
- var finish = function finish() {
- return transmux({
- bytes: bytes,
- transmuxer: segment.transmuxer,
- audioAppendStart: segment.audioAppendStart,
- gopsToAlignWith: segment.gopsToAlignWith,
- remux: isMuxed,
- onData: function onData(result) {
- result.type = result.type === 'combined' ? 'video' : result.type;
- dataFn(segment, result);
- },
- onTrackInfo: function onTrackInfo(trackInfo) {
- if (trackInfoFn) {
- if (isMuxed) {
- trackInfo.isMuxed = true;
- }
-
- trackInfoFn(segment, trackInfo);
- }
- },
- onAudioTimingInfo: function onAudioTimingInfo(audioTimingInfo) {
- // we only want the first start value we encounter
- if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
- audioStartFn(audioTimingInfo.start);
- audioStartFn = null;
- } // we want to continually update the end time
-
-
- if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
- audioEndFn(audioTimingInfo.end);
- }
- },
- onVideoTimingInfo: function onVideoTimingInfo(videoTimingInfo) {
- // we only want the first start value we encounter
- if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
- videoStartFn(videoTimingInfo.start);
- videoStartFn = null;
- } // we want to continually update the end time
-
-
- if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
- videoEndFn(videoTimingInfo.end);
- }
- },
- onVideoSegmentTimingInfo: function onVideoSegmentTimingInfo(videoSegmentTimingInfo) {
- videoSegmentTimingInfoFn(videoSegmentTimingInfo);
- },
- onAudioSegmentTimingInfo: function onAudioSegmentTimingInfo(audioSegmentTimingInfo) {
- audioSegmentTimingInfoFn(audioSegmentTimingInfo);
- },
- onId3: function onId3(id3Frames, dispatchType) {
- id3Fn(segment, id3Frames, dispatchType);
- },
- onCaptions: function onCaptions(captions) {
- captionsFn(segment, [captions]);
- },
- isEndOfTimeline: isEndOfTimeline,
- onEndedTimeline: function onEndedTimeline() {
- endedTimelineFn();
- },
- onDone: function onDone(result) {
- if (!doneFn) {
- return;
- }
-
- result.type = result.type === 'combined' ? 'video' : result.type;
- doneFn(null, segment, result);
- }
- });
- }; // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
- // Meaning cached frame data may corrupt our notion of where this segment
- // really starts. To get around this, probe for the info needed.
-
-
- workerCallback({
- action: 'probeTs',
- transmuxer: segment.transmuxer,
- data: bytes,
- baseStartTime: segment.baseStartTime,
- callback: function callback(data) {
- segment.bytes = bytes = data.data;
- var probeResult = data.result;
-
- if (probeResult) {
- trackInfoFn(segment, {
- hasAudio: probeResult.hasAudio,
- hasVideo: probeResult.hasVideo,
- isMuxed: isMuxed
- });
- trackInfoFn = null;
-
- if (probeResult.hasAudio && !isMuxed) {
- audioStartFn(probeResult.audioStart);
- }
-
- if (probeResult.hasVideo) {
- videoStartFn(probeResult.videoStart);
- }
-
- audioStartFn = null;
- videoStartFn = null;
- }
-
- finish();
- }
- });
-};
-
-var handleSegmentBytes = function handleSegmentBytes(_ref5) {
- var segment = _ref5.segment,
- bytes = _ref5.bytes,
- trackInfoFn = _ref5.trackInfoFn,
- timingInfoFn = _ref5.timingInfoFn,
- videoSegmentTimingInfoFn = _ref5.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref5.audioSegmentTimingInfoFn,
- id3Fn = _ref5.id3Fn,
- captionsFn = _ref5.captionsFn,
- isEndOfTimeline = _ref5.isEndOfTimeline,
- endedTimelineFn = _ref5.endedTimelineFn,
- dataFn = _ref5.dataFn,
- doneFn = _ref5.doneFn;
- var bytesAsUint8Array = new Uint8Array(bytes); // TODO:
- // We should have a handler that fetches the number of bytes required
- // to check if something is fmp4. This will allow us to save bandwidth
- // because we can only blacklist a playlist and abort requests
- // by codec after trackinfo triggers.
-
- if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
- segment.isFmp4 = true;
- var tracks = segment.map.tracks;
- var trackInfo = {
- isFmp4: true,
- hasVideo: !!tracks.video,
- hasAudio: !!tracks.audio
- }; // if we have a audio track, with a codec that is not set to
- // encrypted audio
-
- if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
- trackInfo.audioCodec = tracks.audio.codec;
- } // if we have a video track, with a codec that is not set to
- // encrypted video
-
-
- if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
- trackInfo.videoCodec = tracks.video.codec;
- }
-
- if (tracks.video && tracks.audio) {
- trackInfo.isMuxed = true;
- } // since we don't support appending fmp4 data on progress, we know we have the full
- // segment here
-
-
- trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
- // time. The end time can be roughly calculated by the receiver using the duration.
- //
- // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
- // that is the true start of the segment (where the playback engine should begin
- // decoding).
-
- var finishLoading = function finishLoading(captions) {
- // if the track still has audio at this point it is only possible
- // for it to be audio only. See `tracks.video && tracks.audio` if statement
- // above.
- // we make sure to use segment.bytes here as that
- dataFn(segment, {
- data: bytesAsUint8Array,
- type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
- });
-
- if (captions && captions.length) {
- captionsFn(segment, captions);
- }
-
- doneFn(null, segment, {});
- };
-
- workerCallback({
- action: 'probeMp4StartTime',
- timescales: segment.map.timescales,
- data: bytesAsUint8Array,
- transmuxer: segment.transmuxer,
- callback: function callback(_ref6) {
- var data = _ref6.data,
- startTime = _ref6.startTime;
- // transfer bytes back to us
- bytes = data.buffer;
- segment.bytes = bytesAsUint8Array = data;
-
- if (trackInfo.hasAudio && !trackInfo.isMuxed) {
- timingInfoFn(segment, 'audio', 'start', startTime);
- }
-
- if (trackInfo.hasVideo) {
- timingInfoFn(segment, 'video', 'start', startTime);
- } // Run through the CaptionParser in case there are captions.
- // Initialize CaptionParser if it hasn't been yet
-
-
- if (!tracks.video || !data.byteLength || !segment.transmuxer) {
- finishLoading();
- return;
- }
-
- workerCallback({
- action: 'pushMp4Captions',
- endAction: 'mp4Captions',
- transmuxer: segment.transmuxer,
- data: bytesAsUint8Array,
- timescales: segment.map.timescales,
- trackIds: [tracks.video.id],
- callback: function callback(message) {
- // transfer bytes back to us
- bytes = message.data.buffer;
- segment.bytes = bytesAsUint8Array = message.data;
- finishLoading(message.captions);
- }
- });
- }
- });
- return;
- } // VTT or other segments that don't need processing
-
-
- if (!segment.transmuxer) {
- doneFn(null, segment, {});
- return;
- }
-
- if (typeof segment.container === 'undefined') {
- segment.container = detectContainerForBytes(bytesAsUint8Array);
- }
-
- if (segment.container !== 'ts' && segment.container !== 'aac') {
- trackInfoFn(segment, {
- hasAudio: false,
- hasVideo: false
- });
- doneFn(null, segment, {});
- return;
- } // ts or aac
-
-
- transmuxAndNotify({
- segment: segment,
- bytes: bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
-};
-
-var decrypt = function decrypt(_ref7, callback) {
- var id = _ref7.id,
- key = _ref7.key,
- encryptedBytes = _ref7.encryptedBytes,
- decryptionWorker = _ref7.decryptionWorker;
-
- var decryptionHandler = function decryptionHandler(event) {
- if (event.data.source === id) {
- decryptionWorker.removeEventListener('message', decryptionHandler);
- var decrypted = event.data.decrypted;
- callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
- }
- };
-
- decryptionWorker.addEventListener('message', decryptionHandler);
- var keyBytes;
-
- if (key.bytes.slice) {
- keyBytes = key.bytes.slice();
- } else {
- keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
- } // incrementally decrypt the bytes
-
-
- decryptionWorker.postMessage(createTransferableMessage({
- source: id,
- encrypted: encryptedBytes,
- key: keyBytes,
- iv: key.iv
- }), [encryptedBytes.buffer, keyBytes.buffer]);
-};
-/**
- * Decrypt the segment via the decryption web worker
- *
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after decryption has completed
- */
-
-
-var decryptSegment = function decryptSegment(_ref8) {
- var decryptionWorker = _ref8.decryptionWorker,
- segment = _ref8.segment,
- trackInfoFn = _ref8.trackInfoFn,
- timingInfoFn = _ref8.timingInfoFn,
- videoSegmentTimingInfoFn = _ref8.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref8.audioSegmentTimingInfoFn,
- id3Fn = _ref8.id3Fn,
- captionsFn = _ref8.captionsFn,
- isEndOfTimeline = _ref8.isEndOfTimeline,
- endedTimelineFn = _ref8.endedTimelineFn,
- dataFn = _ref8.dataFn,
- doneFn = _ref8.doneFn;
- decrypt({
- id: segment.requestId,
- key: segment.key,
- encryptedBytes: segment.encryptedBytes,
- decryptionWorker: decryptionWorker
- }, function (decryptedBytes) {
- segment.bytes = decryptedBytes;
- handleSegmentBytes({
- segment: segment,
- bytes: segment.bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- });
-};
-/**
- * This function waits for all XHRs to finish (with either success or failure)
- * before continueing processing via it's callback. The function gathers errors
- * from each request into a single errors array so that the error status for
- * each request can be examined later.
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after all resources have been
- * downloaded and any decryption completed
- */
-
-
-var waitForCompletion = function waitForCompletion(_ref9) {
- var activeXhrs = _ref9.activeXhrs,
- decryptionWorker = _ref9.decryptionWorker,
- trackInfoFn = _ref9.trackInfoFn,
- timingInfoFn = _ref9.timingInfoFn,
- videoSegmentTimingInfoFn = _ref9.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref9.audioSegmentTimingInfoFn,
- id3Fn = _ref9.id3Fn,
- captionsFn = _ref9.captionsFn,
- isEndOfTimeline = _ref9.isEndOfTimeline,
- endedTimelineFn = _ref9.endedTimelineFn,
- dataFn = _ref9.dataFn,
- doneFn = _ref9.doneFn;
- var count = 0;
- var didError = false;
- return function (error, segment) {
- if (didError) {
- return;
- }
-
- if (error) {
- didError = true; // If there are errors, we have to abort any outstanding requests
-
- abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
- // handle the aborted events from those requests, there are some cases where we may
- // never get an aborted event. For instance, if the network connection is lost and
- // there were two requests, the first may have triggered an error immediately, while
- // the second request remains unsent. In that case, the aborted algorithm will not
- // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
- //
- // We also can't rely on the ready state of the XHR, since the request that
- // triggered the connection error may also show as a ready state of 0 (unsent).
- // Therefore, we have to finish this group of requests immediately after the first
- // seen error.
-
- return doneFn(error, segment);
- }
-
- count += 1;
-
- if (count === activeXhrs.length) {
- var segmentFinish = function segmentFinish() {
- if (segment.encryptedBytes) {
- return decryptSegment({
- decryptionWorker: decryptionWorker,
- segment: segment,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- } // Otherwise, everything is ready just continue
-
-
- handleSegmentBytes({
- segment: segment,
- bytes: segment.bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- }; // Keep track of when *all* of the requests have completed
-
-
- segment.endOfAllRequests = Date.now();
-
- if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
- return decrypt({
- decryptionWorker: decryptionWorker,
- // add -init to the "id" to differentiate between segment
- // and init segment decryption, just in case they happen
- // at the same time at some point in the future.
- id: segment.requestId + '-init',
- encryptedBytes: segment.map.encryptedBytes,
- key: segment.map.key
- }, function (decryptedBytes) {
- segment.map.bytes = decryptedBytes;
- parseInitSegment(segment, function (parseError) {
- if (parseError) {
- abortAll(activeXhrs);
- return doneFn(parseError, segment);
- }
-
- segmentFinish();
- });
- });
- }
-
- segmentFinish();
- }
- };
-};
-/**
- * Calls the abort callback if any request within the batch was aborted. Will only call
- * the callback once per batch of requests, even if multiple were aborted.
- *
- * @param {Object} loadendState - state to check to see if the abort function was called
- * @param {Function} abortFn - callback to call for abort
- */
-
-
-var handleLoadEnd = function handleLoadEnd(_ref10) {
- var loadendState = _ref10.loadendState,
- abortFn = _ref10.abortFn;
- return function (event) {
- var request = event.target;
-
- if (request.aborted && abortFn && !loadendState.calledAbortFn) {
- abortFn();
- loadendState.calledAbortFn = true;
- }
- };
-};
-/**
- * Simple progress event callback handler that gathers some stats before
- * executing a provided callback with the `segment` object
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} progressFn - a callback that is executed each time a progress event
- * is received
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Event} event - the progress event object from XMLHttpRequest
- */
-
-
-var handleProgress = function handleProgress(_ref11) {
- var segment = _ref11.segment,
- progressFn = _ref11.progressFn;
- _ref11.trackInfoFn;
- _ref11.timingInfoFn;
- _ref11.videoSegmentTimingInfoFn;
- _ref11.audioSegmentTimingInfoFn;
- _ref11.id3Fn;
- _ref11.captionsFn;
- _ref11.isEndOfTimeline;
- _ref11.endedTimelineFn;
- _ref11.dataFn;
- return function (event) {
- var request = event.target;
-
- if (request.aborted) {
- return;
- }
-
- segment.stats = videojs.mergeOptions(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
-
- if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
- segment.stats.firstBytesReceivedAt = Date.now();
- }
-
- return progressFn(event, segment);
- };
-};
-/**
- * Load all resources and does any processing necessary for a media-segment
- *
- * Features:
- * decrypts the media-segment if it has a key uri and an iv
- * aborts *all* requests if *any* one request fails
- *
- * The segment object, at minimum, has the following format:
- * {
- * resolvedUri: String,
- * [transmuxer]: Object,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [key]: {
- * resolvedUri: String
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * iv: {
- * bytes: Uint32Array
- * }
- * },
- * [map]: {
- * resolvedUri: String,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [bytes]: Uint8Array
- * }
- * }
- * ...where [name] denotes optional properties
- *
- * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
- * @param {Object} xhrOptions - the base options to provide to all xhr requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
- * decryption routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} abortFn - a callback called (only once) if any piece of a request was
- * aborted
- * @param {Function} progressFn - a callback that receives progress events from the main
- * segment's xhr request
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that receives data from the main segment's xhr
- * request, transmuxed if needed
- * @param {Function} doneFn - a callback that is executed only once all requests have
- * succeeded or failed
- * @return {Function} a function that, when invoked, immediately aborts all
- * outstanding requests
- */
-
-
-var mediaSegmentRequest = function mediaSegmentRequest(_ref12) {
- var xhr = _ref12.xhr,
- xhrOptions = _ref12.xhrOptions,
- decryptionWorker = _ref12.decryptionWorker,
- segment = _ref12.segment,
- abortFn = _ref12.abortFn,
- progressFn = _ref12.progressFn,
- trackInfoFn = _ref12.trackInfoFn,
- timingInfoFn = _ref12.timingInfoFn,
- videoSegmentTimingInfoFn = _ref12.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref12.audioSegmentTimingInfoFn,
- id3Fn = _ref12.id3Fn,
- captionsFn = _ref12.captionsFn,
- isEndOfTimeline = _ref12.isEndOfTimeline,
- endedTimelineFn = _ref12.endedTimelineFn,
- dataFn = _ref12.dataFn,
- doneFn = _ref12.doneFn;
- var activeXhrs = [];
- var finishProcessingFn = waitForCompletion({
- activeXhrs: activeXhrs,
- decryptionWorker: decryptionWorker,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- }); // optionally, request the decryption key
-
- if (segment.key && !segment.key.bytes) {
- var objects = [segment.key];
-
- if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
- objects.push(segment.map.key);
- }
-
- var keyRequestOptions = videojs.mergeOptions(xhrOptions, {
- uri: segment.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- var keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
- var keyXhr = xhr(keyRequestOptions, keyRequestCallback);
- activeXhrs.push(keyXhr);
- } // optionally, request the associated media init segment
-
-
- if (segment.map && !segment.map.bytes) {
- var differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
-
- if (differentMapKey) {
- var mapKeyRequestOptions = videojs.mergeOptions(xhrOptions, {
- uri: segment.map.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- var mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
- var mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
- activeXhrs.push(mapKeyXhr);
- }
-
- var initSegmentOptions = videojs.mergeOptions(xhrOptions, {
- uri: segment.map.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment.map)
- });
- var initSegmentRequestCallback = handleInitSegmentResponse({
- segment: segment,
- finishProcessingFn: finishProcessingFn
- });
- var initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
- activeXhrs.push(initSegmentXhr);
- }
-
- var segmentRequestOptions = videojs.mergeOptions(xhrOptions, {
- uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment)
- });
- var segmentRequestCallback = handleSegmentResponse({
- segment: segment,
- finishProcessingFn: finishProcessingFn,
- responseType: segmentRequestOptions.responseType
- });
- var segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
- segmentXhr.addEventListener('progress', handleProgress({
- segment: segment,
- progressFn: progressFn,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn
- }));
- activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
- // multiple times, provide a shared state object
-
- var loadendState = {};
- activeXhrs.forEach(function (activeXhr) {
- activeXhr.addEventListener('loadend', handleLoadEnd({
- loadendState: loadendState,
- abortFn: abortFn
- }));
- });
- return function () {
- return abortAll(activeXhrs);
- };
-};
-
-/**
- * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
- * codec strings, or translating codec strings into objects that can be examined.
- */
-var logFn$1 = logger('CodecUtils');
-/**
- * Returns a set of codec strings parsed from the playlist or the default
- * codec strings if no codecs were specified in the playlist
- *
- * @param {Playlist} media the current media playlist
- * @return {Object} an object with the video and audio codecs
- */
-
-var getCodecs = function getCodecs(media) {
- // if the codecs were explicitly specified, use them instead of the
- // defaults
- var mediaAttributes = media.attributes || {};
-
- if (mediaAttributes.CODECS) {
- return parseCodecs(mediaAttributes.CODECS);
- }
-};
-
-var isMaat = function isMaat(master, media) {
- var mediaAttributes = media.attributes || {};
- return master && master.mediaGroups && master.mediaGroups.AUDIO && mediaAttributes.AUDIO && master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
-};
-var isMuxed = function isMuxed(master, media) {
- if (!isMaat(master, media)) {
- return true;
- }
-
- var mediaAttributes = media.attributes || {};
- var audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
-
- for (var groupId in audioGroup) {
- // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
- // or there are listed playlists (the case for DASH, as the manifest will have already
- // provided all of the details necessary to generate the audio playlist, as opposed to
- // HLS' externally requested playlists), then the content is demuxed.
- if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
- return true;
- }
- }
-
- return false;
-};
-var unwrapCodecList = function unwrapCodecList(codecList) {
- var codecs = {};
- codecList.forEach(function (_ref) {
- var mediaType = _ref.mediaType,
- type = _ref.type,
- details = _ref.details;
- codecs[mediaType] = codecs[mediaType] || [];
- codecs[mediaType].push(translateLegacyCodec("" + type + details));
- });
- Object.keys(codecs).forEach(function (mediaType) {
- if (codecs[mediaType].length > 1) {
- logFn$1("multiple " + mediaType + " codecs found as attributes: " + codecs[mediaType].join(', ') + ". Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.");
- codecs[mediaType] = null;
- return;
- }
-
- codecs[mediaType] = codecs[mediaType][0];
- });
- return codecs;
-};
-var codecCount = function codecCount(codecObj) {
- var count = 0;
-
- if (codecObj.audio) {
- count++;
- }
-
- if (codecObj.video) {
- count++;
- }
-
- return count;
-};
-/**
- * Calculates the codec strings for a working configuration of
- * SourceBuffers to play variant streams in a master playlist. If
- * there is no possible working configuration, an empty object will be
- * returned.
- *
- * @param master {Object} the m3u8 object for the master playlist
- * @param media {Object} the m3u8 object for the variant playlist
- * @return {Object} the codec strings.
- *
- * @private
- */
-
-var codecsForPlaylist = function codecsForPlaylist(master, media) {
- var mediaAttributes = media.attributes || {};
- var codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
- // Put another way, there is no way to have a video-only multiple-audio HLS!
-
- if (isMaat(master, media) && !codecInfo.audio) {
- if (!isMuxed(master, media)) {
- // It is possible for codecs to be specified on the audio media group playlist but
- // not on the rendition playlist. This is mostly the case for DASH, where audio and
- // video are always separate (and separately specified).
- var defaultCodecs = unwrapCodecList(codecsFromDefault(master, mediaAttributes.AUDIO) || []);
-
- if (defaultCodecs.audio) {
- codecInfo.audio = defaultCodecs.audio;
- }
- }
- }
-
- return codecInfo;
-};
-
-var logFn = logger('PlaylistSelector');
-
-var representationToString = function representationToString(representation) {
- if (!representation || !representation.playlist) {
- return;
- }
-
- var playlist = representation.playlist;
- return JSON.stringify({
- id: playlist.id,
- bandwidth: representation.bandwidth,
- width: representation.width,
- height: representation.height,
- codecs: playlist.attributes && playlist.attributes.CODECS || ''
- });
-}; // Utilities
-
-/**
- * Returns the CSS value for the specified property on an element
- * using `getComputedStyle`. Firefox has a long-standing issue where
- * getComputedStyle() may return null when running in an iframe with
- * `display: none`.
- *
- * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
- * @param {HTMLElement} el the htmlelement to work on
- * @param {string} the proprety to get the style for
- */
-
-
-var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
- if (!el) {
- return '';
- }
-
- var result = window.getComputedStyle(el);
-
- if (!result) {
- return '';
- }
-
- return result[property];
-};
-/**
- * Resuable stable sort function
- *
- * @param {Playlists} array
- * @param {Function} sortFn Different comparators
- * @function stableSort
- */
-
-
-var stableSort = function stableSort(array, sortFn) {
- var newArray = array.slice();
- array.sort(function (left, right) {
- var cmp = sortFn(left, right);
-
- if (cmp === 0) {
- return newArray.indexOf(left) - newArray.indexOf(right);
- }
-
- return cmp;
- });
-};
-/**
- * A comparator function to sort two playlist object by bandwidth.
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the bandwidth attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the bandwidth of right is greater than left and
- * exactly zero if the two are equal.
- */
-
-
-var comparePlaylistBandwidth = function comparePlaylistBandwidth(left, right) {
- var leftBandwidth;
- var rightBandwidth;
-
- if (left.attributes.BANDWIDTH) {
- leftBandwidth = left.attributes.BANDWIDTH;
- }
-
- leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
-
- if (right.attributes.BANDWIDTH) {
- rightBandwidth = right.attributes.BANDWIDTH;
- }
-
- rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
- return leftBandwidth - rightBandwidth;
-};
-/**
- * A comparator function to sort two playlist object by resolution (width).
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the resolution.width attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the resolution.width of right is greater than left and
- * exactly zero if the two are equal.
- */
-
-var comparePlaylistResolution = function comparePlaylistResolution(left, right) {
- var leftWidth;
- var rightWidth;
-
- if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
- leftWidth = left.attributes.RESOLUTION.width;
- }
-
- leftWidth = leftWidth || window.Number.MAX_VALUE;
-
- if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
- rightWidth = right.attributes.RESOLUTION.width;
- }
-
- rightWidth = rightWidth || window.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
- // have the same media dimensions/ resolution
-
- if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
- return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
- }
-
- return leftWidth - rightWidth;
-};
-/**
- * Chooses the appropriate media playlist based on bandwidth and player size
- *
- * @param {Object} master
- * Object representation of the master manifest
- * @param {number} playerBandwidth
- * Current calculated bandwidth of the player
- * @param {number} playerWidth
- * Current width of the player element (should account for the device pixel ratio)
- * @param {number} playerHeight
- * Current height of the player element (should account for the device pixel ratio)
- * @param {boolean} limitRenditionByPlayerDimensions
- * True if the player width and height should be used during the selection, false otherwise
- * @param {Object} masterPlaylistController
- * the current masterPlaylistController object
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-
-var simpleSelector = function simpleSelector(master, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, masterPlaylistController) {
- // If we end up getting called before `master` is available, exit early
- if (!master) {
- return;
- }
-
- var options = {
- bandwidth: playerBandwidth,
- width: playerWidth,
- height: playerHeight,
- limitRenditionByPlayerDimensions: limitRenditionByPlayerDimensions
- };
- var playlists = master.playlists; // if playlist is audio only, select between currently active audio group playlists.
-
- if (Playlist.isAudioOnly(master)) {
- playlists = masterPlaylistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
- // at the buttom of this function for debugging.
-
- options.audioOnly = true;
- } // convert the playlists to an intermediary representation to make comparisons easier
-
-
- var sortedPlaylistReps = playlists.map(function (playlist) {
- var bandwidth;
- var width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
- var height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
- bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
- bandwidth = bandwidth || window.Number.MAX_VALUE;
- return {
- bandwidth: bandwidth,
- width: width,
- height: height,
- playlist: playlist
- };
- });
- stableSort(sortedPlaylistReps, function (left, right) {
- return left.bandwidth - right.bandwidth;
- }); // filter out any playlists that have been excluded due to
- // incompatible configurations
-
- sortedPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return !Playlist.isIncompatible(rep.playlist);
- }); // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
-
- var enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return Playlist.isEnabled(rep.playlist);
- });
-
- if (!enabledPlaylistReps.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return !Playlist.isDisabled(rep.playlist);
- });
- } // filter out any variant that has greater effective bitrate
- // than the current estimated bandwidth
-
-
- var bandwidthPlaylistReps = enabledPlaylistReps.filter(function (rep) {
- return rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth;
- });
- var highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
- // and then taking the very first element
-
- var bandwidthBestRep = bandwidthPlaylistReps.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0]; // if we're not going to limit renditions by player size, make an early decision.
-
- if (limitRenditionByPlayerDimensions === false) {
- var _chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
-
- if (_chosenRep && _chosenRep.playlist) {
- var type = 'sortedPlaylistReps';
-
- if (bandwidthBestRep) {
- type = 'bandwidthBestRep';
- }
-
- if (enabledPlaylistReps[0]) {
- type = 'enabledPlaylistReps';
- }
-
- logFn("choosing " + representationToString(_chosenRep) + " using " + type + " with options", options);
- return _chosenRep.playlist;
- }
-
- logFn('could not choose a playlist with options', options);
- return null;
- } // filter out playlists without resolution information
-
-
- var haveResolution = bandwidthPlaylistReps.filter(function (rep) {
- return rep.width && rep.height;
- }); // sort variants by resolution
-
- stableSort(haveResolution, function (left, right) {
- return left.width - right.width;
- }); // if we have the exact resolution as the player use it
-
- var resolutionBestRepList = haveResolution.filter(function (rep) {
- return rep.width === playerWidth && rep.height === playerHeight;
- });
- highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
-
- var resolutionBestRep = resolutionBestRepList.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0];
- var resolutionPlusOneList;
- var resolutionPlusOneSmallest;
- var resolutionPlusOneRep; // find the smallest variant that is larger than the player
- // if there is no match of exact resolution
-
- if (!resolutionBestRep) {
- resolutionPlusOneList = haveResolution.filter(function (rep) {
- return rep.width > playerWidth || rep.height > playerHeight;
- }); // find all the variants have the same smallest resolution
-
- resolutionPlusOneSmallest = resolutionPlusOneList.filter(function (rep) {
- return rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height;
- }); // ensure that we also pick the highest bandwidth variant that
- // is just-larger-than the video player
-
- highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
- resolutionPlusOneRep = resolutionPlusOneSmallest.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0];
- } // fallback chain of variants
-
-
- var chosenRep = resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
-
- if (chosenRep && chosenRep.playlist) {
- var _type = 'sortedPlaylistReps';
-
- if (resolutionPlusOneRep) {
- _type = 'resolutionPlusOneRep';
- } else if (resolutionBestRep) {
- _type = 'resolutionBestRep';
- } else if (bandwidthBestRep) {
- _type = 'bandwidthBestRep';
- } else if (enabledPlaylistReps[0]) {
- _type = 'enabledPlaylistReps';
- }
-
- logFn("choosing " + representationToString(chosenRep) + " using " + _type + " with options", options);
- return chosenRep.playlist;
- }
-
- logFn('could not choose a playlist with options', options);
- return null;
-};
-
-/**
- * Chooses the appropriate media playlist based on the most recent
- * bandwidth estimate and the player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-
-var lastBandwidthSelector = function lastBandwidthSelector() {
- var pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
- return simpleSelector(this.playlists.master, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
-};
-/**
- * Chooses the appropriate media playlist based on an
- * exponential-weighted moving average of the bandwidth after
- * filtering for player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @param {number} decay - a number between 0 and 1. Higher values of
- * this parameter will cause previous bandwidth estimates to lose
- * significance more quickly.
- * @return {Function} a function which can be invoked to create a new
- * playlist selector function.
- * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
- */
-
-var movingAverageBandwidthSelector = function movingAverageBandwidthSelector(decay) {
- var average = -1;
- var lastSystemBandwidth = -1;
-
- if (decay < 0 || decay > 1) {
- throw new Error('Moving average bandwidth decay must be between 0 and 1.');
- }
-
- return function () {
- var pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
-
- if (average < 0) {
- average = this.systemBandwidth;
- lastSystemBandwidth = this.systemBandwidth;
- } // stop the average value from decaying for every 250ms
- // when the systemBandwidth is constant
- // and
- // stop average from setting to a very low value when the
- // systemBandwidth becomes 0 in case of chunk cancellation
-
-
- if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
- average = decay * this.systemBandwidth + (1 - decay) * average;
- lastSystemBandwidth = this.systemBandwidth;
- }
-
- return simpleSelector(this.playlists.master, average, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
- };
-};
-/**
- * Chooses the appropriate media playlist based on the potential to rebuffer
- *
- * @param {Object} settings
- * Object of information required to use this selector
- * @param {Object} settings.master
- * Object representation of the master manifest
- * @param {number} settings.currentTime
- * The current time of the player
- * @param {number} settings.bandwidth
- * Current measured bandwidth
- * @param {number} settings.duration
- * Duration of the media
- * @param {number} settings.segmentDuration
- * Segment duration to be used in round trip time calculations
- * @param {number} settings.timeUntilRebuffer
- * Time left in seconds until the player has to rebuffer
- * @param {number} settings.currentTimeline
- * The current timeline segments are being loaded from
- * @param {SyncController} settings.syncController
- * SyncController for determining if we have a sync point for a given playlist
- * @return {Object|null}
- * {Object} return.playlist
- * The highest bandwidth playlist with the least amount of rebuffering
- * {Number} return.rebufferingImpact
- * The amount of time in seconds switching to this playlist will rebuffer. A
- * negative value means that switching will cause zero rebuffering.
- */
-
-var minRebufferMaxBandwidthSelector = function minRebufferMaxBandwidthSelector(settings) {
- var master = settings.master,
- currentTime = settings.currentTime,
- bandwidth = settings.bandwidth,
- duration = settings.duration,
- segmentDuration = settings.segmentDuration,
- timeUntilRebuffer = settings.timeUntilRebuffer,
- currentTimeline = settings.currentTimeline,
- syncController = settings.syncController; // filter out any playlists that have been excluded due to
- // incompatible configurations
-
- var compatiblePlaylists = master.playlists.filter(function (playlist) {
- return !Playlist.isIncompatible(playlist);
- }); // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
-
- var enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
-
- if (!enabledPlaylists.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylists = compatiblePlaylists.filter(function (playlist) {
- return !Playlist.isDisabled(playlist);
- });
- }
-
- var bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
- var rebufferingEstimates = bandwidthPlaylists.map(function (playlist) {
- var syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
- // sync request first. This will double the request time
-
- var numRequests = syncPoint ? 1 : 2;
- var requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
- var rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
- return {
- playlist: playlist,
- rebufferingImpact: rebufferingImpact
- };
- });
- var noRebufferingPlaylists = rebufferingEstimates.filter(function (estimate) {
- return estimate.rebufferingImpact <= 0;
- }); // Sort by bandwidth DESC
-
- stableSort(noRebufferingPlaylists, function (a, b) {
- return comparePlaylistBandwidth(b.playlist, a.playlist);
- });
-
- if (noRebufferingPlaylists.length) {
- return noRebufferingPlaylists[0];
- }
-
- stableSort(rebufferingEstimates, function (a, b) {
- return a.rebufferingImpact - b.rebufferingImpact;
- });
- return rebufferingEstimates[0] || null;
-};
-/**
- * Chooses the appropriate media playlist, which in this case is the lowest bitrate
- * one with video. If no renditions with video exist, return the lowest audio rendition.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Object|null}
- * {Object} return.playlist
- * The lowest bitrate playlist that contains a video codec. If no such rendition
- * exists pick the lowest audio rendition.
- */
-
-var lowestBitrateCompatibleVariantSelector = function lowestBitrateCompatibleVariantSelector() {
- var _this = this;
-
- // filter out any playlists that have been excluded due to
- // incompatible configurations or playback errors
- var playlists = this.playlists.master.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
-
- stableSort(playlists, function (a, b) {
- return comparePlaylistBandwidth(a, b);
- }); // Parse and assume that playlists with no video codec have no video
- // (this is not necessarily true, although it is generally true).
- //
- // If an entire manifest has no valid videos everything will get filtered
- // out.
-
- var playlistsWithVideo = playlists.filter(function (playlist) {
- return !!codecsForPlaylist(_this.playlists.master, playlist).video;
- });
- return playlistsWithVideo[0] || null;
-};
-
-/**
- * Combine all segments into a single Uint8Array
- *
- * @param {Object} segmentObj
- * @return {Uint8Array} concatenated bytes
- * @private
- */
-var concatSegments = function concatSegments(segmentObj) {
- var offset = 0;
- var tempBuffer;
-
- if (segmentObj.bytes) {
- tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
-
- segmentObj.segments.forEach(function (segment) {
- tempBuffer.set(segment, offset);
- offset += segment.byteLength;
- });
- }
-
- return tempBuffer;
-};
-
-/**
- * @file text-tracks.js
- */
-/**
- * Create captions text tracks on video.js if they do not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {Object} tech the video.js tech
- * @param {Object} captionStream the caption stream to create
- * @private
- */
-
-var createCaptionsTrackIfNotExists = function createCaptionsTrackIfNotExists(inbandTextTracks, tech, captionStream) {
- if (!inbandTextTracks[captionStream]) {
- tech.trigger({
- type: 'usage',
- name: 'vhs-608'
- });
- tech.trigger({
- type: 'usage',
- name: 'hls-608'
- });
- var instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
-
- if (/^cc708_/.test(captionStream)) {
- instreamId = 'SERVICE' + captionStream.split('_')[1];
- }
-
- var track = tech.textTracks().getTrackById(instreamId);
-
- if (track) {
- // Resuse an existing track with a CC# id because this was
- // very likely created by videojs-contrib-hls from information
- // in the m3u8 for us to use
- inbandTextTracks[captionStream] = track;
- } else {
- // This section gets called when we have caption services that aren't specified in the manifest.
- // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
- var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
- var label = captionStream;
- var language = captionStream;
- var def = false;
- var captionService = captionServices[instreamId];
-
- if (captionService) {
- label = captionService.label;
- language = captionService.language;
- def = captionService.default;
- } // Otherwise, create a track with the default `CC#` label and
- // without a language
-
-
- inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
- kind: 'captions',
- id: instreamId,
- // TODO: investigate why this doesn't seem to turn the caption on by default
- default: def,
- label: label,
- language: language
- }, false).track;
- }
- }
-};
-/**
- * Add caption text track data to a source handler given an array of captions
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {Array} captionArray an array of caption data
- * @private
- */
-
-var addCaptionData = function addCaptionData(_ref) {
- var inbandTextTracks = _ref.inbandTextTracks,
- captionArray = _ref.captionArray,
- timestampOffset = _ref.timestampOffset;
-
- if (!captionArray) {
- return;
- }
-
- var Cue = window.WebKitDataCue || window.VTTCue;
- captionArray.forEach(function (caption) {
- var track = caption.stream;
- inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
- });
-};
-/**
- * Define properties on a cue for backwards compatability,
- * but warn the user that the way that they are using it
- * is depricated and will be removed at a later date.
- *
- * @param {Cue} cue the cue to add the properties on
- * @private
- */
-
-var deprecateOldCue = function deprecateOldCue(cue) {
- Object.defineProperties(cue.frame, {
- id: {
- get: function get() {
- videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
- return cue.value.key;
- }
- },
- value: {
- get: function get() {
- videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- },
- privateData: {
- get: function get() {
- videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- }
- });
-};
-/**
- * Add metadata text track data to a source handler given an array of metadata
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {Array} metadataArray an array of meta data
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {number} videoDuration the duration of the video
- * @private
- */
-
-
-var addMetadata = function addMetadata(_ref2) {
- var inbandTextTracks = _ref2.inbandTextTracks,
- metadataArray = _ref2.metadataArray,
- timestampOffset = _ref2.timestampOffset,
- videoDuration = _ref2.videoDuration;
-
- if (!metadataArray) {
- return;
- }
-
- var Cue = window.WebKitDataCue || window.VTTCue;
- var metadataTrack = inbandTextTracks.metadataTrack_;
-
- if (!metadataTrack) {
- return;
- }
-
- metadataArray.forEach(function (metadata) {
- var time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
- // ignore this bit of metadata.
- // This likely occurs when you have an non-timed ID3 tag like TIT2,
- // which is the "Title/Songname/Content description" frame
-
- if (typeof time !== 'number' || window.isNaN(time) || time < 0 || !(time < Infinity)) {
- return;
- }
-
- metadata.frames.forEach(function (frame) {
- var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
- cue.frame = frame;
- cue.value = frame;
- deprecateOldCue(cue);
- metadataTrack.addCue(cue);
- });
- });
-
- if (!metadataTrack.cues || !metadataTrack.cues.length) {
- return;
- } // Updating the metadeta cues so that
- // the endTime of each cue is the startTime of the next cue
- // the endTime of last cue is the duration of the video
-
-
- var cues = metadataTrack.cues;
- var cuesArray = []; // Create a copy of the TextTrackCueList...
- // ...disregarding cues with a falsey value
-
- for (var i = 0; i < cues.length; i++) {
- if (cues[i]) {
- cuesArray.push(cues[i]);
- }
- } // Group cues by their startTime value
-
-
- var cuesGroupedByStartTime = cuesArray.reduce(function (obj, cue) {
- var timeSlot = obj[cue.startTime] || [];
- timeSlot.push(cue);
- obj[cue.startTime] = timeSlot;
- return obj;
- }, {}); // Sort startTimes by ascending order
-
- var sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort(function (a, b) {
- return Number(a) - Number(b);
- }); // Map each cue group's endTime to the next group's startTime
-
- sortedStartTimes.forEach(function (startTime, idx) {
- var cueGroup = cuesGroupedByStartTime[startTime];
- var nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
-
- cueGroup.forEach(function (cue) {
- cue.endTime = nextTime;
- });
- });
-};
-/**
- * Create metadata text track on video.js if it does not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {string} dispatchType the inband metadata track dispatch type
- * @param {Object} tech the video.js tech
- * @private
- */
-
-var createMetadataTrackIfNotExists = function createMetadataTrackIfNotExists(inbandTextTracks, dispatchType, tech) {
- if (inbandTextTracks.metadataTrack_) {
- return;
- }
-
- inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'Timed Metadata'
- }, false).track;
- inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
-};
-/**
- * Remove cues from a track on video.js.
- *
- * @param {Double} start start of where we should remove the cue
- * @param {Double} end end of where the we should remove the cue
- * @param {Object} track the text track to remove the cues from
- * @private
- */
-
-var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
- var i;
- var cue;
-
- if (!track) {
- return;
- }
-
- if (!track.cues) {
- return;
- }
-
- i = track.cues.length;
-
- while (i--) {
- cue = track.cues[i]; // Remove any cue within the provided start and end time
-
- if (cue.startTime >= start && cue.endTime <= end) {
- track.removeCue(cue);
- }
- }
-};
-/**
- * Remove duplicate cues from a track on video.js (a cue is considered a
- * duplicate if it has the same time interval and text as another)
- *
- * @param {Object} track the text track to remove the duplicate cues from
- * @private
- */
-
-var removeDuplicateCuesFromTrack = function removeDuplicateCuesFromTrack(track) {
- var cues = track.cues;
-
- if (!cues) {
- return;
- }
-
- for (var i = 0; i < cues.length; i++) {
- var duplicates = [];
- var occurrences = 0;
-
- for (var j = 0; j < cues.length; j++) {
- if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
- occurrences++;
-
- if (occurrences > 1) {
- duplicates.push(cues[j]);
- }
- }
- }
-
- if (duplicates.length) {
- duplicates.forEach(function (dupe) {
- return track.removeCue(dupe);
- });
- }
- }
-};
-
-/**
- * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
- * front of current time.
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {number} currentTime
- * The current time
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- * @return {Array}
- * List of gops considered safe to append over
- */
-
-var gopsSafeToAlignWith = function gopsSafeToAlignWith(buffer, currentTime, mapping) {
- if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
- return [];
- } // pts value for current time + 3 seconds to give a bit more wiggle room
-
-
- var currentTimePts = Math.ceil((currentTime - mapping + 3) * ONE_SECOND_IN_TS);
- var i;
-
- for (i = 0; i < buffer.length; i++) {
- if (buffer[i].pts > currentTimePts) {
- break;
- }
- }
-
- return buffer.slice(i);
-};
-/**
- * Appends gop information (timing and byteLength) received by the transmuxer for the
- * gops appended in the last call to appendBuffer
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Array} gops
- * List of new gop information
- * @param {boolean} replace
- * If true, replace the buffer with the new gop information. If false, append the
- * new gop information to the buffer in the right location of time.
- * @return {Array}
- * Updated list of gop information
- */
-
-var updateGopBuffer = function updateGopBuffer(buffer, gops, replace) {
- if (!gops.length) {
- return buffer;
- }
-
- if (replace) {
- // If we are in safe append mode, then completely overwrite the gop buffer
- // with the most recent appeneded data. This will make sure that when appending
- // future segments, we only try to align with gops that are both ahead of current
- // time and in the last segment appended.
- return gops.slice();
- }
-
- var start = gops[0].pts;
- var i = 0;
-
- for (i; i < buffer.length; i++) {
- if (buffer[i].pts >= start) {
- break;
- }
- }
-
- return buffer.slice(0, i).concat(gops);
-};
-/**
- * Removes gop information in buffer that overlaps with provided start and end
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Double} start
- * position to start the remove at
- * @param {Double} end
- * position to end the remove at
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- */
-
-var removeGopBuffer = function removeGopBuffer(buffer, start, end, mapping) {
- var startPts = Math.ceil((start - mapping) * ONE_SECOND_IN_TS);
- var endPts = Math.ceil((end - mapping) * ONE_SECOND_IN_TS);
- var updatedBuffer = buffer.slice();
- var i = buffer.length;
-
- while (i--) {
- if (buffer[i].pts <= endPts) {
- break;
- }
- }
-
- if (i === -1) {
- // no removal because end of remove range is before start of buffer
- return updatedBuffer;
- }
-
- var j = i + 1;
-
- while (j--) {
- if (buffer[j].pts <= startPts) {
- break;
- }
- } // clamp remove range start to 0 index
-
-
- j = Math.max(j, 0);
- updatedBuffer.splice(j, i - j + 1);
- return updatedBuffer;
-};
-
-var shallowEqual = function shallowEqual(a, b) {
- // if both are undefined
- // or one or the other is undefined
- // they are not equal
- if (!a && !b || !a && b || a && !b) {
- return false;
- } // they are the same object and thus, equal
-
-
- if (a === b) {
- return true;
- } // sort keys so we can make sure they have
- // all the same keys later.
-
-
- var akeys = Object.keys(a).sort();
- var bkeys = Object.keys(b).sort(); // different number of keys, not equal
-
- if (akeys.length !== bkeys.length) {
- return false;
- }
-
- for (var i = 0; i < akeys.length; i++) {
- var key = akeys[i]; // different sorted keys, not equal
-
- if (key !== bkeys[i]) {
- return false;
- } // different values, not equal
-
-
- if (a[key] !== b[key]) {
- return false;
- }
- }
-
- return true;
-};
-
-// https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
-var QUOTA_EXCEEDED_ERR = 22;
-
-/**
- * The segment loader has no recourse except to fetch a segment in the
- * current playlist and use the internal timestamps in that segment to
- * generate a syncPoint. This function returns a good candidate index
- * for that process.
- *
- * @param {Array} segments - the segments array from a playlist.
- * @return {number} An index of a segment from the playlist to load
- */
-
-var getSyncSegmentCandidate = function getSyncSegmentCandidate(currentTimeline, segments, targetTime) {
- segments = segments || [];
- var timelineSegments = [];
- var time = 0;
-
- for (var i = 0; i < segments.length; i++) {
- var segment = segments[i];
-
- if (currentTimeline === segment.timeline) {
- timelineSegments.push(i);
- time += segment.duration;
-
- if (time > targetTime) {
- return i;
- }
- }
- }
-
- if (timelineSegments.length === 0) {
- return 0;
- } // default to the last timeline segment
-
-
- return timelineSegments[timelineSegments.length - 1];
-}; // In the event of a quota exceeded error, keep at least one second of back buffer. This
-// number was arbitrarily chosen and may be updated in the future, but seemed reasonable
-// as a start to prevent any potential issues with removing content too close to the
-// playhead.
-
-var MIN_BACK_BUFFER = 1; // in ms
-
-var CHECK_BUFFER_DELAY = 500;
-
-var finite = function finite(num) {
- return typeof num === 'number' && isFinite(num);
-}; // With most content hovering around 30fps, if a segment has a duration less than a half
-// frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
-// not accurately reflect the rest of the content.
-
-
-var MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
-var illegalMediaSwitch = function illegalMediaSwitch(loaderType, startingMedia, trackInfo) {
- // Although these checks should most likely cover non 'main' types, for now it narrows
- // the scope of our checks.
- if (loaderType !== 'main' || !startingMedia || !trackInfo) {
- return null;
- }
-
- if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
- return 'Neither audio nor video found in segment.';
- }
-
- if (startingMedia.hasVideo && !trackInfo.hasVideo) {
- return 'Only audio found in segment when we expected video.' + ' We can\'t switch to audio only from a stream that had video.' + ' To get rid of this message, please add codec information to the manifest.';
- }
-
- if (!startingMedia.hasVideo && trackInfo.hasVideo) {
- return 'Video found in segment when we expected only audio.' + ' We can\'t switch to a stream with video from an audio only stream.' + ' To get rid of this message, please add codec information to the manifest.';
- }
-
- return null;
-};
-/**
- * Calculates a time value that is safe to remove from the back buffer without interrupting
- * playback.
- *
- * @param {TimeRange} seekable
- * The current seekable range
- * @param {number} currentTime
- * The current time of the player
- * @param {number} targetDuration
- * The target duration of the current playlist
- * @return {number}
- * Time that is safe to remove from the back buffer without interrupting playback
- */
-
-var safeBackBufferTrimTime = function safeBackBufferTrimTime(seekable, currentTime, targetDuration) {
- // 30 seconds before the playhead provides a safe default for trimming.
- //
- // Choosing a reasonable default is particularly important for high bitrate content and
- // VOD videos/live streams with large windows, as the buffer may end up overfilled and
- // throw an APPEND_BUFFER_ERR.
- var trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
-
- if (seekable.length) {
- // Some live playlists may have a shorter window of content than the full allowed back
- // buffer. For these playlists, don't save content that's no longer within the window.
- trimTime = Math.max(trimTime, seekable.start(0));
- } // Don't remove within target duration of the current time to avoid the possibility of
- // removing the GOP currently being played, as removing it can cause playback stalls.
-
-
- var maxTrimTime = currentTime - targetDuration;
- return Math.min(maxTrimTime, trimTime);
-};
-
-var segmentInfoString = function segmentInfoString(segmentInfo) {
- var startOfSegment = segmentInfo.startOfSegment,
- duration = segmentInfo.duration,
- segment = segmentInfo.segment,
- part = segmentInfo.part,
- _segmentInfo$playlist = segmentInfo.playlist,
- seq = _segmentInfo$playlist.mediaSequence,
- id = _segmentInfo$playlist.id,
- _segmentInfo$playlist2 = _segmentInfo$playlist.segments,
- segments = _segmentInfo$playlist2 === void 0 ? [] : _segmentInfo$playlist2,
- index = segmentInfo.mediaIndex,
- partIndex = segmentInfo.partIndex,
- timeline = segmentInfo.timeline;
- var segmentLen = segments.length - 1;
- var selection = 'mediaIndex/partIndex increment';
-
- if (segmentInfo.getMediaInfoForTime) {
- selection = "getMediaInfoForTime (" + segmentInfo.getMediaInfoForTime + ")";
- } else if (segmentInfo.isSyncRequest) {
- selection = 'getSyncSegmentCandidate (isSyncRequest)';
- }
-
- var hasPartIndex = typeof partIndex === 'number';
- var name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
- var zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
- preloadSegment: segment
- }) - 1 : 0;
- return name + " [" + (seq + index) + "/" + (seq + segmentLen) + "]" + (hasPartIndex ? " part [" + partIndex + "/" + zeroBasedPartCount + "]" : '') + (" segment start/end [" + segment.start + " => " + segment.end + "]") + (hasPartIndex ? " part start/end [" + part.start + " => " + part.end + "]" : '') + (" startOfSegment [" + startOfSegment + "]") + (" duration [" + duration + "]") + (" timeline [" + timeline + "]") + (" selected by [" + selection + "]") + (" playlist [" + id + "]");
-};
-
-var timingInfoPropertyForMedia = function timingInfoPropertyForMedia(mediaType) {
- return mediaType + "TimingInfo";
-};
-/**
- * Returns the timestamp offset to use for the segment.
- *
- * @param {number} segmentTimeline
- * The timeline of the segment
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} startOfSegment
- * The estimated segment start
- * @param {TimeRange[]} buffered
- * The loader's buffer
- * @param {boolean} overrideCheck
- * If true, no checks are made to see if the timestamp offset value should be set,
- * but sets it directly to a value.
- *
- * @return {number|null}
- * Either a number representing a new timestamp offset, or null if the segment is
- * part of the same timeline
- */
-
-
-var timestampOffsetForSegment = function timestampOffsetForSegment(_ref) {
- var segmentTimeline = _ref.segmentTimeline,
- currentTimeline = _ref.currentTimeline,
- startOfSegment = _ref.startOfSegment,
- buffered = _ref.buffered,
- overrideCheck = _ref.overrideCheck;
-
- // Check to see if we are crossing a discontinuity to see if we need to set the
- // timestamp offset on the transmuxer and source buffer.
- //
- // Previously, we changed the timestampOffset if the start of this segment was less than
- // the currently set timestampOffset, but this isn't desirable as it can produce bad
- // behavior, especially around long running live streams.
- if (!overrideCheck && segmentTimeline === currentTimeline) {
- return null;
- } // When changing renditions, it's possible to request a segment on an older timeline. For
- // instance, given two renditions with the following:
- //
- // #EXTINF:10
- // segment1
- // #EXT-X-DISCONTINUITY
- // #EXTINF:10
- // segment2
- // #EXTINF:10
- // segment3
- //
- // And the current player state:
- //
- // current time: 8
- // buffer: 0 => 20
- //
- // The next segment on the current rendition would be segment3, filling the buffer from
- // 20s onwards. However, if a rendition switch happens after segment2 was requested,
- // then the next segment to be requested will be segment1 from the new rendition in
- // order to fill time 8 and onwards. Using the buffered end would result in repeated
- // content (since it would position segment1 of the new rendition starting at 20s). This
- // case can be identified when the new segment's timeline is a prior value. Instead of
- // using the buffered end, the startOfSegment can be used, which, hopefully, will be
- // more accurate to the actual start time of the segment.
-
-
- if (segmentTimeline < currentTimeline) {
- return startOfSegment;
- } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
- // value uses the end of the last segment if it is available. While this value
- // should often be correct, it's better to rely on the buffered end, as the new
- // content post discontinuity should line up with the buffered end as if it were
- // time 0 for the new content.
-
-
- return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
-};
-/**
- * Returns whether or not the loader should wait for a timeline change from the timeline
- * change controller before processing the segment.
- *
- * Primary timing in VHS goes by video. This is different from most media players, as
- * audio is more often used as the primary timing source. For the foreseeable future, VHS
- * will continue to use video as the primary timing source, due to the current logic and
- * expectations built around it.
-
- * Since the timing follows video, in order to maintain sync, the video loader is
- * responsible for setting both audio and video source buffer timestamp offsets.
- *
- * Setting different values for audio and video source buffers could lead to
- * desyncing. The following examples demonstrate some of the situations where this
- * distinction is important. Note that all of these cases involve demuxed content. When
- * content is muxed, the audio and video are packaged together, therefore syncing
- * separate media playlists is not an issue.
- *
- * CASE 1: Audio prepares to load a new timeline before video:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the audio loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the video loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the audio loader goes ahead and loads and appends the 6th segment before the video
- * loader crosses the discontinuity, then when appended, the 6th audio segment will use
- * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
- * the audio loader must provide the audioAppendStart value to trim the content in the
- * transmuxer, and that value relies on the audio timestamp offset. Since the audio
- * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
- * segment until that value is provided.
- *
- * CASE 2: Video prepares to load a new timeline before audio:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the video loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the audio loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the video loader goes ahead and loads and appends the 6th segment, then once the
- * segment is loaded and processed, both the video and audio timestamp offsets will be
- * set, since video is used as the primary timing source. This is to ensure content lines
- * up appropriately, as any modifications to the video timing are reflected by audio when
- * the video loader sets the audio and video timestamp offsets to the same value. However,
- * setting the timestamp offset for audio before audio has had a chance to change
- * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
- * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
- *
- * CASE 3: When seeking, audio prepares to load a new timeline before video
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, both audio and video loaders are loading segments from timeline
- * 0, but imagine that the seek originated from timeline 1.
- *
- * When seeking to a new timeline, the timestamp offset will be set based on the expected
- * segment start of the loaded video segment. In order to maintain sync, the audio loader
- * must wait for the video loader to load its segment and update both the audio and video
- * timestamp offsets before it may load and append its own segment. This is the case
- * whether the seek results in a mismatched segment request (e.g., the audio loader
- * chooses to load segment 3 and the video loader chooses to load segment 4) or the
- * loaders choose to load the same segment index from each playlist, as the segments may
- * not be aligned perfectly, even for matching segment indexes.
- *
- * @param {Object} timelinechangeController
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} segmentTimeline
- * The timeline of the segment being loaded
- * @param {('main'|'audio')} loaderType
- * The loader type
- * @param {boolean} audioDisabled
- * Whether the audio is disabled for the loader. This should only be true when the
- * loader may have muxed audio in its segment, but should not append it, e.g., for
- * the main loader when an alternate audio playlist is active.
- *
- * @return {boolean}
- * Whether the loader should wait for a timeline change from the timeline change
- * controller before processing the segment
- */
-
-var shouldWaitForTimelineChange = function shouldWaitForTimelineChange(_ref2) {
- var timelineChangeController = _ref2.timelineChangeController,
- currentTimeline = _ref2.currentTimeline,
- segmentTimeline = _ref2.segmentTimeline,
- loaderType = _ref2.loaderType,
- audioDisabled = _ref2.audioDisabled;
-
- if (currentTimeline === segmentTimeline) {
- return false;
- }
-
- if (loaderType === 'audio') {
- var lastMainTimelineChange = timelineChangeController.lastTimelineChange({
- type: 'main'
- }); // Audio loader should wait if:
- //
- // * main hasn't had a timeline change yet (thus has not loaded its first segment)
- // * main hasn't yet changed to the timeline audio is looking to load
-
- return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
- } // The main loader only needs to wait for timeline changes if there's demuxed audio.
- // Otherwise, there's nothing to wait for, since audio would be muxed into the main
- // loader's segments (or the content is audio/video only and handled by the main
- // loader).
-
-
- if (loaderType === 'main' && audioDisabled) {
- var pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
- type: 'audio'
- }); // Main loader should wait for the audio loader if audio is not pending a timeline
- // change to the current timeline.
- //
- // Since the main loader is responsible for setting the timestamp offset for both
- // audio and video, the main loader must wait for audio to be about to change to its
- // timeline before setting the offset, otherwise, if audio is behind in loading,
- // segments from the previous timeline would be adjusted by the new timestamp offset.
- //
- // This requirement means that video will not cross a timeline until the audio is
- // about to cross to it, so that way audio and video will always cross the timeline
- // together.
- //
- // In addition to normal timeline changes, these rules also apply to the start of a
- // stream (going from a non-existent timeline, -1, to timeline 0). It's important
- // that these rules apply to the first timeline change because if they did not, it's
- // possible that the main loader will cross two timelines before the audio loader has
- // crossed one. Logic may be implemented to handle the startup as a special case, but
- // it's easier to simply treat all timeline changes the same.
-
- if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
- return false;
- }
-
- return true;
- }
-
- return false;
-};
-var mediaDuration = function mediaDuration(audioTimingInfo, videoTimingInfo) {
- var audioDuration = audioTimingInfo && typeof audioTimingInfo.start === 'number' && typeof audioTimingInfo.end === 'number' ? audioTimingInfo.end - audioTimingInfo.start : 0;
- var videoDuration = videoTimingInfo && typeof videoTimingInfo.start === 'number' && typeof videoTimingInfo.end === 'number' ? videoTimingInfo.end - videoTimingInfo.start : 0;
- return Math.max(audioDuration, videoDuration);
-};
-var segmentTooLong = function segmentTooLong(_ref3) {
- var segmentDuration = _ref3.segmentDuration,
- maxDuration = _ref3.maxDuration;
-
- // 0 duration segments are most likely due to metadata only segments or a lack of
- // information.
- if (!segmentDuration) {
- return false;
- } // For HLS:
- //
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
- // The EXTINF duration of each Media Segment in the Playlist
- // file, when rounded to the nearest integer, MUST be less than or equal
- // to the target duration; longer segments can trigger playback stalls
- // or other errors.
- //
- // For DASH, the mpd-parser uses the largest reported segment duration as the target
- // duration. Although that reported duration is occasionally approximate (i.e., not
- // exact), a strict check may report that a segment is too long more often in DASH.
-
-
- return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
-};
-var getTroublesomeSegmentDurationMessage = function getTroublesomeSegmentDurationMessage(segmentInfo, sourceType) {
- // Right now we aren't following DASH's timing model exactly, so only perform
- // this check for HLS content.
- if (sourceType !== 'hls') {
- return null;
- }
-
- var segmentDuration = mediaDuration(segmentInfo.audioTimingInfo, segmentInfo.videoTimingInfo); // Don't report if we lack information.
- //
- // If the segment has a duration of 0 it is either a lack of information or a
- // metadata only segment and shouldn't be reported here.
-
- if (!segmentDuration) {
- return null;
- }
-
- var targetDuration = segmentInfo.playlist.targetDuration;
- var isSegmentWayTooLong = segmentTooLong({
- segmentDuration: segmentDuration,
- maxDuration: targetDuration * 2
- });
- var isSegmentSlightlyTooLong = segmentTooLong({
- segmentDuration: segmentDuration,
- maxDuration: targetDuration
- });
- var segmentTooLongMessage = "Segment with index " + segmentInfo.mediaIndex + " " + ("from playlist " + segmentInfo.playlist.id + " ") + ("has a duration of " + segmentDuration + " ") + ("when the reported duration is " + segmentInfo.duration + " ") + ("and the target duration is " + targetDuration + ". ") + 'For HLS content, a duration in excess of the target duration may result in ' + 'playback issues. See the HLS specification section on EXT-X-TARGETDURATION for ' + 'more details: ' + 'https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1';
-
- if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
- return {
- severity: isSegmentWayTooLong ? 'warn' : 'info',
- message: segmentTooLongMessage
- };
- }
-
- return null;
-};
-/**
- * An object that manages segment loading and appending.
- *
- * @class SegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-
-var SegmentLoader = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose(SegmentLoader, _videojs$EventTarget);
-
- function SegmentLoader(settings, options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this; // check pre-conditions
-
- if (!settings) {
- throw new TypeError('Initialization settings are required');
- }
-
- if (typeof settings.currentTime !== 'function') {
- throw new TypeError('No currentTime getter specified');
- }
-
- if (!settings.mediaSource) {
- throw new TypeError('No MediaSource specified');
- } // public properties
-
-
- _this.bandwidth = settings.bandwidth;
- _this.throughput = {
- rate: 0,
- count: 0
- };
- _this.roundTrip = NaN;
-
- _this.resetStats_();
-
- _this.mediaIndex = null;
- _this.partIndex = null; // private settings
-
- _this.hasPlayed_ = settings.hasPlayed;
- _this.currentTime_ = settings.currentTime;
- _this.seekable_ = settings.seekable;
- _this.seeking_ = settings.seeking;
- _this.duration_ = settings.duration;
- _this.mediaSource_ = settings.mediaSource;
- _this.vhs_ = settings.vhs;
- _this.loaderType_ = settings.loaderType;
- _this.currentMediaInfo_ = void 0;
- _this.startingMediaInfo_ = void 0;
- _this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
- _this.goalBufferLength_ = settings.goalBufferLength;
- _this.sourceType_ = settings.sourceType;
- _this.sourceUpdater_ = settings.sourceUpdater;
- _this.inbandTextTracks_ = settings.inbandTextTracks;
- _this.state_ = 'INIT';
- _this.timelineChangeController_ = settings.timelineChangeController;
- _this.shouldSaveSegmentTimingInfo_ = true;
- _this.parse708captions_ = settings.parse708captions; // private instance variables
-
- _this.checkBufferTimeout_ = null;
- _this.error_ = void 0;
- _this.currentTimeline_ = -1;
- _this.pendingSegment_ = null;
- _this.xhrOptions_ = null;
- _this.pendingSegments_ = [];
- _this.audioDisabled_ = false;
- _this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
-
- _this.gopBuffer_ = [];
- _this.timeMapping_ = 0;
- _this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
- _this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- _this.playlistOfLastInitSegment_ = {
- audio: null,
- video: null
- };
- _this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
- // information yet to start the loading process (e.g., if the audio loader wants to
- // load a segment from the next timeline but the main loader hasn't yet crossed that
- // timeline), then the load call will be added to the queue until it is ready to be
- // processed.
-
- _this.loadQueue_ = [];
- _this.metadataQueue_ = {
- id3: [],
- caption: []
- };
- _this.waitingOnRemove_ = false;
- _this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
-
- _this.activeInitSegmentId_ = null;
- _this.initSegments_ = {}; // HLSe playback
-
- _this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
- _this.keyCache_ = {};
- _this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
- // between a time in the display time and a segment index within
- // a playlist
-
- _this.syncController_ = settings.syncController;
- _this.syncPoint_ = {
- segmentIndex: 0,
- time: 0
- };
- _this.transmuxer_ = _this.createTransmuxer_();
-
- _this.triggerSyncInfoUpdate_ = function () {
- return _this.trigger('syncinfoupdate');
- };
-
- _this.syncController_.on('syncinfoupdate', _this.triggerSyncInfoUpdate_);
-
- _this.mediaSource_.addEventListener('sourceopen', function () {
- if (!_this.isEndOfStream_()) {
- _this.ended_ = false;
- }
- }); // ...for determining the fetch location
-
-
- _this.fetchAtBuffer_ = false;
- _this.logger_ = logger("SegmentLoader[" + _this.loaderType_ + "]");
- Object.defineProperty(_assertThisInitialized(_this), 'state', {
- get: function get() {
- return this.state_;
- },
- set: function set(newState) {
- if (newState !== this.state_) {
- this.logger_(this.state_ + " -> " + newState);
- this.state_ = newState;
- this.trigger('statechange');
- }
- }
- });
-
- _this.sourceUpdater_.on('ready', function () {
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- }); // Only the main loader needs to listen for pending timeline changes, as the main
- // loader should wait for audio to be ready to change its timeline so that both main
- // and audio timelines change together. For more details, see the
- // shouldWaitForTimelineChange function.
-
-
- if (_this.loaderType_ === 'main') {
- _this.timelineChangeController_.on('pendingtimelinechange', function () {
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- });
- } // The main loader only listens on pending timeline changes, but the audio loader,
- // since its loads follow main, needs to listen on timeline changes. For more details,
- // see the shouldWaitForTimelineChange function.
-
-
- if (_this.loaderType_ === 'audio') {
- _this.timelineChangeController_.on('timelinechange', function () {
- if (_this.hasEnoughInfoToLoad_()) {
- _this.processLoadQueue_();
- }
-
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- });
- }
-
- return _this;
- }
-
- var _proto = SegmentLoader.prototype;
-
- _proto.createTransmuxer_ = function createTransmuxer_() {
- return segmentTransmuxer.createTransmuxer({
- remux: false,
- alignGopsAtEnd: this.safeAppend_,
- keepOriginalTimestamps: true,
- parse708captions: this.parse708captions_
- });
- }
- /**
- * reset all of our media stats
- *
- * @private
- */
- ;
-
- _proto.resetStats_ = function resetStats_() {
- this.mediaBytesTransferred = 0;
- this.mediaRequests = 0;
- this.mediaRequestsAborted = 0;
- this.mediaRequestsTimedout = 0;
- this.mediaRequestsErrored = 0;
- this.mediaTransferDuration = 0;
- this.mediaSecondsLoaded = 0;
- this.mediaAppends = 0;
- }
- /**
- * dispose of the SegmentLoader and reset to the default state
- */
- ;
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.state = 'DISPOSED';
- this.pause();
- this.abort_();
-
- if (this.transmuxer_) {
- this.transmuxer_.terminate();
- }
-
- this.resetStats_();
-
- if (this.checkBufferTimeout_) {
- window.clearTimeout(this.checkBufferTimeout_);
- }
-
- if (this.syncController_ && this.triggerSyncInfoUpdate_) {
- this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
- }
-
- this.off();
- };
-
- _proto.setAudio = function setAudio(enable) {
- this.audioDisabled_ = !enable;
-
- if (enable) {
- this.appendInitSegment_.audio = true;
- } else {
- // remove current track audio if it gets disabled
- this.sourceUpdater_.removeAudio(0, this.duration_());
- }
- }
- /**
- * abort anything that is currently doing on with the SegmentLoader
- * and reset to a default state
- */
- ;
-
- _proto.abort = function abort() {
- if (this.state !== 'WAITING') {
- if (this.pendingSegment_) {
- this.pendingSegment_ = null;
- }
-
- return;
- }
-
- this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
- // since we are no longer "waiting" on any requests. XHR callback is not always run
- // when the request is aborted. This will prevent the loader from being stuck in the
- // WAITING state indefinitely.
-
- this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
- // next segment
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
- /**
- * abort all pending xhr requests and null any pending segements
- *
- * @private
- */
- ;
-
- _proto.abort_ = function abort_() {
- if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
- this.pendingSegment_.abortRequests();
- } // clear out the segment being processed
-
-
- this.pendingSegment_ = null;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
- this.waitingOnRemove_ = false;
- window.clearTimeout(this.quotaExceededErrorRetryTimeout_);
- this.quotaExceededErrorRetryTimeout_ = null;
- };
-
- _proto.checkForAbort_ = function checkForAbort_(requestId) {
- // If the state is APPENDING, then aborts will not modify the state, meaning the first
- // callback that happens should reset the state to READY so that loading can continue.
- if (this.state === 'APPENDING' && !this.pendingSegment_) {
- this.state = 'READY';
- return true;
- }
-
- if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
- return true;
- }
-
- return false;
- }
- /**
- * set an error on the segment loader and null out any pending segements
- *
- * @param {Error} error the error to set on the SegmentLoader
- * @return {Error} the error that was set or that is currently set
- */
- ;
-
- _proto.error = function error(_error) {
- if (typeof _error !== 'undefined') {
- this.logger_('error occurred:', _error);
- this.error_ = _error;
- }
-
- this.pendingSegment_ = null;
- return this.error_;
- };
-
- _proto.endOfStream = function endOfStream() {
- this.ended_ = true;
-
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
-
- this.gopBuffer_.length = 0;
- this.pause();
- this.trigger('ended');
- }
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- ;
-
- _proto.buffered_ = function buffered_() {
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- return videojs.createTimeRanges();
- }
-
- if (this.loaderType_ === 'main') {
- var _this$startingMediaIn = this.startingMediaInfo_,
- hasAudio = _this$startingMediaIn.hasAudio,
- hasVideo = _this$startingMediaIn.hasVideo,
- isMuxed = _this$startingMediaIn.isMuxed;
-
- if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
- return this.sourceUpdater_.buffered();
- }
-
- if (hasVideo) {
- return this.sourceUpdater_.videoBuffered();
- }
- } // One case that can be ignored for now is audio only with alt audio,
- // as we don't yet have proper support for that.
-
-
- return this.sourceUpdater_.audioBuffered();
- }
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- ;
-
- _proto.initSegmentForMap = function initSegmentForMap(map, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!map) {
- return null;
- }
-
- var id = initSegmentId(map);
- var storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: map.bytes,
- tracks: map.tracks,
- timescales: map.timescales
- };
- }
-
- return storedMap || map;
- }
- /**
- * Gets and sets key for the provided key
- *
- * @param {Object} key
- * The key object representing the key to get or set
- * @param {boolean=} set
- * If true, the key for the provided key should be saved
- * @return {Object}
- * Key object for desired key
- */
- ;
-
- _proto.segmentKey = function segmentKey(key, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!key) {
- return null;
- }
-
- var id = segmentKeyId(key);
- var storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
-
- if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
- this.keyCache_[id] = storedKey = {
- resolvedUri: key.resolvedUri,
- bytes: key.bytes
- };
- }
-
- var result = {
- resolvedUri: (storedKey || key).resolvedUri
- };
-
- if (storedKey) {
- result.bytes = storedKey.bytes;
- }
-
- return result;
- }
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- ;
-
- _proto.couldBeginLoading_ = function couldBeginLoading_() {
- return this.playlist_ && !this.paused();
- }
- /**
- * load a playlist and start to fill the buffer
- */
- ;
-
- _proto.load = function load() {
- // un-pause
- this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
- // specified
-
- if (!this.playlist_) {
- return;
- } // if all the configuration is ready, initialize and begin loading
-
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- } // if we're in the middle of processing a segment already, don't
- // kick off an additional segment request
-
-
- if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
- return;
- }
-
- this.state = 'READY';
- }
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- ;
-
- _proto.init_ = function init_() {
- this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
- // audio data from the muxed content should be removed
-
- this.resetEverything();
- return this.monitorBuffer_();
- }
- /**
- * set a playlist on the segment loader
- *
- * @param {PlaylistLoader} media the playlist to set on the segment loader
- */
- ;
-
- _proto.playlist = function playlist(newPlaylist, options) {
- if (options === void 0) {
- options = {};
- }
-
- if (!newPlaylist) {
- return;
- }
-
- var oldPlaylist = this.playlist_;
- var segmentInfo = this.pendingSegment_;
- this.playlist_ = newPlaylist;
- this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
- // is always our zero-time so force a sync update each time the playlist
- // is refreshed from the server
- //
- // Use the INIT state to determine if playback has started, as the playlist sync info
- // should be fixed once requests begin (as sync points are generated based on sync
- // info), but not before then.
-
- if (this.state === 'INIT') {
- newPlaylist.syncInfo = {
- mediaSequence: newPlaylist.mediaSequence,
- time: 0
- }; // Setting the date time mapping means mapping the program date time (if available)
- // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
- // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
- // be updated as the playlist is refreshed before the loader starts loading, the
- // program date time mapping needs to be updated as well.
- //
- // This mapping is only done for the main loader because a program date time should
- // map equivalently between playlists.
-
- if (this.loaderType_ === 'main') {
- this.syncController_.setDateTimeMappingForStart(newPlaylist);
- }
- }
-
- var oldId = null;
-
- if (oldPlaylist) {
- if (oldPlaylist.id) {
- oldId = oldPlaylist.id;
- } else if (oldPlaylist.uri) {
- oldId = oldPlaylist.uri;
- }
- }
-
- this.logger_("playlist update [" + oldId + " => " + (newPlaylist.id || newPlaylist.uri) + "]"); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
- // in LIVE, we always want to update with new playlists (including refreshes)
-
- this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
- // buffering now
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- }
-
- if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
- if (this.mediaIndex !== null) {
- // we must "resync" the segment loader when we switch renditions and
- // the segment loader is already synced to the previous rendition
- this.resyncLoader();
- }
-
- this.currentMediaInfo_ = void 0;
- this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
-
- return;
- } // we reloaded the same playlist so we are in a live scenario
- // and we will likely need to adjust the mediaIndex
-
-
- var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
- this.logger_("live window shift [" + mediaSequenceDiff + "]"); // update the mediaIndex on the SegmentLoader
- // this is important because we can abort a request and this value must be
- // equal to the last appended mediaIndex
-
- if (this.mediaIndex !== null) {
- this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
- // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
- // new playlist was incremented by 1.
-
- if (this.mediaIndex < 0) {
- this.mediaIndex = null;
- this.partIndex = null;
- } else {
- var segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
- // unless parts fell off of the playlist for this segment.
- // In that case we need to reset partIndex and resync
-
- if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
- var mediaIndex = this.mediaIndex;
- this.logger_("currently processing part (index " + this.partIndex + ") no longer exists.");
- this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
- // as the part was dropped from our current playlists segment.
- // The mediaIndex will still be valid so keep that around.
-
- this.mediaIndex = mediaIndex;
- }
- }
- } // update the mediaIndex on the SegmentInfo object
- // this is important because we will update this.mediaIndex with this value
- // in `handleAppendsDone_` after the segment has been successfully appended
-
-
- if (segmentInfo) {
- segmentInfo.mediaIndex -= mediaSequenceDiff;
-
- if (segmentInfo.mediaIndex < 0) {
- segmentInfo.mediaIndex = null;
- segmentInfo.partIndex = null;
- } else {
- // we need to update the referenced segment so that timing information is
- // saved for the new playlist's segment, however, if the segment fell off the
- // playlist, we can leave the old reference and just lose the timing info
- if (segmentInfo.mediaIndex >= 0) {
- segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
- }
-
- if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
- segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
- }
- }
- }
-
- this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
- }
- /**
- * Prevent the loader from fetching additional segments. If there
- * is a segment request outstanding, it will finish processing
- * before the loader halts. A segment loader can be unpaused by
- * calling load().
- */
- ;
-
- _proto.pause = function pause() {
- if (this.checkBufferTimeout_) {
- window.clearTimeout(this.checkBufferTimeout_);
- this.checkBufferTimeout_ = null;
- }
- }
- /**
- * Returns whether the segment loader is fetching additional
- * segments when given the opportunity. This property can be
- * modified through calls to pause() and load().
- */
- ;
-
- _proto.paused = function paused() {
- return this.checkBufferTimeout_ === null;
- }
- /**
- * Delete all the buffered data and reset the SegmentLoader
- *
- * @param {Function} [done] an optional callback to be executed when the remove
- * operation is complete
- */
- ;
-
- _proto.resetEverything = function resetEverything(done) {
- this.ended_ = false;
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
- // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
- // we then clamp the value to duration if necessary.
-
- this.remove(0, Infinity, done); // clears fmp4 captions
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
- /**
- * Force the SegmentLoader to resync and start loading around the currentTime instead
- * of starting at the end of the buffer
- *
- * Useful for fast quality changes
- */
- ;
-
- _proto.resetLoader = function resetLoader() {
- this.fetchAtBuffer_ = false;
- this.resyncLoader();
- }
- /**
- * Force the SegmentLoader to restart synchronization and make a conservative guess
- * before returning to the simple walk-forward method
- */
- ;
-
- _proto.resyncLoader = function resyncLoader() {
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
-
- this.mediaIndex = null;
- this.partIndex = null;
- this.syncPoint_ = null;
- this.isPendingTimestampOffset_ = false;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.abort();
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- }
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- * @param {Function} [done] - an optional callback to be executed when the remove
- * @param {boolean} force - force all remove operations to happen
- * operation is complete
- */
- ;
-
- _proto.remove = function remove(start, end, done, force) {
- if (done === void 0) {
- done = function done() {};
- }
-
- if (force === void 0) {
- force = false;
- }
-
- // clamp end to duration if we need to remove everything.
- // This is due to a browser bug that causes issues if we remove to Infinity.
- // videojs/videojs-contrib-hls#1225
- if (end === Infinity) {
- end = this.duration_();
- } // skip removes that would throw an error
- // commonly happens during a rendition switch at the start of a video
- // from start 0 to end 0
-
-
- if (end <= start) {
- this.logger_('skipping remove because end ${end} is <= start ${start}');
- return;
- }
-
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
-
- return;
- } // set it to one to complete this function's removes
-
-
- var removesRemaining = 1;
-
- var removeFinished = function removeFinished() {
- removesRemaining--;
-
- if (removesRemaining === 0) {
- done();
- }
- };
-
- if (force || !this.audioDisabled_) {
- removesRemaining++;
- this.sourceUpdater_.removeAudio(start, end, removeFinished);
- } // While it would be better to only remove video if the main loader has video, this
- // should be safe with audio only as removeVideo will call back even if there's no
- // video buffer.
- //
- // In theory we can check to see if there's video before calling the remove, but in
- // the event that we're switching between renditions and from video to audio only
- // (when we add support for that), we may need to clear the video contents despite
- // what the new media will contain.
-
-
- if (force || this.loaderType_ === 'main') {
- this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
- removesRemaining++;
- this.sourceUpdater_.removeVideo(start, end, removeFinished);
- } // remove any captions and ID3 tags
-
-
- for (var track in this.inbandTextTracks_) {
- removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
-
- removeFinished();
- }
- /**
- * (re-)schedule monitorBufferTick_ to run as soon as possible
- *
- * @private
- */
- ;
-
- _proto.monitorBuffer_ = function monitorBuffer_() {
- if (this.checkBufferTimeout_) {
- window.clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
- }
- /**
- * As long as the SegmentLoader is in the READY state, periodically
- * invoke fillBuffer_().
- *
- * @private
- */
- ;
-
- _proto.monitorBufferTick_ = function monitorBufferTick_() {
- if (this.state === 'READY') {
- this.fillBuffer_();
- }
-
- if (this.checkBufferTimeout_) {
- window.clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
- }
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- ;
-
- _proto.fillBuffer_ = function fillBuffer_() {
- // TODO since the source buffer maintains a queue, and we shouldn't call this function
- // except when we're ready for the next segment, this check can most likely be removed
- if (this.sourceUpdater_.updating()) {
- return;
- } // see if we need to begin loading immediately
-
-
- var segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- this.isPendingTimestampOffset_ = false;
- this.timelineChangeController_.pendingTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
-
- this.loadSegment_(segmentInfo);
- }
- /**
- * Determines if we should call endOfStream on the media source based
- * on the state of the buffer or if appened segment was the final
- * segment in the playlist.
- *
- * @param {number} [mediaIndex] the media index of segment we last appended
- * @param {Object} [playlist] a media playlist object
- * @return {boolean} do we need to call endOfStream on the MediaSource
- */
- ;
-
- _proto.isEndOfStream_ = function isEndOfStream_(mediaIndex, playlist, partIndex) {
- if (mediaIndex === void 0) {
- mediaIndex = this.mediaIndex;
- }
-
- if (playlist === void 0) {
- playlist = this.playlist_;
- }
-
- if (partIndex === void 0) {
- partIndex = this.partIndex;
- }
-
- if (!playlist || !this.mediaSource_) {
- return false;
- }
-
- var segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
-
- var appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
-
- var appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endOfStream
- // so that MediaSources can trigger the `ended` event when it runs out of
- // buffered data instead of waiting for me
-
- return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
- }
- /**
- * Determines what request should be made given current segment loader state.
- *
- * @return {Object} a request object that describes the segment/part to load
- */
- ;
-
- _proto.chooseNextRequest_ = function chooseNextRequest_() {
- var bufferedEnd = lastBufferedEnd(this.buffered_()) || 0;
- var bufferedTime = Math.max(0, bufferedEnd - this.currentTime_());
- var preloaded = !this.hasPlayed_() && bufferedTime >= 1;
- var haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
- var segments = this.playlist_.segments; // return no segment if:
- // 1. we don't have segments
- // 2. The video has not yet played and we already downloaded a segment
- // 3. we already have enough buffered time
-
- if (!segments.length || preloaded || haveEnoughBuffer) {
- return null;
- }
-
- this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
- var next = {
- partIndex: null,
- mediaIndex: null,
- startOfSegment: null,
- playlist: this.playlist_,
- isSyncRequest: Boolean(!this.syncPoint_)
- };
-
- if (next.isSyncRequest) {
- next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
- } else if (this.mediaIndex !== null) {
- var segment = segments[this.mediaIndex];
- var partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
- next.startOfSegment = segment.end ? segment.end : bufferedEnd;
-
- if (segment.parts && segment.parts[partIndex + 1]) {
- next.mediaIndex = this.mediaIndex;
- next.partIndex = partIndex + 1;
- } else {
- next.mediaIndex = this.mediaIndex + 1;
- }
- } else {
- // Find the segment containing the end of the buffer or current time.
- var _Playlist$getMediaInf = Playlist.getMediaInfoForTime({
- playlist: this.playlist_,
- currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
- startingPartIndex: this.syncPoint_.partIndex,
- startingSegmentIndex: this.syncPoint_.segmentIndex,
- startTime: this.syncPoint_.time
- }),
- segmentIndex = _Playlist$getMediaInf.segmentIndex,
- startTime = _Playlist$getMediaInf.startTime,
- _partIndex = _Playlist$getMediaInf.partIndex;
-
- next.getMediaInfoForTime = this.fetchAtBuffer_ ? 'bufferedEnd' : 'currentTime';
- next.mediaIndex = segmentIndex;
- next.startOfSegment = startTime;
- next.partIndex = _partIndex;
- }
-
- var nextSegment = segments[next.mediaIndex];
- var nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
- // the next partIndex is invalid do not choose a next segment.
-
- if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
- return null;
- } // if the next segment has parts, and we don't have a partIndex.
- // Set partIndex to 0
-
-
- if (typeof next.partIndex !== 'number' && nextSegment.parts) {
- next.partIndex = 0;
- }
-
- var ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
- // 1. this is the last segment in the playlist
- // 2. end of stream has been called on the media source already
- // 3. the player is not seeking
-
- if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
- return null;
- }
-
- return this.generateSegmentInfo_(next);
- };
-
- _proto.generateSegmentInfo_ = function generateSegmentInfo_(options) {
- var playlist = options.playlist,
- mediaIndex = options.mediaIndex,
- startOfSegment = options.startOfSegment,
- isSyncRequest = options.isSyncRequest,
- partIndex = options.partIndex,
- forceTimestampOffset = options.forceTimestampOffset,
- getMediaInfoForTime = options.getMediaInfoForTime;
- var segment = playlist.segments[mediaIndex];
- var part = typeof partIndex === 'number' && segment.parts[partIndex];
- var segmentInfo = {
- requestId: 'segment-loader-' + Math.random(),
- // resolve the segment URL relative to the playlist
- uri: part && part.resolvedUri || segment.resolvedUri,
- // the segment's mediaIndex at the time it was requested
- mediaIndex: mediaIndex,
- partIndex: part ? partIndex : null,
- // whether or not to update the SegmentLoader's state with this
- // segment's mediaIndex
- isSyncRequest: isSyncRequest,
- startOfSegment: startOfSegment,
- // the segment's playlist
- playlist: playlist,
- // unencrypted bytes of the segment
- bytes: null,
- // when a key is defined for this segment, the encrypted bytes
- encryptedBytes: null,
- // The target timestampOffset for this segment when we append it
- // to the source buffer
- timestampOffset: null,
- // The timeline that the segment is in
- timeline: segment.timeline,
- // The expected duration of the segment in seconds
- duration: part && part.duration || segment.duration,
- // retain the segment in case the playlist updates while doing an async process
- segment: segment,
- part: part,
- byteLength: 0,
- transmuxer: this.transmuxer_,
- // type of getMediaInfoForTime that was used to get this segment
- getMediaInfoForTime: getMediaInfoForTime
- };
- var overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
- segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
- segmentTimeline: segment.timeline,
- currentTimeline: this.currentTimeline_,
- startOfSegment: startOfSegment,
- buffered: this.buffered_(),
- overrideCheck: overrideCheck
- });
- var audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
-
- if (typeof audioBufferedEnd === 'number') {
- // since the transmuxer is using the actual timing values, but the buffer is
- // adjusted by the timestamp offset, we must adjust the value here
- segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
- }
-
- if (this.sourceUpdater_.videoBuffered().length) {
- segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
- // adjusted by the timestmap offset, we must adjust the value here
- this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
- }
-
- return segmentInfo;
- } // get the timestampoffset for a segment,
- // added so that vtt segment loader can override and prevent
- // adding timestamp offsets.
- ;
-
- _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_(options) {
- return timestampOffsetForSegment(options);
- }
- /**
- * Determines if the network has enough bandwidth to complete the current segment
- * request in a timely manner. If not, the request will be aborted early and bandwidth
- * updated to trigger a playlist switch.
- *
- * @param {Object} stats
- * Object containing stats about the request timing and size
- * @private
- */
- ;
-
- _proto.earlyAbortWhenNeeded_ = function earlyAbortWhenNeeded_(stats) {
- if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
- // TODO: Replace using timeout with a boolean indicating whether this playlist is
- // the lowestEnabledRendition.
- !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
- !this.playlist_.attributes.BANDWIDTH) {
- return;
- } // Wait at least 1 second since the first byte of data has been received before
- // using the calculated bandwidth from the progress event to allow the bitrate
- // to stabilize
-
-
- if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
- return;
- }
-
- var currentTime = this.currentTime_();
- var measuredBandwidth = stats.bandwidth;
- var segmentDuration = this.pendingSegment_.duration;
- var requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
- // if we are only left with less than 1 second when the request completes.
- // A negative timeUntilRebuffering indicates we are already rebuffering
-
- var timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
- // is larger than the estimated time until the player runs out of forward buffer
-
- if (requestTimeRemaining <= timeUntilRebuffer$1) {
- return;
- }
-
- var switchCandidate = minRebufferMaxBandwidthSelector({
- master: this.vhs_.playlists.master,
- currentTime: currentTime,
- bandwidth: measuredBandwidth,
- duration: this.duration_(),
- segmentDuration: segmentDuration,
- timeUntilRebuffer: timeUntilRebuffer$1,
- currentTimeline: this.currentTimeline_,
- syncController: this.syncController_
- });
-
- if (!switchCandidate) {
- return;
- }
-
- var rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
- var timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
- var minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
- // potential round trip time of the new request so that we are not too aggressive
- // with switching to a playlist that might save us a fraction of a second.
-
- if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
- minimumTimeSaving = 1;
- }
-
- if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
- return;
- } // set the bandwidth to that of the desired playlist being sure to scale by
- // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
- // don't trigger a bandwidthupdate as the bandwidth is artifial
-
-
- this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
- this.trigger('earlyabort');
- };
-
- _proto.handleAbort_ = function handleAbort_(segmentInfo) {
- this.logger_("Aborting " + segmentInfoString(segmentInfo));
- this.mediaRequestsAborted += 1;
- }
- /**
- * XHR `progress` event handler
- *
- * @param {Event}
- * The XHR `progress` event
- * @param {Object} simpleSegment
- * A simplified segment object copy
- * @private
- */
- ;
-
- _proto.handleProgress_ = function handleProgress_(event, simpleSegment) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- this.trigger('progress');
- };
-
- _proto.handleTrackInfo_ = function handleTrackInfo_(simpleSegment, trackInfo) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- if (this.checkForIllegalMediaSwitch(trackInfo)) {
- return;
- }
-
- trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
- // Guard against cases where we're not getting track info at all until we are
- // certain that all streams will provide it.
-
- if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.startingMediaInfo_ = trackInfo;
- this.currentMediaInfo_ = trackInfo;
- this.logger_('trackinfo update', trackInfo);
- this.trigger('trackinfo');
- } // trackinfo may cause an abort if the trackinfo
- // causes a codec change to an unsupported codec.
-
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // set trackinfo on the pending segment so that
- // it can append.
-
-
- this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
-
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- };
-
- _proto.handleTimingInfo_ = function handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- var segmentInfo = this.pendingSegment_;
- var timingInfoProperty = timingInfoPropertyForMedia(mediaType);
- segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
- segmentInfo[timingInfoProperty][timeType] = time;
- this.logger_("timinginfo: " + mediaType + " - " + timeType + " - " + time); // check if any calls were waiting on the timing info
-
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- };
-
- _proto.handleCaptions_ = function handleCaptions_(simpleSegment, captionData) {
- var _this2 = this;
-
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // This could only happen with fmp4 segments, but
- // should still not happen in general
-
-
- if (captionData.length === 0) {
- this.logger_('SegmentLoader received no captions from a caption event');
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
- // can be adjusted by the timestamp offset
-
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
- return;
- }
-
- var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
- var captionTracks = {}; // get total start/end and captions for each track/stream
-
- captionData.forEach(function (caption) {
- // caption.stream is actually a track name...
- // set to the existing values in tracks or default values
- captionTracks[caption.stream] = captionTracks[caption.stream] || {
- // Infinity, as any other value will be less than this
- startTime: Infinity,
- captions: [],
- // 0 as an other value will be more than this
- endTime: 0
- };
- var captionTrack = captionTracks[caption.stream];
- captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
- captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
- captionTrack.captions.push(caption);
- });
- Object.keys(captionTracks).forEach(function (trackName) {
- var _captionTracks$trackN = captionTracks[trackName],
- startTime = _captionTracks$trackN.startTime,
- endTime = _captionTracks$trackN.endTime,
- captions = _captionTracks$trackN.captions;
- var inbandTextTracks = _this2.inbandTextTracks_;
-
- _this2.logger_("adding cues from " + startTime + " -> " + endTime + " for " + trackName);
-
- createCaptionsTrackIfNotExists(inbandTextTracks, _this2.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
- // We do this because a rendition change that also changes the timescale for captions
- // will result in captions being re-parsed for certain segments. If we add them again
- // without clearing we will have two of the same captions visible.
-
- removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
- addCaptionData({
- captionArray: captions,
- inbandTextTracks: inbandTextTracks,
- timestampOffset: timestampOffset
- });
- }); // Reset stored captions since we added parsed
- // captions to a text track at this point
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- };
-
- _proto.handleId3_ = function handleId3_(simpleSegment, id3Frames, dispatchType) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
-
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
- return;
- }
-
- var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
- // audio/video source with a metadata track, and an alt audio with a metadata track.
- // However, this probably won't happen, and if it does it can be handled then.
-
- createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
- addMetadata({
- inbandTextTracks: this.inbandTextTracks_,
- metadataArray: id3Frames,
- timestampOffset: timestampOffset,
- videoDuration: this.duration_()
- });
- };
-
- _proto.processMetadataQueue_ = function processMetadataQueue_() {
- this.metadataQueue_.id3.forEach(function (fn) {
- return fn();
- });
- this.metadataQueue_.caption.forEach(function (fn) {
- return fn();
- });
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- };
-
- _proto.processCallQueue_ = function processCallQueue_() {
- var callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
-
- this.callQueue_ = [];
- callQueue.forEach(function (fun) {
- return fun();
- });
- };
-
- _proto.processLoadQueue_ = function processLoadQueue_() {
- var loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
-
- this.loadQueue_ = [];
- loadQueue.forEach(function (fun) {
- return fun();
- });
- }
- /**
- * Determines whether the loader has enough info to load the next segment.
- *
- * @return {boolean}
- * Whether or not the loader has enough info to load the next segment
- */
- ;
-
- _proto.hasEnoughInfoToLoad_ = function hasEnoughInfoToLoad_() {
- // Since primary timing goes by video, only the audio loader potentially needs to wait
- // to load.
- if (this.loaderType_ !== 'audio') {
- return true;
- }
-
- var segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
- // enough info to load.
-
- if (!segmentInfo) {
- return false;
- } // The first segment can and should be loaded immediately so that source buffers are
- // created together (before appending). Source buffer creation uses the presence of
- // audio and video data to determine whether to create audio/video source buffers, and
- // uses processed (transmuxed or parsed) media to determine the types required.
-
-
- if (!this.currentMediaInfo_) {
- return true;
- }
-
- if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
- // can be requested and downloaded and only wait before it is transmuxed or parsed.
- // But in practice, there are a few reasons why it is better to wait until a loader
- // is ready to append that segment before requesting and downloading:
- //
- // 1. Because audio and main loaders cross discontinuities together, if this loader
- // is waiting for the other to catch up, then instead of requesting another
- // segment and using up more bandwidth, by not yet loading, more bandwidth is
- // allotted to the loader currently behind.
- // 2. media-segment-request doesn't have to have logic to consider whether a segment
- // is ready to be processed or not, isolating the queueing behavior to the loader.
- // 3. The audio loader bases some of its segment properties on timing information
- // provided by the main loader, meaning that, if the logic for waiting on
- // processing was in media-segment-request, then it would also need to know how
- // to re-generate the segment information after the main loader caught up.
- shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })) {
- return false;
- }
-
- return true;
- };
-
- _proto.hasEnoughInfoToAppend_ = function hasEnoughInfoToAppend_() {
- if (!this.sourceUpdater_.ready()) {
- return false;
- } // If content needs to be removed or the loader is waiting on an append reattempt,
- // then no additional content should be appended until the prior append is resolved.
-
-
- if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
- return false;
- }
-
- var segmentInfo = this.pendingSegment_; // no segment to append any data for or
- // we do not have information on this specific
- // segment yet
-
- if (!segmentInfo || !segmentInfo.trackInfo) {
- return false;
- }
-
- var _this$currentMediaInf = this.currentMediaInfo_,
- hasAudio = _this$currentMediaInf.hasAudio,
- hasVideo = _this$currentMediaInf.hasVideo,
- isMuxed = _this$currentMediaInf.isMuxed;
-
- if (hasVideo && !segmentInfo.videoTimingInfo) {
- return false;
- } // muxed content only relies on video timing information for now.
-
-
- if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
- return false;
- }
-
- if (shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })) {
- return false;
- }
-
- return true;
- };
-
- _proto.handleData_ = function handleData_(simpleSegment, result) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // If there's anything in the call queue, then this data came later and should be
- // executed after the calls currently queued.
-
-
- if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
- this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
-
- this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
-
- this.updateMediaSecondsLoaded_(segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
- // logic may change behavior depending on the state, and changing state too early may
- // inflate our estimates of bandwidth. In the future this should be re-examined to
- // note more granular states.
- // don't process and append data if the mediaSource is closed
-
- if (this.mediaSource_.readyState === 'closed') {
- return;
- } // if this request included an initialization segment, save that data
- // to the initSegment cache
-
-
- if (simpleSegment.map) {
- simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
-
- segmentInfo.segment.map = simpleSegment.map;
- } // if this request included a segment key, save that data in the cache
-
-
- if (simpleSegment.key) {
- this.segmentKey(simpleSegment.key, true);
- }
-
- segmentInfo.isFmp4 = simpleSegment.isFmp4;
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
-
- if (segmentInfo.isFmp4) {
- this.trigger('fmp4');
- segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
- } else {
- var useVideoTimingInfo = this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- var firstVideoFrameTimeForData;
-
- if (useVideoTimingInfo) {
- firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
- } // Segment loader knows more about segment timing than the transmuxer (in certain
- // aspects), so make any changes required for a more accurate start time.
- // Don't set the end time yet, as the segment may not be finished processing.
-
-
- segmentInfo.timingInfo.start = this.trueSegmentStart_({
- currentStart: segmentInfo.timingInfo.start,
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex,
- currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
- useVideoTimingInfo: useVideoTimingInfo,
- firstVideoFrameTimeForData: firstVideoFrameTimeForData,
- videoTimingInfo: segmentInfo.videoTimingInfo,
- audioTimingInfo: segmentInfo.audioTimingInfo
- });
- } // Init segments for audio and video only need to be appended in certain cases. Now
- // that data is about to be appended, we can check the final cases to determine
- // whether we should append an init segment.
-
-
- this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
- // as we use the start of the segment to offset the best guess (playlist provided)
- // timestamp offset.
-
- this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
- // be appended or not.
-
- if (segmentInfo.isSyncRequest) {
- // first save/update our timing info for this segment.
- // this is what allows us to choose an accurate segment
- // and the main reason we make a sync request.
- this.updateTimingInfoEnd_(segmentInfo);
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo: segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
- var next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
- // after taking into account its timing info, do not append it.
-
- if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
- this.logger_('sync segment was incorrect, not appending');
- return;
- } // otherwise append it like any other segment as our guess was correct.
-
-
- this.logger_('sync segment was correct, appending');
- } // Save some state so that in the future anything waiting on first append (and/or
- // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
- // we need some notion of whether the timestamp offset or other relevant information
- // has had a chance to be set.
-
-
- segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
-
- this.processMetadataQueue_();
- this.appendData_(segmentInfo, result);
- };
-
- _proto.updateAppendInitSegmentStatus = function updateAppendInitSegmentStatus(segmentInfo, type) {
- // alt audio doesn't manage timestamp offset
- if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' && // in the case that we're handling partial data, we don't want to append an init
- // segment for each chunk
- !segmentInfo.changedTimestampOffset) {
- // if the timestamp offset changed, the timeline may have changed, so we have to re-
- // append init segments
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- }
-
- if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
- // make sure we append init segment on playlist changes, in case the media config
- // changed
- this.appendInitSegment_[type] = true;
- }
- };
-
- _proto.getInitSegmentAndUpdateState_ = function getInitSegmentAndUpdateState_(_ref4) {
- var type = _ref4.type,
- initSegment = _ref4.initSegment,
- map = _ref4.map,
- playlist = _ref4.playlist;
-
- // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
- // (Section 3) required to parse the applicable Media Segments. It applies to every
- // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
- // or until the end of the playlist."
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
- if (map) {
- var id = initSegmentId(map);
-
- if (this.activeInitSegmentId_ === id) {
- // don't need to re-append the init segment if the ID matches
- return null;
- } // a map-specified init segment takes priority over any transmuxed (or otherwise
- // obtained) init segment
- //
- // this also caches the init segment for later use
-
-
- initSegment = this.initSegmentForMap(map, true).bytes;
- this.activeInitSegmentId_ = id;
- } // We used to always prepend init segments for video, however, that shouldn't be
- // necessary. Instead, we should only append on changes, similar to what we've always
- // done for audio. This is more important (though may not be that important) for
- // frame-by-frame appending for LHLS, simply because of the increased quantity of
- // appends.
-
-
- if (initSegment && this.appendInitSegment_[type]) {
- // Make sure we track the playlist that we last used for the init segment, so that
- // we can re-append the init segment in the event that we get data from a new
- // playlist. Discontinuities and track changes are handled in other sections.
- this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
-
- this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
- // we are appending the muxer init segment
-
- this.activeInitSegmentId_ = null;
- return initSegment;
- }
-
- return null;
- };
-
- _proto.handleQuotaExceededError_ = function handleQuotaExceededError_(_ref5, error) {
- var _this3 = this;
-
- var segmentInfo = _ref5.segmentInfo,
- type = _ref5.type,
- bytes = _ref5.bytes;
- var audioBuffered = this.sourceUpdater_.audioBuffered();
- var videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
- // should be cleared out during the buffer removals. However, log in case it helps
- // debug.
-
- if (audioBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
- }
-
- if (videoBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
- }
-
- var audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
- var audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
- var videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
- var videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
-
- if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
- // Can't remove enough buffer to make room for new segment (or the browser doesn't
- // allow for appends of segments this size). In the future, it may be possible to
- // split up the segment and append in pieces, but for now, error out this playlist
- // in an attempt to switch to a more manageable rendition.
- this.logger_('On QUOTA_EXCEEDED_ERR, single segment too large to append to ' + 'buffer, triggering an error. ' + ("Appended byte length: " + bytes.byteLength + ", ") + ("audio buffer: " + timeRangesToArray(audioBuffered).join(', ') + ", ") + ("video buffer: " + timeRangesToArray(videoBuffered).join(', ') + ", "));
- this.error({
- message: 'Quota exceeded error with append of a single segment of content',
- excludeUntil: Infinity
- });
- this.trigger('error');
- return;
- } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
- // that the segment-loader should block on future events until this one is handled, so
- // that it doesn't keep moving onto further segments. Adding the call to the call
- // queue will prevent further appends until waitingOnRemove_ and
- // quotaExceededErrorRetryTimeout_ are cleared.
- //
- // Note that this will only block the current loader. In the case of demuxed content,
- // the other load may keep filling as fast as possible. In practice, this should be
- // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
- // source buffer, or video fills without enough room for audio to append (and without
- // the availability of clearing out seconds of back buffer to make room for audio).
- // But it might still be good to handle this case in the future as a TODO.
-
-
- this.waitingOnRemove_ = true;
- this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }));
- var currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
- // before retrying.
-
- var timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
- this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to " + timeToRemoveUntil);
- this.remove(0, timeToRemoveUntil, function () {
- _this3.logger_("On QUOTA_EXCEEDED_ERR, retrying append in " + MIN_BACK_BUFFER + "s");
-
- _this3.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
- // attempts (since we can't clear less than the minimum)
-
- _this3.quotaExceededErrorRetryTimeout_ = window.setTimeout(function () {
- _this3.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
-
- _this3.quotaExceededErrorRetryTimeout_ = null;
-
- _this3.processCallQueue_();
- }, MIN_BACK_BUFFER * 1000);
- }, true);
- };
-
- _proto.handleAppendError_ = function handleAppendError_(_ref6, error) {
- var segmentInfo = _ref6.segmentInfo,
- type = _ref6.type,
- bytes = _ref6.bytes;
-
- // if there's no error, nothing to do
- if (!error) {
- return;
- }
-
- if (error.code === QUOTA_EXCEEDED_ERR) {
- this.handleQuotaExceededError_({
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }); // A quota exceeded error should be recoverable with a future re-append, so no need
- // to trigger an append error.
-
- return;
- }
-
- this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
- this.error(type + " append of " + bytes.length + "b failed for segment " + ("#" + segmentInfo.mediaIndex + " in playlist " + segmentInfo.playlist.id)); // If an append errors, we often can't recover.
- // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
- //
- // Trigger a special error so that it can be handled separately from normal,
- // recoverable errors.
-
- this.trigger('appenderror');
- };
-
- _proto.appendToSourceBuffer_ = function appendToSourceBuffer_(_ref7) {
- var segmentInfo = _ref7.segmentInfo,
- type = _ref7.type,
- initSegment = _ref7.initSegment,
- data = _ref7.data,
- bytes = _ref7.bytes;
-
- // If this is a re-append, bytes were already created and don't need to be recreated
- if (!bytes) {
- var segments = [data];
- var byteLength = data.byteLength;
-
- if (initSegment) {
- // if the media initialization segment is changing, append it before the content
- // segment
- segments.unshift(initSegment);
- byteLength += initSegment.byteLength;
- } // Technically we should be OK appending the init segment separately, however, we
- // haven't yet tested that, and prepending is how we have always done things.
-
-
- bytes = concatSegments({
- bytes: byteLength,
- segments: segments
- });
- }
-
- this.sourceUpdater_.appendBuffer({
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }, this.handleAppendError_.bind(this, {
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }));
- };
-
- _proto.handleSegmentTimingInfo_ = function handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
- if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
- return;
- }
-
- var segment = this.pendingSegment_.segment;
- var timingInfoProperty = type + "TimingInfo";
-
- if (!segment[timingInfoProperty]) {
- segment[timingInfoProperty] = {};
- }
-
- segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
- segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
- segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
- segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
- segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
-
- segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
- };
-
- _proto.appendData_ = function appendData_(segmentInfo, result) {
- var type = result.type,
- data = result.data;
-
- if (!data || !data.byteLength) {
- return;
- }
-
- if (type === 'audio' && this.audioDisabled_) {
- return;
- }
-
- var initSegment = this.getInitSegmentAndUpdateState_({
- type: type,
- initSegment: result.initSegment,
- playlist: segmentInfo.playlist,
- map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
- });
- this.appendToSourceBuffer_({
- segmentInfo: segmentInfo,
- type: type,
- initSegment: initSegment,
- data: data
- });
- }
- /**
- * load a specific segment from a request into the buffer
- *
- * @private
- */
- ;
-
- _proto.loadSegment_ = function loadSegment_(segmentInfo) {
- var _this4 = this;
-
- this.state = 'WAITING';
- this.pendingSegment_ = segmentInfo;
- this.trimBackBuffer_(segmentInfo);
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
-
- if (!this.hasEnoughInfoToLoad_()) {
- this.loadQueue_.push(function () {
- // regenerate the audioAppendStart, timestampOffset, etc as they
- // may have changed since this function was added to the queue.
- var options = _extends({}, segmentInfo, {
- forceTimestampOffset: true
- });
-
- _extends(segmentInfo, _this4.generateSegmentInfo_(options));
-
- _this4.isPendingTimestampOffset_ = false;
-
- _this4.updateTransmuxerAndRequestSegment_(segmentInfo);
- });
- return;
- }
-
- this.updateTransmuxerAndRequestSegment_(segmentInfo);
- };
-
- _proto.updateTransmuxerAndRequestSegment_ = function updateTransmuxerAndRequestSegment_(segmentInfo) {
- var _this5 = this;
-
- // We'll update the source buffer's timestamp offset once we have transmuxed data, but
- // the transmuxer still needs to be updated before then.
- //
- // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
- // offset must be passed to the transmuxer for stream correcting adjustments.
- if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
- this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
-
- segmentInfo.gopsToAlignWith = [];
- this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
-
- this.transmuxer_.postMessage({
- action: 'reset'
- });
- this.transmuxer_.postMessage({
- action: 'setTimestampOffset',
- timestampOffset: segmentInfo.timestampOffset
- });
- }
-
- var simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
- var isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
- var isWalkingForward = this.mediaIndex !== null;
- var isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
- // the first timeline
- segmentInfo.timeline > 0;
- var isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
- this.logger_("Requesting " + segmentInfoString(segmentInfo)); // If there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),
- // then this init segment has never been seen before and should be appended.
- //
- // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
- // both to true and leave the decision of whether to append the init segment to append time.
-
- if (simpleSegment.map && !simpleSegment.map.bytes) {
- this.logger_('going to request init segment.');
- this.appendInitSegment_ = {
- video: true,
- audio: true
- };
- }
-
- segmentInfo.abortRequests = mediaSegmentRequest({
- xhr: this.vhs_.xhr,
- xhrOptions: this.xhrOptions_,
- decryptionWorker: this.decrypter_,
- segment: simpleSegment,
- abortFn: this.handleAbort_.bind(this, segmentInfo),
- progressFn: this.handleProgress_.bind(this),
- trackInfoFn: this.handleTrackInfo_.bind(this),
- timingInfoFn: this.handleTimingInfo_.bind(this),
- videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
- audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
- captionsFn: this.handleCaptions_.bind(this),
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: function endedTimelineFn() {
- _this5.logger_('received endedtimeline callback');
- },
- id3Fn: this.handleId3_.bind(this),
- dataFn: this.handleData_.bind(this),
- doneFn: this.segmentRequestFinished_.bind(this)
- });
- }
- /**
- * trim the back buffer so that we don't have too much data
- * in the source buffer
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- */
- ;
-
- _proto.trimBackBuffer_ = function trimBackBuffer_(segmentInfo) {
- var removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
- // buffer and a very conservative "garbage collector"
- // We manually clear out the old buffer to ensure
- // we don't trigger the QuotaExceeded error
- // on the source buffer during subsequent appends
-
- if (removeToTime > 0) {
- this.remove(0, removeToTime);
- }
- }
- /**
- * created a simplified copy of the segment object with just the
- * information necessary to perform the XHR and decryption
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- * @return {Object} a simplified segment object copy
- */
- ;
-
- _proto.createSimplifiedSegmentObj_ = function createSimplifiedSegmentObj_(segmentInfo) {
- var segment = segmentInfo.segment;
- var part = segmentInfo.part;
- var simpleSegment = {
- resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
- byterange: part ? part.byterange : segment.byterange,
- requestId: segmentInfo.requestId,
- transmuxer: segmentInfo.transmuxer,
- audioAppendStart: segmentInfo.audioAppendStart,
- gopsToAlignWith: segmentInfo.gopsToAlignWith,
- part: segmentInfo.part
- };
- var previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
-
- if (previousSegment && previousSegment.timeline === segment.timeline) {
- // The baseStartTime of a segment is used to handle rollover when probing the TS
- // segment to retrieve timing information. Since the probe only looks at the media's
- // times (e.g., PTS and DTS values of the segment), and doesn't consider the
- // player's time (e.g., player.currentTime()), baseStartTime should reflect the
- // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
- // seconds of media time, so should be used here. The previous segment is used since
- // the end of the previous segment should represent the beginning of the current
- // segment, so long as they are on the same timeline.
- if (previousSegment.videoTimingInfo) {
- simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
- } else if (previousSegment.audioTimingInfo) {
- simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
- }
- }
-
- if (segment.key) {
- // if the media sequence is greater than 2^32, the IV will be incorrect
- // assuming 10s segments, that would be about 1300 years
- var iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
- simpleSegment.key = this.segmentKey(segment.key);
- simpleSegment.key.iv = iv;
- }
-
- if (segment.map) {
- simpleSegment.map = this.initSegmentForMap(segment.map);
- }
-
- return simpleSegment;
- };
-
- _proto.saveTransferStats_ = function saveTransferStats_(stats) {
- // every request counts as a media request even if it has been aborted
- // or canceled due to a timeout
- this.mediaRequests += 1;
-
- if (stats) {
- this.mediaBytesTransferred += stats.bytesReceived;
- this.mediaTransferDuration += stats.roundTripTime;
- }
- };
-
- _proto.saveBandwidthRelatedStats_ = function saveBandwidthRelatedStats_(duration, stats) {
- // byteLength will be used for throughput, and should be based on bytes receieved,
- // which we only know at the end of the request and should reflect total bytes
- // downloaded rather than just bytes processed from components of the segment
- this.pendingSegment_.byteLength = stats.bytesReceived;
-
- if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_("Ignoring segment's bandwidth because its duration of " + duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
- return;
- }
-
- this.bandwidth = stats.bandwidth;
- this.roundTrip = stats.roundTripTime;
- };
-
- _proto.handleTimeout_ = function handleTimeout_() {
- // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functinality between segment loaders
- this.mediaRequestsTimedout += 1;
- this.bandwidth = 1;
- this.roundTrip = NaN;
- this.trigger('bandwidthupdate');
- }
- /**
- * Handle the callback from the segmentRequest function and set the
- * associated SegmentLoader state and errors if necessary
- *
- * @private
- */
- ;
-
- _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
- // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
- // check the call queue directly since this function doesn't need to deal with any
- // data, and can continue even if the source buffers are not set up and we didn't get
- // any data from the segment
- if (this.callQueue_.length) {
- this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
-
- if (!this.pendingSegment_) {
- return;
- } // the request was aborted and the SegmentLoader has already started
- // another request. this can happen when the timeout for an aborted
- // request triggers due to a limitation in the XHR library
- // do not count this as any sort of request or we risk double-counting
-
-
- if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
- return;
- } // an error occurred from the active pendingSegment_ so reset everything
-
-
- if (error) {
- this.pendingSegment_ = null;
- this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
-
- if (error.code === REQUEST_ERRORS.ABORTED) {
- return;
- }
-
- this.pause(); // the error is really just that at least one of the requests timed-out
- // set the bandwidth to a very low value and trigger an ABR switch to
- // take emergency action
-
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- return;
- } // if control-flow has arrived here, then the error is real
- // emit an error event to blacklist the current playlist
-
-
- this.mediaRequestsErrored += 1;
- this.error(error);
- this.trigger('error');
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
- // generated for ABR purposes
-
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
- segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
-
- if (result.gopInfo) {
- this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
- } // Although we may have already started appending on progress, we shouldn't switch the
- // state away from loading until we are officially done loading the segment data.
-
-
- this.state = 'APPENDING'; // used for testing
-
- this.trigger('appending');
- this.waitForAppendsToComplete_(segmentInfo);
- };
-
- _proto.setTimeMapping_ = function setTimeMapping_(timeline) {
- var timelineMapping = this.syncController_.mappingForTimeline(timeline);
-
- if (timelineMapping !== null) {
- this.timeMapping_ = timelineMapping;
- }
- };
-
- _proto.updateMediaSecondsLoaded_ = function updateMediaSecondsLoaded_(segment) {
- if (typeof segment.start === 'number' && typeof segment.end === 'number') {
- this.mediaSecondsLoaded += segment.end - segment.start;
- } else {
- this.mediaSecondsLoaded += segment.duration;
- }
- };
-
- _proto.shouldUpdateTransmuxerTimestampOffset_ = function shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
- if (timestampOffset === null) {
- return false;
- } // note that we're potentially using the same timestamp offset for both video and
- // audio
-
-
- if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- return true;
- }
-
- if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- return true;
- }
-
- return false;
- };
-
- _proto.trueSegmentStart_ = function trueSegmentStart_(_ref8) {
- var currentStart = _ref8.currentStart,
- playlist = _ref8.playlist,
- mediaIndex = _ref8.mediaIndex,
- firstVideoFrameTimeForData = _ref8.firstVideoFrameTimeForData,
- currentVideoTimestampOffset = _ref8.currentVideoTimestampOffset,
- useVideoTimingInfo = _ref8.useVideoTimingInfo,
- videoTimingInfo = _ref8.videoTimingInfo,
- audioTimingInfo = _ref8.audioTimingInfo;
-
- if (typeof currentStart !== 'undefined') {
- // if start was set once, keep using it
- return currentStart;
- }
-
- if (!useVideoTimingInfo) {
- return audioTimingInfo.start;
- }
-
- var previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
- // within that segment. Since the transmuxer maintains a cache of incomplete data
- // from and/or the last frame seen, the start time may reflect a frame that starts
- // in the previous segment. Check for that case and ensure the start time is
- // accurate for the segment.
-
- if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
- return firstVideoFrameTimeForData;
- }
-
- return videoTimingInfo.start;
- };
-
- _proto.waitForAppendsToComplete_ = function waitForAppendsToComplete_(segmentInfo) {
- if (!this.currentMediaInfo_) {
- this.error({
- message: 'No starting media returned, likely due to an unsupported media format.',
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return;
- } // Although transmuxing is done, appends may not yet be finished. Throw a marker
- // on each queue this loader is responsible for to ensure that the appends are
- // complete.
-
-
- var _this$currentMediaInf2 = this.currentMediaInfo_,
- hasAudio = _this$currentMediaInf2.hasAudio,
- hasVideo = _this$currentMediaInf2.hasVideo,
- isMuxed = _this$currentMediaInf2.isMuxed;
- var waitForVideo = this.loaderType_ === 'main' && hasVideo;
- var waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
- segmentInfo.waitingOnAppends = 0; // segments with no data
-
- if (!segmentInfo.hasAppendedData_) {
- if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
- // When there's no audio or video data in the segment, there's no audio or video
- // timing information.
- //
- // If there's no audio or video timing information, then the timestamp offset
- // can't be adjusted to the appropriate value for the transmuxer and source
- // buffers.
- //
- // Therefore, the next segment should be used to set the timestamp offset.
- this.isPendingTimestampOffset_ = true;
- } // override settings for metadata only segments
-
-
- segmentInfo.timingInfo = {
- start: 0
- };
- segmentInfo.waitingOnAppends++;
-
- if (!this.isPendingTimestampOffset_) {
- // update the timestampoffset
- this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
- // no video/audio data.
-
- this.processMetadataQueue_();
- } // append is "done" instantly with no data.
-
-
- this.checkAppendsDone_(segmentInfo);
- return;
- } // Since source updater could call back synchronously, do the increments first.
-
-
- if (waitForVideo) {
- segmentInfo.waitingOnAppends++;
- }
-
- if (waitForAudio) {
- segmentInfo.waitingOnAppends++;
- }
-
- if (waitForVideo) {
- this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
-
- if (waitForAudio) {
- this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
- };
-
- _proto.checkAppendsDone_ = function checkAppendsDone_(segmentInfo) {
- if (this.checkForAbort_(segmentInfo.requestId)) {
- return;
- }
-
- segmentInfo.waitingOnAppends--;
-
- if (segmentInfo.waitingOnAppends === 0) {
- this.handleAppendsDone_();
- }
- };
-
- _proto.checkForIllegalMediaSwitch = function checkForIllegalMediaSwitch(trackInfo) {
- var illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.currentMediaInfo_, trackInfo);
-
- if (illegalMediaSwitchError) {
- this.error({
- message: illegalMediaSwitchError,
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return true;
- }
-
- return false;
- };
-
- _proto.updateSourceBufferTimestampOffset_ = function updateSourceBufferTimestampOffset_(segmentInfo) {
- if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
- // priority, timing-wise, so we must wait
- typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
- segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
- this.loaderType_ !== 'main') {
- return;
- }
-
- var didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
- // the timing info here comes from video. In the event that the audio is longer than
- // the video, this will trim the start of the audio.
- // This also trims any offset from 0 at the beginning of the media
-
- segmentInfo.timestampOffset -= segmentInfo.timingInfo.start; // In the event that there are part segment downloads, each will try to update the
- // timestamp offset. Retaining this bit of state prevents us from updating in the
- // future (within the same segment), however, there may be a better way to handle it.
-
- segmentInfo.changedTimestampOffset = true;
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (didChange) {
- this.trigger('timestampoffset');
- }
- };
-
- _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_(segmentInfo) {
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
- var useVideoTimingInfo = this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- var prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
-
- if (!prioritizedTimingInfo) {
- return;
- }
-
- segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
- // current example is the case of fmp4), so use the rough duration to calculate an
- // end time.
- prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
- }
- /**
- * callback to run when appendBuffer is finished. detects if we are
- * in a good state to do things with the data we got, or if we need
- * to wait for more
- *
- * @private
- */
- ;
-
- _proto.handleAppendsDone_ = function handleAppendsDone_() {
- // appendsdone can cause an abort
- if (this.pendingSegment_) {
- this.trigger('appendsdone');
- }
-
- if (!this.pendingSegment_) {
- this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
- // all appending cases?
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
-
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
- // best to wait until all appends are done so we're sure that the primary media is
- // finished (and we have its end time).
-
- this.updateTimingInfoEnd_(segmentInfo);
-
- if (this.shouldSaveSegmentTimingInfo_) {
- // Timeline mappings should only be saved for the main loader. This is for multiple
- // reasons:
- //
- // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
- // and the main loader try to save the timeline mapping, whichever comes later
- // will overwrite the first. In theory this is OK, as the mappings should be the
- // same, however, it breaks for (2)
- // 2) In the event of a live stream, the initial live point will make for a somewhat
- // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
- // the mapping will be off for one of the streams, dependent on which one was
- // first saved (see (1)).
- // 3) Primary timing goes by video in VHS, so the mapping should be video.
- //
- // Since the audio loader will wait for the main loader to load the first segment,
- // the main loader will save the first timeline mapping, and ensure that there won't
- // be a case where audio loads two segments without saving a mapping (thus leading
- // to missing segment timing info).
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo: segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
- }
-
- var segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
-
- if (segmentDurationMessage) {
- if (segmentDurationMessage.severity === 'warn') {
- videojs.log.warn(segmentDurationMessage.message);
- } else {
- this.logger_(segmentDurationMessage.message);
- }
- }
-
- this.recordThroughput_(segmentInfo);
- this.pendingSegment_ = null;
- this.state = 'READY';
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate'); // if the sync request was not appended
- // then it was not the correct segment.
- // throw it away and use the data it gave us
- // to get the correct one.
-
- if (!segmentInfo.hasAppendedData_) {
- this.logger_("Throwing away un-appended sync request " + segmentInfoString(segmentInfo));
- return;
- }
- }
-
- this.logger_("Appended " + segmentInfoString(segmentInfo));
- this.addSegmentMetadataCue_(segmentInfo);
- this.fetchAtBuffer_ = true;
-
- if (this.currentTimeline_ !== segmentInfo.timeline) {
- this.timelineChangeController_.lastTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- }); // If audio is not disabled, the main segment loader is responsible for updating
- // the audio timeline as well. If the content is video only, this won't have any
- // impact.
-
- if (this.loaderType_ === 'main' && !this.audioDisabled_) {
- this.timelineChangeController_.lastTimelineChange({
- type: 'audio',
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
- }
-
- this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
- // the following conditional otherwise it may consider this a bad "guess"
- // and attempt to resync when the post-update seekable window and live
- // point would mean that this was the perfect segment to fetch
-
- this.trigger('syncinfoupdate');
- var segment = segmentInfo.segment; // If we previously appended a segment that ends more than 3 targetDurations before
- // the currentTime_ that means that our conservative guess was too conservative.
- // In that case, reset the loader state so that we try to use any information gained
- // from the previous request to create a new, more accurate, sync-point.
-
- if (segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3) {
- this.resetEverything();
- return;
- }
-
- var isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
- // and conservatively guess
-
- if (isWalkingForward) {
- this.trigger('bandwidthupdate');
- }
-
- this.trigger('progress');
- this.mediaIndex = segmentInfo.mediaIndex;
- this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
- // buffer, end the stream. this ensures the "ended" event will
- // fire if playback reaches that point.
-
- if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
- this.endOfStream();
- } // used for testing
-
-
- this.trigger('appended');
-
- if (segmentInfo.hasAppendedData_) {
- this.mediaAppends++;
- }
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
- /**
- * Records the current throughput of the decrypt, transmux, and append
- * portion of the semgment pipeline. `throughput.rate` is a the cumulative
- * moving average of the throughput. `throughput.count` is the number of
- * data points in the average.
- *
- * @private
- * @param {Object} segmentInfo the object returned by loadSegment
- */
- ;
-
- _proto.recordThroughput_ = function recordThroughput_(segmentInfo) {
- if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_("Ignoring segment's throughput because its duration of " + segmentInfo.duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
- return;
- }
-
- var rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
- // by zero in the case where the throughput is ridiculously high
-
- var segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
-
- var segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
- // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
-
- this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
- }
- /**
- * Adds a cue to the segment-metadata track with some metadata information about the
- * segment
- *
- * @private
- * @param {Object} segmentInfo
- * the object returned by loadSegment
- * @method addSegmentMetadataCue_
- */
- ;
-
- _proto.addSegmentMetadataCue_ = function addSegmentMetadataCue_(segmentInfo) {
- if (!this.segmentMetadataTrack_) {
- return;
- }
-
- var segment = segmentInfo.segment;
- var start = segment.start;
- var end = segment.end; // Do not try adding the cue if the start and end times are invalid.
-
- if (!finite(start) || !finite(end)) {
- return;
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
- var Cue = window.WebKitDataCue || window.VTTCue;
- var value = {
- custom: segment.custom,
- dateTimeObject: segment.dateTimeObject,
- dateTimeString: segment.dateTimeString,
- bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
- resolution: segmentInfo.playlist.attributes.RESOLUTION,
- codecs: segmentInfo.playlist.attributes.CODECS,
- byteLength: segmentInfo.byteLength,
- uri: segmentInfo.uri,
- timeline: segmentInfo.timeline,
- playlist: segmentInfo.playlist.id,
- start: start,
- end: end
- };
- var data = JSON.stringify(value);
- var cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
- // the differences of WebKitDataCue in safari and VTTCue in other browsers
-
- cue.value = value;
- this.segmentMetadataTrack_.addCue(cue);
- };
-
- return SegmentLoader;
-}(videojs.EventTarget);
-
-function noop() {}
-
-var toTitleCase = function toTitleCase(string) {
- if (typeof string !== 'string') {
- return string;
- }
-
- return string.replace(/./, function (w) {
- return w.toUpperCase();
- });
-};
-
-var bufferTypes = ['video', 'audio'];
-
-var _updating = function updating(type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
-};
-
-var nextQueueIndexOfType = function nextQueueIndexOfType(type, queue) {
- for (var i = 0; i < queue.length; i++) {
- var queueEntry = queue[i];
-
- if (queueEntry.type === 'mediaSource') {
- // If the next entry is a media source entry (uses multiple source buffers), block
- // processing to allow it to go through first.
- return null;
- }
-
- if (queueEntry.type === type) {
- return i;
- }
- }
-
- return null;
-};
-
-var shiftQueue = function shiftQueue(type, sourceUpdater) {
- if (sourceUpdater.queue.length === 0) {
- return;
- }
-
- var queueIndex = 0;
- var queueEntry = sourceUpdater.queue[queueIndex];
-
- if (queueEntry.type === 'mediaSource') {
- if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
- sourceUpdater.queue.shift();
- queueEntry.action(sourceUpdater);
-
- if (queueEntry.doneFn) {
- queueEntry.doneFn();
- } // Only specific source buffer actions must wait for async updateend events. Media
- // Source actions process synchronously. Therefore, both audio and video source
- // buffers are now clear to process the next queue entries.
-
-
- shiftQueue('audio', sourceUpdater);
- shiftQueue('video', sourceUpdater);
- } // Media Source actions require both source buffers, so if the media source action
- // couldn't process yet (because one or both source buffers are busy), block other
- // queue actions until both are available and the media source action can process.
-
-
- return;
- }
-
- if (type === 'mediaSource') {
- // If the queue was shifted by a media source action (this happens when pushing a
- // media source action onto the queue), then it wasn't from an updateend event from an
- // audio or video source buffer, so there's no change from previous state, and no
- // processing should be done.
- return;
- } // Media source queue entries don't need to consider whether the source updater is
- // started (i.e., source buffers are created) as they don't need the source buffers, but
- // source buffer queue entries do.
-
-
- if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || _updating(type, sourceUpdater)) {
- return;
- }
-
- if (queueEntry.type !== type) {
- queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
-
- if (queueIndex === null) {
- // Either there's no queue entry that uses this source buffer type in the queue, or
- // there's a media source queue entry before the next entry of this type, in which
- // case wait for that action to process first.
- return;
- }
-
- queueEntry = sourceUpdater.queue[queueIndex];
- }
-
- sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
- //
- // The queue pending operation must be set before the action is performed in the event
- // that the action results in a synchronous event that is acted upon. For instance, if
- // an exception is thrown that can be handled, it's possible that new actions will be
- // appended to an empty queue and immediately executed, but would not have the correct
- // pending information if this property was set after the action was performed.
-
- sourceUpdater.queuePending[type] = queueEntry;
- queueEntry.action(type, sourceUpdater);
-
- if (!queueEntry.doneFn) {
- // synchronous operation, process next entry
- sourceUpdater.queuePending[type] = null;
- shiftQueue(type, sourceUpdater);
- return;
- }
-};
-
-var cleanupBuffer = function cleanupBuffer(type, sourceUpdater) {
- var buffer = sourceUpdater[type + "Buffer"];
- var titleType = toTitleCase(type);
-
- if (!buffer) {
- return;
- }
-
- buffer.removeEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
- buffer.removeEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
- sourceUpdater.codecs[type] = null;
- sourceUpdater[type + "Buffer"] = null;
-};
-
-var inSourceBuffers = function inSourceBuffers(mediaSource, sourceBuffer) {
- return mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
-};
-
-var actions = {
- appendBuffer: function appendBuffer(bytes, segmentInfo, onError) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Appending segment " + segmentInfo.mediaIndex + "'s " + bytes.length + " bytes to " + type + "Buffer");
-
- try {
- sourceBuffer.appendBuffer(bytes);
- } catch (e) {
- sourceUpdater.logger_("Error with code " + e.code + " " + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + ("when appending segment " + segmentInfo.mediaIndex + " to " + type + "Buffer"));
- sourceUpdater.queuePending[type] = null;
- onError(e);
- }
- };
- },
- remove: function remove(start, end) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Removing " + start + " to " + end + " from " + type + "Buffer");
-
- try {
- sourceBuffer.remove(start, end);
- } catch (e) {
- sourceUpdater.logger_("Remove " + start + " to " + end + " from " + type + "Buffer failed");
- }
- };
- },
- timestampOffset: function timestampOffset(offset) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Setting " + type + "timestampOffset to " + offset);
- sourceBuffer.timestampOffset = offset;
- };
- },
- callback: function callback(_callback) {
- return function (type, sourceUpdater) {
- _callback();
- };
- },
- endOfStream: function endOfStream(error) {
- return function (sourceUpdater) {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
-
- sourceUpdater.logger_("Calling mediaSource endOfStream(" + (error || '') + ")");
-
- try {
- sourceUpdater.mediaSource.endOfStream(error);
- } catch (e) {
- videojs.log.warn('Failed to call media source endOfStream', e);
- }
- };
- },
- duration: function duration(_duration) {
- return function (sourceUpdater) {
- sourceUpdater.logger_("Setting mediaSource duration to " + _duration);
-
- try {
- sourceUpdater.mediaSource.duration = _duration;
- } catch (e) {
- videojs.log.warn('Failed to set media source duration', e);
- }
- };
- },
- abort: function abort() {
- return function (type, sourceUpdater) {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
-
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("calling abort on " + type + "Buffer");
-
- try {
- sourceBuffer.abort();
- } catch (e) {
- videojs.log.warn("Failed to abort on " + type + "Buffer", e);
- }
- };
- },
- addSourceBuffer: function addSourceBuffer(type, codec) {
- return function (sourceUpdater) {
- var titleType = toTitleCase(type);
- var mime = getMimeForCodec(codec);
- sourceUpdater.logger_("Adding " + type + "Buffer with codec " + codec + " to mediaSource");
- var sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
- sourceBuffer.addEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
- sourceBuffer.addEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
- sourceUpdater.codecs[type] = codec;
- sourceUpdater[type + "Buffer"] = sourceBuffer;
- };
- },
- removeSourceBuffer: function removeSourceBuffer(type) {
- return function (sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Removing " + type + "Buffer with codec " + sourceUpdater.codecs[type] + " from mediaSource");
-
- try {
- sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
- } catch (e) {
- videojs.log.warn("Failed to removeSourceBuffer " + type + "Buffer", e);
- }
- };
- },
- changeType: function changeType(codec) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- var mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- } // do not update codec if we don't need to.
-
-
- if (sourceUpdater.codecs[type] === codec) {
- return;
- }
-
- sourceUpdater.logger_("changing " + type + "Buffer codec from " + sourceUpdater.codecs[type] + " to " + codec);
- sourceBuffer.changeType(mime);
- sourceUpdater.codecs[type] = codec;
- };
- }
-};
-
-var pushQueue = function pushQueue(_ref) {
- var type = _ref.type,
- sourceUpdater = _ref.sourceUpdater,
- action = _ref.action,
- doneFn = _ref.doneFn,
- name = _ref.name;
- sourceUpdater.queue.push({
- type: type,
- action: action,
- doneFn: doneFn,
- name: name
- });
- shiftQueue(type, sourceUpdater);
-};
-
-var onUpdateend = function onUpdateend(type, sourceUpdater) {
- return function (e) {
- // Although there should, in theory, be a pending action for any updateend receieved,
- // there are some actions that may trigger updateend events without set definitions in
- // the w3c spec. For instance, setting the duration on the media source may trigger
- // updateend events on source buffers. This does not appear to be in the spec. As such,
- // if we encounter an updateend without a corresponding pending action from our queue
- // for that source buffer type, process the next action.
- if (sourceUpdater.queuePending[type]) {
- var doneFn = sourceUpdater.queuePending[type].doneFn;
- sourceUpdater.queuePending[type] = null;
-
- if (doneFn) {
- // if there's an error, report it
- doneFn(sourceUpdater[type + "Error_"]);
- }
- }
-
- shiftQueue(type, sourceUpdater);
- };
-};
-/**
- * A queue of callbacks to be serialized and applied when a
- * MediaSource and its associated SourceBuffers are not in the
- * updating state. It is used by the segment loader to update the
- * underlying SourceBuffers when new data is loaded, for instance.
- *
- * @class SourceUpdater
- * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
- * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
- */
-
-
-var SourceUpdater = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose(SourceUpdater, _videojs$EventTarget);
-
- function SourceUpdater(mediaSource) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- _this.mediaSource = mediaSource;
-
- _this.sourceopenListener_ = function () {
- return shiftQueue('mediaSource', _assertThisInitialized(_this));
- };
-
- _this.mediaSource.addEventListener('sourceopen', _this.sourceopenListener_);
-
- _this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
-
- _this.audioTimestampOffset_ = 0;
- _this.videoTimestampOffset_ = 0;
- _this.queue = [];
- _this.queuePending = {
- audio: null,
- video: null
- };
- _this.delayedAudioAppendQueue_ = [];
- _this.videoAppendQueued_ = false;
- _this.codecs = {};
- _this.onVideoUpdateEnd_ = onUpdateend('video', _assertThisInitialized(_this));
- _this.onAudioUpdateEnd_ = onUpdateend('audio', _assertThisInitialized(_this));
-
- _this.onVideoError_ = function (e) {
- // used for debugging
- _this.videoError_ = e;
- };
-
- _this.onAudioError_ = function (e) {
- // used for debugging
- _this.audioError_ = e;
- };
-
- _this.createdSourceBuffers_ = false;
- _this.initializedEme_ = false;
- _this.triggeredReady_ = false;
- return _this;
- }
-
- var _proto = SourceUpdater.prototype;
-
- _proto.initializedEme = function initializedEme() {
- this.initializedEme_ = true;
- this.triggerReady();
- };
-
- _proto.hasCreatedSourceBuffers = function hasCreatedSourceBuffers() {
- // if false, likely waiting on one of the segment loaders to get enough data to create
- // source buffers
- return this.createdSourceBuffers_;
- };
-
- _proto.hasInitializedAnyEme = function hasInitializedAnyEme() {
- return this.initializedEme_;
- };
-
- _proto.ready = function ready() {
- return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
- };
-
- _proto.createSourceBuffers = function createSourceBuffers(codecs) {
- if (this.hasCreatedSourceBuffers()) {
- // already created them before
- return;
- } // the intial addOrChangeSourceBuffers will always be
- // two add buffers.
-
-
- this.addOrChangeSourceBuffers(codecs);
- this.createdSourceBuffers_ = true;
- this.trigger('createdsourcebuffers');
- this.triggerReady();
- };
-
- _proto.triggerReady = function triggerReady() {
- // only allow ready to be triggered once, this prevents the case
- // where:
- // 1. we trigger createdsourcebuffers
- // 2. ie 11 synchronously initializates eme
- // 3. the synchronous initialization causes us to trigger ready
- // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
- if (this.ready() && !this.triggeredReady_) {
- this.triggeredReady_ = true;
- this.trigger('ready');
- }
- }
- /**
- * Add a type of source buffer to the media source.
- *
- * @param {string} type
- * The type of source buffer to add.
- *
- * @param {string} codec
- * The codec to add the source buffer with.
- */
- ;
-
- _proto.addSourceBuffer = function addSourceBuffer(type, codec) {
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.addSourceBuffer(type, codec),
- name: 'addSourceBuffer'
- });
- }
- /**
- * call abort on a source buffer.
- *
- * @param {string} type
- * The type of source buffer to call abort on.
- */
- ;
-
- _proto.abort = function abort(type) {
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.abort(type),
- name: 'abort'
- });
- }
- /**
- * Call removeSourceBuffer and remove a specific type
- * of source buffer on the mediaSource.
- *
- * @param {string} type
- * The type of source buffer to remove.
- */
- ;
-
- _proto.removeSourceBuffer = function removeSourceBuffer(type) {
- if (!this.canRemoveSourceBuffer()) {
- videojs.log.error('removeSourceBuffer is not supported!');
- return;
- }
-
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.removeSourceBuffer(type),
- name: 'removeSourceBuffer'
- });
- }
- /**
- * Whether or not the removeSourceBuffer function is supported
- * on the mediaSource.
- *
- * @return {boolean}
- * if removeSourceBuffer can be called.
- */
- ;
-
- _proto.canRemoveSourceBuffer = function canRemoveSourceBuffer() {
- // IE reports that it supports removeSourceBuffer, but often throws
- // errors when attempting to use the function. So we report that it
- // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
- // throws errors, so we report that it does not support this as well.
- return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window.MediaSource && window.MediaSource.prototype && typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
- }
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- ;
-
- SourceUpdater.canChangeType = function canChangeType() {
- return window.SourceBuffer && window.SourceBuffer.prototype && typeof window.SourceBuffer.prototype.changeType === 'function';
- }
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- ;
-
- _proto.canChangeType = function canChangeType() {
- return this.constructor.canChangeType();
- }
- /**
- * Call the changeType function on a source buffer, given the code and type.
- *
- * @param {string} type
- * The type of source buffer to call changeType on.
- *
- * @param {string} codec
- * The codec string to change type with on the source buffer.
- */
- ;
-
- _proto.changeType = function changeType(type, codec) {
- if (!this.canChangeType()) {
- videojs.log.error('changeType is not supported!');
- return;
- }
-
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.changeType(codec),
- name: 'changeType'
- });
- }
- /**
- * Add source buffers with a codec or, if they are already created,
- * call changeType on source buffers using changeType.
- *
- * @param {Object} codecs
- * Codecs to switch to
- */
- ;
-
- _proto.addOrChangeSourceBuffers = function addOrChangeSourceBuffers(codecs) {
- var _this2 = this;
-
- if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
- throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
- }
-
- Object.keys(codecs).forEach(function (type) {
- var codec = codecs[type];
-
- if (!_this2.hasCreatedSourceBuffers()) {
- return _this2.addSourceBuffer(type, codec);
- }
-
- if (_this2.canChangeType()) {
- _this2.changeType(type, codec);
- }
- });
- }
- /**
- * Queue an update to append an ArrayBuffer.
- *
- * @param {MediaObject} object containing audioBytes and/or videoBytes
- * @param {Function} done the function to call when done
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
- */
- ;
-
- _proto.appendBuffer = function appendBuffer(options, doneFn) {
- var _this3 = this;
-
- var segmentInfo = options.segmentInfo,
- type = options.type,
- bytes = options.bytes;
- this.processedAppend_ = true;
-
- if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
- this.delayedAudioAppendQueue_.push([options, doneFn]);
- this.logger_("delayed audio append of " + bytes.length + " until video append");
- return;
- } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
- // not be fired. This means that the queue will be blocked until the next action
- // taken by the segment-loader. Provide a mechanism for segment-loader to handle
- // these errors by calling the doneFn with the specific error.
-
-
- var onError = doneFn;
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.appendBuffer(bytes, segmentInfo || {
- mediaIndex: -1
- }, onError),
- doneFn: doneFn,
- name: 'appendBuffer'
- });
-
- if (type === 'video') {
- this.videoAppendQueued_ = true;
-
- if (!this.delayedAudioAppendQueue_.length) {
- return;
- }
-
- var queue = this.delayedAudioAppendQueue_.slice();
- this.logger_("queuing delayed audio " + queue.length + " appendBuffers");
- this.delayedAudioAppendQueue_.length = 0;
- queue.forEach(function (que) {
- _this3.appendBuffer.apply(_this3, que);
- });
- }
- }
- /**
- * Get the audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The audio buffer's buffered time range
- */
- ;
-
- _proto.audioBuffered = function audioBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
- return videojs.createTimeRange();
- }
-
- return this.audioBuffer.buffered ? this.audioBuffer.buffered : videojs.createTimeRange();
- }
- /**
- * Get the video buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The video buffer's buffered time range
- */
- ;
-
- _proto.videoBuffered = function videoBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
- return videojs.createTimeRange();
- }
-
- return this.videoBuffer.buffered ? this.videoBuffer.buffered : videojs.createTimeRange();
- }
- /**
- * Get a combined video/audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * the combined time range
- */
- ;
-
- _proto.buffered = function buffered() {
- var video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
- var audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
-
- if (audio && !video) {
- return this.audioBuffered();
- }
-
- if (video && !audio) {
- return this.videoBuffered();
- }
-
- return bufferIntersection(this.audioBuffered(), this.videoBuffered());
- }
- /**
- * Add a callback to the queue that will set duration on the mediaSource.
- *
- * @param {number} duration
- * The duration to set
- *
- * @param {Function} [doneFn]
- * function to run after duration has been set.
- */
- ;
-
- _proto.setDuration = function setDuration(duration, doneFn) {
- if (doneFn === void 0) {
- doneFn = noop;
- }
-
- // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.duration(duration),
- name: 'duration',
- doneFn: doneFn
- });
- }
- /**
- * Add a mediaSource endOfStream call to the queue
- *
- * @param {Error} [error]
- * Call endOfStream with an error
- *
- * @param {Function} [doneFn]
- * A function that should be called when the
- * endOfStream call has finished.
- */
- ;
-
- _proto.endOfStream = function endOfStream(error, doneFn) {
- if (error === void 0) {
- error = null;
- }
-
- if (doneFn === void 0) {
- doneFn = noop;
- }
-
- if (typeof error !== 'string') {
- error = undefined;
- } // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
-
-
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.endOfStream(error),
- name: 'endOfStream',
- doneFn: doneFn
- });
- }
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- ;
-
- _proto.removeAudio = function removeAudio(start, end, done) {
- if (done === void 0) {
- done = noop;
- }
-
- if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- ;
-
- _proto.removeVideo = function removeVideo(start, end, done) {
- if (done === void 0) {
- done = noop;
- }
-
- if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
- /**
- * Whether the underlying sourceBuffer is updating or not
- *
- * @return {boolean} the updating status of the SourceBuffer
- */
- ;
-
- _proto.updating = function updating() {
- // the audio/video source buffer is updating
- if (_updating('audio', this) || _updating('video', this)) {
- return true;
- }
-
- return false;
- }
- /**
- * Set/get the timestampoffset on the audio SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- ;
-
- _proto.audioTimestampOffset = function audioTimestampOffset(offset) {
- if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
- this.audioTimestampOffset_ !== offset) {
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.audioTimestampOffset_ = offset;
- }
-
- return this.audioTimestampOffset_;
- }
- /**
- * Set/get the timestampoffset on the video SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- ;
-
- _proto.videoTimestampOffset = function videoTimestampOffset(offset) {
- if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
- this.videoTimestampOffset !== offset) {
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.videoTimestampOffset_ = offset;
- }
-
- return this.videoTimestampOffset_;
- }
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the audio queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- ;
-
- _proto.audioQueueCallback = function audioQueueCallback(callback) {
- if (!this.audioBuffer) {
- return;
- }
-
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the video queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- ;
-
- _proto.videoQueueCallback = function videoQueueCallback(callback) {
- if (!this.videoBuffer) {
- return;
- }
-
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
- /**
- * dispose of the source updater and the underlying sourceBuffer
- */
- ;
-
- _proto.dispose = function dispose() {
- var _this4 = this;
-
- this.trigger('dispose');
- bufferTypes.forEach(function (type) {
- _this4.abort(type);
-
- if (_this4.canRemoveSourceBuffer()) {
- _this4.removeSourceBuffer(type);
- } else {
- _this4[type + "QueueCallback"](function () {
- return cleanupBuffer(type, _this4);
- });
- }
- });
- this.videoAppendQueued_ = false;
- this.delayedAudioAppendQueue_.length = 0;
-
- if (this.sourceopenListener_) {
- this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
- }
-
- this.off();
- };
-
- return SourceUpdater;
-}(videojs.EventTarget);
-
-var uint8ToUtf8 = function uint8ToUtf8(uintArray) {
- return decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
-};
-
-var VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(function (char) {
- return char.charCodeAt(0);
-}));
-/**
- * An object that manages segment loading and appending.
- *
- * @class VTTSegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-
-var VTTSegmentLoader = /*#__PURE__*/function (_SegmentLoader) {
- _inheritsLoose(VTTSegmentLoader, _SegmentLoader);
-
- function VTTSegmentLoader(settings, options) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _SegmentLoader.call(this, settings, options) || this; // SegmentLoader requires a MediaSource be specified or it will throw an error;
- // however, VTTSegmentLoader has no need of a media source, so delete the reference
-
- _this.mediaSource_ = null;
- _this.subtitlesTrack_ = null;
- _this.loaderType_ = 'subtitle';
- _this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
- // the sync controller leads to improper behavior.
-
- _this.shouldSaveSegmentTimingInfo_ = false;
- return _this;
- }
-
- var _proto = VTTSegmentLoader.prototype;
-
- _proto.createTransmuxer_ = function createTransmuxer_() {
- // don't need to transmux any subtitles
- return null;
- }
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- ;
-
- _proto.buffered_ = function buffered_() {
- if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
- return videojs.createTimeRanges();
- }
-
- var cues = this.subtitlesTrack_.cues;
- var start = cues[0].startTime;
- var end = cues[cues.length - 1].startTime;
- return videojs.createTimeRanges([[start, end]]);
- }
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- ;
-
- _proto.initSegmentForMap = function initSegmentForMap(map, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!map) {
- return null;
- }
-
- var id = initSegmentId(map);
- var storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- // append WebVTT line terminators to the media initialization segment if it exists
- // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
- // requires two or more WebVTT line terminators between the WebVTT header and the
- // rest of the file
- var combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
- var combinedSegment = new Uint8Array(combinedByteLength);
- combinedSegment.set(map.bytes);
- combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: combinedSegment
- };
- }
-
- return storedMap || map;
- }
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- ;
-
- _proto.couldBeginLoading_ = function couldBeginLoading_() {
- return this.playlist_ && this.subtitlesTrack_ && !this.paused();
- }
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- ;
-
- _proto.init_ = function init_() {
- this.state = 'READY';
- this.resetEverything();
- return this.monitorBuffer_();
- }
- /**
- * Set a subtitle track on the segment loader to add subtitles to
- *
- * @param {TextTrack=} track
- * The text track to add loaded subtitles to
- * @return {TextTrack}
- * Returns the subtitles track
- */
- ;
-
- _proto.track = function track(_track) {
- if (typeof _track === 'undefined') {
- return this.subtitlesTrack_;
- }
-
- this.subtitlesTrack_ = _track; // if we were unpaused but waiting for a sourceUpdater, start
- // buffering now
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- this.init_();
- }
-
- return this.subtitlesTrack_;
- }
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- */
- ;
-
- _proto.remove = function remove(start, end) {
- removeCuesFromTrack(start, end, this.subtitlesTrack_);
- }
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- ;
-
- _proto.fillBuffer_ = function fillBuffer_() {
- var _this2 = this;
-
- // see if we need to begin loading immediately
- var segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
- // We don't have the timestamp offset that we need to sync subtitles.
- // Rerun on a timestamp offset or user interaction.
- var checkTimestampOffset = function checkTimestampOffset() {
- _this2.state = 'READY';
-
- if (!_this2.paused()) {
- // if not paused, queue a buffer check as soon as possible
- _this2.monitorBuffer_();
- }
- };
-
- this.syncController_.one('timestampoffset', checkTimestampOffset);
- this.state = 'WAITING_ON_TIMELINE';
- return;
- }
-
- this.loadSegment_(segmentInfo);
- } // never set a timestamp offset for vtt segments.
- ;
-
- _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_() {
- return null;
- };
-
- _proto.chooseNextRequest_ = function chooseNextRequest_() {
- return this.skipEmptySegments_(_SegmentLoader.prototype.chooseNextRequest_.call(this));
- }
- /**
- * Prevents the segment loader from requesting segments we know contain no subtitles
- * by walking forward until we find the next segment that we don't know whether it is
- * empty or not.
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @return {Object}
- * a segment info object that describes the current segment
- */
- ;
-
- _proto.skipEmptySegments_ = function skipEmptySegments_(segmentInfo) {
- while (segmentInfo && segmentInfo.segment.empty) {
- // stop at the last possible segmentInfo
- if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
- segmentInfo = null;
- break;
- }
-
- segmentInfo = this.generateSegmentInfo_({
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex + 1,
- startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
- isSyncRequest: segmentInfo.isSyncRequest
- });
- }
-
- return segmentInfo;
- };
-
- _proto.stopForError = function stopForError(error) {
- this.error(error);
- this.state = 'READY';
- this.pause();
- this.trigger('error');
- }
- /**
- * append a decrypted segement to the SourceBuffer through a SourceUpdater
- *
- * @private
- */
- ;
-
- _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
- var _this3 = this;
-
- if (!this.subtitlesTrack_) {
- this.state = 'READY';
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats); // the request was aborted
-
- if (!this.pendingSegment_) {
- this.state = 'READY';
- this.mediaRequestsAborted += 1;
- return;
- }
-
- if (error) {
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- }
-
- if (error.code === REQUEST_ERRORS.ABORTED) {
- this.mediaRequestsAborted += 1;
- } else {
- this.mediaRequestsErrored += 1;
- }
-
- this.stopForError(error);
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functionality between segment loaders
-
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
- this.state = 'APPENDING'; // used for tests
-
- this.trigger('appending');
- var segment = segmentInfo.segment;
-
- if (segment.map) {
- segment.map.bytes = simpleSegment.map.bytes;
- }
-
- segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, wait till it finished loading
-
- if (typeof window.WebVTT !== 'function' && this.subtitlesTrack_ && this.subtitlesTrack_.tech_) {
- var loadHandler;
-
- var errorHandler = function errorHandler() {
- _this3.subtitlesTrack_.tech_.off('vttjsloaded', loadHandler);
-
- _this3.stopForError({
- message: 'Error loading vtt.js'
- });
-
- return;
- };
-
- loadHandler = function loadHandler() {
- _this3.subtitlesTrack_.tech_.off('vttjserror', errorHandler);
-
- _this3.segmentRequestFinished_(error, simpleSegment, result);
- };
-
- this.state = 'WAITING_ON_VTTJS';
- this.subtitlesTrack_.tech_.one('vttjsloaded', loadHandler);
- this.subtitlesTrack_.tech_.one('vttjserror', errorHandler);
- return;
- }
-
- segment.requested = true;
-
- try {
- this.parseVTTCues_(segmentInfo);
- } catch (e) {
- this.stopForError({
- message: e.message
- });
- return;
- }
-
- this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
-
- if (segmentInfo.cues.length) {
- segmentInfo.timingInfo = {
- start: segmentInfo.cues[0].startTime,
- end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
- };
- } else {
- segmentInfo.timingInfo = {
- start: segmentInfo.startOfSegment,
- end: segmentInfo.startOfSegment + segmentInfo.duration
- };
- }
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate');
- this.pendingSegment_ = null;
- this.state = 'READY';
- return;
- }
-
- segmentInfo.byteLength = segmentInfo.bytes.byteLength;
- this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
- // the subtitle track
-
- segmentInfo.cues.forEach(function (cue) {
- _this3.subtitlesTrack_.addCue(_this3.featuresNativeTextTracks_ ? new window.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
- }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
- // cues to have identical time-intervals, but if the text is also identical
- // we can safely assume it is a duplicate that can be removed (ex. when a cue
- // "overlaps" VTT segments)
-
- removeDuplicateCuesFromTrack(this.subtitlesTrack_);
- this.handleAppendsDone_();
- };
-
- _proto.handleData_ = function handleData_() {// noop as we shouldn't be getting video/audio data captions
- // that we do not support here.
- };
-
- _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_() {// noop
- }
- /**
- * Uses the WebVTT parser to parse the segment response
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @private
- */
- ;
-
- _proto.parseVTTCues_ = function parseVTTCues_(segmentInfo) {
- var decoder;
- var decodeBytesToString = false;
-
- if (typeof window.TextDecoder === 'function') {
- decoder = new window.TextDecoder('utf8');
- } else {
- decoder = window.WebVTT.StringDecoder();
- decodeBytesToString = true;
- }
-
- var parser = new window.WebVTT.Parser(window, window.vttjs, decoder);
- segmentInfo.cues = [];
- segmentInfo.timestampmap = {
- MPEGTS: 0,
- LOCAL: 0
- };
- parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
-
- parser.ontimestampmap = function (map) {
- segmentInfo.timestampmap = map;
- };
-
- parser.onparsingerror = function (error) {
- videojs.log.warn('Error encountered when parsing cues: ' + error.message);
- };
-
- if (segmentInfo.segment.map) {
- var mapData = segmentInfo.segment.map.bytes;
-
- if (decodeBytesToString) {
- mapData = uint8ToUtf8(mapData);
- }
-
- parser.parse(mapData);
- }
-
- var segmentData = segmentInfo.bytes;
-
- if (decodeBytesToString) {
- segmentData = uint8ToUtf8(segmentData);
- }
-
- parser.parse(segmentData);
- parser.flush();
- }
- /**
- * Updates the start and end times of any cues parsed by the WebVTT parser using
- * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
- * from the SyncController
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @param {Object} mappingObj
- * object containing a mapping from TS to media time
- * @param {Object} playlist
- * the playlist object containing the segment
- * @private
- */
- ;
-
- _proto.updateTimeMapping_ = function updateTimeMapping_(segmentInfo, mappingObj, playlist) {
- var segment = segmentInfo.segment;
-
- if (!mappingObj) {
- // If the sync controller does not have a mapping of TS to Media Time for the
- // timeline, then we don't have enough information to update the cue
- // start/end times
- return;
- }
-
- if (!segmentInfo.cues.length) {
- // If there are no cues, we also do not have enough information to figure out
- // segment timing. Mark that the segment contains no cues so we don't re-request
- // an empty segment.
- segment.empty = true;
- return;
- }
-
- var timestampmap = segmentInfo.timestampmap;
- var diff = timestampmap.MPEGTS / ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
- segmentInfo.cues.forEach(function (cue) {
- // First convert cue time to TS time using the timestamp-map provided within the vtt
- cue.startTime += diff;
- cue.endTime += diff;
- });
-
- if (!playlist.syncInfo) {
- var firstStart = segmentInfo.cues[0].startTime;
- var lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
- playlist.syncInfo = {
- mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
- time: Math.min(firstStart, lastStart - segment.duration)
- };
- }
- };
-
- return VTTSegmentLoader;
-}(SegmentLoader);
-
-/**
- * @file ad-cue-tags.js
- */
-/**
- * Searches for an ad cue that overlaps with the given mediaTime
- *
- * @param {Object} track
- * the track to find the cue for
- *
- * @param {number} mediaTime
- * the time to find the cue at
- *
- * @return {Object|null}
- * the found cue or null
- */
-
-var findAdCue = function findAdCue(track, mediaTime) {
- var cues = track.cues;
-
- for (var i = 0; i < cues.length; i++) {
- var cue = cues[i];
-
- if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
- return cue;
- }
- }
-
- return null;
-};
-var updateAdCues = function updateAdCues(media, track, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- if (!media.segments) {
- return;
- }
-
- var mediaTime = offset;
- var cue;
-
- for (var i = 0; i < media.segments.length; i++) {
- var segment = media.segments[i];
-
- if (!cue) {
- // Since the cues will span for at least the segment duration, adding a fudge
- // factor of half segment duration will prevent duplicate cues from being
- // created when timing info is not exact (e.g. cue start time initialized
- // at 10.006677, but next call mediaTime is 10.003332 )
- cue = findAdCue(track, mediaTime + segment.duration / 2);
- }
-
- if (cue) {
- if ('cueIn' in segment) {
- // Found a CUE-IN so end the cue
- cue.endTime = mediaTime;
- cue.adEndTime = mediaTime;
- mediaTime += segment.duration;
- cue = null;
- continue;
- }
-
- if (mediaTime < cue.endTime) {
- // Already processed this mediaTime for this cue
- mediaTime += segment.duration;
- continue;
- } // otherwise extend cue until a CUE-IN is found
-
-
- cue.endTime += segment.duration;
- } else {
- if ('cueOut' in segment) {
- cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
- cue.adStartTime = mediaTime; // Assumes tag format to be
- // #EXT-X-CUE-OUT:30
-
- cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
- track.addCue(cue);
- }
-
- if ('cueOutCont' in segment) {
- // Entered into the middle of an ad cue
- // Assumes tag formate to be
- // #EXT-X-CUE-OUT-CONT:10/30
- var _segment$cueOutCont$s = segment.cueOutCont.split('/').map(parseFloat),
- adOffset = _segment$cueOutCont$s[0],
- adTotal = _segment$cueOutCont$s[1];
-
- cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, '');
- cue.adStartTime = mediaTime - adOffset;
- cue.adEndTime = cue.adStartTime + adTotal;
- track.addCue(cue);
- }
- }
-
- mediaTime += segment.duration;
- }
-};
-
-var syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
-// the equivalence display-time 0 === segment-index 0
-{
- name: 'VOD',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (duration !== Infinity) {
- var syncPoint = {
- time: 0,
- segmentIndex: 0,
- partIndex: null
- };
- return syncPoint;
- }
-
- return null;
- }
-}, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
-{
- name: 'ProgramDateTime',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
- return null;
- }
-
- var syncPoint = null;
- var lastDistance = null;
- var partsAndSegments = getPartsAndSegments(playlist);
- currentTime = currentTime || 0;
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
- var partAndSegment = partsAndSegments[index];
- var segment = partAndSegment.segment;
- var datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
-
- if (!datetimeMapping) {
- continue;
- }
-
- if (segment.dateTimeObject) {
- var segmentTime = segment.dateTimeObject.getTime() / 1000;
- var start = segmentTime + datetimeMapping; // take part duration into account.
-
- if (segment.parts && typeof partAndSegment.partIndex === 'number') {
- for (var z = 0; z < partAndSegment.partIndex; z++) {
- start += segment.parts[z].duration;
- }
- }
-
- var distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
- break;
- }
-
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
- }
-
- return syncPoint;
- }
-}, // Stategy "Segment": We have a known time mapping for a timeline and a
-// segment in the current timeline with timing data
-{
- name: 'Segment',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- var syncPoint = null;
- var lastDistance = null;
- currentTime = currentTime || 0;
- var partsAndSegments = getPartsAndSegments(playlist);
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
- var partAndSegment = partsAndSegments[index];
- var segment = partAndSegment.segment;
- var start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
-
- if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
- var distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
- }
- }
-
- return syncPoint;
- }
-}, // Stategy "Discontinuity": We have a discontinuity with a known
-// display-time
-{
- name: 'Discontinuity',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- var syncPoint = null;
- currentTime = currentTime || 0;
-
- if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- var lastDistance = null;
-
- for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
- var segmentIndex = playlist.discontinuityStarts[i];
- var discontinuity = playlist.discontinuitySequence + i + 1;
- var discontinuitySync = syncController.discontinuities[discontinuity];
-
- if (discontinuitySync) {
- var distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: discontinuitySync.time,
- segmentIndex: segmentIndex,
- partIndex: null
- };
- }
- }
- }
- }
-
- return syncPoint;
- }
-}, // Stategy "Playlist": We have a playlist with a known mapping of
-// segment index to display time
-{
- name: 'Playlist',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (playlist.syncInfo) {
- var syncPoint = {
- time: playlist.syncInfo.time,
- segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
- partIndex: null
- };
- return syncPoint;
- }
-
- return null;
- }
-}];
-
-var SyncController = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose(SyncController, _videojs$EventTarget);
-
- function SyncController(options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this; // ...for synching across variants
-
- _this.timelines = [];
- _this.discontinuities = [];
- _this.timelineToDatetimeMappings = {};
- _this.logger_ = logger('SyncController');
- return _this;
- }
- /**
- * Find a sync-point for the playlist specified
- *
- * A sync-point is defined as a known mapping from display-time to
- * a segment-index in the current playlist.
- *
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinite if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Object}
- * A sync-point object
- */
-
-
- var _proto = SyncController.prototype;
-
- _proto.getSyncPoint = function getSyncPoint(playlist, duration, currentTimeline, currentTime) {
- var syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
-
- if (!syncPoints.length) {
- // Signal that we need to attempt to get a sync-point manually
- // by fetching a segment in the playlist and constructing
- // a sync-point from that information
- return null;
- } // Now find the sync-point that is closest to the currentTime because
- // that should result in the most accurate guess about which segment
- // to fetch
-
-
- return this.selectSyncPoint_(syncPoints, {
- key: 'time',
- value: currentTime
- });
- }
- /**
- * Calculate the amount of time that has expired off the playlist during playback
- *
- * @param {Playlist} playlist
- * Playlist object to calculate expired from
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playling a live source)
- * @return {number|null}
- * The amount of time that has expired off the playlist during playback. Null
- * if no sync-points for the playlist can be found.
- */
- ;
-
- _proto.getExpiredTime = function getExpiredTime(playlist, duration) {
- if (!playlist || !playlist.segments) {
- return null;
- }
-
- var syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
-
- if (!syncPoints.length) {
- return null;
- }
-
- var syncPoint = this.selectSyncPoint_(syncPoints, {
- key: 'segmentIndex',
- value: 0
- }); // If the sync-point is beyond the start of the playlist, we want to subtract the
- // duration from index 0 to syncPoint.segmentIndex instead of adding.
-
- if (syncPoint.segmentIndex > 0) {
- syncPoint.time *= -1;
- }
-
- return Math.abs(syncPoint.time + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: syncPoint.segmentIndex,
- endIndex: 0
- }));
- }
- /**
- * Runs each sync-point strategy and returns a list of sync-points returned by the
- * strategies
- *
- * @private
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Array}
- * A list of sync-point objects
- */
- ;
-
- _proto.runStrategies_ = function runStrategies_(playlist, duration, currentTimeline, currentTime) {
- var syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
-
- for (var i = 0; i < syncPointStrategies.length; i++) {
- var strategy = syncPointStrategies[i];
- var syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
-
- if (syncPoint) {
- syncPoint.strategy = strategy.name;
- syncPoints.push({
- strategy: strategy.name,
- syncPoint: syncPoint
- });
- }
- }
-
- return syncPoints;
- }
- /**
- * Selects the sync-point nearest the specified target
- *
- * @private
- * @param {Array} syncPoints
- * List of sync-points to select from
- * @param {Object} target
- * Object specifying the property and value we are targeting
- * @param {string} target.key
- * Specifies the property to target. Must be either 'time' or 'segmentIndex'
- * @param {number} target.value
- * The value to target for the specified key.
- * @return {Object}
- * The sync-point nearest the target
- */
- ;
-
- _proto.selectSyncPoint_ = function selectSyncPoint_(syncPoints, target) {
- var bestSyncPoint = syncPoints[0].syncPoint;
- var bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
- var bestStrategy = syncPoints[0].strategy;
-
- for (var i = 1; i < syncPoints.length; i++) {
- var newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
-
- if (newDistance < bestDistance) {
- bestDistance = newDistance;
- bestSyncPoint = syncPoints[i].syncPoint;
- bestStrategy = syncPoints[i].strategy;
- }
- }
-
- this.logger_("syncPoint for [" + target.key + ": " + target.value + "] chosen with strategy" + (" [" + bestStrategy + "]: [time:" + bestSyncPoint.time + ",") + (" segmentIndex:" + bestSyncPoint.segmentIndex) + (typeof bestSyncPoint.partIndex === 'number' ? ",partIndex:" + bestSyncPoint.partIndex : '') + ']');
- return bestSyncPoint;
- }
- /**
- * Save any meta-data present on the segments when segments leave
- * the live window to the playlist to allow for synchronization at the
- * playlist level later.
- *
- * @param {Playlist} oldPlaylist - The previous active playlist
- * @param {Playlist} newPlaylist - The updated and most current playlist
- */
- ;
-
- _proto.saveExpiredSegmentInfo = function saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
- var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // When a segment expires from the playlist and it has a start time
- // save that information as a possible sync-point reference in future
-
- for (var i = mediaSequenceDiff - 1; i >= 0; i--) {
- var lastRemovedSegment = oldPlaylist.segments[i];
-
- if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
- newPlaylist.syncInfo = {
- mediaSequence: oldPlaylist.mediaSequence + i,
- time: lastRemovedSegment.start
- };
- this.logger_("playlist refresh sync: [time:" + newPlaylist.syncInfo.time + "," + (" mediaSequence: " + newPlaylist.syncInfo.mediaSequence + "]"));
- this.trigger('syncinfoupdate');
- break;
- }
- }
- }
- /**
- * Save the mapping from playlist's ProgramDateTime to display. This should only happen
- * before segments start to load.
- *
- * @param {Playlist} playlist - The currently active playlist
- */
- ;
-
- _proto.setDateTimeMappingForStart = function setDateTimeMappingForStart(playlist) {
- // It's possible for the playlist to be updated before playback starts, meaning time
- // zero is not yet set. If, during these playlist refreshes, a discontinuity is
- // crossed, then the old time zero mapping (for the prior timeline) would be retained
- // unless the mappings are cleared.
- this.timelineToDatetimeMappings = {};
-
- if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
- var firstSegment = playlist.segments[0];
- var playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
- this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
- }
- }
- /**
- * Calculates and saves timeline mappings, playlist sync info, and segment timing values
- * based on the latest timing information.
- *
- * @param {Object} options
- * Options object
- * @param {SegmentInfo} options.segmentInfo
- * The current active request information
- * @param {boolean} options.shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved for timeline mapping and program date time mappings.
- */
- ;
-
- _proto.saveSegmentTimingInfo = function saveSegmentTimingInfo(_ref) {
- var segmentInfo = _ref.segmentInfo,
- shouldSaveTimelineMapping = _ref.shouldSaveTimelineMapping;
- var didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
- var segment = segmentInfo.segment;
-
- if (didCalculateSegmentTimeMapping) {
- this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
- // now with segment timing information
-
- if (!segmentInfo.playlist.syncInfo) {
- segmentInfo.playlist.syncInfo = {
- mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
- time: segment.start
- };
- }
- }
-
- var dateTime = segment.dateTimeObject;
-
- if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
- this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
- }
- };
-
- _proto.timestampOffsetForTimeline = function timestampOffsetForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
-
- return this.timelines[timeline].time;
- };
-
- _proto.mappingForTimeline = function mappingForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
-
- return this.timelines[timeline].mapping;
- }
- /**
- * Use the "media time" for a segment to generate a mapping to "display time" and
- * save that display time to the segment.
- *
- * @private
- * @param {SegmentInfo} segmentInfo
- * The current active request information
- * @param {Object} timingInfo
- * The start and end time of the current segment in "media time"
- * @param {boolean} shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved in timelines.
- * @return {boolean}
- * Returns false if segment time mapping could not be calculated
- */
- ;
-
- _proto.calculateSegmentTimeMapping_ = function calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
- // TODO: remove side effects
- var segment = segmentInfo.segment;
- var part = segmentInfo.part;
- var mappingObj = this.timelines[segmentInfo.timeline];
- var start;
- var end;
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- mappingObj = {
- time: segmentInfo.startOfSegment,
- mapping: segmentInfo.startOfSegment - timingInfo.start
- };
-
- if (shouldSaveTimelineMapping) {
- this.timelines[segmentInfo.timeline] = mappingObj;
- this.trigger('timestampoffset');
- this.logger_("time mapping for timeline " + segmentInfo.timeline + ": " + ("[time: " + mappingObj.time + "] [mapping: " + mappingObj.mapping + "]"));
- }
-
- start = segmentInfo.startOfSegment;
- end = timingInfo.end + mappingObj.mapping;
- } else if (mappingObj) {
- start = timingInfo.start + mappingObj.mapping;
- end = timingInfo.end + mappingObj.mapping;
- } else {
- return false;
- }
-
- if (part) {
- part.start = start;
- part.end = end;
- } // If we don't have a segment start yet or the start value we got
- // is less than our current segment.start value, save a new start value.
- // We have to do this because parts will have segment timing info saved
- // multiple times and we want segment start to be the earliest part start
- // value for that segment.
-
-
- if (!segment.start || start < segment.start) {
- segment.start = start;
- }
-
- segment.end = end;
- return true;
- }
- /**
- * Each time we have discontinuity in the playlist, attempt to calculate the location
- * in display of the start of the discontinuity and save that. We also save an accuracy
- * value so that we save values with the most accuracy (closest to 0.)
- *
- * @private
- * @param {SegmentInfo} segmentInfo - The current active request information
- */
- ;
-
- _proto.saveDiscontinuitySyncInfo_ = function saveDiscontinuitySyncInfo_(segmentInfo) {
- var playlist = segmentInfo.playlist;
- var segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
- // the start of the range and it's accuracy is 0 (greater accuracy values
- // mean more approximation)
-
- if (segment.discontinuity) {
- this.discontinuities[segment.timeline] = {
- time: segment.start,
- accuracy: 0
- };
- } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- // Search for future discontinuities that we can provide better timing
- // information for and save that information for sync purposes
- for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
- var segmentIndex = playlist.discontinuityStarts[i];
- var discontinuity = playlist.discontinuitySequence + i + 1;
- var mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
- var accuracy = Math.abs(mediaIndexDiff);
-
- if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
- var time = void 0;
-
- if (mediaIndexDiff < 0) {
- time = segment.start - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex,
- endIndex: segmentIndex
- });
- } else {
- time = segment.end + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex + 1,
- endIndex: segmentIndex
- });
- }
-
- this.discontinuities[discontinuity] = {
- time: time,
- accuracy: accuracy
- };
- }
- }
- }
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.off();
- };
-
- return SyncController;
-}(videojs.EventTarget);
-
-/**
- * The TimelineChangeController acts as a source for segment loaders to listen for and
- * keep track of latest and pending timeline changes. This is useful to ensure proper
- * sync, as each loader may need to make a consideration for what timeline the other
- * loader is on before making changes which could impact the other loader's media.
- *
- * @class TimelineChangeController
- * @extends videojs.EventTarget
- */
-
-var TimelineChangeController = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose(TimelineChangeController, _videojs$EventTarget);
-
- function TimelineChangeController() {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- _this.pendingTimelineChanges_ = {};
- _this.lastTimelineChanges_ = {};
- return _this;
- }
-
- var _proto = TimelineChangeController.prototype;
-
- _proto.clearPendingTimelineChange = function clearPendingTimelineChange(type) {
- this.pendingTimelineChanges_[type] = null;
- this.trigger('pendingtimelinechange');
- };
-
- _proto.pendingTimelineChange = function pendingTimelineChange(_ref) {
- var type = _ref.type,
- from = _ref.from,
- to = _ref.to;
-
- if (typeof from === 'number' && typeof to === 'number') {
- this.pendingTimelineChanges_[type] = {
- type: type,
- from: from,
- to: to
- };
- this.trigger('pendingtimelinechange');
- }
-
- return this.pendingTimelineChanges_[type];
- };
-
- _proto.lastTimelineChange = function lastTimelineChange(_ref2) {
- var type = _ref2.type,
- from = _ref2.from,
- to = _ref2.to;
-
- if (typeof from === 'number' && typeof to === 'number') {
- this.lastTimelineChanges_[type] = {
- type: type,
- from: from,
- to: to
- };
- delete this.pendingTimelineChanges_[type];
- this.trigger('timelinechange');
- }
-
- return this.lastTimelineChanges_[type];
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.pendingTimelineChanges_ = {};
- this.lastTimelineChanges_ = {};
- this.off();
- };
-
- return TimelineChangeController;
-}(videojs.EventTarget);
-
-/* rollup-plugin-worker-factory start for worker!/Users/gkatsevman/p/http-streaming-release/src/decrypter-worker.js */
-var workerCode = transform(getWorkerString(function () {
-
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function require(path, base) {
- return commonjsRequire(path, base === undefined || base === null ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
-
- function commonjsRequire() {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
-
- var createClass = createCommonjsModule(function (module) {
- 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);
- }
- }
-
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
-
- module.exports = _createClass;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- var setPrototypeOf = createCommonjsModule(function (module) {
- function _setPrototypeOf(o, p) {
- module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _setPrototypeOf(o, p);
- }
-
- module.exports = _setPrototypeOf;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- var inheritsLoose = createCommonjsModule(function (module) {
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- setPrototypeOf(subClass, superClass);
- }
-
- module.exports = _inheritsLoose;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- /**
- * @file stream.js
- */
-
- /**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
-
- var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
- }();
- /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
-
- /**
- * Returns the subarray of a Uint8Array without PKCS#7 padding.
- *
- * @param padded {Uint8Array} unencrypted bytes that have been padded
- * @return {Uint8Array} the unpadded bytes
- * @see http://tools.ietf.org/html/rfc5652
- */
-
-
- function unpad(padded) {
- return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
- }
- /*! @name aes-decrypter @version 3.1.2 @license Apache-2.0 */
-
- /**
- * @file aes.js
- *
- * This file contains an adaptation of the AES decryption algorithm
- * from the Standford Javascript Cryptography Library. That work is
- * covered by the following copyright and permissions notice:
- *
- * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. 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 AUTHORS ``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 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.
- *
- * The views and conclusions contained in the software and documentation
- * are those of the authors and should not be interpreted as representing
- * official policies, either expressed or implied, of the authors.
- */
-
- /**
- * Expand the S-box tables.
- *
- * @private
- */
-
-
- var precompute = function precompute() {
- var tables = [[[], [], [], [], []], [[], [], [], [], []]];
- var encTable = tables[0];
- var decTable = tables[1];
- var sbox = encTable[4];
- var sboxInv = decTable[4];
- var i;
- var x;
- var xInv;
- var d = [];
- var th = [];
- var x2;
- var x4;
- var x8;
- var s;
- var tEnc;
- var tDec; // Compute double and third tables
-
- for (i = 0; i < 256; i++) {
- th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
- }
-
- for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
- // Compute sbox
- s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
- s = s >> 8 ^ s & 255 ^ 99;
- sbox[x] = s;
- sboxInv[s] = x; // Compute MixColumns
-
- x8 = d[x4 = d[x2 = d[x]]];
- tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- tEnc = d[s] * 0x101 ^ s * 0x1010100;
-
- for (i = 0; i < 4; i++) {
- encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
- decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
- }
- } // Compactify. Considerable speedup on Firefox.
-
-
- for (i = 0; i < 5; i++) {
- encTable[i] = encTable[i].slice(0);
- decTable[i] = decTable[i].slice(0);
- }
-
- return tables;
- };
-
- var aesTables = null;
- /**
- * Schedule out an AES key for both encryption and decryption. This
- * is a low-level class. Use a cipher mode to do bulk encryption.
- *
- * @class AES
- * @param key {Array} The key as an array of 4, 6 or 8 words.
- */
-
- var AES = /*#__PURE__*/function () {
- function AES(key) {
- /**
- * The expanded S-box and inverse S-box tables. These will be computed
- * on the client so that we don't have to send them down the wire.
- *
- * There are two tables, _tables[0] is for encryption and
- * _tables[1] is for decryption.
- *
- * The first 4 sub-tables are the expanded S-box with MixColumns. The
- * last (_tables[01][4]) is the S-box itself.
- *
- * @private
- */
- // if we have yet to precompute the S-box tables
- // do so now
- if (!aesTables) {
- aesTables = precompute();
- } // then make a copy of that object for use
-
-
- this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
- var i;
- var j;
- var tmp;
- var sbox = this._tables[0][4];
- var decTable = this._tables[1];
- var keyLen = key.length;
- var rcon = 1;
-
- if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
- throw new Error('Invalid aes key size');
- }
-
- var encKey = key.slice(0);
- var decKey = [];
- this._key = [encKey, decKey]; // schedule encryption keys
-
- for (i = keyLen; i < 4 * keyLen + 28; i++) {
- tmp = encKey[i - 1]; // apply sbox
-
- if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
- tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
-
- if (i % keyLen === 0) {
- tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
- rcon = rcon << 1 ^ (rcon >> 7) * 283;
- }
- }
-
- encKey[i] = encKey[i - keyLen] ^ tmp;
- } // schedule decryption keys
-
-
- for (j = 0; i; j++, i--) {
- tmp = encKey[j & 3 ? i : i - 4];
-
- if (i <= 4 || j < 4) {
- decKey[j] = tmp;
- } else {
- decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
- }
- }
- }
- /**
- * Decrypt 16 bytes, specified as four 32-bit words.
- *
- * @param {number} encrypted0 the first word to decrypt
- * @param {number} encrypted1 the second word to decrypt
- * @param {number} encrypted2 the third word to decrypt
- * @param {number} encrypted3 the fourth word to decrypt
- * @param {Int32Array} out the array to write the decrypted words
- * into
- * @param {number} offset the offset into the output array to start
- * writing results
- * @return {Array} The plaintext.
- */
-
-
- var _proto = AES.prototype;
-
- _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
- var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
-
- var a = encrypted0 ^ key[0];
- var b = encrypted3 ^ key[1];
- var c = encrypted2 ^ key[2];
- var d = encrypted1 ^ key[3];
- var a2;
- var b2;
- var c2; // key.length === 2 ?
-
- var nInnerRounds = key.length / 4 - 2;
- var i;
- var kIndex = 4;
- var table = this._tables[1]; // load up the tables
-
- var table0 = table[0];
- var table1 = table[1];
- var table2 = table[2];
- var table3 = table[3];
- var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
-
- for (i = 0; i < nInnerRounds; i++) {
- a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
- b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
- c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
- d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
- kIndex += 4;
- a = a2;
- b = b2;
- c = c2;
- } // Last round.
-
-
- for (i = 0; i < 4; i++) {
- out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
- a2 = a;
- a = b;
- b = c;
- c = d;
- d = a2;
- }
- };
-
- return AES;
- }();
- /**
- * A wrapper around the Stream class to use setTimeout
- * and run stream "jobs" Asynchronously
- *
- * @class AsyncStream
- * @extends Stream
- */
-
-
- var AsyncStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(AsyncStream, _Stream);
-
- function AsyncStream() {
- var _this;
-
- _this = _Stream.call(this, Stream) || this;
- _this.jobs = [];
- _this.delay = 1;
- _this.timeout_ = null;
- return _this;
- }
- /**
- * process an async job
- *
- * @private
- */
-
-
- var _proto = AsyncStream.prototype;
-
- _proto.processJob_ = function processJob_() {
- this.jobs.shift()();
-
- if (this.jobs.length) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- } else {
- this.timeout_ = null;
- }
- }
- /**
- * push a job into the stream
- *
- * @param {Function} job the job to push into the stream
- */
- ;
-
- _proto.push = function push(job) {
- this.jobs.push(job);
-
- if (!this.timeout_) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- }
- };
-
- return AsyncStream;
- }(Stream);
- /**
- * Convert network-order (big-endian) bytes into their little-endian
- * representation.
- */
-
-
- var ntoh = function ntoh(word) {
- return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
- };
- /**
- * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * use for the first round of CBC.
- * @return {Uint8Array} the decrypted bytes
- *
- * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
- * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
- * @see https://tools.ietf.org/html/rfc2315
- */
-
-
- var decrypt = function decrypt(encrypted, key, initVector) {
- // word-level access to the encrypted bytes
- var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
- var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
-
- var decrypted = new Uint8Array(encrypted.byteLength);
- var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
- // decrypted data
-
- var init0;
- var init1;
- var init2;
- var init3;
- var encrypted0;
- var encrypted1;
- var encrypted2;
- var encrypted3; // iteration variable
-
- var wordIx; // pull out the words of the IV to ensure we don't modify the
- // passed-in reference and easier access
-
- init0 = initVector[0];
- init1 = initVector[1];
- init2 = initVector[2];
- init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
- // to each decrypted block
-
- for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
- // convert big-endian (network order) words into little-endian
- // (javascript order)
- encrypted0 = ntoh(encrypted32[wordIx]);
- encrypted1 = ntoh(encrypted32[wordIx + 1]);
- encrypted2 = ntoh(encrypted32[wordIx + 2]);
- encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
-
- decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
- // plaintext
-
- decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
- decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
- decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
- decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
-
- init0 = encrypted0;
- init1 = encrypted1;
- init2 = encrypted2;
- init3 = encrypted3;
- }
-
- return decrypted;
- };
- /**
- * The `Decrypter` class that manages decryption of AES
- * data through `AsyncStream` objects and the `decrypt`
- * function
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * @param {Function} done the function to run when done
- * @class Decrypter
- */
-
-
- var Decrypter = /*#__PURE__*/function () {
- function Decrypter(encrypted, key, initVector, done) {
- var step = Decrypter.STEP;
- var encrypted32 = new Int32Array(encrypted.buffer);
- var decrypted = new Uint8Array(encrypted.byteLength);
- var i = 0;
- this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
-
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
-
- for (i = step; i < encrypted32.length; i += step) {
- initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
- } // invoke the done() callback when everything is finished
-
-
- this.asyncStream_.push(function () {
- // remove pkcs#7 padding from the decrypted bytes
- done(null, unpad(decrypted));
- });
- }
- /**
- * a getter for step the maximum number of bytes to process at one time
- *
- * @return {number} the value of step 32000
- */
-
-
- var _proto = Decrypter.prototype;
- /**
- * @private
- */
-
- _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
- return function () {
- var bytes = decrypt(encrypted, key, initVector);
- decrypted.set(bytes, encrypted.byteOffset);
- };
- };
-
- createClass(Decrypter, null, [{
- key: "STEP",
- get: function get() {
- // 4 * 8000;
- return 32000;
- }
- }]);
- return Decrypter;
- }();
- /**
- * @file bin-utils.js
- */
-
- /**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-
-
- var createTransferableMessage = function createTransferableMessage(message) {
- var transferable = {};
- Object.keys(message).forEach(function (key) {
- var value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
- return transferable;
- };
- /* global self */
-
- /**
- * Our web worker interface so that things can talk to aes-decrypter
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- */
-
-
- self.onmessage = function (event) {
- var data = event.data;
- var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
- var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
- var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
- /* eslint-disable no-new, handle-callback-err */
-
- new Decrypter(encrypted, key, iv, function (err, bytes) {
- self.postMessage(createTransferableMessage({
- source: data.source,
- decrypted: bytes
- }), [bytes.buffer]);
- });
- /* eslint-enable */
- };
-}));
-var Decrypter = factory(workerCode);
-/* rollup-plugin-worker-factory end for worker!/Users/gkatsevman/p/http-streaming-release/src/decrypter-worker.js */
-
-/**
- * Convert the properties of an HLS track into an audioTrackKind.
- *
- * @private
- */
-
-var audioTrackKind_ = function audioTrackKind_(properties) {
- var kind = properties.default ? 'main' : 'alternative';
-
- if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
- kind = 'main-desc';
- }
-
- return kind;
-};
-/**
- * Pause provided segment loader and playlist loader if active
- *
- * @param {SegmentLoader} segmentLoader
- * SegmentLoader to pause
- * @param {Object} mediaType
- * Active media type
- * @function stopLoaders
- */
-
-
-var stopLoaders = function stopLoaders(segmentLoader, mediaType) {
- segmentLoader.abort();
- segmentLoader.pause();
-
- if (mediaType && mediaType.activePlaylistLoader) {
- mediaType.activePlaylistLoader.pause();
- mediaType.activePlaylistLoader = null;
- }
-};
-/**
- * Start loading provided segment loader and playlist loader
- *
- * @param {PlaylistLoader} playlistLoader
- * PlaylistLoader to start loading
- * @param {Object} mediaType
- * Active media type
- * @function startLoaders
- */
-
-var startLoaders = function startLoaders(playlistLoader, mediaType) {
- // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
- // playlist loader
- mediaType.activePlaylistLoader = playlistLoader;
- playlistLoader.load();
-};
-/**
- * Returns a function to be called when the media group changes. It performs a
- * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
- * change of group is merely a rendition switch of the same content at another encoding,
- * rather than a change of content, such as switching audio from English to Spanish.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a non-destructive resync of SegmentLoader when the active media
- * group changes.
- * @function onGroupChanged
- */
-
-var onGroupChanged = function onGroupChanged(type, settings) {
- return function () {
- var _settings$segmentLoad = settings.segmentLoaders,
- segmentLoader = _settings$segmentLoad[type],
- mainSegmentLoader = _settings$segmentLoad.main,
- mediaType = settings.mediaTypes[type];
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.getActiveGroup();
- var previousActiveLoader = mediaType.activePlaylistLoader;
- var lastGroup = mediaType.lastGroup_; // the group did not change do nothing
-
- if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup || activeGroup.isMasterPlaylist) {
- // there is no group active or active group is a main playlist and won't change
- return;
- }
-
- if (!activeGroup.playlistLoader) {
- if (previousActiveLoader) {
- // The previous group had a playlist loader but the new active group does not
- // this means we are switching from demuxed to muxed audio. In this case we want to
- // do a destructive reset of the main segment loader and not restart the audio
- // loaders.
- mainSegmentLoader.resetEverything();
- }
-
- return;
- } // Non-destructive resync
-
-
- segmentLoader.resyncLoader();
- startLoaders(activeGroup.playlistLoader, mediaType);
- };
-};
-var onGroupChanging = function onGroupChanging(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- mediaType.lastGroup_ = null;
- segmentLoader.abort();
- segmentLoader.pause();
- };
-};
-/**
- * Returns a function to be called when the media track changes. It performs a
- * destructive reset of the SegmentLoader to ensure we start loading as close to
- * currentTime as possible.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a destructive reset of SegmentLoader when the active media
- * track changes.
- * @function onTrackChanged
- */
-
-var onTrackChanged = function onTrackChanged(type, settings) {
- return function () {
- var masterPlaylistLoader = settings.masterPlaylistLoader,
- _settings$segmentLoad2 = settings.segmentLoaders,
- segmentLoader = _settings$segmentLoad2[type],
- mainSegmentLoader = _settings$segmentLoad2.main,
- mediaType = settings.mediaTypes[type];
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.getActiveGroup();
- var previousActiveLoader = mediaType.activePlaylistLoader;
- var lastTrack = mediaType.lastTrack_; // track did not change, do nothing
-
- if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup) {
- // there is no group active so we do not want to restart loaders
- return;
- }
-
- if (activeGroup.isMasterPlaylist) {
- // track did not change, do nothing
- if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
- return;
- }
-
- var mpc = settings.vhs.masterPlaylistController_;
- var newPlaylist = mpc.selectPlaylist(); // media will not change do nothing
-
- if (mpc.media() === newPlaylist) {
- return;
- }
-
- mediaType.logger_("track change. Switching master audio from " + lastTrack.id + " to " + activeTrack.id);
- masterPlaylistLoader.pause();
- mainSegmentLoader.resetEverything();
- mpc.fastQualityChange_(newPlaylist);
- return;
- }
-
- if (type === 'AUDIO') {
- if (!activeGroup.playlistLoader) {
- // when switching from demuxed audio/video to muxed audio/video (noted by no
- // playlist loader for the audio group), we want to do a destructive reset of the
- // main segment loader and not restart the audio loaders
- mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
- // it should be stopped
-
- mainSegmentLoader.resetEverything();
- return;
- } // although the segment loader is an audio segment loader, call the setAudio
- // function to ensure it is prepared to re-append the init segment (or handle other
- // config changes)
-
-
- segmentLoader.setAudio(true);
- mainSegmentLoader.setAudio(false);
- }
-
- if (previousActiveLoader === activeGroup.playlistLoader) {
- // Nothing has actually changed. This can happen because track change events can fire
- // multiple times for a "single" change. One for enabling the new active track, and
- // one for disabling the track that was active
- startLoaders(activeGroup.playlistLoader, mediaType);
- return;
- }
-
- if (segmentLoader.track) {
- // For WebVTT, set the new text track in the segmentloader
- segmentLoader.track(activeTrack);
- } // destructive reset
-
-
- segmentLoader.resetEverything();
- startLoaders(activeGroup.playlistLoader, mediaType);
- };
-};
-var onError = {
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning (or error if the playlist is blacklisted) to
- * console and switches back to default audio track.
- * @function onError.AUDIO
- */
- AUDIO: function AUDIO(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type],
- blacklistCurrentPlaylist = settings.blacklistCurrentPlaylist;
- stopLoaders(segmentLoader, mediaType); // switch back to default audio track
-
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.activeGroup();
- var id = (activeGroup.filter(function (group) {
- return group.default;
- })[0] || activeGroup[0]).id;
- var defaultTrack = mediaType.tracks[id];
-
- if (activeTrack === defaultTrack) {
- // Default track encountered an error. All we can do now is blacklist the current
- // rendition and hope another will switch audio groups
- blacklistCurrentPlaylist({
- message: 'Problem encountered loading the default audio track.'
- });
- return;
- }
-
- videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
-
- for (var trackId in mediaType.tracks) {
- mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
- }
-
- mediaType.onTrackChanged();
- };
- },
-
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning to console and disables the active subtitle track
- * @function onError.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
- stopLoaders(segmentLoader, mediaType);
- var track = mediaType.activeTrack();
-
- if (track) {
- track.mode = 'disabled';
- }
-
- mediaType.onTrackChanged();
- };
- }
-};
-var setupListeners = {
- /**
- * Setup event listeners for audio playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.AUDIO
- */
- AUDIO: function AUDIO(type, playlistLoader, settings) {
- if (!playlistLoader) {
- // no playlist loader means audio will be muxed with the video
- return;
- }
-
- var tech = settings.tech,
- requestOptions = settings.requestOptions,
- segmentLoader = settings.segmentLoaders[type];
- playlistLoader.on('loadedmetadata', function () {
- var media = playlistLoader.media();
- segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
-
- if (!tech.paused() || media.endList && tech.preload() !== 'none') {
- segmentLoader.load();
- }
- });
- playlistLoader.on('loadedplaylist', function () {
- segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
-
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
- playlistLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup event listeners for subtitle playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, playlistLoader, settings) {
- var tech = settings.tech,
- requestOptions = settings.requestOptions,
- segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- playlistLoader.on('loadedmetadata', function () {
- var media = playlistLoader.media();
- segmentLoader.playlist(media, requestOptions);
- segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
-
- if (!tech.paused() || media.endList && tech.preload() !== 'none') {
- segmentLoader.load();
- }
- });
- playlistLoader.on('loadedplaylist', function () {
- segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
-
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
- playlistLoader.on('error', onError[type](type, settings));
- }
-};
-var initialize = {
- /**
- * Setup PlaylistLoaders and AudioTracks for the audio groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.AUDIO
- */
- 'AUDIO': function AUDIO(type, settings) {
- var vhs = settings.vhs,
- sourceType = settings.sourceType,
- segmentLoader = settings.segmentLoaders[type],
- requestOptions = settings.requestOptions,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$ = settings.mediaTypes[type],
- groups = _settings$mediaTypes$.groups,
- tracks = _settings$mediaTypes$.tracks,
- logger_ = _settings$mediaTypes$.logger_,
- masterPlaylistLoader = settings.masterPlaylistLoader;
- var audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master); // force a default if we have none
-
- if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
- mediaGroups[type] = {
- main: {
- default: {
- default: true
- }
- }
- };
- }
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- var properties = mediaGroups[type][groupId][variantLabel];
- var playlistLoader = void 0;
-
- if (audioOnlyMaster) {
- logger_("AUDIO group '" + groupId + "' label '" + variantLabel + "' is a master playlist");
- properties.isMasterPlaylist = true;
- playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
- // use the resolved media playlist object
- } else if (sourceType === 'vhs-json' && properties.playlists) {
- playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
- } else if (properties.resolvedUri) {
- playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
- // should we even have properties.playlists in this check.
- } else if (properties.playlists && sourceType === 'dash') {
- playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
- } else {
- // no resolvedUri means the audio is muxed with the video when using this
- // audio track
- playlistLoader = null;
- }
-
- properties = videojs.mergeOptions({
- id: variantLabel,
- playlistLoader: playlistLoader
- }, properties);
- setupListeners[type](type, properties.playlistLoader, settings);
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = new videojs.AudioTrack({
- id: variantLabel,
- kind: audioTrackKind_(properties),
- enabled: false,
- language: properties.language,
- default: properties.default,
- label: variantLabel
- });
- tracks[variantLabel] = track;
- }
- }
- } // setup single error event handler for the segment loader
-
-
- segmentLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup PlaylistLoaders and TextTracks for the subtitle groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.SUBTITLES
- */
- 'SUBTITLES': function SUBTITLES(type, settings) {
- var tech = settings.tech,
- vhs = settings.vhs,
- sourceType = settings.sourceType,
- segmentLoader = settings.segmentLoaders[type],
- requestOptions = settings.requestOptions,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$2 = settings.mediaTypes[type],
- groups = _settings$mediaTypes$2.groups,
- tracks = _settings$mediaTypes$2.tracks,
- masterPlaylistLoader = settings.masterPlaylistLoader;
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- if (mediaGroups[type][groupId][variantLabel].forced) {
- // Subtitle playlists with the forced attribute are not selectable in Safari.
- // According to Apple's HLS Authoring Specification:
- // If content has forced subtitles and regular subtitles in a given language,
- // the regular subtitles track in that language MUST contain both the forced
- // subtitles and the regular subtitles for that language.
- // Because of this requirement and that Safari does not add forced subtitles,
- // forced subtitles are skipped here to maintain consistent experience across
- // all platforms
- continue;
- }
-
- var properties = mediaGroups[type][groupId][variantLabel];
- var playlistLoader = void 0;
-
- if (sourceType === 'hls') {
- playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
- } else if (sourceType === 'dash') {
- var playlists = properties.playlists.filter(function (p) {
- return p.excludeUntil !== Infinity;
- });
-
- if (!playlists.length) {
- return;
- }
-
- playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
- } else if (sourceType === 'vhs-json') {
- playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
- // as provided, otherwise use the resolved URI to load the playlist
- properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
- }
-
- properties = videojs.mergeOptions({
- id: variantLabel,
- playlistLoader: playlistLoader
- }, properties);
- setupListeners[type](type, properties.playlistLoader, settings);
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = tech.addRemoteTextTrack({
- id: variantLabel,
- kind: 'subtitles',
- default: properties.default && properties.autoselect,
- language: properties.language,
- label: variantLabel
- }, false).track;
- tracks[variantLabel] = track;
- }
- }
- } // setup single error event handler for the segment loader
-
-
- segmentLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup TextTracks for the closed-caption groups
- *
- * @param {String} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize['CLOSED-CAPTIONS']
- */
- 'CLOSED-CAPTIONS': function CLOSEDCAPTIONS(type, settings) {
- var tech = settings.tech,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$3 = settings.mediaTypes[type],
- groups = _settings$mediaTypes$3.groups,
- tracks = _settings$mediaTypes$3.tracks;
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- var properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
-
- if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
- continue;
- }
-
- var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
- var newProps = {
- label: variantLabel,
- language: properties.language,
- instreamId: properties.instreamId,
- default: properties.default && properties.autoselect
- };
-
- if (captionServices[newProps.instreamId]) {
- newProps = videojs.mergeOptions(newProps, captionServices[newProps.instreamId]);
- }
-
- if (newProps.default === undefined) {
- delete newProps.default;
- } // No PlaylistLoader is required for Closed-Captions because the captions are
- // embedded within the video stream
-
-
- groups[groupId].push(videojs.mergeOptions({
- id: variantLabel
- }, properties));
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = tech.addRemoteTextTrack({
- id: newProps.instreamId,
- kind: 'captions',
- default: newProps.default,
- language: newProps.language,
- label: newProps.label
- }, false).track;
- tracks[variantLabel] = track;
- }
- }
- }
- }
-};
-
-var groupMatch = function groupMatch(list, media) {
- for (var i = 0; i < list.length; i++) {
- if (playlistMatch(media, list[i])) {
- return true;
- }
-
- if (list[i].playlists && groupMatch(list[i].playlists, media)) {
- return true;
- }
- }
-
- return false;
-};
-/**
- * Returns a function used to get the active group of the provided type
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media group for the provided type. Takes an
- * optional parameter {TextTrack} track. If no track is provided, a list of all
- * variants in the group, otherwise the variant corresponding to the provided
- * track is returned.
- * @function activeGroup
- */
-
-
-var activeGroup = function activeGroup(type, settings) {
- return function (track) {
- var masterPlaylistLoader = settings.masterPlaylistLoader,
- groups = settings.mediaTypes[type].groups;
- var media = masterPlaylistLoader.media();
-
- if (!media) {
- return null;
- }
-
- var variants = null; // set to variants to main media active group
-
- if (media.attributes[type]) {
- variants = groups[media.attributes[type]];
- }
-
- var groupKeys = Object.keys(groups);
-
- if (!variants) {
- // find the masterPlaylistLoader media
- // that is in a media group if we are dealing
- // with audio only
- if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.master)) {
- for (var i = 0; i < groupKeys.length; i++) {
- var groupPropertyList = groups[groupKeys[i]];
-
- if (groupMatch(groupPropertyList, media)) {
- variants = groupPropertyList;
- break;
- }
- } // use the main group if it exists
-
- } else if (groups.main) {
- variants = groups.main; // only one group, use that one
- } else if (groupKeys.length === 1) {
- variants = groups[groupKeys[0]];
- }
- }
-
- if (typeof track === 'undefined') {
- return variants;
- }
-
- if (track === null || !variants) {
- // An active track was specified so a corresponding group is expected. track === null
- // means no track is currently active so there is no corresponding group
- return null;
- }
-
- return variants.filter(function (props) {
- return props.id === track.id;
- })[0] || null;
- };
-};
-var activeTrack = {
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.AUDIO
- */
- AUDIO: function AUDIO(type, settings) {
- return function () {
- var tracks = settings.mediaTypes[type].tracks;
-
- for (var id in tracks) {
- if (tracks[id].enabled) {
- return tracks[id];
- }
- }
-
- return null;
- };
- },
-
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, settings) {
- return function () {
- var tracks = settings.mediaTypes[type].tracks;
-
- for (var id in tracks) {
- if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
- return tracks[id];
- }
- }
-
- return null;
- };
- }
-};
-var getActiveGroup = function getActiveGroup(type, _ref) {
- var mediaTypes = _ref.mediaTypes;
- return function () {
- var activeTrack_ = mediaTypes[type].activeTrack();
-
- if (!activeTrack_) {
- return null;
- }
-
- return mediaTypes[type].activeGroup(activeTrack_);
- };
-};
-/**
- * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
- * Closed-Captions) specified in the master manifest.
- *
- * @param {Object} settings
- * Object containing required information for setting up the media groups
- * @param {Tech} settings.tech
- * The tech of the player
- * @param {Object} settings.requestOptions
- * XHR request options used by the segment loaders
- * @param {PlaylistLoader} settings.masterPlaylistLoader
- * PlaylistLoader for the master source
- * @param {VhsHandler} settings.vhs
- * VHS SourceHandler
- * @param {Object} settings.master
- * The parsed master manifest
- * @param {Object} settings.mediaTypes
- * Object to store the loaders, tracks, and utility methods for each media type
- * @param {Function} settings.blacklistCurrentPlaylist
- * Blacklists the current rendition and forces a rendition switch.
- * @function setupMediaGroups
- */
-
-var setupMediaGroups = function setupMediaGroups(settings) {
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
- initialize[type](type, settings);
- });
- var mediaTypes = settings.mediaTypes,
- masterPlaylistLoader = settings.masterPlaylistLoader,
- tech = settings.tech,
- vhs = settings.vhs,
- _settings$segmentLoad3 = settings.segmentLoaders,
- audioSegmentLoader = _settings$segmentLoad3['AUDIO'],
- mainSegmentLoader = _settings$segmentLoad3.main; // setup active group and track getters and change event handlers
-
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- mediaTypes[type].activeGroup = activeGroup(type, settings);
- mediaTypes[type].activeTrack = activeTrack[type](type, settings);
- mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
- mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
- mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
- mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
- }); // DO NOT enable the default subtitle or caption track.
- // DO enable the default audio track
-
- var audioGroup = mediaTypes.AUDIO.activeGroup();
-
- if (audioGroup) {
- var groupId = (audioGroup.filter(function (group) {
- return group.default;
- })[0] || audioGroup[0]).id;
- mediaTypes.AUDIO.tracks[groupId].enabled = true;
- mediaTypes.AUDIO.onGroupChanged();
- mediaTypes.AUDIO.onTrackChanged();
- var activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
- // track is changed, but needs to be handled here since the track may not be considered
- // changed on the first call to onTrackChanged
-
- if (!activeAudioGroup.playlistLoader) {
- // either audio is muxed with video or the stream is audio only
- mainSegmentLoader.setAudio(true);
- } else {
- // audio is demuxed
- mainSegmentLoader.setAudio(false);
- audioSegmentLoader.setAudio(true);
- }
- }
-
- masterPlaylistLoader.on('mediachange', function () {
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- return mediaTypes[type].onGroupChanged();
- });
- });
- masterPlaylistLoader.on('mediachanging', function () {
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- return mediaTypes[type].onGroupChanging();
- });
- }); // custom audio track change event handler for usage event
-
- var onAudioTrackChanged = function onAudioTrackChanged() {
- mediaTypes.AUDIO.onTrackChanged();
- tech.trigger({
- type: 'usage',
- name: 'vhs-audio-change'
- });
- tech.trigger({
- type: 'usage',
- name: 'hls-audio-change'
- });
- };
-
- tech.audioTracks().addEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
- vhs.on('dispose', function () {
- tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
- }); // clear existing audio tracks and add the ones we just created
-
- tech.clearTracks('audio');
-
- for (var id in mediaTypes.AUDIO.tracks) {
- tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
- }
-};
-/**
- * Creates skeleton object used to store the loaders, tracks, and utility methods for each
- * media type
- *
- * @return {Object}
- * Object to store the loaders, tracks, and utility methods for each media type
- * @function createMediaTypes
- */
-
-var createMediaTypes = function createMediaTypes() {
- var mediaTypes = {};
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
- mediaTypes[type] = {
- groups: {},
- tracks: {},
- activePlaylistLoader: null,
- activeGroup: noop,
- activeTrack: noop,
- getActiveGroup: noop,
- onGroupChanged: noop,
- onTrackChanged: noop,
- lastTrack_: null,
- logger_: logger("MediaGroups[" + type + "]")
- };
- });
- return mediaTypes;
-};
-
-var ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
-var Vhs$1; // SegmentLoader stats that need to have each loader's
-// values summed to calculate the final value
-
-var loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
-
-var sumLoaderStat = function sumLoaderStat(stat) {
- return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
-};
-
-var shouldSwitchToMedia = function shouldSwitchToMedia(_ref) {
- var currentPlaylist = _ref.currentPlaylist,
- nextPlaylist = _ref.nextPlaylist,
- forwardBuffer = _ref.forwardBuffer,
- bufferLowWaterLine = _ref.bufferLowWaterLine,
- bufferHighWaterLine = _ref.bufferHighWaterLine,
- duration = _ref.duration,
- experimentalBufferBasedABR = _ref.experimentalBufferBasedABR,
- log = _ref.log;
-
- // we have no other playlist to switch to
- if (!nextPlaylist) {
- videojs.log.warn('We received no playlist to switch to. Please check your stream.');
- return false;
- }
-
- var sharedLogLine = "allowing switch " + (currentPlaylist && currentPlaylist.id || 'null') + " -> " + nextPlaylist.id; // If the playlist is live, then we want to not take low water line into account.
- // This is because in LIVE, the player plays 3 segments from the end of the
- // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
- // in those segments, a viewer will never experience a rendition upswitch.
-
- if (!currentPlaylist || !currentPlaylist.endList) {
- log(sharedLogLine + " as current playlist " + (!currentPlaylist ? 'is not set' : 'is live'));
- return true;
- } // no need to switch playlist is the same
-
-
- if (nextPlaylist.id === currentPlaylist.id) {
- return false;
- }
-
- var maxBufferLowWaterLine = experimentalBufferBasedABR ? Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE; // For the same reason as LIVE, we ignore the low water line when the VOD
- // duration is below the max potential low water line
-
- if (duration < maxBufferLowWaterLine) {
- log(sharedLogLine + " as duration < max low water line (" + duration + " < " + maxBufferLowWaterLine + ")");
- return true;
- }
-
- var nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
- var currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
- // we can switch down
-
- if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
- var logLine = sharedLogLine + " as next bandwidth < current bandwidth (" + nextBandwidth + " < " + currBandwidth + ")";
-
- if (experimentalBufferBasedABR) {
- logLine += " and forwardBuffer < bufferHighWaterLine (" + forwardBuffer + " < " + bufferHighWaterLine + ")";
- }
-
- log(logLine);
- return true;
- } // and if our buffer is higher than the low water line,
- // we can switch up
-
-
- if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
- var _logLine = sharedLogLine + " as forwardBuffer >= bufferLowWaterLine (" + forwardBuffer + " >= " + bufferLowWaterLine + ")";
-
- if (experimentalBufferBasedABR) {
- _logLine += " and next bandwidth > current bandwidth (" + nextBandwidth + " > " + currBandwidth + ")";
- }
-
- log(_logLine);
- return true;
- }
-
- log("not " + sharedLogLine + " as no switching criteria met");
- return false;
-};
-/**
- * the master playlist controller controller all interactons
- * between playlists and segmentloaders. At this time this mainly
- * involves a master playlist and a series of audio playlists
- * if they are available
- *
- * @class MasterPlaylistController
- * @extends videojs.EventTarget
- */
-
-
-var MasterPlaylistController = /*#__PURE__*/function (_videojs$EventTarget) {
- _inheritsLoose(MasterPlaylistController, _videojs$EventTarget);
-
- function MasterPlaylistController(options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- var src = options.src,
- handleManifestRedirects = options.handleManifestRedirects,
- withCredentials = options.withCredentials,
- tech = options.tech,
- bandwidth = options.bandwidth,
- externVhs = options.externVhs,
- useCueTags = options.useCueTags,
- blacklistDuration = options.blacklistDuration,
- enableLowInitialPlaylist = options.enableLowInitialPlaylist,
- sourceType = options.sourceType,
- cacheEncryptionKeys = options.cacheEncryptionKeys,
- experimentalBufferBasedABR = options.experimentalBufferBasedABR;
-
- if (!src) {
- throw new Error('A non-empty playlist URL or JSON manifest string is required');
- }
-
- var maxPlaylistRetries = options.maxPlaylistRetries;
-
- if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
- maxPlaylistRetries = Infinity;
- }
-
- Vhs$1 = externVhs;
- _this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
- _this.withCredentials = withCredentials;
- _this.tech_ = tech;
- _this.vhs_ = tech.vhs;
- _this.sourceType_ = sourceType;
- _this.useCueTags_ = useCueTags;
- _this.blacklistDuration = blacklistDuration;
- _this.maxPlaylistRetries = maxPlaylistRetries;
- _this.enableLowInitialPlaylist = enableLowInitialPlaylist;
-
- if (_this.useCueTags_) {
- _this.cueTagsTrack_ = _this.tech_.addTextTrack('metadata', 'ad-cues');
- _this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
- }
-
- _this.requestOptions_ = {
- withCredentials: withCredentials,
- handleManifestRedirects: handleManifestRedirects,
- maxPlaylistRetries: maxPlaylistRetries,
- timeout: null
- };
-
- _this.on('error', _this.pauseLoading);
-
- _this.mediaTypes_ = createMediaTypes();
- _this.mediaSource = new window.MediaSource();
- _this.handleDurationChange_ = _this.handleDurationChange_.bind(_assertThisInitialized(_this));
- _this.handleSourceOpen_ = _this.handleSourceOpen_.bind(_assertThisInitialized(_this));
- _this.handleSourceEnded_ = _this.handleSourceEnded_.bind(_assertThisInitialized(_this));
-
- _this.mediaSource.addEventListener('durationchange', _this.handleDurationChange_); // load the media source into the player
-
-
- _this.mediaSource.addEventListener('sourceopen', _this.handleSourceOpen_);
-
- _this.mediaSource.addEventListener('sourceended', _this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
- // everything, and the MediaSource should not be detached without a proper disposal
-
-
- _this.seekable_ = videojs.createTimeRanges();
- _this.hasPlayed_ = false;
- _this.syncController_ = new SyncController(options);
- _this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'segment-metadata'
- }, false).track;
- _this.decrypter_ = new Decrypter();
- _this.sourceUpdater_ = new SourceUpdater(_this.mediaSource);
- _this.inbandTextTracks_ = {};
- _this.timelineChangeController_ = new TimelineChangeController();
- var segmentLoaderSettings = {
- vhs: _this.vhs_,
- parse708captions: options.parse708captions,
- mediaSource: _this.mediaSource,
- currentTime: _this.tech_.currentTime.bind(_this.tech_),
- seekable: function seekable() {
- return _this.seekable();
- },
- seeking: function seeking() {
- return _this.tech_.seeking();
- },
- duration: function duration() {
- return _this.duration();
- },
- hasPlayed: function hasPlayed() {
- return _this.hasPlayed_;
- },
- goalBufferLength: function goalBufferLength() {
- return _this.goalBufferLength();
- },
- bandwidth: bandwidth,
- syncController: _this.syncController_,
- decrypter: _this.decrypter_,
- sourceType: _this.sourceType_,
- inbandTextTracks: _this.inbandTextTracks_,
- cacheEncryptionKeys: cacheEncryptionKeys,
- sourceUpdater: _this.sourceUpdater_,
- timelineChangeController: _this.timelineChangeController_
- }; // The source type check not only determines whether a special DASH playlist loader
- // should be used, but also covers the case where the provided src is a vhs-json
- // manifest object (instead of a URL). In the case of vhs-json, the default
- // PlaylistLoader should be used.
-
- _this.masterPlaylistLoader_ = _this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, _this.vhs_, _this.requestOptions_) : new PlaylistLoader(src, _this.vhs_, _this.requestOptions_);
-
- _this.setupMasterPlaylistLoaderListeners_(); // setup segment loaders
- // combined audio/video or just video when alternate audio track is selected
-
-
- _this.mainSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
- segmentMetadataTrack: _this.segmentMetadataTrack_,
- loaderType: 'main'
- }), options); // alternate audio track
-
- _this.audioSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
- loaderType: 'audio'
- }), options);
- _this.subtitleSegmentLoader_ = new VTTSegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
- loaderType: 'vtt',
- featuresNativeTextTracks: _this.tech_.featuresNativeTextTracks
- }), options);
-
- _this.setupSegmentLoaderListeners_();
-
- if (_this.experimentalBufferBasedABR) {
- _this.masterPlaylistLoader_.one('loadedplaylist', function () {
- return _this.startABRTimer_();
- });
-
- _this.tech_.on('pause', function () {
- return _this.stopABRTimer_();
- });
-
- _this.tech_.on('play', function () {
- return _this.startABRTimer_();
- });
- } // Create SegmentLoader stat-getters
- // mediaRequests_
- // mediaRequestsAborted_
- // mediaRequestsTimedout_
- // mediaRequestsErrored_
- // mediaTransferDuration_
- // mediaBytesTransferred_
- // mediaAppends_
-
-
- loaderStats.forEach(function (stat) {
- _this[stat + '_'] = sumLoaderStat.bind(_assertThisInitialized(_this), stat);
- });
- _this.logger_ = logger('MPC');
- _this.triggeredFmp4Usage = false;
-
- if (_this.tech_.preload() === 'none') {
- _this.loadOnPlay_ = function () {
- _this.loadOnPlay_ = null;
-
- _this.masterPlaylistLoader_.load();
- };
-
- _this.tech_.one('play', _this.loadOnPlay_);
- } else {
- _this.masterPlaylistLoader_.load();
- }
-
- _this.timeToLoadedData__ = -1;
- _this.mainAppendsToLoadedData__ = -1;
- _this.audioAppendsToLoadedData__ = -1;
- var event = _this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
-
- _this.tech_.one(event, function () {
- var timeToLoadedDataStart = Date.now();
-
- _this.tech_.one('loadeddata', function () {
- _this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
- _this.mainAppendsToLoadedData__ = _this.mainSegmentLoader_.mediaAppends;
- _this.audioAppendsToLoadedData__ = _this.audioSegmentLoader_.mediaAppends;
- });
- });
-
- return _this;
- }
-
- var _proto = MasterPlaylistController.prototype;
-
- _proto.mainAppendsToLoadedData_ = function mainAppendsToLoadedData_() {
- return this.mainAppendsToLoadedData__;
- };
-
- _proto.audioAppendsToLoadedData_ = function audioAppendsToLoadedData_() {
- return this.audioAppendsToLoadedData__;
- };
-
- _proto.appendsToLoadedData_ = function appendsToLoadedData_() {
- var main = this.mainAppendsToLoadedData_();
- var audio = this.audioAppendsToLoadedData_();
-
- if (main === -1 || audio === -1) {
- return -1;
- }
-
- return main + audio;
- };
-
- _proto.timeToLoadedData_ = function timeToLoadedData_() {
- return this.timeToLoadedData__;
- }
- /**
- * Run selectPlaylist and switch to the new playlist if we should
- *
- * @private
- *
- */
- ;
-
- _proto.checkABR_ = function checkABR_() {
- var nextPlaylist = this.selectPlaylist();
-
- if (this.shouldSwitchToMedia_(nextPlaylist)) {
- this.switchMedia_(nextPlaylist, 'abr');
- }
- };
-
- _proto.switchMedia_ = function switchMedia_(playlist, cause, delay) {
- var oldMedia = this.media();
- var oldId = oldMedia && (oldMedia.id || oldMedia.uri);
- var newId = playlist.id || playlist.uri;
-
- if (oldId && oldId !== newId) {
- this.logger_("switch media " + oldId + " -> " + newId + " from " + cause);
- this.tech_.trigger({
- type: 'usage',
- name: "vhs-rendition-change-" + cause
- });
- }
-
- this.masterPlaylistLoader_.media(playlist, delay);
- }
- /**
- * Start a timer that periodically calls checkABR_
- *
- * @private
- */
- ;
-
- _proto.startABRTimer_ = function startABRTimer_() {
- var _this2 = this;
-
- this.stopABRTimer_();
- this.abrTimer_ = window.setInterval(function () {
- return _this2.checkABR_();
- }, 250);
- }
- /**
- * Stop the timer that periodically calls checkABR_
- *
- * @private
- */
- ;
-
- _proto.stopABRTimer_ = function stopABRTimer_() {
- // if we're scrubbing, we don't need to pause.
- // This getter will be added to Video.js in version 7.11.
- if (this.tech_.scrubbing && this.tech_.scrubbing()) {
- return;
- }
-
- window.clearInterval(this.abrTimer_);
- this.abrTimer_ = null;
- }
- /**
- * Get a list of playlists for the currently selected audio playlist
- *
- * @return {Array} the array of audio playlists
- */
- ;
-
- _proto.getAudioTrackPlaylists_ = function getAudioTrackPlaylists_() {
- var master = this.master(); // if we don't have any audio groups then we can only
- // assume that the audio tracks are contained in masters
- // playlist array, use that or an empty array.
-
- if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
- return master && master.playlists || [];
- }
-
- var AUDIO = master.mediaGroups.AUDIO;
- var groupKeys = Object.keys(AUDIO);
- var track; // get the current active track
-
- if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
- track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from master if mediaTypes_ isn't setup yet
- } else {
- // default group is `main` or just the first group.
- var defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
-
- for (var label in defaultGroup) {
- if (defaultGroup[label].default) {
- track = {
- label: label
- };
- break;
- }
- }
- } // no active track no playlists.
-
-
- if (!track) {
- return [];
- }
-
- var playlists = []; // get all of the playlists that are possible for the
- // active track.
-
- for (var group in AUDIO) {
- if (AUDIO[group][track.label]) {
- var properties = AUDIO[group][track.label];
-
- if (properties.playlists) {
- playlists.push.apply(playlists, properties.playlists);
- } else {
- playlists.push(properties);
- }
- }
- }
-
- return playlists;
- }
- /**
- * Register event handlers on the master playlist loader. A helper
- * function for construction time.
- *
- * @private
- */
- ;
-
- _proto.setupMasterPlaylistLoaderListeners_ = function setupMasterPlaylistLoaderListeners_() {
- var _this3 = this;
-
- this.masterPlaylistLoader_.on('loadedmetadata', function () {
- var media = _this3.masterPlaylistLoader_.media();
-
- var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
- // timeout the request.
-
- if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
- _this3.requestOptions_.timeout = 0;
- } else {
- _this3.requestOptions_.timeout = requestTimeout;
- } // if this isn't a live video and preload permits, start
- // downloading segments
-
-
- if (media.endList && _this3.tech_.preload() !== 'none') {
- _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
-
- _this3.mainSegmentLoader_.load();
- }
-
- setupMediaGroups({
- sourceType: _this3.sourceType_,
- segmentLoaders: {
- AUDIO: _this3.audioSegmentLoader_,
- SUBTITLES: _this3.subtitleSegmentLoader_,
- main: _this3.mainSegmentLoader_
- },
- tech: _this3.tech_,
- requestOptions: _this3.requestOptions_,
- masterPlaylistLoader: _this3.masterPlaylistLoader_,
- vhs: _this3.vhs_,
- master: _this3.master(),
- mediaTypes: _this3.mediaTypes_,
- blacklistCurrentPlaylist: _this3.blacklistCurrentPlaylist.bind(_this3)
- });
-
- _this3.triggerPresenceUsage_(_this3.master(), media);
-
- _this3.setupFirstPlay();
-
- if (!_this3.mediaTypes_.AUDIO.activePlaylistLoader || _this3.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
- _this3.trigger('selectedinitialmedia');
- } else {
- // We must wait for the active audio playlist loader to
- // finish setting up before triggering this event so the
- // representations API and EME setup is correct
- _this3.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', function () {
- _this3.trigger('selectedinitialmedia');
- });
- }
- });
- this.masterPlaylistLoader_.on('loadedplaylist', function () {
- if (_this3.loadOnPlay_) {
- _this3.tech_.off('play', _this3.loadOnPlay_);
- }
-
- var updatedPlaylist = _this3.masterPlaylistLoader_.media();
-
- if (!updatedPlaylist) {
- // exclude any variants that are not supported by the browser before selecting
- // an initial media as the playlist selectors do not consider browser support
- _this3.excludeUnsupportedVariants_();
-
- var selectedMedia;
-
- if (_this3.enableLowInitialPlaylist) {
- selectedMedia = _this3.selectInitialPlaylist();
- }
-
- if (!selectedMedia) {
- selectedMedia = _this3.selectPlaylist();
- }
-
- if (!selectedMedia || !_this3.shouldSwitchToMedia_(selectedMedia)) {
- return;
- }
-
- _this3.initialMedia_ = selectedMedia;
-
- _this3.switchMedia_(_this3.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
- // fire again since the playlist will be requested. In the case of vhs-json
- // (where the manifest object is provided as the source), when the media
- // playlist's `segments` list is already available, a media playlist won't be
- // requested, and loadedplaylist won't fire again, so the playlist handler must be
- // called on its own here.
-
-
- var haveJsonSource = _this3.sourceType_ === 'vhs-json' && _this3.initialMedia_.segments;
-
- if (!haveJsonSource) {
- return;
- }
-
- updatedPlaylist = _this3.initialMedia_;
- }
-
- _this3.handleUpdatedMediaPlaylist(updatedPlaylist);
- });
- this.masterPlaylistLoader_.on('error', function () {
- _this3.blacklistCurrentPlaylist(_this3.masterPlaylistLoader_.error);
- });
- this.masterPlaylistLoader_.on('mediachanging', function () {
- _this3.mainSegmentLoader_.abort();
-
- _this3.mainSegmentLoader_.pause();
- });
- this.masterPlaylistLoader_.on('mediachange', function () {
- var media = _this3.masterPlaylistLoader_.media();
-
- var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
- // timeout the request.
-
- if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
- _this3.requestOptions_.timeout = 0;
- } else {
- _this3.requestOptions_.timeout = requestTimeout;
- } // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `loadedplaylist`
-
-
- _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
-
- _this3.mainSegmentLoader_.load();
-
- _this3.tech_.trigger({
- type: 'mediachange',
- bubbles: true
- });
- });
- this.masterPlaylistLoader_.on('playlistunchanged', function () {
- var updatedPlaylist = _this3.masterPlaylistLoader_.media(); // ignore unchanged playlists that have already been
- // excluded for not-changing. We likely just have a really slowly updating
- // playlist.
-
-
- if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
- return;
- }
-
- var playlistOutdated = _this3.stuckAtPlaylistEnd_(updatedPlaylist);
-
- if (playlistOutdated) {
- // Playlist has stopped updating and we're stuck at its end. Try to
- // blacklist it and switch to another playlist in the hope that that
- // one is updating (and give the player a chance to re-adjust to the
- // safe live point).
- _this3.blacklistCurrentPlaylist({
- message: 'Playlist no longer updating.',
- reason: 'playlist-unchanged'
- }); // useful for monitoring QoS
-
-
- _this3.tech_.trigger('playliststuck');
- }
- });
- this.masterPlaylistLoader_.on('renditiondisabled', function () {
- _this3.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-disabled'
- });
-
- _this3.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-disabled'
- });
- });
- this.masterPlaylistLoader_.on('renditionenabled', function () {
- _this3.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-enabled'
- });
-
- _this3.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-enabled'
- });
- });
- }
- /**
- * Given an updated media playlist (whether it was loaded for the first time, or
- * refreshed for live playlists), update any relevant properties and state to reflect
- * changes in the media that should be accounted for (e.g., cues and duration).
- *
- * @param {Object} updatedPlaylist the updated media playlist object
- *
- * @private
- */
- ;
-
- _proto.handleUpdatedMediaPlaylist = function handleUpdatedMediaPlaylist(updatedPlaylist) {
- if (this.useCueTags_) {
- this.updateAdCues_(updatedPlaylist);
- } // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `mediachange`
-
-
- this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
- this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
- // as it is possible that it was temporarily stopped while waiting for
- // a playlist (e.g., in case the playlist errored and we re-requested it).
-
- if (!this.tech_.paused()) {
- this.mainSegmentLoader_.load();
-
- if (this.audioSegmentLoader_) {
- this.audioSegmentLoader_.load();
- }
- }
- }
- /**
- * A helper function for triggerring presence usage events once per source
- *
- * @private
- */
- ;
-
- _proto.triggerPresenceUsage_ = function triggerPresenceUsage_(master, media) {
- var mediaGroups = master.mediaGroups || {};
- var defaultDemuxed = true;
- var audioGroupKeys = Object.keys(mediaGroups.AUDIO);
-
- for (var mediaGroup in mediaGroups.AUDIO) {
- for (var label in mediaGroups.AUDIO[mediaGroup]) {
- var properties = mediaGroups.AUDIO[mediaGroup][label];
-
- if (!properties.uri) {
- defaultDemuxed = false;
- }
- }
- }
-
- if (defaultDemuxed) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-demuxed'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-demuxed'
- });
- }
-
- if (Object.keys(mediaGroups.SUBTITLES).length) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-webvtt'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-webvtt'
- });
- }
-
- if (Vhs$1.Playlist.isAes(media)) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-aes'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-aes'
- });
- }
-
- if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-alternate-audio'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-alternate-audio'
- });
- }
-
- if (this.useCueTags_) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-playlist-cue-tags'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-playlist-cue-tags'
- });
- }
- };
-
- _proto.shouldSwitchToMedia_ = function shouldSwitchToMedia_(nextPlaylist) {
- var currentPlaylist = this.masterPlaylistLoader_.media();
- var buffered = this.tech_.buffered();
- var forwardBuffer = buffered.length ? buffered.end(buffered.length - 1) - this.tech_.currentTime() : 0;
- var bufferLowWaterLine = this.bufferLowWaterLine();
- var bufferHighWaterLine = this.bufferHighWaterLine();
- return shouldSwitchToMedia({
- currentPlaylist: currentPlaylist,
- nextPlaylist: nextPlaylist,
- forwardBuffer: forwardBuffer,
- bufferLowWaterLine: bufferLowWaterLine,
- bufferHighWaterLine: bufferHighWaterLine,
- duration: this.duration(),
- experimentalBufferBasedABR: this.experimentalBufferBasedABR,
- log: this.logger_
- });
- }
- /**
- * Register event handlers on the segment loaders. A helper function
- * for construction time.
- *
- * @private
- */
- ;
-
- _proto.setupSegmentLoaderListeners_ = function setupSegmentLoaderListeners_() {
- var _this4 = this;
-
- if (!this.experimentalBufferBasedABR) {
- this.mainSegmentLoader_.on('bandwidthupdate', function () {
- var nextPlaylist = _this4.selectPlaylist();
-
- if (_this4.shouldSwitchToMedia_(nextPlaylist)) {
- _this4.switchMedia_(nextPlaylist, 'bandwidthupdate');
- }
-
- _this4.tech_.trigger('bandwidthupdate');
- });
- this.mainSegmentLoader_.on('progress', function () {
- _this4.trigger('progress');
- });
- }
-
- this.mainSegmentLoader_.on('error', function () {
- _this4.blacklistCurrentPlaylist(_this4.mainSegmentLoader_.error());
- });
- this.mainSegmentLoader_.on('appenderror', function () {
- _this4.error = _this4.mainSegmentLoader_.error_;
-
- _this4.trigger('error');
- });
- this.mainSegmentLoader_.on('syncinfoupdate', function () {
- _this4.onSyncInfoUpdate_();
- });
- this.mainSegmentLoader_.on('timestampoffset', function () {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-timestamp-offset'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-timestamp-offset'
- });
- });
- this.audioSegmentLoader_.on('syncinfoupdate', function () {
- _this4.onSyncInfoUpdate_();
- });
- this.audioSegmentLoader_.on('appenderror', function () {
- _this4.error = _this4.audioSegmentLoader_.error_;
-
- _this4.trigger('error');
- });
- this.mainSegmentLoader_.on('ended', function () {
- _this4.logger_('main segment loader ended');
-
- _this4.onEndOfStream();
- });
- this.mainSegmentLoader_.on('earlyabort', function (event) {
- // never try to early abort with the new ABR algorithm
- if (_this4.experimentalBufferBasedABR) {
- return;
- }
-
- _this4.delegateLoaders_('all', ['abort']);
-
- _this4.blacklistCurrentPlaylist({
- message: 'Aborted early because there isn\'t enough bandwidth to complete the ' + 'request without rebuffering.'
- }, ABORT_EARLY_BLACKLIST_SECONDS);
- });
-
- var updateCodecs = function updateCodecs() {
- if (!_this4.sourceUpdater_.hasCreatedSourceBuffers()) {
- return _this4.tryToCreateSourceBuffers_();
- }
-
- var codecs = _this4.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
-
-
- if (!codecs) {
- return;
- }
-
- _this4.sourceUpdater_.addOrChangeSourceBuffers(codecs);
- };
-
- this.mainSegmentLoader_.on('trackinfo', updateCodecs);
- this.audioSegmentLoader_.on('trackinfo', updateCodecs);
- this.mainSegmentLoader_.on('fmp4', function () {
- if (!_this4.triggeredFmp4Usage) {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-fmp4'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-fmp4'
- });
-
- _this4.triggeredFmp4Usage = true;
- }
- });
- this.audioSegmentLoader_.on('fmp4', function () {
- if (!_this4.triggeredFmp4Usage) {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-fmp4'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-fmp4'
- });
-
- _this4.triggeredFmp4Usage = true;
- }
- });
- this.audioSegmentLoader_.on('ended', function () {
- _this4.logger_('audioSegmentLoader ended');
-
- _this4.onEndOfStream();
- });
- };
-
- _proto.mediaSecondsLoaded_ = function mediaSecondsLoaded_() {
- return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
- }
- /**
- * Call load on our SegmentLoaders
- */
- ;
-
- _proto.load = function load() {
- this.mainSegmentLoader_.load();
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.load();
- }
-
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.load();
- }
- }
- /**
- * Re-tune playback quality level for the current player
- * conditions without performing destructive actions, like
- * removing already buffered content
- *
- * @private
- * @deprecated
- */
- ;
-
- _proto.smoothQualityChange_ = function smoothQualityChange_(media) {
- if (media === void 0) {
- media = this.selectPlaylist();
- }
-
- this.fastQualityChange_(media);
- }
- /**
- * Re-tune playback quality level for the current player
- * conditions. This method will perform destructive actions like removing
- * already buffered content in order to readjust the currently active
- * playlist quickly. This is good for manual quality changes
- *
- * @private
- */
- ;
-
- _proto.fastQualityChange_ = function fastQualityChange_(media) {
- var _this5 = this;
-
- if (media === void 0) {
- media = this.selectPlaylist();
- }
-
- if (media === this.masterPlaylistLoader_.media()) {
- this.logger_('skipping fastQualityChange because new media is same as old');
- return;
- }
-
- this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
- // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
- // ahead is roughly the minimum that will accomplish this across a variety of content
- // in IE and Edge, but seeking in place is sufficient on all other browsers)
- // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
- // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
-
- this.mainSegmentLoader_.resetEverything(function () {
- // Since this is not a typical seek, we avoid the seekTo method which can cause segments
- // from the previously enabled rendition to load before the new playlist has finished loading
- if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
- _this5.tech_.setCurrentTime(_this5.tech_.currentTime() + 0.04);
- } else {
- _this5.tech_.setCurrentTime(_this5.tech_.currentTime());
- }
- }); // don't need to reset audio as it is reset when media changes
- }
- /**
- * Begin playback.
- */
- ;
-
- _proto.play = function play() {
- if (this.setupFirstPlay()) {
- return;
- }
-
- if (this.tech_.ended()) {
- this.tech_.setCurrentTime(0);
- }
-
- if (this.hasPlayed_) {
- this.load();
- }
-
- var seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
- // seek forward to the live point
-
- if (this.tech_.duration() === Infinity) {
- if (this.tech_.currentTime() < seekable.start(0)) {
- return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
- }
- }
- }
- /**
- * Seek to the latest media position if this is a live video and the
- * player and video are loaded and initialized.
- */
- ;
-
- _proto.setupFirstPlay = function setupFirstPlay() {
- var _this6 = this;
-
- var media = this.masterPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
- // If 1) there is no active media
- // 2) the player is paused
- // 3) the first play has already been setup
- // then exit early
-
- if (!media || this.tech_.paused() || this.hasPlayed_) {
- return false;
- } // when the video is a live stream
-
-
- if (!media.endList) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- // without a seekable range, the player cannot seek to begin buffering at the live
- // point
- return false;
- }
-
- if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
- // IE11 throws an InvalidStateError if you try to set currentTime while the
- // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
- this.tech_.one('loadedmetadata', function () {
- _this6.trigger('firstplay');
-
- _this6.tech_.setCurrentTime(seekable.end(0));
-
- _this6.hasPlayed_ = true;
- });
- return false;
- } // trigger firstplay to inform the source handler to ignore the next seek event
-
-
- this.trigger('firstplay'); // seek to the live point
-
- this.tech_.setCurrentTime(seekable.end(0));
- }
-
- this.hasPlayed_ = true; // we can begin loading now that everything is ready
-
- this.load();
- return true;
- }
- /**
- * handle the sourceopen event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleSourceOpen_ = function handleSourceOpen_() {
- // Only attempt to create the source buffer if none already exist.
- // handleSourceOpen is also called when we are "re-opening" a source buffer
- // after `endOfStream` has been called (in response to a seek for instance)
- this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
- // code in video.js but is required because play() must be invoked
- // *after* the media source has opened.
-
- if (this.tech_.autoplay()) {
- var playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
- // on browsers which return a promise
-
- if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
- playPromise.then(null, function (e) {});
- }
- }
-
- this.trigger('sourceopen');
- }
- /**
- * handle the sourceended event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleSourceEnded_ = function handleSourceEnded_() {
- if (!this.inbandTextTracks_.metadataTrack_) {
- return;
- }
-
- var cues = this.inbandTextTracks_.metadataTrack_.cues;
-
- if (!cues || !cues.length) {
- return;
- }
-
- var duration = this.duration();
- cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
- }
- /**
- * handle the durationchange event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleDurationChange_ = function handleDurationChange_() {
- this.tech_.trigger('durationchange');
- }
- /**
- * Calls endOfStream on the media source when all active stream types have called
- * endOfStream
- *
- * @param {string} streamType
- * Stream type of the segment loader that called endOfStream
- * @private
- */
- ;
-
- _proto.onEndOfStream = function onEndOfStream() {
- var isEndOfStream = this.mainSegmentLoader_.ended_;
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- // if the audio playlist loader exists, then alternate audio is active
- if (!this.mainSegmentLoader_.currentMediaInfo_ || this.mainSegmentLoader_.currentMediaInfo_.hasVideo) {
- // if we do not know if the main segment loader contains video yet or if we
- // definitively know the main segment loader contains video, then we need to wait
- // for both main and audio segment loaders to call endOfStream
- isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
- } else {
- // otherwise just rely on the audio loader
- isEndOfStream = this.audioSegmentLoader_.ended_;
- }
- }
-
- if (!isEndOfStream) {
- return;
- }
-
- this.stopABRTimer_();
- this.sourceUpdater_.endOfStream();
- }
- /**
- * Check if a playlist has stopped being updated
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist has stopped being updated or not
- */
- ;
-
- _proto.stuckAtPlaylistEnd_ = function stuckAtPlaylistEnd_(playlist) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- // playlist doesn't have enough information to determine whether we are stuck
- return false;
- }
-
- var expired = this.syncController_.getExpiredTime(playlist, this.duration());
-
- if (expired === null) {
- return false;
- } // does not use the safe live end to calculate playlist end, since we
- // don't want to say we are stuck while there is still content
-
-
- var absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
-
- if (!buffered.length) {
- // return true if the playhead reached the absolute end of the playlist
- return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
- }
-
- var bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
- // end of playlist
-
- return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
- }
- /**
- * Blacklists a playlist when an error occurs for a set amount of time
- * making it unavailable for selection by the rendition selection algorithm
- * and then forces a new playlist (rendition) selection.
- *
- * @param {Object=} error an optional error that may include the playlist
- * to blacklist
- * @param {number=} blacklistDuration an optional number of seconds to blacklist the
- * playlist
- */
- ;
-
- _proto.blacklistCurrentPlaylist = function blacklistCurrentPlaylist(error, blacklistDuration) {
- if (error === void 0) {
- error = {};
- }
-
- // If the `error` was generated by the playlist loader, it will contain
- // the playlist we were trying to load (but failed) and that should be
- // blacklisted instead of the currently selected playlist which is likely
- // out-of-date in this scenario
- var currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
- blacklistDuration = blacklistDuration || error.blacklistDuration || this.blacklistDuration; // If there is no current playlist, then an error occurred while we were
- // trying to load the master OR while we were disposing of the tech
-
- if (!currentPlaylist) {
- this.error = error;
-
- if (this.mediaSource.readyState !== 'open') {
- this.trigger('error');
- } else {
- this.sourceUpdater_.endOfStream('network');
- }
-
- return;
- }
-
- currentPlaylist.playlistErrors_++;
- var playlists = this.masterPlaylistLoader_.master.playlists;
- var enabledPlaylists = playlists.filter(isEnabled);
- var isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === currentPlaylist; // Don't blacklist the only playlist unless it was blacklisted
- // forever
-
- if (playlists.length === 1 && blacklistDuration !== Infinity) {
- videojs.log.warn("Problem encountered with playlist " + currentPlaylist.id + ". " + 'Trying again since it is the only playlist.');
- this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
-
- return this.masterPlaylistLoader_.load(isFinalRendition);
- }
-
- if (isFinalRendition) {
- // Since we're on the final non-blacklisted playlist, and we're about to blacklist
- // it, instead of erring the player or retrying this playlist, clear out the current
- // blacklist. This allows other playlists to be attempted in case any have been
- // fixed.
- var reincluded = false;
- playlists.forEach(function (playlist) {
- // skip current playlist which is about to be blacklisted
- if (playlist === currentPlaylist) {
- return;
- }
-
- var excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
-
- if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
- reincluded = true;
- delete playlist.excludeUntil;
- }
- });
-
- if (reincluded) {
- videojs.log.warn('Removing other playlists from the exclusion list because the last ' + 'rendition is about to be excluded.'); // Technically we are retrying a playlist, in that we are simply retrying a previous
- // playlist. This is needed for users relying on the retryplaylist event to catch a
- // case where the player might be stuck and looping through "dead" playlists.
-
- this.tech_.trigger('retryplaylist');
- }
- } // Blacklist this playlist
-
-
- var excludeUntil;
-
- if (currentPlaylist.playlistErrors_ > this.maxPlaylistRetries) {
- excludeUntil = Infinity;
- } else {
- excludeUntil = Date.now() + blacklistDuration * 1000;
- }
-
- currentPlaylist.excludeUntil = excludeUntil;
-
- if (error.reason) {
- currentPlaylist.lastExcludeReason_ = error.reason;
- }
-
- this.tech_.trigger('blacklistplaylist');
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-blacklisted'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-blacklisted'
- }); // TODO: should we select a new playlist if this blacklist wasn't for the currentPlaylist?
- // Would be something like media().id !=== currentPlaylist.id and we would need something
- // like `pendingMedia` in playlist loaders to check against that too. This will prevent us
- // from loading a new playlist on any blacklist.
- // Select a new playlist
-
- var nextPlaylist = this.selectPlaylist();
-
- if (!nextPlaylist) {
- this.error = 'Playback cannot continue. No available working or supported playlists.';
- this.trigger('error');
- return;
- }
-
- var logFn = error.internal ? this.logger_ : videojs.log.warn;
- var errorMessage = error.message ? ' ' + error.message : '';
- logFn((error.internal ? 'Internal problem' : 'Problem') + " encountered with playlist " + currentPlaylist.id + "." + (errorMessage + " Switching to playlist " + nextPlaylist.id + ".")); // if audio group changed reset audio loaders
-
- if (nextPlaylist.attributes.AUDIO !== currentPlaylist.attributes.AUDIO) {
- this.delegateLoaders_('audio', ['abort', 'pause']);
- } // if subtitle group changed reset subtitle loaders
-
-
- if (nextPlaylist.attributes.SUBTITLES !== currentPlaylist.attributes.SUBTITLES) {
- this.delegateLoaders_('subtitle', ['abort', 'pause']);
- }
-
- this.delegateLoaders_('main', ['abort', 'pause']);
- var delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
- var shouldDelay = typeof nextPlaylist.lastRequest === 'number' && Date.now() - nextPlaylist.lastRequest <= delayDuration; // delay if it's a final rendition or if the last refresh is sooner than half targetDuration
-
- return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
- }
- /**
- * Pause all segment/playlist loaders
- */
- ;
-
- _proto.pauseLoading = function pauseLoading() {
- this.delegateLoaders_('all', ['abort', 'pause']);
- this.stopABRTimer_();
- }
- /**
- * Call a set of functions in order on playlist loaders, segment loaders,
- * or both types of loaders.
- *
- * @param {string} filter
- * Filter loaders that should call fnNames using a string. Can be:
- * * all - run on all loaders
- * * audio - run on all audio loaders
- * * subtitle - run on all subtitle loaders
- * * main - run on the main/master loaders
- *
- * @param {Array|string} fnNames
- * A string or array of function names to call.
- */
- ;
-
- _proto.delegateLoaders_ = function delegateLoaders_(filter, fnNames) {
- var _this7 = this;
-
- var loaders = [];
- var dontFilterPlaylist = filter === 'all';
-
- if (dontFilterPlaylist || filter === 'main') {
- loaders.push(this.masterPlaylistLoader_);
- }
-
- var mediaTypes = [];
-
- if (dontFilterPlaylist || filter === 'audio') {
- mediaTypes.push('AUDIO');
- }
-
- if (dontFilterPlaylist || filter === 'subtitle') {
- mediaTypes.push('CLOSED-CAPTIONS');
- mediaTypes.push('SUBTITLES');
- }
-
- mediaTypes.forEach(function (mediaType) {
- var loader = _this7.mediaTypes_[mediaType] && _this7.mediaTypes_[mediaType].activePlaylistLoader;
-
- if (loader) {
- loaders.push(loader);
- }
- });
- ['main', 'audio', 'subtitle'].forEach(function (name) {
- var loader = _this7[name + "SegmentLoader_"];
-
- if (loader && (filter === name || filter === 'all')) {
- loaders.push(loader);
- }
- });
- loaders.forEach(function (loader) {
- return fnNames.forEach(function (fnName) {
- if (typeof loader[fnName] === 'function') {
- loader[fnName]();
- }
- });
- });
- }
- /**
- * set the current time on all segment loaders
- *
- * @param {TimeRange} currentTime the current time to set
- * @return {TimeRange} the current time
- */
- ;
-
- _proto.setCurrentTime = function setCurrentTime(currentTime) {
- var buffered = findRange(this.tech_.buffered(), currentTime);
-
- if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
- // return immediately if the metadata is not ready yet
- return 0;
- } // it's clearly an edge-case but don't thrown an error if asked to
- // seek within an empty playlist
-
-
- if (!this.masterPlaylistLoader_.media().segments) {
- return 0;
- } // if the seek location is already buffered, continue buffering as usual
-
-
- if (buffered && buffered.length) {
- return currentTime;
- } // cancel outstanding requests so we begin buffering at the new
- // location
-
-
- this.mainSegmentLoader_.resetEverything();
- this.mainSegmentLoader_.abort();
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.resetEverything();
- this.audioSegmentLoader_.abort();
- }
-
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.resetEverything();
- this.subtitleSegmentLoader_.abort();
- } // start segment loader loading in case they are paused
-
-
- this.load();
- }
- /**
- * get the current duration
- *
- * @return {TimeRange} the duration
- */
- ;
-
- _proto.duration = function duration() {
- if (!this.masterPlaylistLoader_) {
- return 0;
- }
-
- var media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- // no playlists loaded yet, so can't determine a duration
- return 0;
- } // Don't rely on the media source for duration in the case of a live playlist since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, just return Infinity.
-
-
- if (!media.endList) {
- return Infinity;
- } // Since this is a VOD video, it is safe to rely on the media source's duration (if
- // available). If it's not available, fall back to a playlist-calculated estimate.
-
-
- if (this.mediaSource) {
- return this.mediaSource.duration;
- }
-
- return Vhs$1.Playlist.duration(media);
- }
- /**
- * check the seekable range
- *
- * @return {TimeRange} the seekable range
- */
- ;
-
- _proto.seekable = function seekable() {
- return this.seekable_;
- };
-
- _proto.onSyncInfoUpdate_ = function onSyncInfoUpdate_() {
- var audioSeekable;
-
- if (!this.masterPlaylistLoader_) {
- return;
- }
-
- var media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- return;
- }
-
- var expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- // not enough information to update seekable
- return;
- }
-
- var master = this.masterPlaylistLoader_.master;
- var mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
-
- if (mainSeekable.length === 0) {
- return;
- }
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
- expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- return;
- }
-
- audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
-
- if (audioSeekable.length === 0) {
- return;
- }
- }
-
- var oldEnd;
- var oldStart;
-
- if (this.seekable_ && this.seekable_.length) {
- oldEnd = this.seekable_.end(0);
- oldStart = this.seekable_.start(0);
- }
-
- if (!audioSeekable) {
- // seekable has been calculated based on buffering video data so it
- // can be returned directly
- this.seekable_ = mainSeekable;
- } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
- // seekables are pretty far off, rely on main
- this.seekable_ = mainSeekable;
- } else {
- this.seekable_ = videojs.createTimeRanges([[audioSeekable.start(0) > mainSeekable.start(0) ? audioSeekable.start(0) : mainSeekable.start(0), audioSeekable.end(0) < mainSeekable.end(0) ? audioSeekable.end(0) : mainSeekable.end(0)]]);
- } // seekable is the same as last time
-
-
- if (this.seekable_ && this.seekable_.length) {
- if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
- return;
- }
- }
-
- this.logger_("seekable updated [" + printableRange(this.seekable_) + "]");
- this.tech_.trigger('seekablechanged');
- }
- /**
- * Update the player duration
- */
- ;
-
- _proto.updateDuration = function updateDuration(isLive) {
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- this.updateDuration_ = null;
- }
-
- if (this.mediaSource.readyState !== 'open') {
- this.updateDuration_ = this.updateDuration.bind(this, isLive);
- this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
- return;
- }
-
- if (isLive) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- return;
- } // Even in the case of a live playlist, the native MediaSource's duration should not
- // be set to Infinity (even though this would be expected for a live playlist), since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, the duration should be greater than or
- // equal to the last possible seekable value.
- // MediaSource duration starts as NaN
- // It is possible (and probable) that this case will never be reached for many
- // sources, since the MediaSource reports duration as the highest value without
- // accounting for timestamp offset. For example, if the timestamp offset is -100 and
- // we buffered times 0 to 100 with real times of 100 to 200, even though current
- // time will be between 0 and 100, the native media source may report the duration
- // as 200. However, since we report duration separate from the media source (as
- // Infinity), and as long as the native media source duration value is greater than
- // our reported seekable range, seeks will work as expected. The large number as
- // duration for live is actually a strategy used by some players to work around the
- // issue of live seekable ranges cited above.
-
-
- if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
- this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
- }
-
- return;
- }
-
- var buffered = this.tech_.buffered();
- var duration = Vhs$1.Playlist.duration(this.masterPlaylistLoader_.media());
-
- if (buffered.length > 0) {
- duration = Math.max(duration, buffered.end(buffered.length - 1));
- }
-
- if (this.mediaSource.duration !== duration) {
- this.sourceUpdater_.setDuration(duration);
- }
- }
- /**
- * dispose of the MasterPlaylistController and everything
- * that it controls
- */
- ;
-
- _proto.dispose = function dispose() {
- var _this8 = this;
-
- this.trigger('dispose');
- this.decrypter_.terminate();
- this.masterPlaylistLoader_.dispose();
- this.mainSegmentLoader_.dispose();
-
- if (this.loadOnPlay_) {
- this.tech_.off('play', this.loadOnPlay_);
- }
-
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- var groups = _this8.mediaTypes_[type].groups;
-
- for (var id in groups) {
- groups[id].forEach(function (group) {
- if (group.playlistLoader) {
- group.playlistLoader.dispose();
- }
- });
- }
- });
- this.audioSegmentLoader_.dispose();
- this.subtitleSegmentLoader_.dispose();
- this.sourceUpdater_.dispose();
- this.timelineChangeController_.dispose();
- this.stopABRTimer_();
-
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- }
-
- this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
-
- this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
- this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
- this.off();
- }
- /**
- * return the master playlist object if we have one
- *
- * @return {Object} the master playlist object that we parsed
- */
- ;
-
- _proto.master = function master() {
- return this.masterPlaylistLoader_.master;
- }
- /**
- * return the currently selected playlist
- *
- * @return {Object} the currently selected playlist object that we parsed
- */
- ;
-
- _proto.media = function media() {
- // playlist loader will not return media if it has not been fully loaded
- return this.masterPlaylistLoader_.media() || this.initialMedia_;
- };
-
- _proto.areMediaTypesKnown_ = function areMediaTypesKnown_() {
- var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader; // one or both loaders has not loaded sufficently to get codecs
-
- if (!this.mainSegmentLoader_.currentMediaInfo_ || usingAudioLoader && !this.audioSegmentLoader_.currentMediaInfo_) {
- return false;
- }
-
- return true;
- };
-
- _proto.getCodecsOrExclude_ = function getCodecsOrExclude_() {
- var _this9 = this;
-
- var media = {
- main: this.mainSegmentLoader_.currentMediaInfo_ || {},
- audio: this.audioSegmentLoader_.currentMediaInfo_ || {}
- }; // set "main" media equal to video
-
- media.video = media.main;
- var playlistCodecs = codecsForPlaylist(this.master(), this.media());
- var codecs = {};
- var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
-
- if (media.main.hasVideo) {
- codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
- }
-
- if (media.main.isMuxed) {
- codecs.video += "," + (playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC);
- }
-
- if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
- codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
-
- media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
- } // no codecs, no playback.
-
-
- if (!codecs.audio && !codecs.video) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: 'Could not determine codecs for playlist.',
- blacklistDuration: Infinity
- });
- return;
- } // fmp4 relies on browser support, while ts relies on muxer support
-
-
- var supportFunction = function supportFunction(isFmp4, codec) {
- return isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
- };
-
- var unsupportedCodecs = {};
- var unsupportedAudio;
- ['video', 'audio'].forEach(function (type) {
- if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
- var supporter = media[type].isFmp4 ? 'browser' : 'muxer';
- unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
- unsupportedCodecs[supporter].push(codecs[type]);
-
- if (type === 'audio') {
- unsupportedAudio = supporter;
- }
- }
- });
-
- if (usingAudioLoader && unsupportedAudio && this.media().attributes.AUDIO) {
- var audioGroup = this.media().attributes.AUDIO;
- this.master().playlists.forEach(function (variant) {
- var variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
-
- if (variantAudioGroup === audioGroup && variant !== _this9.media()) {
- variant.excludeUntil = Infinity;
- }
- });
- this.logger_("excluding audio group " + audioGroup + " as " + unsupportedAudio + " does not support codec(s): \"" + codecs.audio + "\"");
- } // if we have any unsupported codecs blacklist this playlist.
-
-
- if (Object.keys(unsupportedCodecs).length) {
- var message = Object.keys(unsupportedCodecs).reduce(function (acc, supporter) {
- if (acc) {
- acc += ', ';
- }
-
- acc += supporter + " does not support codec(s): \"" + unsupportedCodecs[supporter].join(',') + "\"";
- return acc;
- }, '') + '.';
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- internal: true,
- message: message,
- blacklistDuration: Infinity
- });
- return;
- } // check if codec switching is happening
-
-
- if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
- var switchMessages = [];
- ['video', 'audio'].forEach(function (type) {
- var newCodec = (parseCodecs(_this9.sourceUpdater_.codecs[type] || '')[0] || {}).type;
- var oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
-
- if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
- switchMessages.push("\"" + _this9.sourceUpdater_.codecs[type] + "\" -> \"" + codecs[type] + "\"");
- }
- });
-
- if (switchMessages.length) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: "Codec switching not supported: " + switchMessages.join(', ') + ".",
- blacklistDuration: Infinity,
- internal: true
- });
- return;
- }
- } // TODO: when using the muxer shouldn't we just return
- // the codecs that the muxer outputs?
-
-
- return codecs;
- }
- /**
- * Create source buffers and exlude any incompatible renditions.
- *
- * @private
- */
- ;
-
- _proto.tryToCreateSourceBuffers_ = function tryToCreateSourceBuffers_() {
- // media source is not ready yet or sourceBuffers are already
- // created.
- if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
- return;
- }
-
- if (!this.areMediaTypesKnown_()) {
- return;
- }
-
- var codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
-
- if (!codecs) {
- return;
- }
-
- this.sourceUpdater_.createSourceBuffers(codecs);
- var codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
- this.excludeIncompatibleVariants_(codecString);
- }
- /**
- * Excludes playlists with codecs that are unsupported by the muxer and browser.
- */
- ;
-
- _proto.excludeUnsupportedVariants_ = function excludeUnsupportedVariants_() {
- var _this10 = this;
-
- var playlists = this.master().playlists;
- var ids = []; // TODO: why don't we have a property to loop through all
- // playlist? Why did we ever mix indexes and keys?
-
- Object.keys(playlists).forEach(function (key) {
- var variant = playlists[key]; // check if we already processed this playlist.
-
- if (ids.indexOf(variant.id) !== -1) {
- return;
- }
-
- ids.push(variant.id);
- var codecs = codecsForPlaylist(_this10.master, variant);
- var unsupported = [];
-
- if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
- unsupported.push("audio codec " + codecs.audio);
- }
-
- if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
- unsupported.push("video codec " + codecs.video);
- }
-
- if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
- unsupported.push("text codec " + codecs.text);
- }
-
- if (unsupported.length) {
- variant.excludeUntil = Infinity;
-
- _this10.logger_("excluding " + variant.id + " for unsupported: " + unsupported.join(', '));
- }
- });
- }
- /**
- * Blacklist playlists that are known to be codec or
- * stream-incompatible with the SourceBuffer configuration. For
- * instance, Media Source Extensions would cause the video element to
- * stall waiting for video data if you switched from a variant with
- * video and audio to an audio-only one.
- *
- * @param {Object} media a media playlist compatible with the current
- * set of SourceBuffers. Variants in the current master playlist that
- * do not appear to have compatible codec or stream configurations
- * will be excluded from the default playlist selection algorithm
- * indefinitely.
- * @private
- */
- ;
-
- _proto.excludeIncompatibleVariants_ = function excludeIncompatibleVariants_(codecString) {
- var _this11 = this;
-
- var ids = [];
- var playlists = this.master().playlists;
- var codecs = unwrapCodecList(parseCodecs(codecString));
- var codecCount_ = codecCount(codecs);
- var videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
- var audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
- Object.keys(playlists).forEach(function (key) {
- var variant = playlists[key]; // check if we already processed this playlist.
- // or it if it is already excluded forever.
-
- if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
- return;
- }
-
- ids.push(variant.id);
- var blacklistReasons = []; // get codecs from the playlist for this variant
-
- var variantCodecs = codecsForPlaylist(_this11.masterPlaylistLoader_.master, variant);
- var variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
- // variant is incompatible. Wait for mux.js to probe
-
- if (!variantCodecs.audio && !variantCodecs.video) {
- return;
- } // TODO: we can support this by removing the
- // old media source and creating a new one, but it will take some work.
- // The number of streams cannot change
-
-
- if (variantCodecCount !== codecCount_) {
- blacklistReasons.push("codec count \"" + variantCodecCount + "\" !== \"" + codecCount_ + "\"");
- } // only exclude playlists by codec change, if codecs cannot switch
- // during playback.
-
-
- if (!_this11.sourceUpdater_.canChangeType()) {
- var variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
- var variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
-
- if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
- blacklistReasons.push("video codec \"" + variantVideoDetails.type + "\" !== \"" + videoDetails.type + "\"");
- } // the audio codec cannot change
-
-
- if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
- blacklistReasons.push("audio codec \"" + variantAudioDetails.type + "\" !== \"" + audioDetails.type + "\"");
- }
- }
-
- if (blacklistReasons.length) {
- variant.excludeUntil = Infinity;
-
- _this11.logger_("blacklisting " + variant.id + ": " + blacklistReasons.join(' && '));
- }
- });
- };
-
- _proto.updateAdCues_ = function updateAdCues_(media) {
- var offset = 0;
- var seekable = this.seekable();
-
- if (seekable.length) {
- offset = seekable.start(0);
- }
-
- updateAdCues(media, this.cueTagsTrack_, offset);
- }
- /**
- * Calculates the desired forward buffer length based on current time
- *
- * @return {number} Desired forward buffer length in seconds
- */
- ;
-
- _proto.goalBufferLength = function goalBufferLength() {
- var currentTime = this.tech_.currentTime();
- var initial = Config.GOAL_BUFFER_LENGTH;
- var rate = Config.GOAL_BUFFER_LENGTH_RATE;
- var max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
- return Math.min(initial + currentTime * rate, max);
- }
- /**
- * Calculates the desired buffer low water line based on current time
- *
- * @return {number} Desired buffer low water line in seconds
- */
- ;
-
- _proto.bufferLowWaterLine = function bufferLowWaterLine() {
- var currentTime = this.tech_.currentTime();
- var initial = Config.BUFFER_LOW_WATER_LINE;
- var rate = Config.BUFFER_LOW_WATER_LINE_RATE;
- var max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
- var newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
- return Math.min(initial + currentTime * rate, this.experimentalBufferBasedABR ? newMax : max);
- };
-
- _proto.bufferHighWaterLine = function bufferHighWaterLine() {
- return Config.BUFFER_HIGH_WATER_LINE;
- };
-
- return MasterPlaylistController;
-}(videojs.EventTarget);
-
-/**
- * Returns a function that acts as the Enable/disable playlist function.
- *
- * @param {PlaylistLoader} loader - The master playlist loader
- * @param {string} playlistID - id of the playlist
- * @param {Function} changePlaylistFn - A function to be called after a
- * playlist's enabled-state has been changed. Will NOT be called if a
- * playlist's enabled-state is unchanged
- * @param {boolean=} enable - Value to set the playlist enabled-state to
- * or if undefined returns the current enabled-state for the playlist
- * @return {Function} Function for setting/getting enabled
- */
-
-var enableFunction = function enableFunction(loader, playlistID, changePlaylistFn) {
- return function (enable) {
- var playlist = loader.master.playlists[playlistID];
- var incompatible = isIncompatible(playlist);
- var currentlyEnabled = isEnabled(playlist);
-
- if (typeof enable === 'undefined') {
- return currentlyEnabled;
- }
-
- if (enable) {
- delete playlist.disabled;
- } else {
- playlist.disabled = true;
- }
-
- if (enable !== currentlyEnabled && !incompatible) {
- // Ensure the outside world knows about our changes
- changePlaylistFn();
-
- if (enable) {
- loader.trigger('renditionenabled');
- } else {
- loader.trigger('renditiondisabled');
- }
- }
-
- return enable;
- };
-};
-/**
- * The representation object encapsulates the publicly visible information
- * in a media playlist along with a setter/getter-type function (enabled)
- * for changing the enabled-state of a particular playlist entry
- *
- * @class Representation
- */
-
-
-var Representation = function Representation(vhsHandler, playlist, id) {
- var mpc = vhsHandler.masterPlaylistController_,
- smoothQualityChange = vhsHandler.options_.smoothQualityChange; // Get a reference to a bound version of the quality change function
-
- var changeType = smoothQualityChange ? 'smooth' : 'fast';
- var qualityChangeFunction = mpc[changeType + "QualityChange_"].bind(mpc); // some playlist attributes are optional
-
- if (playlist.attributes) {
- var resolution = playlist.attributes.RESOLUTION;
- this.width = resolution && resolution.width;
- this.height = resolution && resolution.height;
- this.bandwidth = playlist.attributes.BANDWIDTH;
- }
-
- this.codecs = codecsForPlaylist(mpc.master(), playlist);
- this.playlist = playlist; // The id is simply the ordinality of the media playlist
- // within the master playlist
-
- this.id = id; // Partially-apply the enableFunction to create a playlist-
- // specific variant
-
- this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
-};
-/**
- * A mixin function that adds the `representations` api to an instance
- * of the VhsHandler class
- *
- * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
- * representation API into
- */
-
-
-var renditionSelectionMixin = function renditionSelectionMixin(vhsHandler) {
- // Add a single API-specific function to the VhsHandler instance
- vhsHandler.representations = function () {
- var master = vhsHandler.masterPlaylistController_.master();
- var playlists = isAudioOnly(master) ? vhsHandler.masterPlaylistController_.getAudioTrackPlaylists_() : master.playlists;
-
- if (!playlists) {
- return [];
- }
-
- return playlists.filter(function (media) {
- return !isIncompatible(media);
- }).map(function (e, i) {
- return new Representation(vhsHandler, e, e.id);
- });
- };
-};
-
-/**
- * @file playback-watcher.js
- *
- * Playback starts, and now my watch begins. It shall not end until my death. I shall
- * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
- * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
- * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
- * my life and honor to the Playback Watch, for this Player and all the Players to come.
- */
-
-var timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
-/**
- * Returns whether or not the current time should be considered close to buffered content,
- * taking into consideration whether there's enough buffered content for proper playback.
- *
- * @param {Object} options
- * Options object
- * @param {TimeRange} options.buffered
- * Current buffer
- * @param {number} options.targetDuration
- * The active playlist's target duration
- * @param {number} options.currentTime
- * The current time of the player
- * @return {boolean}
- * Whether the current time should be considered close to the buffer
- */
-
-var closeToBufferedContent = function closeToBufferedContent(_ref) {
- var buffered = _ref.buffered,
- targetDuration = _ref.targetDuration,
- currentTime = _ref.currentTime;
-
- if (!buffered.length) {
- return false;
- } // At least two to three segments worth of content should be buffered before there's a
- // full enough buffer to consider taking any actions.
-
-
- if (buffered.end(0) - buffered.start(0) < targetDuration * 2) {
- return false;
- } // It's possible that, on seek, a remove hasn't completed and the buffered range is
- // somewhere past the current time. In that event, don't consider the buffered content
- // close.
-
-
- if (currentTime > buffered.start(0)) {
- return false;
- } // Since target duration generally represents the max (or close to max) duration of a
- // segment, if the buffer is within a segment of the current time, the gap probably
- // won't be closed, and current time should be considered close to buffered content.
-
-
- return buffered.start(0) - currentTime < targetDuration;
-};
-/**
- * @class PlaybackWatcher
- */
-
-var PlaybackWatcher = /*#__PURE__*/function () {
- /**
- * Represents an PlaybackWatcher object.
- *
- * @class
- * @param {Object} options an object that includes the tech and settings
- */
- function PlaybackWatcher(options) {
- var _this = this;
-
- this.masterPlaylistController_ = options.masterPlaylistController;
- this.tech_ = options.tech;
- this.seekable = options.seekable;
- this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
- this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
- this.media = options.media;
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = null;
- this.timer_ = null;
- this.checkCurrentTimeTimeout_ = null;
- this.logger_ = logger('PlaybackWatcher');
- this.logger_('initialize');
-
- var playHandler = function playHandler() {
- return _this.monitorCurrentTime_();
- };
-
- var canPlayHandler = function canPlayHandler() {
- return _this.monitorCurrentTime_();
- };
-
- var waitingHandler = function waitingHandler() {
- return _this.techWaiting_();
- };
-
- var cancelTimerHandler = function cancelTimerHandler() {
- return _this.cancelTimer_();
- };
-
- var fixesBadSeeksHandler = function fixesBadSeeksHandler() {
- return _this.fixesBadSeeks_();
- };
-
- var mpc = this.masterPlaylistController_;
- var loaderTypes = ['main', 'subtitle', 'audio'];
- var loaderChecks = {};
- loaderTypes.forEach(function (type) {
- loaderChecks[type] = {
- reset: function reset() {
- return _this.resetSegmentDownloads_(type);
- },
- updateend: function updateend() {
- return _this.checkSegmentDownloads_(type);
- }
- };
- mpc[type + "SegmentLoader_"].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
- // isn't changing we want to reset. We cannot assume that the new rendition
- // will also be stalled, until after new appends.
-
- mpc[type + "SegmentLoader_"].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
- // This prevents one segment playlists (single vtt or single segment content)
- // from being detected as stalling. As the buffer will not change in those cases, since
- // the buffer is the entire video duration.
-
- _this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
- });
- this.tech_.on('seekablechanged', fixesBadSeeksHandler);
- this.tech_.on('waiting', waitingHandler);
- this.tech_.on(timerCancelEvents, cancelTimerHandler);
- this.tech_.on('canplay', canPlayHandler);
- /*
- An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
- is surfaced in one of two ways:
- 1) The `waiting` event is fired before the player has buffered content, making it impossible
- to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
- we can check if playback is stalled due to a gap, and skip the gap if necessary.
- 2) A source with a gap at the beginning of the stream is loaded programatically while the player
- is in a playing state. To catch this case, it's important that our one-time play listener is setup
- even if the player is in a playing state
- */
-
- this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
-
- this.dispose = function () {
- _this.logger_('dispose');
-
- _this.tech_.off('seekablechanged', fixesBadSeeksHandler);
-
- _this.tech_.off('waiting', waitingHandler);
-
- _this.tech_.off(timerCancelEvents, cancelTimerHandler);
-
- _this.tech_.off('canplay', canPlayHandler);
-
- _this.tech_.off('play', playHandler);
-
- loaderTypes.forEach(function (type) {
- mpc[type + "SegmentLoader_"].off('appendsdone', loaderChecks[type].updateend);
- mpc[type + "SegmentLoader_"].off('playlistupdate', loaderChecks[type].reset);
-
- _this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
- });
-
- if (_this.checkCurrentTimeTimeout_) {
- window.clearTimeout(_this.checkCurrentTimeTimeout_);
- }
-
- _this.cancelTimer_();
- };
- }
- /**
- * Periodically check current time to see if playback stopped
- *
- * @private
- */
-
-
- var _proto = PlaybackWatcher.prototype;
-
- _proto.monitorCurrentTime_ = function monitorCurrentTime_() {
- this.checkCurrentTime_();
-
- if (this.checkCurrentTimeTimeout_) {
- window.clearTimeout(this.checkCurrentTimeTimeout_);
- } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
-
-
- this.checkCurrentTimeTimeout_ = window.setTimeout(this.monitorCurrentTime_.bind(this), 250);
- }
- /**
- * Reset stalled download stats for a specific type of loader
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#playlistupdate
- * @listens Tech#seeking
- * @listens Tech#seeked
- */
- ;
-
- _proto.resetSegmentDownloads_ = function resetSegmentDownloads_(type) {
- var loader = this.masterPlaylistController_[type + "SegmentLoader_"];
-
- if (this[type + "StalledDownloads_"] > 0) {
- this.logger_("resetting possible stalled download count for " + type + " loader");
- }
-
- this[type + "StalledDownloads_"] = 0;
- this[type + "Buffered_"] = loader.buffered_();
- }
- /**
- * Checks on every segment `appendsdone` to see
- * if segment appends are making progress. If they are not
- * and we are still downloading bytes. We blacklist the playlist.
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#appendsdone
- */
- ;
-
- _proto.checkSegmentDownloads_ = function checkSegmentDownloads_(type) {
- var mpc = this.masterPlaylistController_;
- var loader = mpc[type + "SegmentLoader_"];
- var buffered = loader.buffered_();
- var isBufferedDifferent = isRangeDifferent(this[type + "Buffered_"], buffered);
- this[type + "Buffered_"] = buffered; // if another watcher is going to fix the issue or
- // the buffered value for this loader changed
- // appends are working
-
- if (isBufferedDifferent) {
- this.resetSegmentDownloads_(type);
- return;
- }
-
- this[type + "StalledDownloads_"]++;
- this.logger_("found #" + this[type + "StalledDownloads_"] + " " + type + " appends that did not increase buffer (possible stalled download)", {
- playlistId: loader.playlist_ && loader.playlist_.id,
- buffered: timeRangesToArray(buffered)
- }); // after 10 possibly stalled appends with no reset, exclude
-
- if (this[type + "StalledDownloads_"] < 10) {
- return;
- }
-
- this.logger_(type + " loader stalled download exclusion");
- this.resetSegmentDownloads_(type);
- this.tech_.trigger({
- type: 'usage',
- name: "vhs-" + type + "-download-exclusion"
- });
-
- if (type === 'subtitle') {
- return;
- } // TODO: should we exclude audio tracks rather than main tracks
- // when type is audio?
-
-
- mpc.blacklistCurrentPlaylist({
- message: "Excessive " + type + " segment downloading detected."
- }, Infinity);
- }
- /**
- * The purpose of this function is to emulate the "waiting" event on
- * browsers that do not emit it when they are waiting for more
- * data to continue playback
- *
- * @private
- */
- ;
-
- _proto.checkCurrentTime_ = function checkCurrentTime_() {
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = this.tech_.currentTime();
- return;
- }
-
- if (this.tech_.paused() || this.tech_.seeking()) {
- return;
- }
-
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
-
- if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
- // If current time is at the end of the final buffered region, then any playback
- // stall is most likely caused by buffering in a low bandwidth environment. The tech
- // should fire a `waiting` event in this scenario, but due to browser and tech
- // inconsistencies. Calling `techWaiting_` here allows us to simulate
- // responding to a native `waiting` event when the tech fails to emit one.
- return this.techWaiting_();
- }
-
- if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- this.waiting_();
- } else if (currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- } else {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = currentTime;
- }
- }
- /**
- * Cancels any pending timers and resets the 'timeupdate' mechanism
- * designed to detect that we are stalled
- *
- * @private
- */
- ;
-
- _proto.cancelTimer_ = function cancelTimer_() {
- this.consecutiveUpdates = 0;
-
- if (this.timer_) {
- this.logger_('cancelTimer_');
- clearTimeout(this.timer_);
- }
-
- this.timer_ = null;
- }
- /**
- * Fixes situations where there's a bad seek
- *
- * @return {boolean} whether an action was taken to fix the seek
- * @private
- */
- ;
-
- _proto.fixesBadSeeks_ = function fixesBadSeeks_() {
- var seeking = this.tech_.seeking();
-
- if (!seeking) {
- return false;
- }
-
- var seekable = this.seekable();
- var currentTime = this.tech_.currentTime();
- var isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
- var seekTo;
-
- if (isAfterSeekableRange) {
- var seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
-
- seekTo = seekableEnd;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- var seekableStart = seekable.start(0); // sync to the beginning of the live window
- // provide a buffer of .1 seconds to handle rounding/imprecise numbers
-
- seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
- // happen in live with a 3 segment playlist), then don't use a time delta
- seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
- }
-
- if (typeof seekTo !== 'undefined') {
- this.logger_("Trying to seek outside of seekable at time " + currentTime + " with " + ("seekable range " + printableRange(seekable) + ". Seeking to ") + (seekTo + "."));
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- var buffered = this.tech_.buffered();
-
- if (closeToBufferedContent({
- buffered: buffered,
- targetDuration: this.media().targetDuration,
- currentTime: currentTime
- })) {
- seekTo = buffered.start(0) + SAFE_TIME_DELTA;
- this.logger_("Buffered region starts (" + buffered.start(0) + ") " + (" just beyond seek point (" + currentTime + "). Seeking to " + seekTo + "."));
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- return false;
- }
- /**
- * Handler for situations when we determine the player is waiting.
- *
- * @private
- */
- ;
-
- _proto.waiting_ = function waiting_() {
- if (this.techWaiting_()) {
- return;
- } // All tech waiting checks failed. Use last resort correction
-
-
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
- var currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
- // region with no indication that anything is amiss (seen in Firefox). Seeking to
- // currentTime is usually enough to kickstart the player. This checks that the player
- // is currently within a buffered region before attempting a corrective seek.
- // Chrome does not appear to continue `timeupdate` events after a `waiting` event
- // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
- // make sure there is ~3 seconds of forward buffer before taking any corrective action
- // to avoid triggering an `unknownwaiting` event when the network is slow.
-
- if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime);
- this.logger_("Stopped at " + currentTime + " while inside a buffered region " + ("[" + currentRange.start(0) + " -> " + currentRange.end(0) + "]. Attempting to resume ") + 'playback by seeking to the current time.'); // unknown waiting corrections may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-unknown-waiting'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-unknown-waiting'
- });
- return;
- }
- }
- /**
- * Handler for situations when the tech fires a `waiting` event
- *
- * @return {boolean}
- * True if an action (or none) was needed to correct the waiting. False if no
- * checks passed
- * @private
- */
- ;
-
- _proto.techWaiting_ = function techWaiting_() {
- var seekable = this.seekable();
- var currentTime = this.tech_.currentTime();
-
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- // Tech is seeking or bad seek fixed, no action needed
- return true;
- }
-
- if (this.tech_.seeking() || this.timer_ !== null) {
- // Tech is seeking or already waiting on another action, no action needed
- return true;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- var livePoint = seekable.end(seekable.length - 1);
- this.logger_("Fell out of live window at time " + currentTime + ". Seeking to " + ("live point (seekable end) " + livePoint));
- this.cancelTimer_();
- this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-live-resync'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-live-resync'
- });
- return true;
- }
-
- var sourceUpdater = this.tech_.vhs.masterPlaylistController_.sourceUpdater_;
- var buffered = this.tech_.buffered();
- var videoUnderflow = this.videoUnderflow_({
- audioBuffered: sourceUpdater.audioBuffered(),
- videoBuffered: sourceUpdater.videoBuffered(),
- currentTime: currentTime
- });
-
- if (videoUnderflow) {
- // Even though the video underflowed and was stuck in a gap, the audio overplayed
- // the gap, leading currentTime into a buffered range. Seeking to currentTime
- // allows the video to catch up to the audio position without losing any audio
- // (only suffering ~3 seconds of frozen video and a pause in audio playback).
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-video-underflow'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-video-underflow'
- });
- return true;
- }
-
- var nextRange = findNextRange(buffered, currentTime); // check for gap
-
- if (nextRange.length > 0) {
- var difference = nextRange.start(0) - currentTime;
- this.logger_("Stopped at " + currentTime + ", setting timer for " + difference + ", seeking " + ("to " + nextRange.start(0)));
- this.cancelTimer_();
- this.timer_ = setTimeout(this.skipTheGap_.bind(this), difference * 1000, currentTime);
- return true;
- } // All checks failed. Returning false to indicate failure to correct waiting
-
-
- return false;
- };
-
- _proto.afterSeekableWindow_ = function afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow) {
- if (allowSeeksWithinUnsafeLiveWindow === void 0) {
- allowSeeksWithinUnsafeLiveWindow = false;
- }
-
- if (!seekable.length) {
- // we can't make a solid case if there's no seekable, default to false
- return false;
- }
-
- var allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
- var isLive = !playlist.endList;
-
- if (isLive && allowSeeksWithinUnsafeLiveWindow) {
- allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
- }
-
- if (currentTime > allowedEnd) {
- return true;
- }
-
- return false;
- };
-
- _proto.beforeSeekableWindow_ = function beforeSeekableWindow_(seekable, currentTime) {
- if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
- seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
- return true;
- }
-
- return false;
- };
-
- _proto.videoUnderflow_ = function videoUnderflow_(_ref2) {
- var videoBuffered = _ref2.videoBuffered,
- audioBuffered = _ref2.audioBuffered,
- currentTime = _ref2.currentTime;
-
- // audio only content will not have video underflow :)
- if (!videoBuffered) {
- return;
- }
-
- var gap; // find a gap in demuxed content.
-
- if (videoBuffered.length && audioBuffered.length) {
- // in Chrome audio will continue to play for ~3s when we run out of video
- // so we have to check that the video buffer did have some buffer in the
- // past.
- var lastVideoRange = findRange(videoBuffered, currentTime - 3);
- var videoRange = findRange(videoBuffered, currentTime);
- var audioRange = findRange(audioBuffered, currentTime);
-
- if (audioRange.length && !videoRange.length && lastVideoRange.length) {
- gap = {
- start: lastVideoRange.end(0),
- end: audioRange.end(0)
- };
- } // find a gap in muxed content.
-
- } else {
- var nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
- // stuck in a gap due to video underflow.
-
- if (!nextRange.length) {
- gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
- }
- }
-
- if (gap) {
- this.logger_("Encountered a gap in video from " + gap.start + " to " + gap.end + ". " + ("Seeking to current time " + currentTime));
- return true;
- }
-
- return false;
- }
- /**
- * Timer callback. If playback still has not proceeded, then we seek
- * to the start of the next buffered region.
- *
- * @private
- */
- ;
-
- _proto.skipTheGap_ = function skipTheGap_(scheduledCurrentTime) {
- var buffered = this.tech_.buffered();
- var currentTime = this.tech_.currentTime();
- var nextRange = findNextRange(buffered, currentTime);
- this.cancelTimer_();
-
- if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
- return;
- }
-
- this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
-
- this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-gap-skip'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-gap-skip'
- });
- };
-
- _proto.gapFromVideoUnderflow_ = function gapFromVideoUnderflow_(buffered, currentTime) {
- // At least in Chrome, if there is a gap in the video buffer, the audio will continue
- // playing for ~3 seconds after the video gap starts. This is done to account for
- // video buffer underflow/underrun (note that this is not done when there is audio
- // buffer underflow/underrun -- in that case the video will stop as soon as it
- // encounters the gap, as audio stalls are more noticeable/jarring to a user than
- // video stalls). The player's time will reflect the playthrough of audio, so the
- // time will appear as if we are in a buffered region, even if we are stuck in a
- // "gap."
- //
- // Example:
- // video buffer: 0 => 10.1, 10.2 => 20
- // audio buffer: 0 => 20
- // overall buffer: 0 => 10.1, 10.2 => 20
- // current time: 13
- //
- // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
- // however, the audio continued playing until it reached ~3 seconds past the gap
- // (13 seconds), at which point it stops as well. Since current time is past the
- // gap, findNextRange will return no ranges.
- //
- // To check for this issue, we see if there is a gap that starts somewhere within
- // a 3 second range (3 seconds +/- 1 second) back from our current time.
- var gaps = findGaps(buffered);
-
- for (var i = 0; i < gaps.length; i++) {
- var start = gaps.start(i);
- var end = gaps.end(i); // gap is starts no more than 4 seconds back
-
- if (currentTime - start < 4 && currentTime - start > 2) {
- return {
- start: start,
- end: end
- };
- }
- }
-
- return null;
- };
-
- return PlaybackWatcher;
-}();
-
-var defaultOptions = {
- errorInterval: 30,
- getSource: function getSource(next) {
- var tech = this.tech({
- IWillNotUseThisInPlugins: true
- });
- var sourceObj = tech.currentSource_ || this.currentSource();
- return next(sourceObj);
- }
-};
-/**
- * Main entry point for the plugin
- *
- * @param {Player} player a reference to a videojs Player instance
- * @param {Object} [options] an object with plugin options
- * @private
- */
-
-var initPlugin = function initPlugin(player, options) {
- var lastCalled = 0;
- var seekTo = 0;
- var localOptions = videojs.mergeOptions(defaultOptions, options);
- player.ready(function () {
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload-initialized'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload-initialized'
- });
- });
- /**
- * Player modifications to perform that must wait until `loadedmetadata`
- * has been triggered
- *
- * @private
- */
-
- var loadedMetadataHandler = function loadedMetadataHandler() {
- if (seekTo) {
- player.currentTime(seekTo);
- }
- };
- /**
- * Set the source on the player element, play, and seek if necessary
- *
- * @param {Object} sourceObj An object specifying the source url and mime-type to play
- * @private
- */
-
-
- var setSource = function setSource(sourceObj) {
- if (sourceObj === null || sourceObj === undefined) {
- return;
- }
-
- seekTo = player.duration() !== Infinity && player.currentTime() || 0;
- player.one('loadedmetadata', loadedMetadataHandler);
- player.src(sourceObj);
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload'
- });
- player.play();
- };
- /**
- * Attempt to get a source from either the built-in getSource function
- * or a custom function provided via the options
- *
- * @private
- */
-
-
- var errorHandler = function errorHandler() {
- // Do not attempt to reload the source if a source-reload occurred before
- // 'errorInterval' time has elapsed since the last source-reload
- if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload-canceled'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload-canceled'
- });
- return;
- }
-
- if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
- videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
- return;
- }
-
- lastCalled = Date.now();
- return localOptions.getSource.call(player, setSource);
- };
- /**
- * Unbind any event handlers that were bound by the plugin
- *
- * @private
- */
-
-
- var cleanupEvents = function cleanupEvents() {
- player.off('loadedmetadata', loadedMetadataHandler);
- player.off('error', errorHandler);
- player.off('dispose', cleanupEvents);
- };
- /**
- * Cleanup before re-initializing the plugin
- *
- * @param {Object} [newOptions] an object with plugin options
- * @private
- */
-
-
- var reinitPlugin = function reinitPlugin(newOptions) {
- cleanupEvents();
- initPlugin(player, newOptions);
- };
-
- player.on('error', errorHandler);
- player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
- // initializing the plugin
-
- player.reloadSourceOnError = reinitPlugin;
-};
-/**
- * Reload the source when an error is detected as long as there
- * wasn't an error previously within the last 30 seconds
- *
- * @param {Object} [options] an object with plugin options
- */
-
-
-var reloadSourceOnError = function reloadSourceOnError(options) {
- initPlugin(this, options);
-};
-
-var version$4 = "2.9.1";
-
-var version$3 = "5.11.1";
-
-var version$2 = "0.17.0";
-
-var version$1 = "4.7.0";
-
-var version = "3.1.2";
-
-var Vhs = {
- PlaylistLoader: PlaylistLoader,
- Playlist: Playlist,
- utils: utils,
- STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
- INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
- lastBandwidthSelector: lastBandwidthSelector,
- movingAverageBandwidthSelector: movingAverageBandwidthSelector,
- comparePlaylistBandwidth: comparePlaylistBandwidth,
- comparePlaylistResolution: comparePlaylistResolution,
- xhr: xhrFactory()
-}; // Define getter/setters for config properties
-
-Object.keys(Config).forEach(function (prop) {
- Object.defineProperty(Vhs, prop, {
- get: function get() {
- videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
- return Config[prop];
- },
- set: function set(value) {
- videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
-
- if (typeof value !== 'number' || value < 0) {
- videojs.log.warn("value of Vhs." + prop + " must be greater than or equal to 0");
- return;
- }
-
- Config[prop] = value;
- }
- });
-});
-var LOCAL_STORAGE_KEY = 'videojs-vhs';
-/**
- * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
- * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
- * @function handleVhsMediaChange
- */
-
-var handleVhsMediaChange = function handleVhsMediaChange(qualityLevels, playlistLoader) {
- var newPlaylist = playlistLoader.media();
- var selectedIndex = -1;
-
- for (var i = 0; i < qualityLevels.length; i++) {
- if (qualityLevels[i].id === newPlaylist.id) {
- selectedIndex = i;
- break;
- }
- }
-
- qualityLevels.selectedIndex_ = selectedIndex;
- qualityLevels.trigger({
- selectedIndex: selectedIndex,
- type: 'change'
- });
-};
-/**
- * Adds quality levels to list once playlist metadata is available
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
- * @param {Object} vhs Vhs object to listen to for media events.
- * @function handleVhsLoadedMetadata
- */
-
-
-var handleVhsLoadedMetadata = function handleVhsLoadedMetadata(qualityLevels, vhs) {
- vhs.representations().forEach(function (rep) {
- qualityLevels.addQualityLevel(rep);
- });
- handleVhsMediaChange(qualityLevels, vhs.playlists);
-}; // HLS is a source handler, not a tech. Make sure attempts to use it
-// as one do not cause exceptions.
-
-
-Vhs.canPlaySource = function () {
- return videojs.log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
-};
-
-var emeKeySystems = function emeKeySystems(keySystemOptions, mainPlaylist, audioPlaylist) {
- if (!keySystemOptions) {
- return keySystemOptions;
- }
-
- var codecs = {};
-
- if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
- codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
- }
-
- if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
- codecs.audio = audioPlaylist.attributes.CODECS;
- }
-
- var videoContentType = getMimeForCodec(codecs.video);
- var audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
-
- var keySystemContentTypes = {};
-
- for (var keySystem in keySystemOptions) {
- keySystemContentTypes[keySystem] = {};
-
- if (audioContentType) {
- keySystemContentTypes[keySystem].audioContentType = audioContentType;
- }
-
- if (videoContentType) {
- keySystemContentTypes[keySystem].videoContentType = videoContentType;
- } // Default to using the video playlist's PSSH even though they may be different, as
- // videojs-contrib-eme will only accept one in the options.
- //
- // This shouldn't be an issue for most cases as early intialization will handle all
- // unique PSSH values, and if they aren't, then encrypted events should have the
- // specific information needed for the unique license.
-
-
- if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
- keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
- } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
- // so we need to prevent overwriting the URL entirely
-
-
- if (typeof keySystemOptions[keySystem] === 'string') {
- keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
- }
- }
-
- return videojs.mergeOptions(keySystemOptions, keySystemContentTypes);
-};
-/**
- * @typedef {Object} KeySystems
- *
- * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
- * Note: not all options are listed here.
- *
- * @property {Uint8Array} [pssh]
- * Protection System Specific Header
- */
-
-/**
- * Goes through all the playlists and collects an array of KeySystems options objects
- * containing each playlist's keySystems and their pssh values, if available.
- *
- * @param {Object[]} playlists
- * The playlists to look through
- * @param {string[]} keySystems
- * The keySystems to collect pssh values for
- *
- * @return {KeySystems[]}
- * An array of KeySystems objects containing available key systems and their
- * pssh values
- */
-
-
-var getAllPsshKeySystemsOptions = function getAllPsshKeySystemsOptions(playlists, keySystems) {
- return playlists.reduce(function (keySystemsArr, playlist) {
- if (!playlist.contentProtection) {
- return keySystemsArr;
- }
-
- var keySystemsOptions = keySystems.reduce(function (keySystemsObj, keySystem) {
- var keySystemOptions = playlist.contentProtection[keySystem];
-
- if (keySystemOptions && keySystemOptions.pssh) {
- keySystemsObj[keySystem] = {
- pssh: keySystemOptions.pssh
- };
- }
-
- return keySystemsObj;
- }, {});
-
- if (Object.keys(keySystemsOptions).length) {
- keySystemsArr.push(keySystemsOptions);
- }
-
- return keySystemsArr;
- }, []);
-};
-/**
- * Returns a promise that waits for the
- * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
- *
- * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
- * browsers.
- *
- * As per the above ticket, this is particularly important for Chrome, where, if
- * unencrypted content is appended before encrypted content and the key session has not
- * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
- * during playback.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- * @param {Object[]} mainPlaylists
- * The playlists found on the master playlist object
- *
- * @return {Object}
- * Promise that resolves when the key session has been created
- */
-
-
-var waitForKeySessionCreation = function waitForKeySessionCreation(_ref) {
- var player = _ref.player,
- sourceKeySystems = _ref.sourceKeySystems,
- audioMedia = _ref.audioMedia,
- mainPlaylists = _ref.mainPlaylists;
-
- if (!player.eme.initializeMediaKeys) {
- return Promise.resolve();
- } // TODO should all audio PSSH values be initialized for DRM?
- //
- // All unique video rendition pssh values are initialized for DRM, but here only
- // the initial audio playlist license is initialized. In theory, an encrypted
- // event should be fired if the user switches to an alternative audio playlist
- // where a license is required, but this case hasn't yet been tested. In addition, there
- // may be many alternate audio playlists unlikely to be used (e.g., multiple different
- // languages).
-
-
- var playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
- var keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
- var initializationFinishedPromises = [];
- var keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
- // only place where it should not be deduped is for ms-prefixed APIs, but the early
- // return for IE11 above, and the existence of modern EME APIs in addition to
- // ms-prefixed APIs on Edge should prevent this from being a concern.
- // initializeMediaKeys also won't use the webkit-prefixed APIs.
-
- keySystemsOptionsArr.forEach(function (keySystemsOptions) {
- keySessionCreatedPromises.push(new Promise(function (resolve, reject) {
- player.tech_.one('keysessioncreated', resolve);
- }));
- initializationFinishedPromises.push(new Promise(function (resolve, reject) {
- player.eme.initializeMediaKeys({
- keySystems: keySystemsOptions
- }, function (err) {
- if (err) {
- reject(err);
- return;
- }
-
- resolve();
- });
- }));
- }); // The reasons Promise.race is chosen over Promise.any:
- //
- // * Promise.any is only available in Safari 14+.
- // * None of these promises are expected to reject. If they do reject, it might be
- // better here for the race to surface the rejection, rather than mask it by using
- // Promise.any.
-
- return Promise.race([// If a session was previously created, these will all finish resolving without
- // creating a new session, otherwise it will take until the end of all license
- // requests, which is why the key session check is used (to make setup much faster).
- Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
- Promise.race(keySessionCreatedPromises)]);
-};
-/**
- * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
- * there are keySystems on the source, sets up source options to prepare the source for
- * eme.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} media
- * The active media playlist
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- *
- * @return {boolean}
- * Whether or not options were configured and EME is available
- */
-
-var setupEmeOptions = function setupEmeOptions(_ref2) {
- var player = _ref2.player,
- sourceKeySystems = _ref2.sourceKeySystems,
- media = _ref2.media,
- audioMedia = _ref2.audioMedia;
- var sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
-
- if (!sourceOptions) {
- return false;
- }
-
- player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
- // do nothing.
-
- if (sourceOptions && !player.eme) {
- videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
- return false;
- }
-
- return true;
-};
-
-var getVhsLocalStorage = function getVhsLocalStorage() {
- if (!window.localStorage) {
- return null;
- }
-
- var storedObject = window.localStorage.getItem(LOCAL_STORAGE_KEY);
-
- if (!storedObject) {
- return null;
- }
-
- try {
- return JSON.parse(storedObject);
- } catch (e) {
- // someone may have tampered with the value
- return null;
- }
-};
-
-var updateVhsLocalStorage = function updateVhsLocalStorage(options) {
- if (!window.localStorage) {
- return false;
- }
-
- var objectToStore = getVhsLocalStorage();
- objectToStore = objectToStore ? videojs.mergeOptions(objectToStore, options) : options;
-
- try {
- window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
- } catch (e) {
- // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
- // storage is set to 0).
- // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
- // No need to perform any operation.
- return false;
- }
-
- return objectToStore;
-};
-/**
- * Parses VHS-supported media types from data URIs. See
- * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
- * for information on data URIs.
- *
- * @param {string} dataUri
- * The data URI
- *
- * @return {string|Object}
- * The parsed object/string, or the original string if no supported media type
- * was found
- */
-
-
-var expandDataUri = function expandDataUri(dataUri) {
- if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
- return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
- } // no known case for this data URI, return the string as-is
-
-
- return dataUri;
-};
-/**
- * Whether the browser has built-in HLS support.
- */
-
-
-Vhs.supportsNativeHls = function () {
- if (!document || !document.createElement) {
- return false;
- }
-
- var video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
-
- if (!videojs.getTech('Html5').isSupported()) {
- return false;
- } // HLS manifests can go by many mime-types
-
-
- var canPlay = [// Apple santioned
- 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
- 'audio/mpegurl', // Very common
- 'audio/x-mpegurl', // Very common
- 'application/x-mpegurl', // Included for completeness
- 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
- return canPlay.some(function (canItPlay) {
- return /maybe|probably/i.test(video.canPlayType(canItPlay));
- });
-}();
-
-Vhs.supportsNativeDash = function () {
- if (!document || !document.createElement || !videojs.getTech('Html5').isSupported()) {
- return false;
- }
-
- return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
-}();
-
-Vhs.supportsTypeNatively = function (type) {
- if (type === 'hls') {
- return Vhs.supportsNativeHls;
- }
-
- if (type === 'dash') {
- return Vhs.supportsNativeDash;
- }
-
- return false;
-};
-/**
- * HLS is a source handler, not a tech. Make sure attempts to use it
- * as one do not cause exceptions.
- */
-
-
-Vhs.isSupported = function () {
- return videojs.log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
-};
-
-var Component = videojs.getComponent('Component');
-/**
- * The Vhs Handler object, where we orchestrate all of the parts
- * of HLS to interact with video.js
- *
- * @class VhsHandler
- * @extends videojs.Component
- * @param {Object} source the soruce object
- * @param {Tech} tech the parent tech object
- * @param {Object} options optional and required options
- */
-
-var VhsHandler = /*#__PURE__*/function (_Component) {
- _inheritsLoose(VhsHandler, _Component);
-
- function VhsHandler(source, tech, options) {
- var _this;
-
- _this = _Component.call(this, tech, videojs.mergeOptions(options.hls, options.vhs)) || this;
-
- if (options.hls && Object.keys(options.hls).length) {
- videojs.log.warn('Using hls options is deprecated. Use vhs instead.');
- } // if a tech level `initialBandwidth` option was passed
- // use that over the VHS level `bandwidth` option
-
-
- if (typeof options.initialBandwidth === 'number') {
- _this.options_.bandwidth = options.initialBandwidth;
- }
-
- _this.logger_ = logger('VhsHandler'); // tech.player() is deprecated but setup a reference to HLS for
- // backwards-compatibility
-
- if (tech.options_ && tech.options_.playerId) {
- var _player = videojs(tech.options_.playerId);
-
- if (!_player.hasOwnProperty('hls')) {
- Object.defineProperty(_player, 'hls', {
- get: function get() {
- videojs.log.warn('player.hls is deprecated. Use player.tech().vhs instead.');
- tech.trigger({
- type: 'usage',
- name: 'hls-player-access'
- });
- return _assertThisInitialized(_this);
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('vhs')) {
- Object.defineProperty(_player, 'vhs', {
- get: function get() {
- videojs.log.warn('player.vhs is deprecated. Use player.tech().vhs instead.');
- tech.trigger({
- type: 'usage',
- name: 'vhs-player-access'
- });
- return _assertThisInitialized(_this);
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('dash')) {
- Object.defineProperty(_player, 'dash', {
- get: function get() {
- videojs.log.warn('player.dash is deprecated. Use player.tech().vhs instead.');
- return _assertThisInitialized(_this);
- },
- configurable: true
- });
- }
-
- _this.player_ = _player;
- }
-
- _this.tech_ = tech;
- _this.source_ = source;
- _this.stats = {};
- _this.ignoreNextSeekingEvent_ = false;
-
- _this.setOptions_();
-
- if (_this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
- tech.overrideNativeAudioTracks(true);
- tech.overrideNativeVideoTracks(true);
- } else if (_this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
- // overriding native HLS only works if audio tracks have been emulated
- // error early if we're misconfigured
- throw new Error('Overriding native HLS requires emulated tracks. ' + 'See https://git.io/vMpjB');
- } // listen for fullscreenchange events for this player so that we
- // can adjust our quality selection quickly
-
-
- _this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
- var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
-
- if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
- _this.masterPlaylistController_.fastQualityChange_();
- } else {
- // When leaving fullscreen, since the in page pixel dimensions should be smaller
- // than full screen, see if there should be a rendition switch down to preserve
- // bandwidth.
- _this.masterPlaylistController_.checkABR_();
- }
- });
-
- _this.on(_this.tech_, 'seeking', function () {
- if (this.ignoreNextSeekingEvent_) {
- this.ignoreNextSeekingEvent_ = false;
- return;
- }
-
- this.setCurrentTime(this.tech_.currentTime());
- });
-
- _this.on(_this.tech_, 'error', function () {
- // verify that the error was real and we are loaded
- // enough to have mpc loaded.
- if (this.tech_.error() && this.masterPlaylistController_) {
- this.masterPlaylistController_.pauseLoading();
- }
- });
-
- _this.on(_this.tech_, 'play', _this.play);
-
- return _this;
- }
-
- var _proto = VhsHandler.prototype;
-
- _proto.setOptions_ = function setOptions_() {
- var _this2 = this;
-
- // defaults
- this.options_.withCredentials = this.options_.withCredentials || false;
- this.options_.handleManifestRedirects = this.options_.handleManifestRedirects === false ? false : true;
- this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
- this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
- this.options_.smoothQualityChange = this.options_.smoothQualityChange || false;
- this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
- this.options_.customTagParsers = this.options_.customTagParsers || [];
- this.options_.customTagMappers = this.options_.customTagMappers || [];
- this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
-
- if (typeof this.options_.blacklistDuration !== 'number') {
- this.options_.blacklistDuration = 5 * 60;
- }
-
- if (typeof this.options_.bandwidth !== 'number') {
- if (this.options_.useBandwidthFromLocalStorage) {
- var storedObject = getVhsLocalStorage();
-
- if (storedObject && storedObject.bandwidth) {
- this.options_.bandwidth = storedObject.bandwidth;
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-bandwidth-from-local-storage'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-bandwidth-from-local-storage'
- });
- }
-
- if (storedObject && storedObject.throughput) {
- this.options_.throughput = storedObject.throughput;
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-throughput-from-local-storage'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-throughput-from-local-storage'
- });
- }
- }
- } // if bandwidth was not set by options or pulled from local storage, start playlist
- // selection at a reasonable bandwidth
-
-
- if (typeof this.options_.bandwidth !== 'number') {
- this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
- } // If the bandwidth number is unchanged from the initial setting
- // then this takes precedence over the enableLowInitialPlaylist option
-
-
- this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
-
- ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'smoothQualityChange', 'customTagParsers', 'customTagMappers', 'handleManifestRedirects', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'experimentalBufferBasedABR', 'liveRangeSafeTimeDelta', 'experimentalLLHLS'].forEach(function (option) {
- if (typeof _this2.source_[option] !== 'undefined') {
- _this2.options_[option] = _this2.source_[option];
- }
- });
- this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
- this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
- }
- /**
- * called when player.src gets called, handle a new source
- *
- * @param {Object} src the source object to handle
- */
- ;
-
- _proto.src = function src(_src, type) {
- var _this3 = this;
-
- // do nothing if the src is falsey
- if (!_src) {
- return;
- }
-
- this.setOptions_(); // add master playlist controller options
-
- this.options_.src = expandDataUri(this.source_.src);
- this.options_.tech = this.tech_;
- this.options_.externVhs = Vhs;
- this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
-
- this.options_.seekTo = function (time) {
- _this3.tech_.setCurrentTime(time);
- };
-
- if (this.options_.smoothQualityChange) {
- videojs.log.warn('smoothQualityChange is deprecated and will be removed in the next major version');
- }
-
- this.masterPlaylistController_ = new MasterPlaylistController(this.options_);
- var playbackWatcherOptions = videojs.mergeOptions({
- liveRangeSafeTimeDelta: SAFE_TIME_DELTA
- }, this.options_, {
- seekable: function seekable() {
- return _this3.seekable();
- },
- media: function media() {
- return _this3.masterPlaylistController_.media();
- },
- masterPlaylistController: this.masterPlaylistController_
- });
- this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
- this.masterPlaylistController_.on('error', function () {
- var player = videojs.players[_this3.tech_.options_.playerId];
- var error = _this3.masterPlaylistController_.error;
-
- if (typeof error === 'object' && !error.code) {
- error.code = 3;
- } else if (typeof error === 'string') {
- error = {
- message: error,
- code: 3
- };
- }
-
- player.error(error);
- });
- var defaultSelector = this.options_.experimentalBufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
- // compatibility with < v2
-
- this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
- this.masterPlaylistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
-
- this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
- this.mediaSource = this.masterPlaylistController_.mediaSource; // Proxy assignment of some properties to the master playlist
- // controller. Using a custom property for backwards compatibility
- // with < v2
-
- Object.defineProperties(this, {
- selectPlaylist: {
- get: function get() {
- return this.masterPlaylistController_.selectPlaylist;
- },
- set: function set(selectPlaylist) {
- this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
- }
- },
- throughput: {
- get: function get() {
- return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
- },
- set: function set(throughput) {
- this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
- // for the cumulative average
-
- this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
- }
- },
- bandwidth: {
- get: function get() {
- return this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
- },
- set: function set(bandwidth) {
- this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
- // `count` is set to zero that current value of `rate` isn't included
- // in the cumulative average
-
- this.masterPlaylistController_.mainSegmentLoader_.throughput = {
- rate: 0,
- count: 0
- };
- }
- },
-
- /**
- * `systemBandwidth` is a combination of two serial processes bit-rates. The first
- * is the network bitrate provided by `bandwidth` and the second is the bitrate of
- * the entire process after that - decryption, transmuxing, and appending - provided
- * by `throughput`.
- *
- * Since the two process are serial, the overall system bandwidth is given by:
- * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
- */
- systemBandwidth: {
- get: function get() {
- var invBandwidth = 1 / (this.bandwidth || 1);
- var invThroughput;
-
- if (this.throughput > 0) {
- invThroughput = 1 / this.throughput;
- } else {
- invThroughput = 0;
- }
-
- var systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
- return systemBitrate;
- },
- set: function set() {
- videojs.log.error('The "systemBandwidth" property is read-only');
- }
- }
- });
-
- if (this.options_.bandwidth) {
- this.bandwidth = this.options_.bandwidth;
- }
-
- if (this.options_.throughput) {
- this.throughput = this.options_.throughput;
- }
-
- Object.defineProperties(this.stats, {
- bandwidth: {
- get: function get() {
- return _this3.bandwidth || 0;
- },
- enumerable: true
- },
- mediaRequests: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequests_() || 0;
- },
- enumerable: true
- },
- mediaRequestsAborted: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsAborted_() || 0;
- },
- enumerable: true
- },
- mediaRequestsTimedout: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsTimedout_() || 0;
- },
- enumerable: true
- },
- mediaRequestsErrored: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsErrored_() || 0;
- },
- enumerable: true
- },
- mediaTransferDuration: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaTransferDuration_() || 0;
- },
- enumerable: true
- },
- mediaBytesTransferred: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaBytesTransferred_() || 0;
- },
- enumerable: true
- },
- mediaSecondsLoaded: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaSecondsLoaded_() || 0;
- },
- enumerable: true
- },
- mediaAppends: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaAppends_() || 0;
- },
- enumerable: true
- },
- mainAppendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.mainAppendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- audioAppendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.audioAppendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- appendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.appendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- timeToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.timeToLoadedData_() || 0;
- },
- enumerable: true
- },
- buffered: {
- get: function get() {
- return timeRangesToArray(_this3.tech_.buffered());
- },
- enumerable: true
- },
- currentTime: {
- get: function get() {
- return _this3.tech_.currentTime();
- },
- enumerable: true
- },
- currentSource: {
- get: function get() {
- return _this3.tech_.currentSource_;
- },
- enumerable: true
- },
- currentTech: {
- get: function get() {
- return _this3.tech_.name_;
- },
- enumerable: true
- },
- duration: {
- get: function get() {
- return _this3.tech_.duration();
- },
- enumerable: true
- },
- master: {
- get: function get() {
- return _this3.playlists.master;
- },
- enumerable: true
- },
- playerDimensions: {
- get: function get() {
- return _this3.tech_.currentDimensions();
- },
- enumerable: true
- },
- seekable: {
- get: function get() {
- return timeRangesToArray(_this3.tech_.seekable());
- },
- enumerable: true
- },
- timestamp: {
- get: function get() {
- return Date.now();
- },
- enumerable: true
- },
- videoPlaybackQuality: {
- get: function get() {
- return _this3.tech_.getVideoPlaybackQuality();
- },
- enumerable: true
- }
- });
- this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
- this.tech_.on('bandwidthupdate', function () {
- if (_this3.options_.useBandwidthFromLocalStorage) {
- updateVhsLocalStorage({
- bandwidth: _this3.bandwidth,
- throughput: Math.round(_this3.throughput)
- });
- }
- });
- this.masterPlaylistController_.on('selectedinitialmedia', function () {
- // Add the manual rendition mix-in to VhsHandler
- renditionSelectionMixin(_this3);
- });
- this.masterPlaylistController_.sourceUpdater_.on('createdsourcebuffers', function () {
- _this3.setupEme_();
- }); // the bandwidth of the primary segment loader is our best
- // estimate of overall bandwidth
-
- this.on(this.masterPlaylistController_, 'progress', function () {
- this.tech_.trigger('progress');
- }); // In the live case, we need to ignore the very first `seeking` event since
- // that will be the result of the seek-to-live behavior
-
- this.on(this.masterPlaylistController_, 'firstplay', function () {
- this.ignoreNextSeekingEvent_ = true;
- });
- this.setupQualityLevels_(); // do nothing if the tech has been disposed already
- // this can occur if someone sets the src in player.ready(), for instance
-
- if (!this.tech_.el()) {
- return;
- }
-
- this.mediaSourceUrl_ = window.URL.createObjectURL(this.masterPlaylistController_.mediaSource);
- this.tech_.src(this.mediaSourceUrl_);
- }
- /**
- * If necessary and EME is available, sets up EME options and waits for key session
- * creation.
- *
- * This function also updates the source updater so taht it can be used, as for some
- * browsers, EME must be configured before content is appended (if appending unencrypted
- * content before encrypted content).
- */
- ;
-
- _proto.setupEme_ = function setupEme_() {
- var _this4 = this;
-
- var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
- var didSetupEmeOptions = setupEmeOptions({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- media: this.playlists.media(),
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
- }); // In IE11 this is too early to initialize media keys, and IE11 does not support
- // promises.
-
- if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
- // If EME options were not set up, we've done all we could to initialize EME.
- this.masterPlaylistController_.sourceUpdater_.initializedEme();
- return;
- }
-
- this.logger_('waiting for EME key session creation');
- waitForKeySessionCreation({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
- mainPlaylists: this.playlists.master.playlists
- }).then(function () {
- _this4.logger_('created EME key session');
-
- _this4.masterPlaylistController_.sourceUpdater_.initializedEme();
- }).catch(function (err) {
- _this4.logger_('error while creating EME key session', err);
-
- _this4.player_.error({
- message: 'Failed to initialize media keys for EME',
- code: 3
- });
- });
- }
- /**
- * Initializes the quality levels and sets listeners to update them.
- *
- * @method setupQualityLevels_
- * @private
- */
- ;
-
- _proto.setupQualityLevels_ = function setupQualityLevels_() {
- var _this5 = this;
-
- var player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
- // or qualityLevels_ listeners have already been setup, do nothing.
-
- if (!player || !player.qualityLevels || this.qualityLevels_) {
- return;
- }
-
- this.qualityLevels_ = player.qualityLevels();
- this.masterPlaylistController_.on('selectedinitialmedia', function () {
- handleVhsLoadedMetadata(_this5.qualityLevels_, _this5);
- });
- this.playlists.on('mediachange', function () {
- handleVhsMediaChange(_this5.qualityLevels_, _this5.playlists);
- });
- }
- /**
- * return the version
- */
- ;
-
- VhsHandler.version = function version$5() {
- return {
- '@videojs/http-streaming': version$4,
- 'mux.js': version$3,
- 'mpd-parser': version$2,
- 'm3u8-parser': version$1,
- 'aes-decrypter': version
- };
- }
- /**
- * return the version
- */
- ;
-
- _proto.version = function version() {
- return this.constructor.version();
- };
-
- _proto.canChangeType = function canChangeType() {
- return SourceUpdater.canChangeType();
- }
- /**
- * Begin playing the video.
- */
- ;
-
- _proto.play = function play() {
- this.masterPlaylistController_.play();
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.setCurrentTime = function setCurrentTime(currentTime) {
- this.masterPlaylistController_.setCurrentTime(currentTime);
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.duration = function duration() {
- return this.masterPlaylistController_.duration();
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.seekable = function seekable() {
- return this.masterPlaylistController_.seekable();
- }
- /**
- * Abort all outstanding work and cleanup.
- */
- ;
-
- _proto.dispose = function dispose() {
- if (this.playbackWatcher_) {
- this.playbackWatcher_.dispose();
- }
-
- if (this.masterPlaylistController_) {
- this.masterPlaylistController_.dispose();
- }
-
- if (this.qualityLevels_) {
- this.qualityLevels_.dispose();
- }
-
- if (this.player_) {
- delete this.player_.vhs;
- delete this.player_.dash;
- delete this.player_.hls;
- }
-
- if (this.tech_ && this.tech_.vhs) {
- delete this.tech_.vhs;
- } // don't check this.tech_.hls as it will log a deprecated warning
-
-
- if (this.tech_) {
- delete this.tech_.hls;
- }
-
- if (this.mediaSourceUrl_ && window.URL.revokeObjectURL) {
- window.URL.revokeObjectURL(this.mediaSourceUrl_);
- this.mediaSourceUrl_ = null;
- }
-
- _Component.prototype.dispose.call(this);
- };
-
- _proto.convertToProgramTime = function convertToProgramTime(time, callback) {
- return getProgramTime({
- playlist: this.masterPlaylistController_.media(),
- time: time,
- callback: callback
- });
- } // the player must be playing before calling this
- ;
-
- _proto.seekToProgramTime = function seekToProgramTime$1(programTime, callback, pauseAfterSeek, retryCount) {
- if (pauseAfterSeek === void 0) {
- pauseAfterSeek = true;
- }
-
- if (retryCount === void 0) {
- retryCount = 2;
- }
-
- return seekToProgramTime({
- programTime: programTime,
- playlist: this.masterPlaylistController_.media(),
- retryCount: retryCount,
- pauseAfterSeek: pauseAfterSeek,
- seekTo: this.options_.seekTo,
- tech: this.options_.tech,
- callback: callback
- });
- };
-
- return VhsHandler;
-}(Component);
-/**
- * The Source Handler object, which informs video.js what additional
- * MIME types are supported and sets up playback. It is registered
- * automatically to the appropriate tech based on the capabilities of
- * the browser it is running in. It is not necessary to use or modify
- * this object in normal usage.
- */
-
-
-var VhsSourceHandler = {
- name: 'videojs-http-streaming',
- VERSION: version$4,
- canHandleSource: function canHandleSource(srcObj, options) {
- if (options === void 0) {
- options = {};
- }
-
- var localOptions = videojs.mergeOptions(videojs.options, options);
- return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
- },
- handleSource: function handleSource(source, tech, options) {
- if (options === void 0) {
- options = {};
- }
-
- var localOptions = videojs.mergeOptions(videojs.options, options);
- tech.vhs = new VhsHandler(source, tech, localOptions);
-
- if (!videojs.hasOwnProperty('hls')) {
- Object.defineProperty(tech, 'hls', {
- get: function get() {
- videojs.log.warn('player.tech().hls is deprecated. Use player.tech().vhs instead.');
- return tech.vhs;
- },
- configurable: true
- });
- }
-
- tech.vhs.xhr = xhrFactory();
- tech.vhs.src(source.src, source.type);
- return tech.vhs;
- },
- canPlayType: function canPlayType(type, options) {
- if (options === void 0) {
- options = {};
- }
-
- var _videojs$mergeOptions = videojs.mergeOptions(videojs.options, options),
- _videojs$mergeOptions2 = _videojs$mergeOptions.vhs.overrideNative,
- overrideNative = _videojs$mergeOptions2 === void 0 ? !videojs.browser.IS_ANY_SAFARI : _videojs$mergeOptions2;
-
- var supportedType = simpleTypeFromSourceType(type);
- var canUseMsePlayback = supportedType && (!Vhs.supportsTypeNatively(supportedType) || overrideNative);
- return canUseMsePlayback ? 'maybe' : '';
- }
-};
-/**
- * Check to see if the native MediaSource object exists and supports
- * an MP4 container with both H.264 video and AAC-LC audio.
- *
- * @return {boolean} if native media sources are supported
- */
-
-var supportsNativeMediaSources = function supportsNativeMediaSources() {
- return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
-}; // register source handlers with the appropriate techs
-
-
-if (supportsNativeMediaSources()) {
- videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
-}
-
-videojs.VhsHandler = VhsHandler;
-Object.defineProperty(videojs, 'HlsHandler', {
- get: function get() {
- videojs.log.warn('videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.');
- return VhsHandler;
- },
- configurable: true
-});
-videojs.VhsSourceHandler = VhsSourceHandler;
-Object.defineProperty(videojs, 'HlsSourceHandler', {
- get: function get() {
- videojs.log.warn('videojs.HlsSourceHandler is deprecated. ' + 'Use videojs.VhsSourceHandler instead.');
- return VhsSourceHandler;
- },
- configurable: true
-});
-videojs.Vhs = Vhs;
-Object.defineProperty(videojs, 'Hls', {
- get: function get() {
- videojs.log.warn('videojs.Hls is deprecated. Use videojs.Vhs instead.');
- return Vhs;
- },
- configurable: true
-});
-
-if (!videojs.use) {
- videojs.registerComponent('Hls', Vhs);
- videojs.registerComponent('Vhs', Vhs);
-}
-
-videojs.options.vhs = videojs.options.vhs || {};
-videojs.options.hls = videojs.options.hls || {};
-
-if (videojs.registerPlugin) {
- videojs.registerPlugin('reloadSourceOnError', reloadSourceOnError);
-} else {
- videojs.plugin('reloadSourceOnError', reloadSourceOnError);
-}
-
-export { LOCAL_STORAGE_KEY, Vhs, VhsHandler, VhsSourceHandler, emeKeySystems, expandDataUri, getAllPsshKeySystemsOptions, setupEmeOptions, waitForKeySessionCreation };
diff --git a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.js b/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.js
deleted file mode 100644
index f39bb86..0000000
--- a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.js
+++ /dev/null
@@ -1,30873 +0,0 @@
-/*! @name @videojs/http-streaming @version 2.9.1 @license Apache-2.0 */
-(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('global/document'), require('global/window'), require('video.js'), require('xmldom')) :
- typeof define === 'function' && define.amd ? define(['exports', 'global/document', 'global/window', 'video.js', 'xmldom'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.httpStreaming = {}, global.document, global.window, global.videojs, global.window));
-}(this, (function (exports, document, window, videojs, xmldom) { 'use strict';
-
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
-
- var document__default = /*#__PURE__*/_interopDefaultLegacy(document);
- var window__default = /*#__PURE__*/_interopDefaultLegacy(window);
- var videojs__default = /*#__PURE__*/_interopDefaultLegacy(videojs);
-
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
-
- function commonjsRequire () {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
-
- var assertThisInitialized = createCommonjsModule(function (module) {
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
-
- return self;
- }
-
- module.exports = _assertThisInitialized;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
-
- var setPrototypeOf = createCommonjsModule(function (module) {
- function _setPrototypeOf(o, p) {
- module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _setPrototypeOf(o, p);
- }
-
- module.exports = _setPrototypeOf;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
-
- var inheritsLoose = createCommonjsModule(function (module) {
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- setPrototypeOf(subClass, superClass);
- }
-
- module.exports = _inheritsLoose;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
-
- var urlToolkit = createCommonjsModule(function (module, exports) {
- // see https://tools.ietf.org/html/rfc1808
- (function (root) {
- var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/;
- var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
- var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
- var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
- var URLToolkit = {
- // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
- // E.g
- // With opts.alwaysNormalize = false (default, spec compliant)
- // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
- // With opts.alwaysNormalize = true (not spec compliant)
- // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
- buildAbsoluteURL: function buildAbsoluteURL(baseURL, relativeURL, opts) {
- opts = opts || {}; // remove any remaining space and CRLF
-
- baseURL = baseURL.trim();
- relativeURL = relativeURL.trim();
-
- if (!relativeURL) {
- // 2a) If the embedded URL is entirely empty, it inherits the
- // entire base URL (i.e., is set equal to the base URL)
- // and we are done.
- if (!opts.alwaysNormalize) {
- return baseURL;
- }
-
- var basePartsForNormalise = URLToolkit.parseURL(baseURL);
-
- if (!basePartsForNormalise) {
- throw new Error('Error trying to parse base URL.');
- }
-
- basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
- return URLToolkit.buildURLFromParts(basePartsForNormalise);
- }
-
- var relativeParts = URLToolkit.parseURL(relativeURL);
-
- if (!relativeParts) {
- throw new Error('Error trying to parse relative URL.');
- }
-
- if (relativeParts.scheme) {
- // 2b) If the embedded URL starts with a scheme name, it is
- // interpreted as an absolute URL and we are done.
- if (!opts.alwaysNormalize) {
- return relativeURL;
- }
-
- relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
- return URLToolkit.buildURLFromParts(relativeParts);
- }
-
- var baseParts = URLToolkit.parseURL(baseURL);
-
- if (!baseParts) {
- throw new Error('Error trying to parse base URL.');
- }
-
- if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
- // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
- // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
- var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
- baseParts.netLoc = pathParts[1];
- baseParts.path = pathParts[2];
- }
-
- if (baseParts.netLoc && !baseParts.path) {
- baseParts.path = '/';
- }
-
- var builtParts = {
- // 2c) Otherwise, the embedded URL inherits the scheme of
- // the base URL.
- scheme: baseParts.scheme,
- netLoc: relativeParts.netLoc,
- path: null,
- params: relativeParts.params,
- query: relativeParts.query,
- fragment: relativeParts.fragment
- };
-
- if (!relativeParts.netLoc) {
- // 3) If the embedded URL's is non-empty, we skip to
- // Step 7. Otherwise, the embedded URL inherits the
- // (if any) of the base URL.
- builtParts.netLoc = baseParts.netLoc; // 4) If the embedded URL path is preceded by a slash "/", the
- // path is not relative and we skip to Step 7.
-
- if (relativeParts.path[0] !== '/') {
- if (!relativeParts.path) {
- // 5) If the embedded URL path is empty (and not preceded by a
- // slash), then the embedded URL inherits the base URL path
- builtParts.path = baseParts.path; // 5a) if the embedded URL's is non-empty, we skip to
- // step 7; otherwise, it inherits the of the base
- // URL (if any) and
-
- if (!relativeParts.params) {
- builtParts.params = baseParts.params; // 5b) if the embedded URL's is non-empty, we skip to
- // step 7; otherwise, it inherits the of the base
- // URL (if any) and we skip to step 7.
-
- if (!relativeParts.query) {
- builtParts.query = baseParts.query;
- }
- }
- } else {
- // 6) The last segment of the base URL's path (anything
- // following the rightmost slash "/", or the entire path if no
- // slash is present) is removed and the embedded URL's path is
- // appended in its place.
- var baseURLPath = baseParts.path;
- var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
- builtParts.path = URLToolkit.normalizePath(newPath);
- }
- }
- }
-
- if (builtParts.path === null) {
- builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
- }
-
- return URLToolkit.buildURLFromParts(builtParts);
- },
- parseURL: function parseURL(url) {
- var parts = URL_REGEX.exec(url);
-
- if (!parts) {
- return null;
- }
-
- return {
- scheme: parts[1] || '',
- netLoc: parts[2] || '',
- path: parts[3] || '',
- params: parts[4] || '',
- query: parts[5] || '',
- fragment: parts[6] || ''
- };
- },
- normalizePath: function normalizePath(path) {
- // The following operations are
- // then applied, in order, to the new path:
- // 6a) All occurrences of "./", where "." is a complete path
- // segment, are removed.
- // 6b) If the path ends with "." as a complete path segment,
- // that "." is removed.
- path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "/../", where is a
- // complete path segment not equal to "..", are removed.
- // Removal of these path segments is performed iteratively,
- // removing the leftmost matching pattern on each iteration,
- // until no matching pattern remains.
- // 6d) If the path ends with "/..", where is a
- // complete path segment not equal to "..", that
- // "/.." is removed.
-
- while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
-
- return path.split('').reverse().join('');
- },
- buildURLFromParts: function buildURLFromParts(parts) {
- return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
- }
- };
- module.exports = URLToolkit;
- })();
- });
-
- var DEFAULT_LOCATION = 'http://example.com';
-
- var resolveUrl$1 = function resolveUrl(baseUrl, relativeUrl) {
- // return early if we don't need to resolve
- if (/^[a-z]+:/i.test(relativeUrl)) {
- return relativeUrl;
- } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
-
-
- if (/^data:/.test(baseUrl)) {
- baseUrl = window__default['default'].location && window__default['default'].location.href || '';
- } // IE11 supports URL but not the URL constructor
- // feature detect the behavior we want
-
-
- var nativeURL = typeof window__default['default'].URL === 'function';
- var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
- // and if baseUrl isn't an absolute url
-
- var removeLocation = !window__default['default'].location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
-
- if (nativeURL) {
- baseUrl = new window__default['default'].URL(baseUrl, window__default['default'].location || DEFAULT_LOCATION);
- } else if (!/\/\//i.test(baseUrl)) {
- baseUrl = urlToolkit.buildAbsoluteURL(window__default['default'].location && window__default['default'].location.href || '', baseUrl);
- }
-
- if (nativeURL) {
- var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
- // and if we're location-less, remove the location
- // otherwise, return the url unmodified
-
- if (removeLocation) {
- return newUrl.href.slice(DEFAULT_LOCATION.length);
- } else if (protocolLess) {
- return newUrl.href.slice(newUrl.protocol.length);
- }
-
- return newUrl.href;
- }
-
- return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
- };
-
- /**
- * @file resolve-url.js - Handling how URLs are resolved and manipulated
- */
- var resolveUrl = resolveUrl$1;
- /**
- * Checks whether xhr request was redirected and returns correct url depending
- * on `handleManifestRedirects` option
- *
- * @api private
- *
- * @param {string} url - an url being requested
- * @param {XMLHttpRequest} req - xhr request result
- *
- * @return {string}
- */
-
- var resolveManifestRedirect = function resolveManifestRedirect(handleManifestRedirect, url, req) {
- // To understand how the responseURL below is set and generated:
- // - https://fetch.spec.whatwg.org/#concept-response-url
- // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
- if (handleManifestRedirect && req && req.responseURL && url !== req.responseURL) {
- return req.responseURL;
- }
-
- return url;
- };
-
- var logger = function logger(source) {
- if (videojs__default['default'].log.debug) {
- return videojs__default['default'].log.debug.bind(videojs__default['default'], 'VHS:', source + " >");
- }
-
- return function () {};
- };
-
- var _extends_1 = createCommonjsModule(function (module) {
- function _extends() {
- module.exports = _extends = Object.assign || function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
-
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
-
- return target;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _extends.apply(this, arguments);
- }
-
- module.exports = _extends;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
-
- /**
- * @file stream.js
- */
-
- /**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
- var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
- }();
-
- var atob = function atob(s) {
- return window__default['default'].atob ? window__default['default'].atob(s) : Buffer.from(s, 'base64').toString('binary');
- };
-
- function decodeB64ToUint8Array(b64Text) {
- var decodedString = atob(b64Text);
- var array = new Uint8Array(decodedString.length);
-
- for (var i = 0; i < decodedString.length; i++) {
- array[i] = decodedString.charCodeAt(i);
- }
-
- return array;
- }
-
- /*! @name m3u8-parser @version 4.7.0 @license Apache-2.0 */
- /**
- * A stream that buffers string input and generates a `data` event for each
- * line.
- *
- * @class LineStream
- * @extends Stream
- */
-
- var LineStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(LineStream, _Stream);
-
- function LineStream() {
- var _this;
-
- _this = _Stream.call(this) || this;
- _this.buffer = '';
- return _this;
- }
- /**
- * Add new data to be parsed.
- *
- * @param {string} data the text to process
- */
-
-
- var _proto = LineStream.prototype;
-
- _proto.push = function push(data) {
- var nextNewline;
- this.buffer += data;
- nextNewline = this.buffer.indexOf('\n');
-
- for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
- this.trigger('data', this.buffer.substring(0, nextNewline));
- this.buffer = this.buffer.substring(nextNewline + 1);
- }
- };
-
- return LineStream;
- }(Stream);
-
- var TAB = String.fromCharCode(0x09);
-
- var parseByterange = function parseByterange(byterangeString) {
- // optionally match and capture 0+ digits before `@`
- // optionally match and capture 0+ digits after `@`
- var match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || '');
- var result = {};
-
- if (match[1]) {
- result.length = parseInt(match[1], 10);
- }
-
- if (match[2]) {
- result.offset = parseInt(match[2], 10);
- }
-
- return result;
- };
- /**
- * "forgiving" attribute list psuedo-grammar:
- * attributes -> keyvalue (',' keyvalue)*
- * keyvalue -> key '=' value
- * key -> [^=]*
- * value -> '"' [^"]* '"' | [^,]*
- */
-
-
- var attributeSeparator = function attributeSeparator() {
- var key = '[^=]*';
- var value = '"[^"]*"|[^,]*';
- var keyvalue = '(?:' + key + ')=(?:' + value + ')';
- return new RegExp('(?:^|,)(' + keyvalue + ')');
- };
- /**
- * Parse attributes from a line given the separator
- *
- * @param {string} attributes the attribute line to parse
- */
-
-
- var parseAttributes$1 = function parseAttributes(attributes) {
- // split the string using attributes as the separator
- var attrs = attributes.split(attributeSeparator());
- var result = {};
- var i = attrs.length;
- var attr;
-
- while (i--) {
- // filter out unmatched portions of the string
- if (attrs[i] === '') {
- continue;
- } // split the key and value
-
-
- attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
-
- attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
- attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
- attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
- result[attr[0]] = attr[1];
- }
-
- return result;
- };
- /**
- * A line-level M3U8 parser event stream. It expects to receive input one
- * line at a time and performs a context-free parse of its contents. A stream
- * interpretation of a manifest can be useful if the manifest is expected to
- * be too large to fit comfortably into memory or the entirety of the input
- * is not immediately available. Otherwise, it's probably much easier to work
- * with a regular `Parser` object.
- *
- * Produces `data` events with an object that captures the parser's
- * interpretation of the input. That object has a property `tag` that is one
- * of `uri`, `comment`, or `tag`. URIs only have a single additional
- * property, `line`, which captures the entirety of the input without
- * interpretation. Comments similarly have a single additional property
- * `text` which is the input without the leading `#`.
- *
- * Tags always have a property `tagType` which is the lower-cased version of
- * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
- * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
- * tags are given the tag type `unknown` and a single additional property
- * `data` with the remainder of the input.
- *
- * @class ParseStream
- * @extends Stream
- */
-
-
- var ParseStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(ParseStream, _Stream);
-
- function ParseStream() {
- var _this;
-
- _this = _Stream.call(this) || this;
- _this.customParsers = [];
- _this.tagMappers = [];
- return _this;
- }
- /**
- * Parses an additional line of input.
- *
- * @param {string} line a single line of an M3U8 file to parse
- */
-
-
- var _proto = ParseStream.prototype;
-
- _proto.push = function push(line) {
- var _this2 = this;
-
- var match;
- var event; // strip whitespace
-
- line = line.trim();
-
- if (line.length === 0) {
- // ignore empty lines
- return;
- } // URIs
-
-
- if (line[0] !== '#') {
- this.trigger('data', {
- type: 'uri',
- uri: line
- });
- return;
- } // map tags
-
-
- var newLines = this.tagMappers.reduce(function (acc, mapper) {
- var mappedLine = mapper(line); // skip if unchanged
-
- if (mappedLine === line) {
- return acc;
- }
-
- return acc.concat([mappedLine]);
- }, [line]);
- newLines.forEach(function (newLine) {
- for (var i = 0; i < _this2.customParsers.length; i++) {
- if (_this2.customParsers[i].call(_this2, newLine)) {
- return;
- }
- } // Comments
-
-
- if (newLine.indexOf('#EXT') !== 0) {
- _this2.trigger('data', {
- type: 'comment',
- text: newLine.slice(1)
- });
-
- return;
- } // strip off any carriage returns here so the regex matching
- // doesn't have to account for them.
-
-
- newLine = newLine.replace('\r', ''); // Tags
-
- match = /^#EXTM3U/.exec(newLine);
-
- if (match) {
- _this2.trigger('data', {
- type: 'tag',
- tagType: 'm3u'
- });
-
- return;
- }
-
- match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'inf'
- };
-
- if (match[1]) {
- event.duration = parseFloat(match[1]);
- }
-
- if (match[2]) {
- event.title = match[2];
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'targetduration'
- };
-
- if (match[1]) {
- event.duration = parseInt(match[1], 10);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-VERSION:?([0-9.]*)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'version'
- };
-
- if (match[1]) {
- event.version = parseInt(match[1], 10);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'media-sequence'
- };
-
- if (match[1]) {
- event.number = parseInt(match[1], 10);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'discontinuity-sequence'
- };
-
- if (match[1]) {
- event.number = parseInt(match[1], 10);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'playlist-type'
- };
-
- if (match[1]) {
- event.playlistType = match[1];
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-BYTERANGE:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = _extends_1(parseByterange(match[1]), {
- type: 'tag',
- tagType: 'byterange'
- });
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'allow-cache'
- };
-
- if (match[1]) {
- event.allowed = !/NO/.test(match[1]);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-MAP:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'map'
- };
-
- if (match[1]) {
- var attributes = parseAttributes$1(match[1]);
-
- if (attributes.URI) {
- event.uri = attributes.URI;
- }
-
- if (attributes.BYTERANGE) {
- event.byterange = parseByterange(attributes.BYTERANGE);
- }
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-STREAM-INF:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'stream-inf'
- };
-
- if (match[1]) {
- event.attributes = parseAttributes$1(match[1]);
-
- if (event.attributes.RESOLUTION) {
- var split = event.attributes.RESOLUTION.split('x');
- var resolution = {};
-
- if (split[0]) {
- resolution.width = parseInt(split[0], 10);
- }
-
- if (split[1]) {
- resolution.height = parseInt(split[1], 10);
- }
-
- event.attributes.RESOLUTION = resolution;
- }
-
- if (event.attributes.BANDWIDTH) {
- event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
- }
-
- if (event.attributes['PROGRAM-ID']) {
- event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
- }
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-MEDIA:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'media'
- };
-
- if (match[1]) {
- event.attributes = parseAttributes$1(match[1]);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-ENDLIST/.exec(newLine);
-
- if (match) {
- _this2.trigger('data', {
- type: 'tag',
- tagType: 'endlist'
- });
-
- return;
- }
-
- match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
-
- if (match) {
- _this2.trigger('data', {
- type: 'tag',
- tagType: 'discontinuity'
- });
-
- return;
- }
-
- match = /^#EXT-X-PROGRAM-DATE-TIME:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'program-date-time'
- };
-
- if (match[1]) {
- event.dateTimeString = match[1];
- event.dateTimeObject = new Date(match[1]);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-KEY:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'key'
- };
-
- if (match[1]) {
- event.attributes = parseAttributes$1(match[1]); // parse the IV string into a Uint32Array
-
- if (event.attributes.IV) {
- if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
- event.attributes.IV = event.attributes.IV.substring(2);
- }
-
- event.attributes.IV = event.attributes.IV.match(/.{8}/g);
- event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
- event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
- event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
- event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
- event.attributes.IV = new Uint32Array(event.attributes.IV);
- }
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-START:?(.*)$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'start'
- };
-
- if (match[1]) {
- event.attributes = parseAttributes$1(match[1]);
- event.attributes['TIME-OFFSET'] = parseFloat(event.attributes['TIME-OFFSET']);
- event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-CUE-OUT-CONT:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'cue-out-cont'
- };
-
- if (match[1]) {
- event.data = match[1];
- } else {
- event.data = '';
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-CUE-OUT:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'cue-out'
- };
-
- if (match[1]) {
- event.data = match[1];
- } else {
- event.data = '';
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-CUE-IN:?(.*)?$/.exec(newLine);
-
- if (match) {
- event = {
- type: 'tag',
- tagType: 'cue-in'
- };
-
- if (match[1]) {
- event.data = match[1];
- } else {
- event.data = '';
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'skip'
- };
- event.attributes = parseAttributes$1(match[1]);
-
- if (event.attributes.hasOwnProperty('SKIPPED-SEGMENTS')) {
- event.attributes['SKIPPED-SEGMENTS'] = parseInt(event.attributes['SKIPPED-SEGMENTS'], 10);
- }
-
- if (event.attributes.hasOwnProperty('RECENTLY-REMOVED-DATERANGES')) {
- event.attributes['RECENTLY-REMOVED-DATERANGES'] = event.attributes['RECENTLY-REMOVED-DATERANGES'].split(TAB);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-PART:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'part'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['DURATION'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseFloat(event.attributes[key]);
- }
- });
- ['INDEPENDENT', 'GAP'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = /YES/.test(event.attributes[key]);
- }
- });
-
- if (event.attributes.hasOwnProperty('BYTERANGE')) {
- event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
- }
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'server-control'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['CAN-SKIP-UNTIL', 'PART-HOLD-BACK', 'HOLD-BACK'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseFloat(event.attributes[key]);
- }
- });
- ['CAN-SKIP-DATERANGES', 'CAN-BLOCK-RELOAD'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = /YES/.test(event.attributes[key]);
- }
- });
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'part-inf'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['PART-TARGET'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseFloat(event.attributes[key]);
- }
- });
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'preload-hint'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['BYTERANGE-START', 'BYTERANGE-LENGTH'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseInt(event.attributes[key], 10);
- var subkey = key === 'BYTERANGE-LENGTH' ? 'length' : 'offset';
- event.attributes.byterange = event.attributes.byterange || {};
- event.attributes.byterange[subkey] = event.attributes[key]; // only keep the parsed byterange object.
-
- delete event.attributes[key];
- }
- });
-
- _this2.trigger('data', event);
-
- return;
- }
-
- match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
-
- if (match && match[1]) {
- event = {
- type: 'tag',
- tagType: 'rendition-report'
- };
- event.attributes = parseAttributes$1(match[1]);
- ['LAST-MSN', 'LAST-PART'].forEach(function (key) {
- if (event.attributes.hasOwnProperty(key)) {
- event.attributes[key] = parseInt(event.attributes[key], 10);
- }
- });
-
- _this2.trigger('data', event);
-
- return;
- } // unknown tag type
-
-
- _this2.trigger('data', {
- type: 'tag',
- data: newLine.slice(4)
- });
- });
- }
- /**
- * Add a parser for custom headers
- *
- * @param {Object} options a map of options for the added parser
- * @param {RegExp} options.expression a regular expression to match the custom header
- * @param {string} options.customType the custom type to register to the output
- * @param {Function} [options.dataParser] function to parse the line into an object
- * @param {boolean} [options.segment] should tag data be attached to the segment object
- */
- ;
-
- _proto.addParser = function addParser(_ref) {
- var _this3 = this;
-
- var expression = _ref.expression,
- customType = _ref.customType,
- dataParser = _ref.dataParser,
- segment = _ref.segment;
-
- if (typeof dataParser !== 'function') {
- dataParser = function dataParser(line) {
- return line;
- };
- }
-
- this.customParsers.push(function (line) {
- var match = expression.exec(line);
-
- if (match) {
- _this3.trigger('data', {
- type: 'custom',
- data: dataParser(line),
- customType: customType,
- segment: segment
- });
-
- return true;
- }
- });
- }
- /**
- * Add a custom header mapper
- *
- * @param {Object} options
- * @param {RegExp} options.expression a regular expression to match the custom header
- * @param {Function} options.map function to translate tag into a different tag
- */
- ;
-
- _proto.addTagMapper = function addTagMapper(_ref2) {
- var expression = _ref2.expression,
- map = _ref2.map;
-
- var mapFn = function mapFn(line) {
- if (expression.test(line)) {
- return map(line);
- }
-
- return line;
- };
-
- this.tagMappers.push(mapFn);
- };
-
- return ParseStream;
- }(Stream);
-
- var camelCase = function camelCase(str) {
- return str.toLowerCase().replace(/-(\w)/g, function (a) {
- return a[1].toUpperCase();
- });
- };
-
- var camelCaseKeys = function camelCaseKeys(attributes) {
- var result = {};
- Object.keys(attributes).forEach(function (key) {
- result[camelCase(key)] = attributes[key];
- });
- return result;
- }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
- // we need this helper because defaults are based upon targetDuration and
- // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
- // target durations are set.
-
-
- var setHoldBack = function setHoldBack(manifest) {
- var serverControl = manifest.serverControl,
- targetDuration = manifest.targetDuration,
- partTargetDuration = manifest.partTargetDuration;
-
- if (!serverControl) {
- return;
- }
-
- var tag = '#EXT-X-SERVER-CONTROL';
- var hb = 'holdBack';
- var phb = 'partHoldBack';
- var minTargetDuration = targetDuration && targetDuration * 3;
- var minPartDuration = partTargetDuration && partTargetDuration * 2;
-
- if (targetDuration && !serverControl.hasOwnProperty(hb)) {
- serverControl[hb] = minTargetDuration;
- this.trigger('info', {
- message: tag + " defaulting HOLD-BACK to targetDuration * 3 (" + minTargetDuration + ")."
- });
- }
-
- if (minTargetDuration && serverControl[hb] < minTargetDuration) {
- this.trigger('warn', {
- message: tag + " clamping HOLD-BACK (" + serverControl[hb] + ") to targetDuration * 3 (" + minTargetDuration + ")"
- });
- serverControl[hb] = minTargetDuration;
- } // default no part hold back to part target duration * 3
-
-
- if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
- serverControl[phb] = partTargetDuration * 3;
- this.trigger('info', {
- message: tag + " defaulting PART-HOLD-BACK to partTargetDuration * 3 (" + serverControl[phb] + ")."
- });
- } // if part hold back is too small default it to part target duration * 2
-
-
- if (partTargetDuration && serverControl[phb] < minPartDuration) {
- this.trigger('warn', {
- message: tag + " clamping PART-HOLD-BACK (" + serverControl[phb] + ") to partTargetDuration * 2 (" + minPartDuration + ")."
- });
- serverControl[phb] = minPartDuration;
- }
- };
- /**
- * A parser for M3U8 files. The current interpretation of the input is
- * exposed as a property `manifest` on parser objects. It's just two lines to
- * create and parse a manifest once you have the contents available as a string:
- *
- * ```js
- * var parser = new m3u8.Parser();
- * parser.push(xhr.responseText);
- * ```
- *
- * New input can later be applied to update the manifest object by calling
- * `push` again.
- *
- * The parser attempts to create a usable manifest object even if the
- * underlying input is somewhat nonsensical. It emits `info` and `warning`
- * events during the parse if it encounters input that seems invalid or
- * requires some property of the manifest object to be defaulted.
- *
- * @class Parser
- * @extends Stream
- */
-
-
- var Parser = /*#__PURE__*/function (_Stream) {
- inheritsLoose(Parser, _Stream);
-
- function Parser() {
- var _this;
-
- _this = _Stream.call(this) || this;
- _this.lineStream = new LineStream();
- _this.parseStream = new ParseStream();
-
- _this.lineStream.pipe(_this.parseStream);
- /* eslint-disable consistent-this */
-
-
- var self = assertThisInitialized(_this);
- /* eslint-enable consistent-this */
-
-
- var uris = [];
- var currentUri = {}; // if specified, the active EXT-X-MAP definition
-
- var currentMap; // if specified, the active decryption key
-
- var _key;
-
- var hasParts = false;
-
- var noop = function noop() {};
-
- var defaultMediaGroups = {
- 'AUDIO': {},
- 'VIDEO': {},
- 'CLOSED-CAPTIONS': {},
- 'SUBTITLES': {}
- }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
- // used in MPDs with Widevine encrypted streams.
-
- var widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
-
- var currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
-
- _this.manifest = {
- allowCache: true,
- discontinuityStarts: [],
- segments: []
- }; // keep track of the last seen segment's byte range end, as segments are not required
- // to provide the offset, in which case it defaults to the next byte after the
- // previous segment
-
- var lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
-
- var lastPartByterangeEnd = 0;
-
- _this.on('end', function () {
- // only add preloadSegment if we don't yet have a uri for it.
- // and we actually have parts/preloadHints
- if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
- return;
- }
-
- if (!currentUri.map && currentMap) {
- currentUri.map = currentMap;
- }
-
- if (!currentUri.key && _key) {
- currentUri.key = _key;
- }
-
- if (!currentUri.timeline && typeof currentTimeline === 'number') {
- currentUri.timeline = currentTimeline;
- }
-
- _this.manifest.preloadSegment = currentUri;
- }); // update the manifest with the m3u8 entry from the parse stream
-
-
- _this.parseStream.on('data', function (entry) {
- var mediaGroup;
- var rendition;
- ({
- tag: function tag() {
- // switch based on the tag type
- (({
- version: function version() {
- if (entry.version) {
- this.manifest.version = entry.version;
- }
- },
- 'allow-cache': function allowCache() {
- this.manifest.allowCache = entry.allowed;
-
- if (!('allowed' in entry)) {
- this.trigger('info', {
- message: 'defaulting allowCache to YES'
- });
- this.manifest.allowCache = true;
- }
- },
- byterange: function byterange() {
- var byterange = {};
-
- if ('length' in entry) {
- currentUri.byterange = byterange;
- byterange.length = entry.length;
-
- if (!('offset' in entry)) {
- /*
- * From the latest spec (as of this writing):
- * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
- *
- * Same text since EXT-X-BYTERANGE's introduction in draft 7:
- * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
- *
- * "If o [offset] is not present, the sub-range begins at the next byte
- * following the sub-range of the previous media segment."
- */
- entry.offset = lastByterangeEnd;
- }
- }
-
- if ('offset' in entry) {
- currentUri.byterange = byterange;
- byterange.offset = entry.offset;
- }
-
- lastByterangeEnd = byterange.offset + byterange.length;
- },
- endlist: function endlist() {
- this.manifest.endList = true;
- },
- inf: function inf() {
- if (!('mediaSequence' in this.manifest)) {
- this.manifest.mediaSequence = 0;
- this.trigger('info', {
- message: 'defaulting media sequence to zero'
- });
- }
-
- if (!('discontinuitySequence' in this.manifest)) {
- this.manifest.discontinuitySequence = 0;
- this.trigger('info', {
- message: 'defaulting discontinuity sequence to zero'
- });
- }
-
- if (entry.duration > 0) {
- currentUri.duration = entry.duration;
- }
-
- if (entry.duration === 0) {
- currentUri.duration = 0.01;
- this.trigger('info', {
- message: 'updating zero segment duration to a small value'
- });
- }
-
- this.manifest.segments = uris;
- },
- key: function key() {
- if (!entry.attributes) {
- this.trigger('warn', {
- message: 'ignoring key declaration without attribute list'
- });
- return;
- } // clear the active encryption key
-
-
- if (entry.attributes.METHOD === 'NONE') {
- _key = null;
- return;
- }
-
- if (!entry.attributes.URI) {
- this.trigger('warn', {
- message: 'ignoring key declaration without URI'
- });
- return;
- }
-
- if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
- this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
-
- this.manifest.contentProtection['com.apple.fps.1_0'] = {
- attributes: entry.attributes
- };
- return;
- } // check if the content is encrypted for Widevine
- // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
-
-
- if (entry.attributes.KEYFORMAT === widevineUuid) {
- var VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
-
- if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
- this.trigger('warn', {
- message: 'invalid key method provided for Widevine'
- });
- return;
- }
-
- if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
- this.trigger('warn', {
- message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
- });
- }
-
- if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
- this.trigger('warn', {
- message: 'invalid key URI provided for Widevine'
- });
- return;
- }
-
- if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
- this.trigger('warn', {
- message: 'invalid key ID provided for Widevine'
- });
- return;
- } // if Widevine key attributes are valid, store them as `contentProtection`
- // on the manifest to emulate Widevine tag structure in a DASH mpd
-
-
- this.manifest.contentProtection = this.manifest.contentProtection || {};
- this.manifest.contentProtection['com.widevine.alpha'] = {
- attributes: {
- schemeIdUri: entry.attributes.KEYFORMAT,
- // remove '0x' from the key id string
- keyId: entry.attributes.KEYID.substring(2)
- },
- // decode the base64-encoded PSSH box
- pssh: decodeB64ToUint8Array(entry.attributes.URI.split(',')[1])
- };
- return;
- }
-
- if (!entry.attributes.METHOD) {
- this.trigger('warn', {
- message: 'defaulting key method to AES-128'
- });
- } // setup an encryption key for upcoming segments
-
-
- _key = {
- method: entry.attributes.METHOD || 'AES-128',
- uri: entry.attributes.URI
- };
-
- if (typeof entry.attributes.IV !== 'undefined') {
- _key.iv = entry.attributes.IV;
- }
- },
- 'media-sequence': function mediaSequence() {
- if (!isFinite(entry.number)) {
- this.trigger('warn', {
- message: 'ignoring invalid media sequence: ' + entry.number
- });
- return;
- }
-
- this.manifest.mediaSequence = entry.number;
- },
- 'discontinuity-sequence': function discontinuitySequence() {
- if (!isFinite(entry.number)) {
- this.trigger('warn', {
- message: 'ignoring invalid discontinuity sequence: ' + entry.number
- });
- return;
- }
-
- this.manifest.discontinuitySequence = entry.number;
- currentTimeline = entry.number;
- },
- 'playlist-type': function playlistType() {
- if (!/VOD|EVENT/.test(entry.playlistType)) {
- this.trigger('warn', {
- message: 'ignoring unknown playlist type: ' + entry.playlist
- });
- return;
- }
-
- this.manifest.playlistType = entry.playlistType;
- },
- map: function map() {
- currentMap = {};
-
- if (entry.uri) {
- currentMap.uri = entry.uri;
- }
-
- if (entry.byterange) {
- currentMap.byterange = entry.byterange;
- }
-
- if (_key) {
- currentMap.key = _key;
- }
- },
- 'stream-inf': function streamInf() {
- this.manifest.playlists = uris;
- this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
-
- if (!entry.attributes) {
- this.trigger('warn', {
- message: 'ignoring empty stream-inf attributes'
- });
- return;
- }
-
- if (!currentUri.attributes) {
- currentUri.attributes = {};
- }
-
- _extends_1(currentUri.attributes, entry.attributes);
- },
- media: function media() {
- this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
-
- if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
- this.trigger('warn', {
- message: 'ignoring incomplete or missing media group'
- });
- return;
- } // find the media group, creating defaults as necessary
-
-
- var mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
- mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
- mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
-
- rendition = {
- default: /yes/i.test(entry.attributes.DEFAULT)
- };
-
- if (rendition.default) {
- rendition.autoselect = true;
- } else {
- rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
- }
-
- if (entry.attributes.LANGUAGE) {
- rendition.language = entry.attributes.LANGUAGE;
- }
-
- if (entry.attributes.URI) {
- rendition.uri = entry.attributes.URI;
- }
-
- if (entry.attributes['INSTREAM-ID']) {
- rendition.instreamId = entry.attributes['INSTREAM-ID'];
- }
-
- if (entry.attributes.CHARACTERISTICS) {
- rendition.characteristics = entry.attributes.CHARACTERISTICS;
- }
-
- if (entry.attributes.FORCED) {
- rendition.forced = /yes/i.test(entry.attributes.FORCED);
- } // insert the new rendition
-
-
- mediaGroup[entry.attributes.NAME] = rendition;
- },
- discontinuity: function discontinuity() {
- currentTimeline += 1;
- currentUri.discontinuity = true;
- this.manifest.discontinuityStarts.push(uris.length);
- },
- 'program-date-time': function programDateTime() {
- if (typeof this.manifest.dateTimeString === 'undefined') {
- // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
- // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
- // to the manifest object
- // TODO: Consider removing this in future major version
- this.manifest.dateTimeString = entry.dateTimeString;
- this.manifest.dateTimeObject = entry.dateTimeObject;
- }
-
- currentUri.dateTimeString = entry.dateTimeString;
- currentUri.dateTimeObject = entry.dateTimeObject;
- },
- targetduration: function targetduration() {
- if (!isFinite(entry.duration) || entry.duration < 0) {
- this.trigger('warn', {
- message: 'ignoring invalid target duration: ' + entry.duration
- });
- return;
- }
-
- this.manifest.targetDuration = entry.duration;
- setHoldBack.call(this, this.manifest);
- },
- start: function start() {
- if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
- this.trigger('warn', {
- message: 'ignoring start declaration without appropriate attribute list'
- });
- return;
- }
-
- this.manifest.start = {
- timeOffset: entry.attributes['TIME-OFFSET'],
- precise: entry.attributes.PRECISE
- };
- },
- 'cue-out': function cueOut() {
- currentUri.cueOut = entry.data;
- },
- 'cue-out-cont': function cueOutCont() {
- currentUri.cueOutCont = entry.data;
- },
- 'cue-in': function cueIn() {
- currentUri.cueIn = entry.data;
- },
- 'skip': function skip() {
- this.manifest.skip = camelCaseKeys(entry.attributes);
- this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
- },
- 'part': function part() {
- var _this2 = this;
-
- hasParts = true; // parts are always specifed before a segment
-
- var segmentIndex = this.manifest.segments.length;
- var part = camelCaseKeys(entry.attributes);
- currentUri.parts = currentUri.parts || [];
- currentUri.parts.push(part);
-
- if (part.byterange) {
- if (!part.byterange.hasOwnProperty('offset')) {
- part.byterange.offset = lastPartByterangeEnd;
- }
-
- lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
- }
-
- var partIndex = currentUri.parts.length - 1;
- this.warnOnMissingAttributes_("#EXT-X-PART #" + partIndex + " for segment #" + segmentIndex, entry.attributes, ['URI', 'DURATION']);
-
- if (this.manifest.renditionReports) {
- this.manifest.renditionReports.forEach(function (r, i) {
- if (!r.hasOwnProperty('lastPart')) {
- _this2.trigger('warn', {
- message: "#EXT-X-RENDITION-REPORT #" + i + " lacks required attribute(s): LAST-PART"
- });
- }
- });
- }
- },
- 'server-control': function serverControl() {
- var attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
-
- if (!attrs.hasOwnProperty('canBlockReload')) {
- attrs.canBlockReload = false;
- this.trigger('info', {
- message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
- });
- }
-
- setHoldBack.call(this, this.manifest);
-
- if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
- this.trigger('warn', {
- message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
- });
- }
- },
- 'preload-hint': function preloadHint() {
- // parts are always specifed before a segment
- var segmentIndex = this.manifest.segments.length;
- var hint = camelCaseKeys(entry.attributes);
- var isPart = hint.type && hint.type === 'PART';
- currentUri.preloadHints = currentUri.preloadHints || [];
- currentUri.preloadHints.push(hint);
-
- if (hint.byterange) {
- if (!hint.byterange.hasOwnProperty('offset')) {
- // use last part byterange end or zero if not a part.
- hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
-
- if (isPart) {
- lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
- }
- }
- }
-
- var index = currentUri.preloadHints.length - 1;
- this.warnOnMissingAttributes_("#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex, entry.attributes, ['TYPE', 'URI']);
-
- if (!hint.type) {
- return;
- } // search through all preload hints except for the current one for
- // a duplicate type.
-
-
- for (var i = 0; i < currentUri.preloadHints.length - 1; i++) {
- var otherHint = currentUri.preloadHints[i];
-
- if (!otherHint.type) {
- continue;
- }
-
- if (otherHint.type === hint.type) {
- this.trigger('warn', {
- message: "#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex + " has the same TYPE " + hint.type + " as preload hint #" + i
- });
- }
- }
- },
- 'rendition-report': function renditionReport() {
- var report = camelCaseKeys(entry.attributes);
- this.manifest.renditionReports = this.manifest.renditionReports || [];
- this.manifest.renditionReports.push(report);
- var index = this.manifest.renditionReports.length - 1;
- var required = ['LAST-MSN', 'URI'];
-
- if (hasParts) {
- required.push('LAST-PART');
- }
-
- this.warnOnMissingAttributes_("#EXT-X-RENDITION-REPORT #" + index, entry.attributes, required);
- },
- 'part-inf': function partInf() {
- this.manifest.partInf = camelCaseKeys(entry.attributes);
- this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
-
- if (this.manifest.partInf.partTarget) {
- this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
- }
-
- setHoldBack.call(this, this.manifest);
- }
- })[entry.tagType] || noop).call(self);
- },
- uri: function uri() {
- currentUri.uri = entry.uri;
- uris.push(currentUri); // if no explicit duration was declared, use the target duration
-
- if (this.manifest.targetDuration && !('duration' in currentUri)) {
- this.trigger('warn', {
- message: 'defaulting segment duration to the target duration'
- });
- currentUri.duration = this.manifest.targetDuration;
- } // annotate with encryption information, if necessary
-
-
- if (_key) {
- currentUri.key = _key;
- }
-
- currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
-
- if (currentMap) {
- currentUri.map = currentMap;
- } // reset the last byterange end as it needs to be 0 between parts
-
-
- lastPartByterangeEnd = 0; // prepare for the next URI
-
- currentUri = {};
- },
- comment: function comment() {// comments are not important for playback
- },
- custom: function custom() {
- // if this is segment-level data attach the output to the segment
- if (entry.segment) {
- currentUri.custom = currentUri.custom || {};
- currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
- } else {
- this.manifest.custom = this.manifest.custom || {};
- this.manifest.custom[entry.customType] = entry.data;
- }
- }
- })[entry.type].call(self);
- });
-
- return _this;
- }
-
- var _proto = Parser.prototype;
-
- _proto.warnOnMissingAttributes_ = function warnOnMissingAttributes_(identifier, attributes, required) {
- var missing = [];
- required.forEach(function (key) {
- if (!attributes.hasOwnProperty(key)) {
- missing.push(key);
- }
- });
-
- if (missing.length) {
- this.trigger('warn', {
- message: identifier + " lacks required attribute(s): " + missing.join(', ')
- });
- }
- }
- /**
- * Parse the input string and update the manifest object.
- *
- * @param {string} chunk a potentially incomplete portion of the manifest
- */
- ;
-
- _proto.push = function push(chunk) {
- this.lineStream.push(chunk);
- }
- /**
- * Flush any remaining input. This can be handy if the last line of an M3U8
- * manifest did not contain a trailing newline but the file has been
- * completely received.
- */
- ;
-
- _proto.end = function end() {
- // flush any buffered input
- this.lineStream.push('\n');
- this.trigger('end');
- }
- /**
- * Add an additional parser for non-standard tags
- *
- * @param {Object} options a map of options for the added parser
- * @param {RegExp} options.expression a regular expression to match the custom header
- * @param {string} options.type the type to register to the output
- * @param {Function} [options.dataParser] function to parse the line into an object
- * @param {boolean} [options.segment] should tag data be attached to the segment object
- */
- ;
-
- _proto.addParser = function addParser(options) {
- this.parseStream.addParser(options);
- }
- /**
- * Add a custom header mapper
- *
- * @param {Object} options
- * @param {RegExp} options.expression a regular expression to match the custom header
- * @param {Function} options.map function to translate tag into a different tag
- */
- ;
-
- _proto.addTagMapper = function addTagMapper(options) {
- this.parseStream.addTagMapper(options);
- };
-
- return Parser;
- }(Stream);
-
- var regexs = {
- // to determine mime types
- mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
- webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
- ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
- // to determine if a codec is audio or video
- video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
- audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
- text: /^(stpp.ttml.im1t)/,
- // mux.js support regex
- muxerVideo: /^(avc0?1)/,
- muxerAudio: /^(mp4a)/,
- // match nothing as muxer does not support text right now.
- // there cannot never be a character before the start of a string
- // so this matches nothing.
- muxerText: /a^/
- };
- var mediaTypes = ['video', 'audio', 'text'];
- var upperMediaTypes = ['Video', 'Audio', 'Text'];
- /**
- * Replace the old apple-style `avc1..` codec string with the standard
- * `avc1.`
- *
- * @param {string} codec
- * Codec string to translate
- * @return {string}
- * The translated codec string
- */
-
- var translateLegacyCodec = function translateLegacyCodec(codec) {
- if (!codec) {
- return codec;
- }
-
- return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
- var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
- var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
- return 'avc1.' + profileHex + '00' + avcLevelHex;
- });
- };
- /**
- * @typedef {Object} ParsedCodecInfo
- * @property {number} codecCount
- * Number of codecs parsed
- * @property {string} [videoCodec]
- * Parsed video codec (if found)
- * @property {string} [videoObjectTypeIndicator]
- * Video object type indicator (if found)
- * @property {string|null} audioProfile
- * Audio profile
- */
-
- /**
- * Parses a codec string to retrieve the number of codecs specified, the video codec and
- * object type indicator, and the audio profile.
- *
- * @param {string} [codecString]
- * The codec string to parse
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
- var parseCodecs = function parseCodecs(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- var codecs = codecString.split(',');
- var result = [];
- codecs.forEach(function (codec) {
- codec = codec.trim();
- var codecType;
- mediaTypes.forEach(function (name) {
- var match = regexs[name].exec(codec.toLowerCase());
-
- if (!match || match.length <= 1) {
- return;
- }
-
- codecType = name; // maintain codec case
-
- var type = codec.substring(0, match[1].length);
- var details = codec.replace(type, '');
- result.push({
- type: type,
- details: details,
- mediaType: name
- });
- });
-
- if (!codecType) {
- result.push({
- type: codec,
- details: '',
- mediaType: 'unknown'
- });
- }
- });
- return result;
- };
- /**
- * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
- * a default alternate audio playlist for the provided audio group.
- *
- * @param {Object} master
- * The master playlist
- * @param {string} audioGroupId
- * ID of the audio group for which to find the default codec info
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
- var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
- if (!master.mediaGroups.AUDIO || !audioGroupId) {
- return null;
- }
-
- var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
-
- if (!audioGroup) {
- return null;
- }
-
- for (var name in audioGroup) {
- var audioType = audioGroup[name];
-
- if (audioType.default && audioType.playlists) {
- // codec should be the same for all playlists within the audio type
- return parseCodecs(audioType.playlists[0].attributes.CODECS);
- }
- }
-
- return null;
- };
- var isAudioCodec = function isAudioCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.audio.test(codec.trim().toLowerCase());
- };
- var isTextCodec = function isTextCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.text.test(codec.trim().toLowerCase());
- };
- var getMimeForCodec = function getMimeForCodec(codecString) {
- if (!codecString || typeof codecString !== 'string') {
- return;
- }
-
- var codecs = codecString.toLowerCase().split(',').map(function (c) {
- return translateLegacyCodec(c.trim());
- }); // default to video type
-
- var type = 'video'; // only change to audio type if the only codec we have is
- // audio
-
- if (codecs.length === 1 && isAudioCodec(codecs[0])) {
- type = 'audio';
- } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
- // text uses application/ for now
- type = 'application';
- } // default the container to mp4
-
-
- var container = 'mp4'; // every codec must be able to go into the container
- // for that container to be the correct one
-
- if (codecs.every(function (c) {
- return regexs.mp4.test(c);
- })) {
- container = 'mp4';
- } else if (codecs.every(function (c) {
- return regexs.webm.test(c);
- })) {
- container = 'webm';
- } else if (codecs.every(function (c) {
- return regexs.ogg.test(c);
- })) {
- container = 'ogg';
- }
-
- return type + "/" + container + ";codecs=\"" + codecString + "\"";
- };
- var browserSupportsCodec = function browserSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return window__default['default'].MediaSource && window__default['default'].MediaSource.isTypeSupported && window__default['default'].MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
- };
- var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return codecString.toLowerCase().split(',').every(function (codec) {
- codec = codec.trim(); // any match is supported.
-
- for (var i = 0; i < upperMediaTypes.length; i++) {
- var type = upperMediaTypes[i];
-
- if (regexs["muxer" + type].test(codec)) {
- return true;
- }
- }
-
- return false;
- });
- };
- var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
- var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
-
- /**
- * ranges
- *
- * Utilities for working with TimeRanges.
- *
- */
-
- var TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
- // can be misleading because of precision differences or when the current media has poorly
- // aligned audio and video, which can cause values to be slightly off from what you would
- // expect. This value is what we consider to be safe to use in such comparisons to account
- // for these scenarios.
-
- var SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
-
- var filterRanges = function filterRanges(timeRanges, predicate) {
- var results = [];
- var i;
-
- if (timeRanges && timeRanges.length) {
- // Search for ranges that match the predicate
- for (i = 0; i < timeRanges.length; i++) {
- if (predicate(timeRanges.start(i), timeRanges.end(i))) {
- results.push([timeRanges.start(i), timeRanges.end(i)]);
- }
- }
- }
-
- return videojs__default['default'].createTimeRanges(results);
- };
- /**
- * Attempts to find the buffered TimeRange that contains the specified
- * time.
- *
- * @param {TimeRanges} buffered - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object
- */
-
-
- var findRange = function findRange(buffered, time) {
- return filterRanges(buffered, function (start, end) {
- return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
- });
- };
- /**
- * Returns the TimeRanges that begin later than the specified time.
- *
- * @param {TimeRanges} timeRanges - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object.
- */
-
- var findNextRange = function findNextRange(timeRanges, time) {
- return filterRanges(timeRanges, function (start) {
- return start - TIME_FUDGE_FACTOR >= time;
- });
- };
- /**
- * Returns gaps within a list of TimeRanges
- *
- * @param {TimeRanges} buffered - the TimeRanges object
- * @return {TimeRanges} a TimeRanges object of gaps
- */
-
- var findGaps = function findGaps(buffered) {
- if (buffered.length < 2) {
- return videojs__default['default'].createTimeRanges();
- }
-
- var ranges = [];
-
- for (var i = 1; i < buffered.length; i++) {
- var start = buffered.end(i - 1);
- var end = buffered.start(i);
- ranges.push([start, end]);
- }
-
- return videojs__default['default'].createTimeRanges(ranges);
- };
- /**
- * Calculate the intersection of two TimeRanges
- *
- * @param {TimeRanges} bufferA
- * @param {TimeRanges} bufferB
- * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
- */
-
- var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
- var start = null;
- var end = null;
- var arity = 0;
- var extents = [];
- var ranges = [];
-
- if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
- return videojs__default['default'].createTimeRange();
- } // Handle the case where we have both buffers and create an
- // intersection of the two
-
-
- var count = bufferA.length; // A) Gather up all start and end times
-
- while (count--) {
- extents.push({
- time: bufferA.start(count),
- type: 'start'
- });
- extents.push({
- time: bufferA.end(count),
- type: 'end'
- });
- }
-
- count = bufferB.length;
-
- while (count--) {
- extents.push({
- time: bufferB.start(count),
- type: 'start'
- });
- extents.push({
- time: bufferB.end(count),
- type: 'end'
- });
- } // B) Sort them by time
-
-
- extents.sort(function (a, b) {
- return a.time - b.time;
- }); // C) Go along one by one incrementing arity for start and decrementing
- // arity for ends
-
- for (count = 0; count < extents.length; count++) {
- if (extents[count].type === 'start') {
- arity++; // D) If arity is ever incremented to 2 we are entering an
- // overlapping range
-
- if (arity === 2) {
- start = extents[count].time;
- }
- } else if (extents[count].type === 'end') {
- arity--; // E) If arity is ever decremented to 1 we leaving an
- // overlapping range
-
- if (arity === 1) {
- end = extents[count].time;
- }
- } // F) Record overlapping ranges
-
-
- if (start !== null && end !== null) {
- ranges.push([start, end]);
- start = null;
- end = null;
- }
- }
-
- return videojs__default['default'].createTimeRanges(ranges);
- };
- /**
- * Gets a human readable string for a TimeRange
- *
- * @param {TimeRange} range
- * @return {string} a human readable string
- */
-
- var printableRange = function printableRange(range) {
- var strArr = [];
-
- if (!range || !range.length) {
- return '';
- }
-
- for (var i = 0; i < range.length; i++) {
- strArr.push(range.start(i) + ' => ' + range.end(i));
- }
-
- return strArr.join(', ');
- };
- /**
- * Calculates the amount of time left in seconds until the player hits the end of the
- * buffer and causes a rebuffer
- *
- * @param {TimeRange} buffered
- * The state of the buffer
- * @param {Numnber} currentTime
- * The current time of the player
- * @param {number} playbackRate
- * The current playback rate of the player. Defaults to 1.
- * @return {number}
- * Time until the player has to start rebuffering in seconds.
- * @function timeUntilRebuffer
- */
-
- var timeUntilRebuffer = function timeUntilRebuffer(buffered, currentTime, playbackRate) {
- if (playbackRate === void 0) {
- playbackRate = 1;
- }
-
- var bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
- return (bufferedEnd - currentTime) / playbackRate;
- };
- /**
- * Converts a TimeRanges object into an array representation
- *
- * @param {TimeRanges} timeRanges
- * @return {Array}
- */
-
- var timeRangesToArray = function timeRangesToArray(timeRanges) {
- var timeRangesList = [];
-
- for (var i = 0; i < timeRanges.length; i++) {
- timeRangesList.push({
- start: timeRanges.start(i),
- end: timeRanges.end(i)
- });
- }
-
- return timeRangesList;
- };
- /**
- * Determines if two time range objects are different.
- *
- * @param {TimeRange} a
- * the first time range object to check
- *
- * @param {TimeRange} b
- * the second time range object to check
- *
- * @return {Boolean}
- * Whether the time range objects differ
- */
-
- var isRangeDifferent = function isRangeDifferent(a, b) {
- // same object
- if (a === b) {
- return false;
- } // one or the other is undefined
-
-
- if (!a && b || !b && a) {
- return true;
- } // length is different
-
-
- if (a.length !== b.length) {
- return true;
- } // see if any start/end pair is different
-
-
- for (var i = 0; i < a.length; i++) {
- if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
- return true;
- }
- } // if the length and every pair is the same
- // this is the same time range
-
-
- return false;
- };
- var lastBufferedEnd = function lastBufferedEnd(a) {
- if (!a || !a.length || !a.end) {
- return;
- }
-
- return a.end(a.length - 1);
- };
-
- /**
- * @file playlist.js
- *
- * Playlist related utilities.
- */
- var createTimeRange = videojs__default['default'].createTimeRange;
- /**
- * A function to get a combined list of parts and segments with durations
- * and indexes.
- *
- * @param {Playlist} playlist the playlist to get the list for.
- *
- * @return {Array} The part/segment list.
- */
-
- var getPartsAndSegments = function getPartsAndSegments(playlist) {
- return (playlist.segments || []).reduce(function (acc, segment, si) {
- if (segment.parts) {
- segment.parts.forEach(function (part, pi) {
- acc.push({
- duration: part.duration,
- segmentIndex: si,
- partIndex: pi,
- part: part,
- segment: segment
- });
- });
- } else {
- acc.push({
- duration: segment.duration,
- segmentIndex: si,
- partIndex: null,
- segment: segment,
- part: null
- });
- }
-
- return acc;
- }, []);
- };
- var getLastParts = function getLastParts(media) {
- var lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
- return lastSegment && lastSegment.parts || [];
- };
- var getKnownPartCount = function getKnownPartCount(_ref) {
- var preloadSegment = _ref.preloadSegment;
-
- if (!preloadSegment) {
- return;
- }
-
- var parts = preloadSegment.parts,
- preloadHints = preloadSegment.preloadHints;
- var partCount = (preloadHints || []).reduce(function (count, hint) {
- return count + (hint.type === 'PART' ? 1 : 0);
- }, 0);
- partCount += parts && parts.length ? parts.length : 0;
- return partCount;
- };
- /**
- * Get the number of seconds to delay from the end of a
- * live playlist.
- *
- * @param {Playlist} master the master playlist
- * @param {Playlist} media the media playlist
- * @return {number} the hold back in seconds.
- */
-
- var liveEdgeDelay = function liveEdgeDelay(master, media) {
- if (media.endList) {
- return 0;
- } // dash suggestedPresentationDelay trumps everything
-
-
- if (master && master.suggestedPresentationDelay) {
- return master.suggestedPresentationDelay;
- }
-
- var hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
-
- if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
- return media.serverControl.partHoldBack;
- } else if (hasParts && media.partTargetDuration) {
- return media.partTargetDuration * 3; // finally look for full segment delays
- } else if (media.serverControl && media.serverControl.holdBack) {
- return media.serverControl.holdBack;
- } else if (media.targetDuration) {
- return media.targetDuration * 3;
- }
-
- return 0;
- };
- /**
- * walk backward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {Number} endSequence the mediaSequence to stop walking on
- */
-
- var backwardDuration = function backwardDuration(playlist, endSequence) {
- var result = 0;
- var i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
- // the interval, use it
-
- var segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
- // information that is earlier than endSequence
-
- if (segment) {
- if (typeof segment.start !== 'undefined') {
- return {
- result: segment.start,
- precise: true
- };
- }
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - segment.duration,
- precise: true
- };
- }
- }
-
- while (i--) {
- segment = playlist.segments[i];
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: result + segment.end,
- precise: true
- };
- }
-
- result += segment.duration;
-
- if (typeof segment.start !== 'undefined') {
- return {
- result: result + segment.start,
- precise: true
- };
- }
- }
-
- return {
- result: result,
- precise: false
- };
- };
- /**
- * walk forward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {number} endSequence the mediaSequence to stop walking on
- */
-
-
- var forwardDuration = function forwardDuration(playlist, endSequence) {
- var result = 0;
- var segment;
- var i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
- // information
-
- for (; i < playlist.segments.length; i++) {
- segment = playlist.segments[i];
-
- if (typeof segment.start !== 'undefined') {
- return {
- result: segment.start - result,
- precise: true
- };
- }
-
- result += segment.duration;
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - result,
- precise: true
- };
- }
- } // indicate we didn't find a useful duration estimate
-
-
- return {
- result: -1,
- precise: false
- };
- };
- /**
- * Calculate the media duration from the segments associated with a
- * playlist. The duration of a subinterval of the available segments
- * may be calculated by specifying an end index.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper boundary
- * for the playlist. Defaults to playlist length.
- * @param {number} expired the amount of time that has dropped
- * off the front of the playlist in a live scenario
- * @return {number} the duration between the first available segment
- * and end index.
- */
-
-
- var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
- if (typeof endSequence === 'undefined') {
- endSequence = playlist.mediaSequence + playlist.segments.length;
- }
-
- if (endSequence < playlist.mediaSequence) {
- return 0;
- } // do a backward walk to estimate the duration
-
-
- var backward = backwardDuration(playlist, endSequence);
-
- if (backward.precise) {
- // if we were able to base our duration estimate on timing
- // information provided directly from the Media Source, return
- // it
- return backward.result;
- } // walk forward to see if a precise duration estimate can be made
- // that way
-
-
- var forward = forwardDuration(playlist, endSequence);
-
- if (forward.precise) {
- // we found a segment that has been buffered and so it's
- // position is known precisely
- return forward.result;
- } // return the less-precise, playlist-based duration estimate
-
-
- return backward.result + expired;
- };
- /**
- * Calculates the duration of a playlist. If a start and end index
- * are specified, the duration will be for the subset of the media
- * timeline between those two indices. The total duration for live
- * playlists is always Infinity.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper
- * boundary for the playlist. Defaults to the playlist media
- * sequence number plus its length.
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @return {number} the duration between the start index and end
- * index.
- */
-
-
- var duration = function duration(playlist, endSequence, expired) {
- if (!playlist) {
- return 0;
- }
-
- if (typeof expired !== 'number') {
- expired = 0;
- } // if a slice of the total duration is not requested, use
- // playlist-level duration indicators when they're present
-
-
- if (typeof endSequence === 'undefined') {
- // if present, use the duration specified in the playlist
- if (playlist.totalDuration) {
- return playlist.totalDuration;
- } // duration should be Infinity for live playlists
-
-
- if (!playlist.endList) {
- return window__default['default'].Infinity;
- }
- } // calculate the total duration based on the segment durations
-
-
- return intervalDuration(playlist, endSequence, expired);
- };
- /**
- * Calculate the time between two indexes in the current playlist
- * neight the start- nor the end-index need to be within the current
- * playlist in which case, the targetDuration of the playlist is used
- * to approximate the durations of the segments
- *
- * @param {Array} options.durationList list to iterate over for durations.
- * @param {number} options.defaultDuration duration to use for elements before or after the durationList
- * @param {number} options.startIndex partsAndSegments index to start
- * @param {number} options.endIndex partsAndSegments index to end.
- * @return {number} the number of seconds between startIndex and endIndex
- */
-
- var sumDurations = function sumDurations(_ref2) {
- var defaultDuration = _ref2.defaultDuration,
- durationList = _ref2.durationList,
- startIndex = _ref2.startIndex,
- endIndex = _ref2.endIndex;
- var durations = 0;
-
- if (startIndex > endIndex) {
- var _ref3 = [endIndex, startIndex];
- startIndex = _ref3[0];
- endIndex = _ref3[1];
- }
-
- if (startIndex < 0) {
- for (var i = startIndex; i < Math.min(0, endIndex); i++) {
- durations += defaultDuration;
- }
-
- startIndex = 0;
- }
-
- for (var _i = startIndex; _i < endIndex; _i++) {
- durations += durationList[_i].duration;
- }
-
- return durations;
- };
- /**
- * Calculates the playlist end time
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
- * playlist end calculation should consider the safe live end
- * (truncate the playlist end by three segments). This is normally
- * used for calculating the end of the playlist's seekable range.
- * This takes into account the value of liveEdgePadding.
- * Setting liveEdgePadding to 0 is equivalent to setting this to false.
- * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
- * If this is provided, it is used in the safe live end calculation.
- * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {number} the end time of playlist
- * @function playlistEnd
- */
-
- var playlistEnd = function playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding) {
- if (!playlist || !playlist.segments) {
- return null;
- }
-
- if (playlist.endList) {
- return duration(playlist);
- }
-
- if (expired === null) {
- return null;
- }
-
- expired = expired || 0;
- var lastSegmentTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
-
- if (useSafeLiveEnd) {
- liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
- lastSegmentTime -= liveEdgePadding;
- } // don't return a time less than zero
-
-
- return Math.max(0, lastSegmentTime);
- };
- /**
- * Calculates the interval of time that is currently seekable in a
- * playlist. The returned time ranges are relative to the earliest
- * moment in the specified playlist that is still available. A full
- * seekable implementation for live streams would need to offset
- * these values by the duration of content that has expired from the
- * stream.
- *
- * @param {Object} playlist a media playlist object
- * dropped off the front of the playlist in a live scenario
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {TimeRanges} the periods of time that are valid targets
- * for seeking
- */
-
- var seekable = function seekable(playlist, expired, liveEdgePadding) {
- var useSafeLiveEnd = true;
- var seekableStart = expired || 0;
- var seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
-
- if (seekableEnd === null) {
- return createTimeRange();
- }
-
- return createTimeRange(seekableStart, seekableEnd);
- };
- /**
- * Determine the index and estimated starting time of the segment that
- * contains a specified playback position in a media playlist.
- *
- * @param {Object} options.playlist the media playlist to query
- * @param {number} options.currentTime The number of seconds since the earliest
- * possible position to determine the containing segment for
- * @param {number} options.startTime the time when the segment/part starts
- * @param {number} options.startingSegmentIndex the segment index to start looking at.
- * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
- *
- * @return {Object} an object with partIndex, segmentIndex, and startTime.
- */
-
- var getMediaInfoForTime = function getMediaInfoForTime(_ref4) {
- var playlist = _ref4.playlist,
- currentTime = _ref4.currentTime,
- startingSegmentIndex = _ref4.startingSegmentIndex,
- startingPartIndex = _ref4.startingPartIndex,
- startTime = _ref4.startTime;
- var time = currentTime - startTime;
- var partsAndSegments = getPartsAndSegments(playlist);
- var startIndex = 0;
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- var partAndSegment = partsAndSegments[i];
-
- if (startingSegmentIndex !== partAndSegment.segmentIndex) {
- continue;
- } // skip this if part index does not match.
-
-
- if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
- continue;
- }
-
- startIndex = i;
- break;
- }
-
- if (time < 0) {
- // Walk backward from startIndex in the playlist, adding durations
- // until we find a segment that contains `time` and return it
- if (startIndex > 0) {
- for (var _i2 = startIndex - 1; _i2 >= 0; _i2--) {
- var _partAndSegment = partsAndSegments[_i2];
- time += _partAndSegment.duration; // TODO: consider not using TIME_FUDGE_FACTOR at all here
-
- if (time + TIME_FUDGE_FACTOR > 0) {
- return {
- partIndex: _partAndSegment.partIndex,
- segmentIndex: _partAndSegment.segmentIndex,
- startTime: startTime - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex: startIndex,
- endIndex: _i2
- })
- };
- }
- }
- } // We were unable to find a good segment within the playlist
- // so select the first segment
-
-
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- } // When startIndex is negative, we first walk forward to first segment
- // adding target durations. If we "run out of time" before getting to
- // the first segment, return the first segment
-
-
- if (startIndex < 0) {
- for (var _i3 = startIndex; _i3 < 0; _i3++) {
- time -= playlist.targetDuration;
-
- if (time < 0) {
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- }
- }
-
- startIndex = 0;
- } // Walk forward from startIndex in the playlist, subtracting durations
- // until we find a segment that contains `time` and return it
-
-
- for (var _i4 = startIndex; _i4 < partsAndSegments.length; _i4++) {
- var _partAndSegment2 = partsAndSegments[_i4];
- time -= _partAndSegment2.duration; // TODO: consider not using TIME_FUDGE_FACTOR at all here
-
- if (time - TIME_FUDGE_FACTOR < 0) {
- return {
- partIndex: _partAndSegment2.partIndex,
- segmentIndex: _partAndSegment2.segmentIndex,
- startTime: startTime + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex: startIndex,
- endIndex: _i4
- })
- };
- }
- } // We are out of possible candidates so load the last one...
-
-
- return {
- segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
- partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
- startTime: currentTime
- };
- };
- /**
- * Check whether the playlist is blacklisted or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is blacklisted or not
- * @function isBlacklisted
- */
-
- var isBlacklisted = function isBlacklisted(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil > Date.now();
- };
- /**
- * Check whether the playlist is compatible with current playback configuration or has
- * been blacklisted permanently for being incompatible.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is incompatible or not
- * @function isIncompatible
- */
-
- var isIncompatible = function isIncompatible(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil === Infinity;
- };
- /**
- * Check whether the playlist is enabled or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is enabled or not
- * @function isEnabled
- */
-
- var isEnabled = function isEnabled(playlist) {
- var blacklisted = isBlacklisted(playlist);
- return !playlist.disabled && !blacklisted;
- };
- /**
- * Check whether the playlist has been manually disabled through the representations api.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is disabled manually or not
- * @function isDisabled
- */
-
- var isDisabled = function isDisabled(playlist) {
- return playlist.disabled;
- };
- /**
- * Returns whether the current playlist is an AES encrypted HLS stream
- *
- * @return {boolean} true if it's an AES encrypted HLS stream
- */
-
- var isAes = function isAes(media) {
- for (var i = 0; i < media.segments.length; i++) {
- if (media.segments[i].key) {
- return true;
- }
- }
-
- return false;
- };
- /**
- * Checks if the playlist has a value for the specified attribute
- *
- * @param {string} attr
- * Attribute to check for
- * @param {Object} playlist
- * The media playlist object
- * @return {boolean}
- * Whether the playlist contains a value for the attribute or not
- * @function hasAttribute
- */
-
- var hasAttribute = function hasAttribute(attr, playlist) {
- return playlist.attributes && playlist.attributes[attr];
- };
- /**
- * Estimates the time required to complete a segment download from the specified playlist
- *
- * @param {number} segmentDuration
- * Duration of requested segment
- * @param {number} bandwidth
- * Current measured bandwidth of the player
- * @param {Object} playlist
- * The media playlist object
- * @param {number=} bytesReceived
- * Number of bytes already received for the request. Defaults to 0
- * @return {number|NaN}
- * The estimated time to request the segment. NaN if bandwidth information for
- * the given playlist is unavailable
- * @function estimateSegmentRequestTime
- */
-
- var estimateSegmentRequestTime = function estimateSegmentRequestTime(segmentDuration, bandwidth, playlist, bytesReceived) {
- if (bytesReceived === void 0) {
- bytesReceived = 0;
- }
-
- if (!hasAttribute('BANDWIDTH', playlist)) {
- return NaN;
- }
-
- var size = segmentDuration * playlist.attributes.BANDWIDTH;
- return (size - bytesReceived * 8) / bandwidth;
- };
- /*
- * Returns whether the current playlist is the lowest rendition
- *
- * @return {Boolean} true if on lowest rendition
- */
-
- var isLowestEnabledRendition = function isLowestEnabledRendition(master, media) {
- if (master.playlists.length === 1) {
- return true;
- }
-
- var currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
- return master.playlists.filter(function (playlist) {
- if (!isEnabled(playlist)) {
- return false;
- }
-
- return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
- }).length === 0;
- };
- var playlistMatch = function playlistMatch(a, b) {
- // both playlits are null
- // or only one playlist is non-null
- // no match
- if (!a && !b || !a && b || a && !b) {
- return false;
- } // playlist objects are the same, match
-
-
- if (a === b) {
- return true;
- } // first try to use id as it should be the most
- // accurate
-
-
- if (a.id && b.id && a.id === b.id) {
- return true;
- } // next try to use reslovedUri as it should be the
- // second most accurate.
-
-
- if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
- return true;
- } // finally try to use uri as it should be accurate
- // but might miss a few cases for relative uris
-
-
- if (a.uri && b.uri && a.uri === b.uri) {
- return true;
- }
-
- return false;
- };
-
- var someAudioVariant = function someAudioVariant(master, callback) {
- var AUDIO = master && master.mediaGroups && master.mediaGroups.AUDIO || {};
- var found = false;
-
- for (var groupName in AUDIO) {
- for (var label in AUDIO[groupName]) {
- found = callback(AUDIO[groupName][label]);
-
- if (found) {
- break;
- }
- }
-
- if (found) {
- break;
- }
- }
-
- return !!found;
- };
-
- var isAudioOnly = function isAudioOnly(master) {
- // we are audio only if we have no main playlists but do
- // have media group playlists.
- if (!master || !master.playlists || !master.playlists.length) {
- // without audio variants or playlists this
- // is not an audio only master.
- var found = someAudioVariant(master, function (variant) {
- return variant.playlists && variant.playlists.length || variant.uri;
- });
- return found;
- } // if every playlist has only an audio codec it is audio only
-
-
- var _loop = function _loop(i) {
- var playlist = master.playlists[i];
- var CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
-
- if (CODECS && CODECS.split(',').every(function (c) {
- return isAudioCodec(c);
- })) {
- return "continue";
- } // playlist is in an audio group it is audio only
-
-
- var found = someAudioVariant(master, function (variant) {
- return playlistMatch(playlist, variant);
- });
-
- if (found) {
- return "continue";
- } // if we make it here this playlist isn't audio and we
- // are not audio only
-
-
- return {
- v: false
- };
- };
-
- for (var i = 0; i < master.playlists.length; i++) {
- var _ret = _loop(i);
-
- if (_ret === "continue") continue;
- if (typeof _ret === "object") return _ret.v;
- } // if we make it past every playlist without returning, then
- // this is an audio only playlist.
-
-
- return true;
- }; // exports
-
- var Playlist = {
- liveEdgeDelay: liveEdgeDelay,
- duration: duration,
- seekable: seekable,
- getMediaInfoForTime: getMediaInfoForTime,
- isEnabled: isEnabled,
- isDisabled: isDisabled,
- isBlacklisted: isBlacklisted,
- isIncompatible: isIncompatible,
- playlistEnd: playlistEnd,
- isAes: isAes,
- hasAttribute: hasAttribute,
- estimateSegmentRequestTime: estimateSegmentRequestTime,
- isLowestEnabledRendition: isLowestEnabledRendition,
- isAudioOnly: isAudioOnly,
- playlistMatch: playlistMatch
- };
-
- var log = videojs__default['default'].log;
- var createPlaylistID = function createPlaylistID(index, uri) {
- return index + "-" + uri;
- };
- /**
- * Parses a given m3u8 playlist
- *
- * @param {Function} [onwarn]
- * a function to call when the parser triggers a warning event.
- * @param {Function} [oninfo]
- * a function to call when the parser triggers an info event.
- * @param {string} manifestString
- * The downloaded manifest string
- * @param {Object[]} [customTagParsers]
- * An array of custom tag parsers for the m3u8-parser instance
- * @param {Object[]} [customTagMappers]
- * An array of custom tag mappers for the m3u8-parser instance
- * @param {boolean} [experimentalLLHLS=false]
- * Whether to keep ll-hls features in the manifest after parsing.
- * @return {Object}
- * The manifest object
- */
-
- var parseManifest = function parseManifest(_ref) {
- var onwarn = _ref.onwarn,
- oninfo = _ref.oninfo,
- manifestString = _ref.manifestString,
- _ref$customTagParsers = _ref.customTagParsers,
- customTagParsers = _ref$customTagParsers === void 0 ? [] : _ref$customTagParsers,
- _ref$customTagMappers = _ref.customTagMappers,
- customTagMappers = _ref$customTagMappers === void 0 ? [] : _ref$customTagMappers,
- experimentalLLHLS = _ref.experimentalLLHLS;
- var parser = new Parser();
-
- if (onwarn) {
- parser.on('warn', onwarn);
- }
-
- if (oninfo) {
- parser.on('info', oninfo);
- }
-
- customTagParsers.forEach(function (customParser) {
- return parser.addParser(customParser);
- });
- customTagMappers.forEach(function (mapper) {
- return parser.addTagMapper(mapper);
- });
- parser.push(manifestString);
- parser.end();
- var manifest = parser.manifest; // remove llhls features from the parsed manifest
- // if we don't want llhls support.
-
- if (!experimentalLLHLS) {
- ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
- if (manifest.hasOwnProperty(k)) {
- delete manifest[k];
- }
- });
-
- if (manifest.segments) {
- manifest.segments.forEach(function (segment) {
- ['parts', 'preloadHints'].forEach(function (k) {
- if (segment.hasOwnProperty(k)) {
- delete segment[k];
- }
- });
- });
- }
- }
-
- if (!manifest.targetDuration) {
- var targetDuration = 10;
-
- if (manifest.segments && manifest.segments.length) {
- targetDuration = manifest.segments.reduce(function (acc, s) {
- return Math.max(acc, s.duration);
- }, 0);
- }
-
- if (onwarn) {
- onwarn("manifest has no targetDuration defaulting to " + targetDuration);
- }
-
- manifest.targetDuration = targetDuration;
- }
-
- var parts = getLastParts(manifest);
-
- if (parts.length && !manifest.partTargetDuration) {
- var partTargetDuration = parts.reduce(function (acc, p) {
- return Math.max(acc, p.duration);
- }, 0);
-
- if (onwarn) {
- onwarn("manifest has no partTargetDuration defaulting to " + partTargetDuration);
- log.error('LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.');
- }
-
- manifest.partTargetDuration = partTargetDuration;
- }
-
- return manifest;
- };
- /**
- * Loops through all supported media groups in master and calls the provided
- * callback for each group
- *
- * @param {Object} master
- * The parsed master manifest object
- * @param {Function} callback
- * Callback to call for each media group
- */
-
- var forEachMediaGroup = function forEachMediaGroup(master, callback) {
- if (!master.mediaGroups) {
- return;
- }
-
- ['AUDIO', 'SUBTITLES'].forEach(function (mediaType) {
- if (!master.mediaGroups[mediaType]) {
- return;
- }
-
- for (var groupKey in master.mediaGroups[mediaType]) {
- for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
- var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
- callback(mediaProperties, mediaType, groupKey, labelKey);
- }
- }
- });
- };
- /**
- * Adds properties and attributes to the playlist to keep consistent functionality for
- * playlists throughout VHS.
- *
- * @param {Object} config
- * Arguments object
- * @param {Object} config.playlist
- * The media playlist
- * @param {string} [config.uri]
- * The uri to the media playlist (if media playlist is not from within a master
- * playlist)
- * @param {string} id
- * ID to use for the playlist
- */
-
- var setupMediaPlaylist = function setupMediaPlaylist(_ref2) {
- var playlist = _ref2.playlist,
- uri = _ref2.uri,
- id = _ref2.id;
- playlist.id = id;
- playlist.playlistErrors_ = 0;
-
- if (uri) {
- // For media playlists, m3u8-parser does not have access to a URI, as HLS media
- // playlists do not contain their own source URI, but one is needed for consistency in
- // VHS.
- playlist.uri = uri;
- } // For HLS master playlists, even though certain attributes MUST be defined, the
- // stream may still be played without them.
- // For HLS media playlists, m3u8-parser does not attach an attributes object to the
- // manifest.
- //
- // To avoid undefined reference errors through the project, and make the code easier
- // to write/read, add an empty attributes object for these cases.
-
-
- playlist.attributes = playlist.attributes || {};
- };
- /**
- * Adds ID, resolvedUri, and attributes properties to each playlist of the master, where
- * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
- * playlist references to the playlists array.
- *
- * @param {Object} master
- * The master playlist
- */
-
- var setupMediaPlaylists = function setupMediaPlaylists(master) {
- var i = master.playlists.length;
-
- while (i--) {
- var playlist = master.playlists[i];
- setupMediaPlaylist({
- playlist: playlist,
- id: createPlaylistID(i, playlist.uri)
- });
- playlist.resolvedUri = resolveUrl(master.uri, playlist.uri);
- master.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
-
- master.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
- // the stream can be played without it. Although an attributes property may have been
- // added to the playlist to prevent undefined references, issue a warning to fix the
- // manifest.
-
- if (!playlist.attributes.BANDWIDTH) {
- log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
- }
- }
- };
- /**
- * Adds resolvedUri properties to each media group.
- *
- * @param {Object} master
- * The master playlist
- */
-
- var resolveMediaGroupUris = function resolveMediaGroupUris(master) {
- forEachMediaGroup(master, function (properties) {
- if (properties.uri) {
- properties.resolvedUri = resolveUrl(master.uri, properties.uri);
- }
- });
- };
- /**
- * Creates a master playlist wrapper to insert a sole media playlist into.
- *
- * @param {Object} media
- * Media playlist
- * @param {string} uri
- * The media URI
- *
- * @return {Object}
- * Master playlist
- */
-
- var masterForMedia = function masterForMedia(media, uri) {
- var id = createPlaylistID(0, uri);
- var master = {
- mediaGroups: {
- 'AUDIO': {},
- 'VIDEO': {},
- 'CLOSED-CAPTIONS': {},
- 'SUBTITLES': {}
- },
- uri: window__default['default'].location.href,
- resolvedUri: window__default['default'].location.href,
- playlists: [{
- uri: uri,
- id: id,
- resolvedUri: uri,
- // m3u8-parser does not attach an attributes property to media playlists so make
- // sure that the property is attached to avoid undefined reference errors
- attributes: {}
- }]
- }; // set up ID reference
-
- master.playlists[id] = master.playlists[0]; // URI reference added for backwards compatibility
-
- master.playlists[uri] = master.playlists[0];
- return master;
- };
- /**
- * Does an in-place update of the master manifest to add updated playlist URI references
- * as well as other properties needed by VHS that aren't included by the parser.
- *
- * @param {Object} master
- * Master manifest object
- * @param {string} uri
- * The source URI
- */
-
- var addPropertiesToMaster = function addPropertiesToMaster(master, uri) {
- master.uri = uri;
-
- for (var i = 0; i < master.playlists.length; i++) {
- if (!master.playlists[i].uri) {
- // Set up phony URIs for the playlists since playlists are referenced by their URIs
- // throughout VHS, but some formats (e.g., DASH) don't have external URIs
- // TODO: consider adding dummy URIs in mpd-parser
- var phonyUri = "placeholder-uri-" + i;
- master.playlists[i].uri = phonyUri;
- }
- }
-
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- var groupId = "placeholder-uri-" + mediaType + "-" + groupKey + "-" + labelKey;
-
- if (!properties.playlists || !properties.playlists.length) {
- properties.playlists = [_extends_1({}, properties)];
- }
-
- properties.playlists.forEach(function (p, i) {
- var id = createPlaylistID(i, groupId);
-
- if (p.uri) {
- p.resolvedUri = p.resolvedUri || resolveUrl(master.uri, p.uri);
- } else {
- // DEPRECATED, this has been added to prevent a breaking change.
- // previously we only ever had a single media group playlist, so
- // we mark the first playlist uri without prepending the index as we used to
- // ideally we would do all of the playlists the same way.
- p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
- // the placeholder again
-
- p.resolvedUri = p.uri;
- }
-
- p.id = p.id || id; // add an empty attributes object, all playlists are
- // expected to have this.
-
- p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
-
- master.playlists[p.id] = p;
- master.playlists[p.uri] = p;
- });
- });
- setupMediaPlaylists(master);
- resolveMediaGroupUris(master);
- };
-
- var mergeOptions$2 = videojs__default['default'].mergeOptions,
- EventTarget$1 = videojs__default['default'].EventTarget;
-
- var addLLHLSQueryDirectives = function addLLHLSQueryDirectives(uri, media) {
- if (media.endList) {
- return uri;
- }
-
- var query = [];
-
- if (media.serverControl && media.serverControl.canBlockReload) {
- var preloadSegment = media.preloadSegment; // next msn is a zero based value, length is not.
-
- var nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
- // that we are going to request a part of that preload segment.
- // the logic below is used to determine that.
-
- if (preloadSegment) {
- var parts = preloadSegment.parts || []; // _HLS_part is a zero based index
-
- var nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
- // length of parts, then we know we had part preload hints
- // and we need to add the _HLS_part= query
-
- if (nextPart > -1 && nextPart !== parts.length - 1) {
- // add existing parts to our preload hints
- query.push("_HLS_part=" + nextPart);
- } // this if statement makes sure that we request the msn
- // of the preload segment if:
- // 1. the preload segment had parts (and was not yet a full segment)
- // but was added to our segments array
- // 2. the preload segment had preload hints for parts that are not in
- // the manifest yet.
- // in all other cases we want the segment after the preload segment
- // which will be given by using media.segments.length because it is 1 based
- // rather than 0 based.
-
-
- if (nextPart > -1 || parts.length) {
- nextMSN--;
- }
- } // add _HLS_msn= in front of any _HLS_part query
-
-
- query.unshift("_HLS_msn=" + nextMSN);
- }
-
- if (media.serverControl && media.serverControl.canSkipUntil) {
- // add _HLS_skip= infront of all other queries.
- query.unshift('_HLS_skip=' + (media.serverControl.canSkipDateranges ? 'v2' : 'YES'));
- }
-
- query.forEach(function (str, i) {
- var symbol = i === 0 ? '?' : '&';
- uri += "" + symbol + str;
- });
- return uri;
- };
- /**
- * Returns a new segment object with properties and
- * the parts array merged.
- *
- * @param {Object} a the old segment
- * @param {Object} b the new segment
- *
- * @return {Object} the merged segment
- */
-
-
- var updateSegment = function updateSegment(a, b) {
- if (!a) {
- return b;
- }
-
- var result = mergeOptions$2(a, b); // if only the old segment has preload hints
- // and the new one does not, remove preload hints.
-
- if (a.preloadHints && !b.preloadHints) {
- delete result.preloadHints;
- } // if only the old segment has parts
- // then the parts are no longer valid
-
-
- if (a.parts && !b.parts) {
- delete result.parts; // if both segments have parts
- // copy part propeties from the old segment
- // to the new one.
- } else if (a.parts && b.parts) {
- for (var i = 0; i < b.parts.length; i++) {
- if (a.parts && a.parts[i]) {
- result.parts[i] = mergeOptions$2(a.parts[i], b.parts[i]);
- }
- }
- } // set skipped to false for segments that have
- // have had information merged from the old segment.
-
-
- if (!a.skipped && b.skipped) {
- result.skipped = false;
- } // set preload to false for segments that have
- // had information added in the new segment.
-
-
- if (a.preload && !b.preload) {
- result.preload = false;
- }
-
- return result;
- };
- /**
- * Returns a new array of segments that is the result of merging
- * properties from an older list of segments onto an updated
- * list. No properties on the updated playlist will be ovewritten.
- *
- * @param {Array} original the outdated list of segments
- * @param {Array} update the updated list of segments
- * @param {number=} offset the index of the first update
- * segment in the original segment list. For non-live playlists,
- * this should always be zero and does not need to be
- * specified. For live playlists, it should be the difference
- * between the media sequence numbers in the original and updated
- * playlists.
- * @return {Array} a list of merged segment objects
- */
-
- var updateSegments = function updateSegments(original, update, offset) {
- var oldSegments = original.slice();
- var newSegments = update.slice();
- offset = offset || 0;
- var result = [];
- var currentMap;
-
- for (var newIndex = 0; newIndex < newSegments.length; newIndex++) {
- var oldSegment = oldSegments[newIndex + offset];
- var newSegment = newSegments[newIndex];
-
- if (oldSegment) {
- currentMap = oldSegment.map || currentMap;
- result.push(updateSegment(oldSegment, newSegment));
- } else {
- // carry over map to new segment if it is missing
- if (currentMap && !newSegment.map) {
- newSegment.map = currentMap;
- }
-
- result.push(newSegment);
- }
- }
-
- return result;
- };
- var resolveSegmentUris = function resolveSegmentUris(segment, baseUri) {
- // preloadSegment will not have a uri at all
- // as the segment isn't actually in the manifest yet, only parts
- if (!segment.resolvedUri && segment.uri) {
- segment.resolvedUri = resolveUrl(baseUri, segment.uri);
- }
-
- if (segment.key && !segment.key.resolvedUri) {
- segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
- }
-
- if (segment.map && !segment.map.resolvedUri) {
- segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
- }
-
- if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
- segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
- }
-
- if (segment.parts && segment.parts.length) {
- segment.parts.forEach(function (p) {
- if (p.resolvedUri) {
- return;
- }
-
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
-
- if (segment.preloadHints && segment.preloadHints.length) {
- segment.preloadHints.forEach(function (p) {
- if (p.resolvedUri) {
- return;
- }
-
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
- };
-
- var getAllSegments = function getAllSegments(media) {
- var segments = media.segments || [];
- var preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
- // a usable segment, only include a preloadSegment that has
- // parts.
-
- if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
- // if preloadHints has a MAP that means that the
- // init segment is going to change. We cannot use any of the parts
- // from this preload segment.
- if (preloadSegment.preloadHints) {
- for (var i = 0; i < preloadSegment.preloadHints.length; i++) {
- if (preloadSegment.preloadHints[i].type === 'MAP') {
- return segments;
- }
- }
- } // set the duration for our preload segment to target duration.
-
-
- preloadSegment.duration = media.targetDuration;
- preloadSegment.preload = true;
- segments.push(preloadSegment);
- }
-
- return segments;
- }; // consider the playlist unchanged if the playlist object is the same or
- // the number of segments is equal, the media sequence number is unchanged,
- // and this playlist hasn't become the end of the playlist
-
-
- var isPlaylistUnchanged = function isPlaylistUnchanged(a, b) {
- return a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence;
- };
- /**
- * Returns a new master playlist that is the result of merging an
- * updated media playlist into the original version. If the
- * updated media playlist does not match any of the playlist
- * entries in the original master playlist, null is returned.
- *
- * @param {Object} master a parsed master M3U8 object
- * @param {Object} media a parsed media M3U8 object
- * @return {Object} a new object that represents the original
- * master playlist with the updated media playlist merged in, or
- * null if the merge produced no change.
- */
-
- var updateMaster$1 = function updateMaster(master, newMedia, unchangedCheck) {
- if (unchangedCheck === void 0) {
- unchangedCheck = isPlaylistUnchanged;
- }
-
- var result = mergeOptions$2(master, {});
- var oldMedia = result.playlists[newMedia.id];
-
- if (!oldMedia) {
- return null;
- }
-
- if (unchangedCheck(oldMedia, newMedia)) {
- return null;
- }
-
- newMedia.segments = getAllSegments(newMedia);
- var mergedPlaylist = mergeOptions$2(oldMedia, newMedia); // always use the new media's preload segment
-
- if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
- delete mergedPlaylist.preloadSegment;
- } // if the update could overlap existing segment information, merge the two segment lists
-
-
- if (oldMedia.segments) {
- if (newMedia.skip) {
- newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
- // old properties into the new segments
-
- for (var i = 0; i < newMedia.skip.skippedSegments; i++) {
- newMedia.segments.unshift({
- skipped: true
- });
- }
- }
-
- mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
- } // resolve any segment URIs to prevent us from having to do it later
-
-
- mergedPlaylist.segments.forEach(function (segment) {
- resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
- }); // TODO Right now in the playlists array there are two references to each playlist, one
- // that is referenced by index, and one by URI. The index reference may no longer be
- // necessary.
-
- for (var _i = 0; _i < result.playlists.length; _i++) {
- if (result.playlists[_i].id === newMedia.id) {
- result.playlists[_i] = mergedPlaylist;
- }
- }
-
- result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
-
- result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
-
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- if (!properties.playlists) {
- return;
- }
-
- for (var _i2 = 0; _i2 < properties.playlists.length; _i2++) {
- if (newMedia.id === properties.playlists[_i2].id) {
- properties.playlists[_i2] = newMedia;
- }
- }
- });
- return result;
- };
- /**
- * Calculates the time to wait before refreshing a live playlist
- *
- * @param {Object} media
- * The current media
- * @param {boolean} update
- * True if there were any updates from the last refresh, false otherwise
- * @return {number}
- * The time in ms to wait before refreshing the live playlist
- */
-
- var refreshDelay = function refreshDelay(media, update) {
- var lastSegment = media.segments[media.segments.length - 1];
- var lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
- var lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
-
- if (update && lastDuration) {
- return lastDuration * 1000;
- } // if the playlist is unchanged since the last reload or last segment duration
- // cannot be determined, try again after half the target duration
-
-
- return (media.partTargetDuration || media.targetDuration || 10) * 500;
- };
- /**
- * Load a playlist from a remote location
- *
- * @class PlaylistLoader
- * @extends Stream
- * @param {string|Object} src url or object of manifest
- * @param {boolean} withCredentials the withCredentials xhr option
- * @class
- */
-
- var PlaylistLoader = /*#__PURE__*/function (_EventTarget) {
- inheritsLoose(PlaylistLoader, _EventTarget);
-
- function PlaylistLoader(src, vhs, options) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _EventTarget.call(this) || this;
-
- if (!src) {
- throw new Error('A non-empty playlist URL or object is required');
- }
-
- _this.logger_ = logger('PlaylistLoader');
- var _options = options,
- _options$withCredenti = _options.withCredentials,
- withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
- _options$handleManife = _options.handleManifestRedirects,
- handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
- _this.src = src;
- _this.vhs_ = vhs;
- _this.withCredentials = withCredentials;
- _this.handleManifestRedirects = handleManifestRedirects;
- var vhsOptions = vhs.options_;
- _this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
- _this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
- _this.experimentalLLHLS = vhsOptions && vhsOptions.experimentalLLHLS || false; // initialize the loader state
-
- _this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
-
- _this.handleMediaupdatetimeout_ = _this.handleMediaupdatetimeout_.bind(assertThisInitialized(_this));
-
- _this.on('mediaupdatetimeout', _this.handleMediaupdatetimeout_);
-
- return _this;
- }
-
- var _proto = PlaylistLoader.prototype;
-
- _proto.handleMediaupdatetimeout_ = function handleMediaupdatetimeout_() {
- var _this2 = this;
-
- if (this.state !== 'HAVE_METADATA') {
- // only refresh the media playlist if no other activity is going on
- return;
- }
-
- var media = this.media();
- var uri = resolveUrl(this.master.uri, media.uri);
-
- if (this.experimentalLLHLS) {
- uri = addLLHLSQueryDirectives(uri, media);
- }
-
- this.state = 'HAVE_CURRENT_METADATA';
- this.request = this.vhs_.xhr({
- uri: uri,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this2.request) {
- return;
- }
-
- if (error) {
- return _this2.playlistRequestError(_this2.request, _this2.media(), 'HAVE_METADATA');
- }
-
- _this2.haveMetadata({
- playlistString: _this2.request.responseText,
- url: _this2.media().uri,
- id: _this2.media().id
- });
- });
- };
-
- _proto.playlistRequestError = function playlistRequestError(xhr, playlist, startingState) {
- var uri = playlist.uri,
- id = playlist.id; // any in-flight request is now finished
-
- this.request = null;
-
- if (startingState) {
- this.state = startingState;
- }
-
- this.error = {
- playlist: this.master.playlists[id],
- status: xhr.status,
- message: "HLS playlist request error at URL: " + uri + ".",
- responseText: xhr.responseText,
- code: xhr.status >= 500 ? 4 : 2
- };
- this.trigger('error');
- };
-
- _proto.parseManifest_ = function parseManifest_(_ref) {
- var _this3 = this;
-
- var url = _ref.url,
- manifestString = _ref.manifestString;
- return parseManifest({
- onwarn: function onwarn(_ref2) {
- var message = _ref2.message;
- return _this3.logger_("m3u8-parser warn for " + url + ": " + message);
- },
- oninfo: function oninfo(_ref3) {
- var message = _ref3.message;
- return _this3.logger_("m3u8-parser info for " + url + ": " + message);
- },
- manifestString: manifestString,
- customTagParsers: this.customTagParsers,
- customTagMappers: this.customTagMappers,
- experimentalLLHLS: this.experimentalLLHLS
- });
- }
- /**
- * Update the playlist loader's state in response to a new or updated playlist.
- *
- * @param {string} [playlistString]
- * Playlist string (if playlistObject is not provided)
- * @param {Object} [playlistObject]
- * Playlist object (if playlistString is not provided)
- * @param {string} url
- * URL of playlist
- * @param {string} id
- * ID to use for playlist
- */
- ;
-
- _proto.haveMetadata = function haveMetadata(_ref4) {
- var _this4 = this;
-
- var playlistString = _ref4.playlistString,
- playlistObject = _ref4.playlistObject,
- url = _ref4.url,
- id = _ref4.id;
- // any in-flight request is now finished
- this.request = null;
- this.state = 'HAVE_METADATA';
- var playlist = playlistObject || this.parseManifest_({
- url: url,
- manifestString: playlistString
- });
- playlist.lastRequest = Date.now();
- setupMediaPlaylist({
- playlist: playlist,
- uri: url,
- id: id
- }); // merge this playlist into the master
-
- var update = updateMaster$1(this.master, playlist);
- this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
-
- if (update) {
- this.master = update;
- this.media_ = this.master.playlists[id];
- } else {
- this.trigger('playlistunchanged');
- } // refresh live playlists after a target duration passes
-
-
- if (!this.media().endList) {
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- _this4.trigger('mediaupdatetimeout');
- }, refreshDelay(this.media(), !!update));
- }
-
- this.trigger('loadedplaylist');
- }
- /**
- * Abort any outstanding work and clean up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.stopRequest();
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- window__default['default'].clearTimeout(this.finalRenditionTimeout);
- this.off();
- };
-
- _proto.stopRequest = function stopRequest() {
- if (this.request) {
- var oldRequest = this.request;
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- }
- /**
- * When called without any arguments, returns the currently
- * active media playlist. When called with a single argument,
- * triggers the playlist loader to asynchronously switch to the
- * specified media playlist. Calling this method while the
- * loader is in the HAVE_NOTHING causes an error to be emitted
- * but otherwise has no effect.
- *
- * @param {Object=} playlist the parsed media playlist
- * object to switch to
- * @param {boolean=} shouldDelay whether we should delay the request by half target duration
- *
- * @return {Playlist} the current loaded media
- */
- ;
-
- _proto.media = function media(playlist, shouldDelay) {
- var _this5 = this;
-
- // getter
- if (!playlist) {
- return this.media_;
- } // setter
-
-
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- } // find the playlist object if the target playlist has been
- // specified by URI
-
-
- if (typeof playlist === 'string') {
- if (!this.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
-
- playlist = this.master.playlists[playlist];
- }
-
- window__default['default'].clearTimeout(this.finalRenditionTimeout);
-
- if (shouldDelay) {
- var delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
- this.finalRenditionTimeout = window__default['default'].setTimeout(this.media.bind(this, playlist, false), delay);
- return;
- }
-
- var startingState = this.state;
- var mediaChange = !this.media_ || playlist.id !== this.media_.id;
- var masterPlaylistRef = this.master.playlists[playlist.id]; // switch to fully loaded playlists immediately
-
- if (masterPlaylistRef && masterPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
- // media playlist or, for the case of demuxed audio, a resolved audio media group)
- playlist.endList && playlist.segments.length) {
- // abort outstanding playlist requests
- if (this.request) {
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- }
-
- this.state = 'HAVE_METADATA';
- this.media_ = playlist; // trigger media change if the active media has been updated
-
- if (mediaChange) {
- this.trigger('mediachanging');
-
- if (startingState === 'HAVE_MASTER') {
- // The initial playlist was a master manifest, and the first media selected was
- // also provided (in the form of a resolved playlist object) as part of the
- // source object (rather than just a URL). Therefore, since the media playlist
- // doesn't need to be requested, loadedmetadata won't trigger as part of the
- // normal flow, and needs an explicit trigger here.
- this.trigger('loadedmetadata');
- } else {
- this.trigger('mediachange');
- }
- }
-
- return;
- } // switching to the active playlist is a no-op
-
-
- if (!mediaChange) {
- return;
- }
-
- this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
-
- if (this.request) {
- if (playlist.resolvedUri === this.request.url) {
- // requesting to switch to the same playlist multiple times
- // has no effect after the first
- return;
- }
-
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- } // request the new playlist
-
-
- if (this.media_) {
- this.trigger('mediachanging');
- }
-
- this.request = this.vhs_.xhr({
- uri: playlist.resolvedUri,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this5.request) {
- return;
- }
-
- playlist.lastRequest = Date.now();
- playlist.resolvedUri = resolveManifestRedirect(_this5.handleManifestRedirects, playlist.resolvedUri, req);
-
- if (error) {
- return _this5.playlistRequestError(_this5.request, playlist, startingState);
- }
-
- _this5.haveMetadata({
- playlistString: req.responseText,
- url: playlist.uri,
- id: playlist.id
- }); // fire loadedmetadata the first time a media playlist is loaded
-
-
- if (startingState === 'HAVE_MASTER') {
- _this5.trigger('loadedmetadata');
- } else {
- _this5.trigger('mediachange');
- }
- });
- }
- /**
- * pause loading of the playlist
- */
- ;
-
- _proto.pause = function pause() {
- this.stopRequest();
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
-
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- } // Need to restore state now that no activity is happening
-
-
- if (this.state === 'SWITCHING_MEDIA') {
- // if the loader was in the process of switching media, it should either return to
- // HAVE_MASTER or HAVE_METADATA depending on if the loader has loaded a media
- // playlist yet. This is determined by the existence of loader.media_
- if (this.media_) {
- this.state = 'HAVE_METADATA';
- } else {
- this.state = 'HAVE_MASTER';
- }
- } else if (this.state === 'HAVE_CURRENT_METADATA') {
- this.state = 'HAVE_METADATA';
- }
- }
- /**
- * start loading of the playlist
- */
- ;
-
- _proto.load = function load(shouldDelay) {
- var _this6 = this;
-
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- var media = this.media();
-
- if (shouldDelay) {
- var delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
- this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- return _this6.load();
- }, delay);
- return;
- }
-
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- }
- /**
- * start loading of the playlist
- */
- ;
-
- _proto.start = function start() {
- var _this7 = this;
-
- this.started = true;
-
- if (typeof this.src === 'object') {
- // in the case of an entirely constructed manifest object (meaning there's no actual
- // manifest on a server), default the uri to the page's href
- if (!this.src.uri) {
- this.src.uri = window__default['default'].location.href;
- } // resolvedUri is added on internally after the initial request. Since there's no
- // request for pre-resolved manifests, add on resolvedUri here.
-
-
- this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
- // request can be skipped (since the top level of the manifest, at a minimum, is
- // already available as a parsed manifest object). However, if the manifest object
- // represents a master playlist, some media playlists may need to be resolved before
- // the starting segment list is available. Therefore, go directly to setup of the
- // initial playlist, and let the normal flow continue from there.
- //
- // Note that the call to setup is asynchronous, as other sections of VHS may assume
- // that the first request is asynchronous.
-
- setTimeout(function () {
- _this7.setupInitialPlaylist(_this7.src);
- }, 0);
- return;
- } // request the specified URL
-
-
- this.request = this.vhs_.xhr({
- uri: this.src,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this7.request) {
- return;
- } // clear the loader's request reference
-
-
- _this7.request = null;
-
- if (error) {
- _this7.error = {
- status: req.status,
- message: "HLS playlist request error at URL: " + _this7.src + ".",
- responseText: req.responseText,
- // MEDIA_ERR_NETWORK
- code: 2
- };
-
- if (_this7.state === 'HAVE_NOTHING') {
- _this7.started = false;
- }
-
- return _this7.trigger('error');
- }
-
- _this7.src = resolveManifestRedirect(_this7.handleManifestRedirects, _this7.src, req);
-
- var manifest = _this7.parseManifest_({
- manifestString: req.responseText,
- url: _this7.src
- });
-
- _this7.setupInitialPlaylist(manifest);
- });
- };
-
- _proto.srcUri = function srcUri() {
- return typeof this.src === 'string' ? this.src : this.src.uri;
- }
- /**
- * Given a manifest object that's either a master or media playlist, trigger the proper
- * events and set the state of the playlist loader.
- *
- * If the manifest object represents a master playlist, `loadedplaylist` will be
- * triggered to allow listeners to select a playlist. If none is selected, the loader
- * will default to the first one in the playlists array.
- *
- * If the manifest object represents a media playlist, `loadedplaylist` will be
- * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
- *
- * In the case of a media playlist, a master playlist object wrapper with one playlist
- * will be created so that all logic can handle playlists in the same fashion (as an
- * assumed manifest object schema).
- *
- * @param {Object} manifest
- * The parsed manifest object
- */
- ;
-
- _proto.setupInitialPlaylist = function setupInitialPlaylist(manifest) {
- this.state = 'HAVE_MASTER';
-
- if (manifest.playlists) {
- this.master = manifest;
- addPropertiesToMaster(this.master, this.srcUri()); // If the initial master playlist has playlists wtih segments already resolved,
- // then resolve URIs in advance, as they are usually done after a playlist request,
- // which may not happen if the playlist is resolved.
-
- manifest.playlists.forEach(function (playlist) {
- playlist.segments = getAllSegments(playlist);
- playlist.segments.forEach(function (segment) {
- resolveSegmentUris(segment, playlist.resolvedUri);
- });
- });
- this.trigger('loadedplaylist');
-
- if (!this.request) {
- // no media playlist was specifically selected so start
- // from the first listed one
- this.media(this.master.playlists[0]);
- }
-
- return;
- } // In order to support media playlists passed in as vhs-json, the case where the uri
- // is not provided as part of the manifest should be considered, and an appropriate
- // default used.
-
-
- var uri = this.srcUri() || window__default['default'].location.href;
- this.master = masterForMedia(manifest, uri);
- this.haveMetadata({
- playlistObject: manifest,
- url: uri,
- id: this.master.playlists[0].id
- });
- this.trigger('loadedmetadata');
- };
-
- return PlaylistLoader;
- }(EventTarget$1);
-
- /**
- * @file xhr.js
- */
- var videojsXHR = videojs__default['default'].xhr,
- mergeOptions$1 = videojs__default['default'].mergeOptions;
-
- var callbackWrapper = function callbackWrapper(request, error, response, callback) {
- var reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
-
- if (!error && reqResponse) {
- request.responseTime = Date.now();
- request.roundTripTime = request.responseTime - request.requestTime;
- request.bytesReceived = reqResponse.byteLength || reqResponse.length;
-
- if (!request.bandwidth) {
- request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
- }
- }
-
- if (response.headers) {
- request.responseHeaders = response.headers;
- } // videojs.xhr now uses a specific code on the error
- // object to signal that a request has timed out instead
- // of setting a boolean on the request object
-
-
- if (error && error.code === 'ETIMEDOUT') {
- request.timedout = true;
- } // videojs.xhr no longer considers status codes outside of 200 and 0
- // (for file uris) to be errors, but the old XHR did, so emulate that
- // behavior. Status 206 may be used in response to byterange requests.
-
-
- if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
- error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
- }
-
- callback(error, request);
- };
-
- var xhrFactory = function xhrFactory() {
- var xhr = function XhrFunction(options, callback) {
- // Add a default timeout
- options = mergeOptions$1({
- timeout: 45e3
- }, options); // Allow an optional user-specified function to modify the option
- // object before we construct the xhr request
-
- var beforeRequest = XhrFunction.beforeRequest || videojs__default['default'].Vhs.xhr.beforeRequest;
-
- if (beforeRequest && typeof beforeRequest === 'function') {
- var newOptions = beforeRequest(options);
-
- if (newOptions) {
- options = newOptions;
- }
- } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
- // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
-
-
- var xhrMethod = videojs__default['default'].Vhs.xhr.original === true ? videojsXHR : videojs__default['default'].Vhs.xhr;
- var request = xhrMethod(options, function (error, response) {
- return callbackWrapper(request, error, response, callback);
- });
- var originalAbort = request.abort;
-
- request.abort = function () {
- request.aborted = true;
- return originalAbort.apply(request, arguments);
- };
-
- request.uri = options.uri;
- request.requestTime = Date.now();
- return request;
- };
-
- xhr.original = true;
- return xhr;
- };
- /**
- * Turns segment byterange into a string suitable for use in
- * HTTP Range requests
- *
- * @param {Object} byterange - an object with two values defining the start and end
- * of a byte-range
- */
-
-
- var byterangeStr = function byterangeStr(byterange) {
- // `byterangeEnd` is one less than `offset + length` because the HTTP range
- // header uses inclusive ranges
- var byterangeEnd = byterange.offset + byterange.length - 1;
- var byterangeStart = byterange.offset;
- return 'bytes=' + byterangeStart + '-' + byterangeEnd;
- };
- /**
- * Defines headers for use in the xhr request for a particular segment.
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- */
-
-
- var segmentXhrHeaders = function segmentXhrHeaders(segment) {
- var headers = {};
-
- if (segment.byterange) {
- headers.Range = byterangeStr(segment.byterange);
- }
-
- return headers;
- };
-
- var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
- var DASH_REGEX = /^application\/dash\+xml/i;
- /**
- * Returns a string that describes the type of source based on a video source object's
- * media type.
- *
- * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
- *
- * @param {string} type
- * Video source object media type
- * @return {('hls'|'dash'|'vhs-json'|null)}
- * VHS source type string
- */
-
- var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
- if (MPEGURL_REGEX.test(type)) {
- return 'hls';
- }
-
- if (DASH_REGEX.test(type)) {
- return 'dash';
- } // Denotes the special case of a manifest object passed to http-streaming instead of a
- // source URL.
- //
- // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
- //
- // In this case, vnd stands for vendor, video.js for the organization, VHS for this
- // project, and the +json suffix identifies the structure of the media type.
-
-
- if (type === 'application/vnd.videojs.vhs+json') {
- return 'vhs-json';
- }
-
- return null;
- };
-
- /**
- * @file bin-utils.js
- */
-
- /**
- * convert a TimeRange to text
- *
- * @param {TimeRange} range the timerange to use for conversion
- * @param {number} i the iterator on the range to convert
- * @return {string} the range in string format
- */
- var textRange = function textRange(range, i) {
- return range.start(i) + '-' + range.end(i);
- };
- /**
- * format a number as hex string
- *
- * @param {number} e The number
- * @param {number} i the iterator
- * @return {string} the hex formatted number as a string
- */
-
-
- var formatHexString = function formatHexString(e, i) {
- var value = e.toString(16);
- return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
- };
-
- var formatAsciiString = function formatAsciiString(e) {
- if (e >= 0x20 && e < 0x7e) {
- return String.fromCharCode(e);
- }
-
- return '.';
- };
- /**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-
-
- var createTransferableMessage = function createTransferableMessage(message) {
- var transferable = {};
- Object.keys(message).forEach(function (key) {
- var value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
- return transferable;
- };
- /**
- * Returns a unique string identifier for a media initialization
- * segment.
- *
- * @param {Object} initSegment
- * the init segment object.
- *
- * @return {string} the generated init segment id
- */
-
- var initSegmentId = function initSegmentId(initSegment) {
- var byterange = initSegment.byterange || {
- length: Infinity,
- offset: 0
- };
- return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
- };
- /**
- * Returns a unique string identifier for a media segment key.
- *
- * @param {Object} key the encryption key
- * @return {string} the unique id for the media segment key.
- */
-
- var segmentKeyId = function segmentKeyId(key) {
- return key.resolvedUri;
- };
- /**
- * utils to help dump binary data to the console
- *
- * @param {Array|TypedArray} data
- * data to dump to a string
- *
- * @return {string} the data as a hex string.
- */
-
- var hexDump = function hexDump(data) {
- var bytes = Array.prototype.slice.call(data);
- var step = 16;
- var result = '';
- var hex;
- var ascii;
-
- for (var j = 0; j < bytes.length / step; j++) {
- hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
- ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
- result += hex + ' ' + ascii + '\n';
- }
-
- return result;
- };
- var tagDump = function tagDump(_ref) {
- var bytes = _ref.bytes;
- return hexDump(bytes);
- };
- var textRanges = function textRanges(ranges) {
- var result = '';
- var i;
-
- for (i = 0; i < ranges.length; i++) {
- result += textRange(ranges, i) + ' ';
- }
-
- return result;
- };
-
- var utils = /*#__PURE__*/Object.freeze({
- __proto__: null,
- createTransferableMessage: createTransferableMessage,
- initSegmentId: initSegmentId,
- segmentKeyId: segmentKeyId,
- hexDump: hexDump,
- tagDump: tagDump,
- textRanges: textRanges
- });
-
- // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
- // 25% was arbitrarily chosen, and may need to be refined over time.
-
- var SEGMENT_END_FUDGE_PERCENT = 0.25;
- /**
- * Converts a player time (any time that can be gotten/set from player.currentTime(),
- * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
- * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
- *
- * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
- * point" (a point where we have a mapping from program time to player time, with player
- * time being the post transmux start of the segment).
- *
- * For more details, see [this doc](../../docs/program-time-from-player-time.md).
- *
- * @param {number} playerTime the player time
- * @param {Object} segment the segment which contains the player time
- * @return {Date} program time
- */
-
- var playerTimeToProgramTime = function playerTimeToProgramTime(playerTime, segment) {
- if (!segment.dateTimeObject) {
- // Can't convert without an "anchor point" for the program time (i.e., a time that can
- // be used to map the start of a segment with a real world time).
- return null;
- }
-
- var transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
- var transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
-
- var startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
- var offsetFromSegmentStart = playerTime - startOfSegment;
- return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
- };
- var originalSegmentVideoDuration = function originalSegmentVideoDuration(videoTimingInfo) {
- return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
- };
- /**
- * Finds a segment that contains the time requested given as an ISO-8601 string. The
- * returned segment might be an estimate or an accurate match.
- *
- * @param {string} programTime The ISO-8601 programTime to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-
- var findSegmentForProgramTime = function findSegmentForProgramTime(programTime, playlist) {
- // Assumptions:
- // - verifyProgramDateTimeTags has already been run
- // - live streams have been started
- var dateTimeObject;
-
- try {
- dateTimeObject = new Date(programTime);
- } catch (e) {
- return null;
- }
-
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- var segment = playlist.segments[0];
-
- if (dateTimeObject < segment.dateTimeObject) {
- // Requested time is before stream start.
- return null;
- }
-
- for (var i = 0; i < playlist.segments.length - 1; i++) {
- segment = playlist.segments[i];
- var nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
-
- if (dateTimeObject < nextSegmentStart) {
- break;
- }
- }
-
- var lastSegment = playlist.segments[playlist.segments.length - 1];
- var lastSegmentStart = lastSegment.dateTimeObject;
- var lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
- var lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
-
- if (dateTimeObject > lastSegmentEnd) {
- // Beyond the end of the stream, or our best guess of the end of the stream.
- return null;
- }
-
- if (dateTimeObject > lastSegmentStart) {
- segment = lastSegment;
- }
-
- return {
- segment: segment,
- estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
- // Although, given that all segments have accurate date time objects, the segment
- // selected should be accurate, unless the video has been transmuxed at some point
- // (determined by the presence of the videoTimingInfo object), the segment's "player
- // time" (the start time in the player) can't be considered accurate.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
- };
- /**
- * Finds a segment that contains the given player time(in seconds).
- *
- * @param {number} time The player time to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-
- var findSegmentForPlayerTime = function findSegmentForPlayerTime(time, playlist) {
- // Assumptions:
- // - there will always be a segment.duration
- // - we can start from zero
- // - segments are in time order
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- var segmentEnd = 0;
- var segment;
-
- for (var i = 0; i < playlist.segments.length; i++) {
- segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
- // should contain the most accurate values we have for the segment's player times.
- //
- // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
- // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
- // calculate an end value.
-
- segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
-
- if (time <= segmentEnd) {
- break;
- }
- }
-
- var lastSegment = playlist.segments[playlist.segments.length - 1];
-
- if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
- // The time requested is beyond the stream end.
- return null;
- }
-
- if (time > segmentEnd) {
- // The time is within or beyond the last segment.
- //
- // Check to see if the time is beyond a reasonable guess of the end of the stream.
- if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
- // Technically, because the duration value is only an estimate, the time may still
- // exist in the last segment, however, there isn't enough information to make even
- // a reasonable estimate.
- return null;
- }
-
- segment = lastSegment;
- }
-
- return {
- segment: segment,
- estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
- // Because videoTimingInfo is only set after transmux, it is the only way to get
- // accurate timing values.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
- };
- /**
- * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
- * If the offset returned is positive, the programTime occurs after the
- * comparisonTimestamp.
- * If the offset is negative, the programTime occurs before the comparisonTimestamp.
- *
- * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
- * @param {string} programTime The programTime as an ISO-8601 string
- * @return {number} offset
- */
-
- var getOffsetFromTimestamp = function getOffsetFromTimestamp(comparisonTimeStamp, programTime) {
- var segmentDateTime;
- var programDateTime;
-
- try {
- segmentDateTime = new Date(comparisonTimeStamp);
- programDateTime = new Date(programTime);
- } catch (e) {// TODO handle error
- }
-
- var segmentTimeEpoch = segmentDateTime.getTime();
- var programTimeEpoch = programDateTime.getTime();
- return (programTimeEpoch - segmentTimeEpoch) / 1000;
- };
- /**
- * Checks that all segments in this playlist have programDateTime tags.
- *
- * @param {Object} playlist A playlist object
- */
-
- var verifyProgramDateTimeTags = function verifyProgramDateTimeTags(playlist) {
- if (!playlist.segments || playlist.segments.length === 0) {
- return false;
- }
-
- for (var i = 0; i < playlist.segments.length; i++) {
- var segment = playlist.segments[i];
-
- if (!segment.dateTimeObject) {
- return false;
- }
- }
-
- return true;
- };
- /**
- * Returns the programTime of the media given a playlist and a playerTime.
- * The playlist must have programDateTime tags for a programDateTime tag to be returned.
- * If the segments containing the time requested have not been buffered yet, an estimate
- * may be returned to the callback.
- *
- * @param {Object} args
- * @param {Object} args.playlist A playlist object to search within
- * @param {number} time A playerTime in seconds
- * @param {Function} callback(err, programTime)
- * @return {string} err.message A detailed error message
- * @return {Object} programTime
- * @return {number} programTime.mediaSeconds The streamTime in seconds
- * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
- */
-
- var getProgramTime = function getProgramTime(_ref) {
- var playlist = _ref.playlist,
- _ref$time = _ref.time,
- time = _ref$time === void 0 ? undefined : _ref$time,
- callback = _ref.callback;
-
- if (!callback) {
- throw new Error('getProgramTime: callback must be provided');
- }
-
- if (!playlist || time === undefined) {
- return callback({
- message: 'getProgramTime: playlist and time must be provided'
- });
- }
-
- var matchedSegment = findSegmentForPlayerTime(time, playlist);
-
- if (!matchedSegment) {
- return callback({
- message: 'valid programTime was not found'
- });
- }
-
- if (matchedSegment.type === 'estimate') {
- return callback({
- message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
- seekTime: matchedSegment.estimatedStart
- });
- }
-
- var programTimeObject = {
- mediaSeconds: time
- };
- var programTime = playerTimeToProgramTime(time, matchedSegment.segment);
-
- if (programTime) {
- programTimeObject.programDateTime = programTime.toISOString();
- }
-
- return callback(null, programTimeObject);
- };
- /**
- * Seeks in the player to a time that matches the given programTime ISO-8601 string.
- *
- * @param {Object} args
- * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
- * @param {Object} args.playlist A playlist to look within
- * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
- * @param {Function} args.seekTo A method to perform a seek
- * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
- * @param {Object} args.tech The tech to seek on
- * @param {Function} args.callback(err, newTime) A callback to return the new time to
- * @return {string} err.message A detailed error message
- * @return {number} newTime The exact time that was seeked to in seconds
- */
-
- var seekToProgramTime = function seekToProgramTime(_ref2) {
- var programTime = _ref2.programTime,
- playlist = _ref2.playlist,
- _ref2$retryCount = _ref2.retryCount,
- retryCount = _ref2$retryCount === void 0 ? 2 : _ref2$retryCount,
- seekTo = _ref2.seekTo,
- _ref2$pauseAfterSeek = _ref2.pauseAfterSeek,
- pauseAfterSeek = _ref2$pauseAfterSeek === void 0 ? true : _ref2$pauseAfterSeek,
- tech = _ref2.tech,
- callback = _ref2.callback;
-
- if (!callback) {
- throw new Error('seekToProgramTime: callback must be provided');
- }
-
- if (typeof programTime === 'undefined' || !playlist || !seekTo) {
- return callback({
- message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
- });
- }
-
- if (!playlist.endList && !tech.hasStarted_) {
- return callback({
- message: 'player must be playing a live stream to start buffering'
- });
- }
-
- if (!verifyProgramDateTimeTags(playlist)) {
- return callback({
- message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
- });
- }
-
- var matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
-
- if (!matchedSegment) {
- return callback({
- message: programTime + " was not found in the stream"
- });
- }
-
- var segment = matchedSegment.segment;
- var mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
-
- if (matchedSegment.type === 'estimate') {
- // we've run out of retries
- if (retryCount === 0) {
- return callback({
- message: programTime + " is not buffered yet. Try again"
- });
- }
-
- seekTo(matchedSegment.estimatedStart + mediaOffset);
- tech.one('seeked', function () {
- seekToProgramTime({
- programTime: programTime,
- playlist: playlist,
- retryCount: retryCount - 1,
- seekTo: seekTo,
- pauseAfterSeek: pauseAfterSeek,
- tech: tech,
- callback: callback
- });
- });
- return;
- } // Since the segment.start value is determined from the buffered end or ending time
- // of the prior segment, the seekToTime doesn't need to account for any transmuxer
- // modifications.
-
-
- var seekToTime = segment.start + mediaOffset;
-
- var seekedCallback = function seekedCallback() {
- return callback(null, tech.currentTime());
- }; // listen for seeked event
-
-
- tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
-
- if (pauseAfterSeek) {
- tech.pause();
- }
-
- seekTo(seekToTime);
- };
-
- /*! @name mpd-parser @version 0.17.0 @license Apache-2.0 */
-
- var isObject = function isObject(obj) {
- return !!obj && typeof obj === 'object';
- };
-
- var merge = function merge() {
- for (var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++) {
- objects[_key] = arguments[_key];
- }
-
- return objects.reduce(function (result, source) {
- if (typeof source !== 'object') {
- return result;
- }
-
- Object.keys(source).forEach(function (key) {
- if (Array.isArray(result[key]) && Array.isArray(source[key])) {
- result[key] = result[key].concat(source[key]);
- } else if (isObject(result[key]) && isObject(source[key])) {
- result[key] = merge(result[key], source[key]);
- } else {
- result[key] = source[key];
- }
- });
- return result;
- }, {});
- };
-
- var values = function values(o) {
- return Object.keys(o).map(function (k) {
- return o[k];
- });
- };
-
- var range = function range(start, end) {
- var result = [];
-
- for (var i = start; i < end; i++) {
- result.push(i);
- }
-
- return result;
- };
-
- var flatten = function flatten(lists) {
- return lists.reduce(function (x, y) {
- return x.concat(y);
- }, []);
- };
-
- var from = function from(list) {
- if (!list.length) {
- return [];
- }
-
- var result = [];
-
- for (var i = 0; i < list.length; i++) {
- result.push(list[i]);
- }
-
- return result;
- };
-
- var findIndexes = function findIndexes(l, key) {
- return l.reduce(function (a, e, i) {
- if (e[key]) {
- a.push(i);
- }
-
- return a;
- }, []);
- };
-
- var errors = {
- INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',
- DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',
- DASH_INVALID_XML: 'DASH_INVALID_XML',
- NO_BASE_URL: 'NO_BASE_URL',
- MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',
- SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',
- UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'
- };
- /**
- * @typedef {Object} SingleUri
- * @property {string} uri - relative location of segment
- * @property {string} resolvedUri - resolved location of segment
- * @property {Object} byterange - Object containing information on how to make byte range
- * requests following byte-range-spec per RFC2616.
- * @property {String} byterange.length - length of range request
- * @property {String} byterange.offset - byte offset of range request
- *
- * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
- */
-
- /**
- * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object
- * that conforms to how m3u8-parser is structured
- *
- * @see https://github.com/videojs/m3u8-parser
- *
- * @param {string} baseUrl - baseUrl provided by nodes
- * @param {string} source - source url for segment
- * @param {string} range - optional range used for range calls,
- * follows RFC 2616, Clause 14.35.1
- * @return {SingleUri} full segment information transformed into a format similar
- * to m3u8-parser
- */
-
- var urlTypeToSegment = function urlTypeToSegment(_ref) {
- var _ref$baseUrl = _ref.baseUrl,
- baseUrl = _ref$baseUrl === void 0 ? '' : _ref$baseUrl,
- _ref$source = _ref.source,
- source = _ref$source === void 0 ? '' : _ref$source,
- _ref$range = _ref.range,
- range = _ref$range === void 0 ? '' : _ref$range,
- _ref$indexRange = _ref.indexRange,
- indexRange = _ref$indexRange === void 0 ? '' : _ref$indexRange;
- var segment = {
- uri: source,
- resolvedUri: resolveUrl$1(baseUrl || '', source)
- };
-
- if (range || indexRange) {
- var rangeStr = range ? range : indexRange;
- var ranges = rangeStr.split('-');
- var startRange = parseInt(ranges[0], 10);
- var endRange = parseInt(ranges[1], 10); // byterange should be inclusive according to
- // RFC 2616, Clause 14.35.1
-
- segment.byterange = {
- length: endRange - startRange + 1,
- offset: startRange
- };
- }
-
- return segment;
- };
-
- var byteRangeToString = function byteRangeToString(byterange) {
- // `endRange` is one less than `offset + length` because the HTTP range
- // header uses inclusive ranges
- var endRange = byterange.offset + byterange.length - 1;
- return byterange.offset + "-" + endRange;
- };
- /**
- * parse the end number attribue that can be a string
- * number, or undefined.
- *
- * @param {string|number|undefined} endNumber
- * The end number attribute.
- *
- * @return {number|null}
- * The result of parsing the end number.
- */
-
-
- var parseEndNumber = function parseEndNumber(endNumber) {
- if (endNumber && typeof endNumber !== 'number') {
- endNumber = parseInt(endNumber, 10);
- }
-
- if (isNaN(endNumber)) {
- return null;
- }
-
- return endNumber;
- };
- /**
- * Functions for calculating the range of available segments in static and dynamic
- * manifests.
- */
-
-
- var segmentRange = {
- /**
- * Returns the entire range of available segments for a static MPD
- *
- * @param {Object} attributes
- * Inheritied MPD attributes
- * @return {{ start: number, end: number }}
- * The start and end numbers for available segments
- */
- static: function _static(attributes) {
- var duration = attributes.duration,
- _attributes$timescale = attributes.timescale,
- timescale = _attributes$timescale === void 0 ? 1 : _attributes$timescale,
- sourceDuration = attributes.sourceDuration;
- var endNumber = parseEndNumber(attributes.endNumber);
- return {
- start: 0,
- end: typeof endNumber === 'number' ? endNumber : Math.ceil(sourceDuration / (duration / timescale))
- };
- },
-
- /**
- * Returns the current live window range of available segments for a dynamic MPD
- *
- * @param {Object} attributes
- * Inheritied MPD attributes
- * @return {{ start: number, end: number }}
- * The start and end numbers for available segments
- */
- dynamic: function dynamic(attributes) {
- var NOW = attributes.NOW,
- clientOffset = attributes.clientOffset,
- availabilityStartTime = attributes.availabilityStartTime,
- _attributes$timescale2 = attributes.timescale,
- timescale = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2,
- duration = attributes.duration,
- _attributes$start = attributes.start,
- start = _attributes$start === void 0 ? 0 : _attributes$start,
- _attributes$minimumUp = attributes.minimumUpdatePeriod,
- minimumUpdatePeriod = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp,
- _attributes$timeShift = attributes.timeShiftBufferDepth,
- timeShiftBufferDepth = _attributes$timeShift === void 0 ? Infinity : _attributes$timeShift;
- var endNumber = parseEndNumber(attributes.endNumber);
- var now = (NOW + clientOffset) / 1000;
- var periodStartWC = availabilityStartTime + start;
- var periodEndWC = now + minimumUpdatePeriod;
- var periodDuration = periodEndWC - periodStartWC;
- var segmentCount = Math.ceil(periodDuration * timescale / duration);
- var availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);
- var availableEnd = Math.floor((now - periodStartWC) * timescale / duration);
- return {
- start: Math.max(0, availableStart),
- end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)
- };
- }
- };
- /**
- * Maps a range of numbers to objects with information needed to build the corresponding
- * segment list
- *
- * @name toSegmentsCallback
- * @function
- * @param {number} number
- * Number of the segment
- * @param {number} index
- * Index of the number in the range list
- * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}
- * Object with segment timing and duration info
- */
-
- /**
- * Returns a callback for Array.prototype.map for mapping a range of numbers to
- * information needed to build the segment list.
- *
- * @param {Object} attributes
- * Inherited MPD attributes
- * @return {toSegmentsCallback}
- * Callback map function
- */
-
- var toSegments = function toSegments(attributes) {
- return function (number, index) {
- var duration = attributes.duration,
- _attributes$timescale3 = attributes.timescale,
- timescale = _attributes$timescale3 === void 0 ? 1 : _attributes$timescale3,
- periodIndex = attributes.periodIndex,
- _attributes$startNumb = attributes.startNumber,
- startNumber = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb;
- return {
- number: startNumber + number,
- duration: duration / timescale,
- timeline: periodIndex,
- time: index * duration
- };
- };
- };
- /**
- * Returns a list of objects containing segment timing and duration info used for
- * building the list of segments. This uses the @duration attribute specified
- * in the MPD manifest to derive the range of segments.
- *
- * @param {Object} attributes
- * Inherited MPD attributes
- * @return {{number: number, duration: number, time: number, timeline: number}[]}
- * List of Objects with segment timing and duration info
- */
-
-
- var parseByDuration = function parseByDuration(attributes) {
- var _attributes$type = attributes.type,
- type = _attributes$type === void 0 ? 'static' : _attributes$type,
- duration = attributes.duration,
- _attributes$timescale4 = attributes.timescale,
- timescale = _attributes$timescale4 === void 0 ? 1 : _attributes$timescale4,
- sourceDuration = attributes.sourceDuration;
-
- var _segmentRange$type = segmentRange[type](attributes),
- start = _segmentRange$type.start,
- end = _segmentRange$type.end;
-
- var segments = range(start, end).map(toSegments(attributes));
-
- if (type === 'static') {
- var index = segments.length - 1; // final segment may be less than full segment duration
-
- segments[index].duration = sourceDuration - duration / timescale * index;
- }
-
- return segments;
- };
- /**
- * Translates SegmentBase into a set of segments.
- * (DASH SPEC Section 5.3.9.3.2) contains a set of nodes. Each
- * node should be translated into segment.
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @return {Object.} list of segments
- */
-
-
- var segmentsFromBase = function segmentsFromBase(attributes) {
- var baseUrl = attributes.baseUrl,
- _attributes$initializ = attributes.initialization,
- initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ,
- sourceDuration = attributes.sourceDuration,
- _attributes$indexRang = attributes.indexRange,
- indexRange = _attributes$indexRang === void 0 ? '' : _attributes$indexRang,
- duration = attributes.duration; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)
-
- if (!baseUrl) {
- throw new Error(errors.NO_BASE_URL);
- }
-
- var initSegment = urlTypeToSegment({
- baseUrl: baseUrl,
- source: initialization.sourceURL,
- range: initialization.range
- });
- var segment = urlTypeToSegment({
- baseUrl: baseUrl,
- source: baseUrl,
- indexRange: indexRange
- });
- segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source
- // (since SegmentBase is only for one total segment)
-
- if (duration) {
- var segmentTimeInfo = parseByDuration(attributes);
-
- if (segmentTimeInfo.length) {
- segment.duration = segmentTimeInfo[0].duration;
- segment.timeline = segmentTimeInfo[0].timeline;
- }
- } else if (sourceDuration) {
- segment.duration = sourceDuration;
- segment.timeline = 0;
- } // This is used for mediaSequence
-
-
- segment.number = 0;
- return [segment];
- };
- /**
- * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist
- * according to the sidx information given.
- *
- * playlist.sidx has metadadata about the sidx where-as the sidx param
- * is the parsed sidx box itself.
- *
- * @param {Object} playlist the playlist to update the sidx information for
- * @param {Object} sidx the parsed sidx box
- * @return {Object} the playlist object with the updated sidx information
- */
-
-
- var addSidxSegmentsToPlaylist = function addSidxSegmentsToPlaylist(playlist, sidx, baseUrl) {
- // Retain init segment information
- var initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial master manifest parsing
-
- var sourceDuration = playlist.sidx.duration; // Retain source timeline
-
- var timeline = playlist.timeline || 0;
- var sidxByteRange = playlist.sidx.byterange;
- var sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx
-
- var timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes
-
- var mediaReferences = sidx.references.filter(function (r) {
- return r.referenceType !== 1;
- });
- var segments = []; // firstOffset is the offset from the end of the sidx box
-
- var startIndex = sidxEnd + sidx.firstOffset;
-
- for (var i = 0; i < mediaReferences.length; i++) {
- var reference = sidx.references[i]; // size of the referenced (sub)segment
-
- var size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale
- // this will be converted to seconds when generating segments
-
- var duration = reference.subsegmentDuration; // should be an inclusive range
-
- var endIndex = startIndex + size - 1;
- var indexRange = startIndex + "-" + endIndex;
- var attributes = {
- baseUrl: baseUrl,
- timescale: timescale,
- timeline: timeline,
- // this is used in parseByDuration
- periodIndex: timeline,
- duration: duration,
- sourceDuration: sourceDuration,
- indexRange: indexRange
- };
- var segment = segmentsFromBase(attributes)[0];
-
- if (initSegment) {
- segment.map = initSegment;
- }
-
- segments.push(segment);
- startIndex += size;
- }
-
- playlist.segments = segments;
- return playlist;
- };
-
- var generateSidxKey = function generateSidxKey(sidx) {
- return sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);
- };
-
- var mergeDiscontiguousPlaylists = function mergeDiscontiguousPlaylists(playlists) {
- var mergedPlaylists = values(playlists.reduce(function (acc, playlist) {
- // assuming playlist IDs are the same across periods
- // TODO: handle multiperiod where representation sets are not the same
- // across periods
- var name = playlist.attributes.id + (playlist.attributes.lang || ''); // Periods after first
-
- if (acc[name]) {
- var _acc$name$segments; // first segment of subsequent periods signal a discontinuity
-
-
- if (playlist.segments[0]) {
- playlist.segments[0].discontinuity = true;
- }
-
- (_acc$name$segments = acc[name].segments).push.apply(_acc$name$segments, playlist.segments); // bubble up contentProtection, this assumes all DRM content
- // has the same contentProtection
-
-
- if (playlist.attributes.contentProtection) {
- acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
- }
- } else {
- // first Period
- acc[name] = playlist;
- }
-
- return acc;
- }, {}));
- return mergedPlaylists.map(function (playlist) {
- playlist.discontinuityStarts = findIndexes(playlist.segments, 'discontinuity');
- return playlist;
- });
- };
-
- var addSidxSegmentsToPlaylist$1 = function addSidxSegmentsToPlaylist$1(playlist, sidxMapping) {
- var sidxKey = generateSidxKey(playlist.sidx);
- var sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
-
- if (sidxMatch) {
- addSidxSegmentsToPlaylist(playlist, sidxMatch, playlist.sidx.resolvedUri);
- }
-
- return playlist;
- };
-
- var addSidxSegmentsToPlaylists = function addSidxSegmentsToPlaylists(playlists, sidxMapping) {
- if (sidxMapping === void 0) {
- sidxMapping = {};
- }
-
- if (!Object.keys(sidxMapping).length) {
- return playlists;
- }
-
- for (var i in playlists) {
- playlists[i] = addSidxSegmentsToPlaylist$1(playlists[i], sidxMapping);
- }
-
- return playlists;
- };
-
- var formatAudioPlaylist = function formatAudioPlaylist(_ref, isAudioOnly) {
- var _attributes;
-
- var attributes = _ref.attributes,
- segments = _ref.segments,
- sidx = _ref.sidx;
- var playlist = {
- attributes: (_attributes = {
- NAME: attributes.id,
- BANDWIDTH: attributes.bandwidth,
- CODECS: attributes.codecs
- }, _attributes['PROGRAM-ID'] = 1, _attributes),
- uri: '',
- endList: (attributes.type || 'static') === 'static',
- timeline: attributes.periodIndex,
- resolvedUri: '',
- targetDuration: attributes.duration,
- segments: segments,
- mediaSequence: segments.length ? segments[0].number : 1
- };
-
- if (attributes.contentProtection) {
- playlist.contentProtection = attributes.contentProtection;
- }
-
- if (sidx) {
- playlist.sidx = sidx;
- }
-
- if (isAudioOnly) {
- playlist.attributes.AUDIO = 'audio';
- playlist.attributes.SUBTITLES = 'subs';
- }
-
- return playlist;
- };
-
- var formatVttPlaylist = function formatVttPlaylist(_ref2) {
- var _m3u8Attributes;
-
- var attributes = _ref2.attributes,
- segments = _ref2.segments;
-
- if (typeof segments === 'undefined') {
- // vtt tracks may use single file in BaseURL
- segments = [{
- uri: attributes.baseUrl,
- timeline: attributes.periodIndex,
- resolvedUri: attributes.baseUrl || '',
- duration: attributes.sourceDuration,
- number: 0
- }]; // targetDuration should be the same duration as the only segment
-
- attributes.duration = attributes.sourceDuration;
- }
-
- var m3u8Attributes = (_m3u8Attributes = {
- NAME: attributes.id,
- BANDWIDTH: attributes.bandwidth
- }, _m3u8Attributes['PROGRAM-ID'] = 1, _m3u8Attributes);
-
- if (attributes.codecs) {
- m3u8Attributes.CODECS = attributes.codecs;
- }
-
- return {
- attributes: m3u8Attributes,
- uri: '',
- endList: (attributes.type || 'static') === 'static',
- timeline: attributes.periodIndex,
- resolvedUri: attributes.baseUrl || '',
- targetDuration: attributes.duration,
- segments: segments,
- mediaSequence: segments.length ? segments[0].number : 1
- };
- };
-
- var organizeAudioPlaylists = function organizeAudioPlaylists(playlists, sidxMapping, isAudioOnly) {
- if (sidxMapping === void 0) {
- sidxMapping = {};
- }
-
- if (isAudioOnly === void 0) {
- isAudioOnly = false;
- }
-
- var mainPlaylist;
- var formattedPlaylists = playlists.reduce(function (a, playlist) {
- var role = playlist.attributes.role && playlist.attributes.role.value || '';
- var language = playlist.attributes.lang || '';
- var label = playlist.attributes.label || 'main';
-
- if (language && !playlist.attributes.label) {
- var roleLabel = role ? " (" + role + ")" : '';
- label = "" + playlist.attributes.lang + roleLabel;
- }
-
- if (!a[label]) {
- a[label] = {
- language: language,
- autoselect: true,
- default: role === 'main',
- playlists: [],
- uri: ''
- };
- }
-
- var formatted = addSidxSegmentsToPlaylist$1(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);
- a[label].playlists.push(formatted);
-
- if (typeof mainPlaylist === 'undefined' && role === 'main') {
- mainPlaylist = playlist;
- mainPlaylist.default = true;
- }
-
- return a;
- }, {}); // if no playlists have role "main", mark the first as main
-
- if (!mainPlaylist) {
- var firstLabel = Object.keys(formattedPlaylists)[0];
- formattedPlaylists[firstLabel].default = true;
- }
-
- return formattedPlaylists;
- };
-
- var organizeVttPlaylists = function organizeVttPlaylists(playlists, sidxMapping) {
- if (sidxMapping === void 0) {
- sidxMapping = {};
- }
-
- return playlists.reduce(function (a, playlist) {
- var label = playlist.attributes.lang || 'text';
-
- if (!a[label]) {
- a[label] = {
- language: label,
- default: false,
- autoselect: false,
- playlists: [],
- uri: ''
- };
- }
-
- a[label].playlists.push(addSidxSegmentsToPlaylist$1(formatVttPlaylist(playlist), sidxMapping));
- return a;
- }, {});
- };
-
- var organizeCaptionServices = function organizeCaptionServices(captionServices) {
- return captionServices.reduce(function (svcObj, svc) {
- if (!svc) {
- return svcObj;
- }
-
- svc.forEach(function (service) {
- var channel = service.channel,
- language = service.language;
- svcObj[language] = {
- autoselect: false,
- default: false,
- instreamId: channel,
- language: language
- };
-
- if (service.hasOwnProperty('aspectRatio')) {
- svcObj[language].aspectRatio = service.aspectRatio;
- }
-
- if (service.hasOwnProperty('easyReader')) {
- svcObj[language].easyReader = service.easyReader;
- }
-
- if (service.hasOwnProperty('3D')) {
- svcObj[language]['3D'] = service['3D'];
- }
- });
- return svcObj;
- }, {});
- };
-
- var formatVideoPlaylist = function formatVideoPlaylist(_ref3) {
- var _attributes2;
-
- var attributes = _ref3.attributes,
- segments = _ref3.segments,
- sidx = _ref3.sidx;
- var playlist = {
- attributes: (_attributes2 = {
- NAME: attributes.id,
- AUDIO: 'audio',
- SUBTITLES: 'subs',
- RESOLUTION: {
- width: attributes.width,
- height: attributes.height
- },
- CODECS: attributes.codecs,
- BANDWIDTH: attributes.bandwidth
- }, _attributes2['PROGRAM-ID'] = 1, _attributes2),
- uri: '',
- endList: (attributes.type || 'static') === 'static',
- timeline: attributes.periodIndex,
- resolvedUri: '',
- targetDuration: attributes.duration,
- segments: segments,
- mediaSequence: segments.length ? segments[0].number : 1
- };
-
- if (attributes.contentProtection) {
- playlist.contentProtection = attributes.contentProtection;
- }
-
- if (sidx) {
- playlist.sidx = sidx;
- }
-
- return playlist;
- };
-
- var videoOnly = function videoOnly(_ref4) {
- var attributes = _ref4.attributes;
- return attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';
- };
-
- var audioOnly = function audioOnly(_ref5) {
- var attributes = _ref5.attributes;
- return attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';
- };
-
- var vttOnly = function vttOnly(_ref6) {
- var attributes = _ref6.attributes;
- return attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';
- };
-
- var toM3u8 = function toM3u8(dashPlaylists, locations, sidxMapping) {
- var _mediaGroups;
-
- if (sidxMapping === void 0) {
- sidxMapping = {};
- }
-
- if (!dashPlaylists.length) {
- return {};
- } // grab all master attributes
-
-
- var _dashPlaylists$0$attr = dashPlaylists[0].attributes,
- duration = _dashPlaylists$0$attr.sourceDuration,
- _dashPlaylists$0$attr2 = _dashPlaylists$0$attr.type,
- type = _dashPlaylists$0$attr2 === void 0 ? 'static' : _dashPlaylists$0$attr2,
- suggestedPresentationDelay = _dashPlaylists$0$attr.suggestedPresentationDelay,
- minimumUpdatePeriod = _dashPlaylists$0$attr.minimumUpdatePeriod;
- var videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
- var audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
- var vttPlaylists = dashPlaylists.filter(vttOnly);
- var captions = dashPlaylists.map(function (playlist) {
- return playlist.attributes.captionServices;
- }).filter(Boolean);
- var master = {
- allowCache: true,
- discontinuityStarts: [],
- segments: [],
- endList: true,
- mediaGroups: (_mediaGroups = {
- AUDIO: {},
- VIDEO: {}
- }, _mediaGroups['CLOSED-CAPTIONS'] = {}, _mediaGroups.SUBTITLES = {}, _mediaGroups),
- uri: '',
- duration: duration,
- playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
- };
-
- if (minimumUpdatePeriod >= 0) {
- master.minimumUpdatePeriod = minimumUpdatePeriod * 1000;
- }
-
- if (locations) {
- master.locations = locations;
- }
-
- if (type === 'dynamic') {
- master.suggestedPresentationDelay = suggestedPresentationDelay;
- }
-
- var isAudioOnly = master.playlists.length === 0;
-
- if (audioPlaylists.length) {
- master.mediaGroups.AUDIO.audio = organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly);
- }
-
- if (vttPlaylists.length) {
- master.mediaGroups.SUBTITLES.subs = organizeVttPlaylists(vttPlaylists, sidxMapping);
- }
-
- if (captions.length) {
- master.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);
- }
-
- return master;
- };
- /**
- * Calculates the R (repetition) value for a live stream (for the final segment
- * in a manifest where the r value is negative 1)
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {number} time
- * current time (typically the total time up until the final segment)
- * @param {number} duration
- * duration property for the given
- *
- * @return {number}
- * R value to reach the end of the given period
- */
-
-
- var getLiveRValue = function getLiveRValue(attributes, time, duration) {
- var NOW = attributes.NOW,
- clientOffset = attributes.clientOffset,
- availabilityStartTime = attributes.availabilityStartTime,
- _attributes$timescale = attributes.timescale,
- timescale = _attributes$timescale === void 0 ? 1 : _attributes$timescale,
- _attributes$start = attributes.start,
- start = _attributes$start === void 0 ? 0 : _attributes$start,
- _attributes$minimumUp = attributes.minimumUpdatePeriod,
- minimumUpdatePeriod = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp;
- var now = (NOW + clientOffset) / 1000;
- var periodStartWC = availabilityStartTime + start;
- var periodEndWC = now + minimumUpdatePeriod;
- var periodDuration = periodEndWC - periodStartWC;
- return Math.ceil((periodDuration * timescale - time) / duration);
- };
- /**
- * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment
- * timing and duration
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object[]} segmentTimeline
- * List of objects representing the attributes of each S element contained within
- *
- * @return {{number: number, duration: number, time: number, timeline: number}[]}
- * List of Objects with segment timing and duration info
- */
-
-
- var parseByTimeline = function parseByTimeline(attributes, segmentTimeline) {
- var _attributes$type = attributes.type,
- type = _attributes$type === void 0 ? 'static' : _attributes$type,
- _attributes$minimumUp2 = attributes.minimumUpdatePeriod,
- minimumUpdatePeriod = _attributes$minimumUp2 === void 0 ? 0 : _attributes$minimumUp2,
- _attributes$media = attributes.media,
- media = _attributes$media === void 0 ? '' : _attributes$media,
- sourceDuration = attributes.sourceDuration,
- _attributes$timescale2 = attributes.timescale,
- timescale = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2,
- _attributes$startNumb = attributes.startNumber,
- startNumber = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb,
- timeline = attributes.periodIndex;
- var segments = [];
- var time = -1;
-
- for (var sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
- var S = segmentTimeline[sIndex];
- var duration = S.d;
- var repeat = S.r || 0;
- var segmentTime = S.t || 0;
-
- if (time < 0) {
- // first segment
- time = segmentTime;
- }
-
- if (segmentTime && segmentTime > time) {
- // discontinuity
- // TODO: How to handle this type of discontinuity
- // timeline++ here would treat it like HLS discontuity and content would
- // get appended without gap
- // E.G.
- //
- //
- //
- //
- // would have $Time$ values of [0, 1, 2, 5]
- // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)
- // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)
- // does the value of sourceDuration consider this when calculating arbitrary
- // negative @r repeat value?
- // E.G. Same elements as above with this added at the end
- //
- // with a sourceDuration of 10
- // Would the 2 gaps be included in the time duration calculations resulting in
- // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments
- // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?
- time = segmentTime;
- }
-
- var count = void 0;
-
- if (repeat < 0) {
- var nextS = sIndex + 1;
-
- if (nextS === segmentTimeline.length) {
- // last segment
- if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {
- count = getLiveRValue(attributes, time, duration);
- } else {
- // TODO: This may be incorrect depending on conclusion of TODO above
- count = (sourceDuration * timescale - time) / duration;
- }
- } else {
- count = (segmentTimeline[nextS].t - time) / duration;
- }
- } else {
- count = repeat + 1;
- }
-
- var end = startNumber + segments.length + count;
- var number = startNumber + segments.length;
-
- while (number < end) {
- segments.push({
- number: number,
- duration: duration / timescale,
- time: time,
- timeline: timeline
- });
- time += duration;
- number++;
- }
- }
-
- return segments;
- };
-
- var identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
- /**
- * Replaces template identifiers with corresponding values. To be used as the callback
- * for String.prototype.replace
- *
- * @name replaceCallback
- * @function
- * @param {string} match
- * Entire match of identifier
- * @param {string} identifier
- * Name of matched identifier
- * @param {string} format
- * Format tag string. Its presence indicates that padding is expected
- * @param {string} width
- * Desired length of the replaced value. Values less than this width shall be left
- * zero padded
- * @return {string}
- * Replacement for the matched identifier
- */
-
- /**
- * Returns a function to be used as a callback for String.prototype.replace to replace
- * template identifiers
- *
- * @param {Obect} values
- * Object containing values that shall be used to replace known identifiers
- * @param {number} values.RepresentationID
- * Value of the Representation@id attribute
- * @param {number} values.Number
- * Number of the corresponding segment
- * @param {number} values.Bandwidth
- * Value of the Representation@bandwidth attribute.
- * @param {number} values.Time
- * Timestamp value of the corresponding segment
- * @return {replaceCallback}
- * Callback to be used with String.prototype.replace to replace identifiers
- */
-
- var identifierReplacement = function identifierReplacement(values) {
- return function (match, identifier, format, width) {
- if (match === '$$') {
- // escape sequence
- return '$';
- }
-
- if (typeof values[identifier] === 'undefined') {
- return match;
- }
-
- var value = '' + values[identifier];
-
- if (identifier === 'RepresentationID') {
- // Format tag shall not be present with RepresentationID
- return value;
- }
-
- if (!format) {
- width = 1;
- } else {
- width = parseInt(width, 10);
- }
-
- if (value.length >= width) {
- return value;
- }
-
- return "" + new Array(width - value.length + 1).join('0') + value;
- };
- };
- /**
- * Constructs a segment url from a template string
- *
- * @param {string} url
- * Template string to construct url from
- * @param {Obect} values
- * Object containing values that shall be used to replace known identifiers
- * @param {number} values.RepresentationID
- * Value of the Representation@id attribute
- * @param {number} values.Number
- * Number of the corresponding segment
- * @param {number} values.Bandwidth
- * Value of the Representation@bandwidth attribute.
- * @param {number} values.Time
- * Timestamp value of the corresponding segment
- * @return {string}
- * Segment url with identifiers replaced
- */
-
-
- var constructTemplateUrl = function constructTemplateUrl(url, values) {
- return url.replace(identifierPattern, identifierReplacement(values));
- };
- /**
- * Generates a list of objects containing timing and duration information about each
- * segment needed to generate segment uris and the complete segment object
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object[]|undefined} segmentTimeline
- * List of objects representing the attributes of each S element contained within
- * the SegmentTimeline element
- * @return {{number: number, duration: number, time: number, timeline: number}[]}
- * List of Objects with segment timing and duration info
- */
-
-
- var parseTemplateInfo = function parseTemplateInfo(attributes, segmentTimeline) {
- if (!attributes.duration && !segmentTimeline) {
- // if neither @duration or SegmentTimeline are present, then there shall be exactly
- // one media segment
- return [{
- number: attributes.startNumber || 1,
- duration: attributes.sourceDuration,
- time: 0,
- timeline: attributes.periodIndex
- }];
- }
-
- if (attributes.duration) {
- return parseByDuration(attributes);
- }
-
- return parseByTimeline(attributes, segmentTimeline);
- };
- /**
- * Generates a list of segments using information provided by the SegmentTemplate element
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object[]|undefined} segmentTimeline
- * List of objects representing the attributes of each S element contained within
- * the SegmentTimeline element
- * @return {Object[]}
- * List of segment objects
- */
-
-
- var segmentsFromTemplate = function segmentsFromTemplate(attributes, segmentTimeline) {
- var templateValues = {
- RepresentationID: attributes.id,
- Bandwidth: attributes.bandwidth || 0
- };
- var _attributes$initializ = attributes.initialization,
- initialization = _attributes$initializ === void 0 ? {
- sourceURL: '',
- range: ''
- } : _attributes$initializ;
- var mapSegment = urlTypeToSegment({
- baseUrl: attributes.baseUrl,
- source: constructTemplateUrl(initialization.sourceURL, templateValues),
- range: initialization.range
- });
- var segments = parseTemplateInfo(attributes, segmentTimeline);
- return segments.map(function (segment) {
- templateValues.Number = segment.number;
- templateValues.Time = segment.time;
- var uri = constructTemplateUrl(attributes.media || '', templateValues);
- var map = {
- uri: uri,
- timeline: segment.timeline,
- duration: segment.duration,
- resolvedUri: resolveUrl$1(attributes.baseUrl || '', uri),
- map: mapSegment,
- number: segment.number
- };
-
- if (attributes.presentationTimeOffset) {
- map.presentationTimeOffset = attributes.presentationTimeOffset;
- }
-
- return map;
- });
- };
- /**
- * Converts a (of type URLType from the DASH spec 5.3.9.2 Table 14)
- * to an object that matches the output of a segment in videojs/mpd-parser
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object} segmentUrl
- * node to translate into a segment object
- * @return {Object} translated segment object
- */
-
-
- var SegmentURLToSegmentObject = function SegmentURLToSegmentObject(attributes, segmentUrl) {
- var baseUrl = attributes.baseUrl,
- _attributes$initializ = attributes.initialization,
- initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ;
- var initSegment = urlTypeToSegment({
- baseUrl: baseUrl,
- source: initialization.sourceURL,
- range: initialization.range
- });
- var segment = urlTypeToSegment({
- baseUrl: baseUrl,
- source: segmentUrl.media,
- range: segmentUrl.mediaRange
- });
- segment.map = initSegment;
- return segment;
- };
- /**
- * Generates a list of segments using information provided by the SegmentList element
- * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of nodes. Each
- * node should be translated into segment.
- *
- * @param {Object} attributes
- * Object containing all inherited attributes from parent elements with attribute
- * names as keys
- * @param {Object[]|undefined} segmentTimeline
- * List of objects representing the attributes of each S element contained within
- * the SegmentTimeline element
- * @return {Object.} list of segments
- */
-
-
- var segmentsFromList = function segmentsFromList(attributes, segmentTimeline) {
- var duration = attributes.duration,
- _attributes$segmentUr = attributes.segmentUrls,
- segmentUrls = _attributes$segmentUr === void 0 ? [] : _attributes$segmentUr; // Per spec (5.3.9.2.1) no way to determine segment duration OR
- // if both SegmentTimeline and @duration are defined, it is outside of spec.
-
- if (!duration && !segmentTimeline || duration && segmentTimeline) {
- throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
- }
-
- var segmentUrlMap = segmentUrls.map(function (segmentUrlObject) {
- return SegmentURLToSegmentObject(attributes, segmentUrlObject);
- });
- var segmentTimeInfo;
-
- if (duration) {
- segmentTimeInfo = parseByDuration(attributes);
- }
-
- if (segmentTimeline) {
- segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
- }
-
- var segments = segmentTimeInfo.map(function (segmentTime, index) {
- if (segmentUrlMap[index]) {
- var segment = segmentUrlMap[index];
- segment.timeline = segmentTime.timeline;
- segment.duration = segmentTime.duration;
- segment.number = segmentTime.number;
- return segment;
- } // Since we're mapping we should get rid of any blank segments (in case
- // the given SegmentTimeline is handling for more elements than we have
- // SegmentURLs for).
-
- }).filter(function (segment) {
- return segment;
- });
- return segments;
- };
-
- var generateSegments = function generateSegments(_ref) {
- var attributes = _ref.attributes,
- segmentInfo = _ref.segmentInfo;
- var segmentAttributes;
- var segmentsFn;
-
- if (segmentInfo.template) {
- segmentsFn = segmentsFromTemplate;
- segmentAttributes = merge(attributes, segmentInfo.template);
-
- if (segmentInfo.template.presentationTimeOffset) {
- segmentAttributes.presentationTimeOffset = segmentInfo.template.presentationTimeOffset / segmentInfo.template.timescale;
- }
- } else if (segmentInfo.base) {
- segmentsFn = segmentsFromBase;
- segmentAttributes = merge(attributes, segmentInfo.base);
- } else if (segmentInfo.list) {
- segmentsFn = segmentsFromList;
- segmentAttributes = merge(attributes, segmentInfo.list);
- }
-
- var segmentsInfo = {
- attributes: attributes
- };
-
- if (!segmentsFn) {
- return segmentsInfo;
- }
-
- var segments = segmentsFn(segmentAttributes, segmentInfo.timeline); // The @duration attribute will be used to determin the playlist's targetDuration which
- // must be in seconds. Since we've generated the segment list, we no longer need
- // @duration to be in @timescale units, so we can convert it here.
-
- if (segmentAttributes.duration) {
- var _segmentAttributes = segmentAttributes,
- duration = _segmentAttributes.duration,
- _segmentAttributes$ti = _segmentAttributes.timescale,
- timescale = _segmentAttributes$ti === void 0 ? 1 : _segmentAttributes$ti;
- segmentAttributes.duration = duration / timescale;
- } else if (segments.length) {
- // if there is no @duration attribute, use the largest segment duration as
- // as target duration
- segmentAttributes.duration = segments.reduce(function (max, segment) {
- return Math.max(max, Math.ceil(segment.duration));
- }, 0);
- } else {
- segmentAttributes.duration = 0;
- }
-
- segmentsInfo.attributes = segmentAttributes;
- segmentsInfo.segments = segments; // This is a sidx box without actual segment information
-
- if (segmentInfo.base && segmentAttributes.indexRange) {
- segmentsInfo.sidx = segments[0];
- segmentsInfo.segments = [];
- }
-
- return segmentsInfo;
- };
-
- var toPlaylists = function toPlaylists(representations) {
- return representations.map(generateSegments);
- };
-
- var findChildren = function findChildren(element, name) {
- return from(element.childNodes).filter(function (_ref) {
- var tagName = _ref.tagName;
- return tagName === name;
- });
- };
-
- var getContent = function getContent(element) {
- return element.textContent.trim();
- };
-
- var parseDuration = function parseDuration(str) {
- var SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
- var SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
- var SECONDS_IN_DAY = 24 * 60 * 60;
- var SECONDS_IN_HOUR = 60 * 60;
- var SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S
-
- var durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
- var match = durationRegex.exec(str);
-
- if (!match) {
- return 0;
- }
-
- var _match$slice = match.slice(1),
- year = _match$slice[0],
- month = _match$slice[1],
- day = _match$slice[2],
- hour = _match$slice[3],
- minute = _match$slice[4],
- second = _match$slice[5];
-
- return parseFloat(year || 0) * SECONDS_IN_YEAR + parseFloat(month || 0) * SECONDS_IN_MONTH + parseFloat(day || 0) * SECONDS_IN_DAY + parseFloat(hour || 0) * SECONDS_IN_HOUR + parseFloat(minute || 0) * SECONDS_IN_MIN + parseFloat(second || 0);
- };
-
- var parseDate = function parseDate(str) {
- // Date format without timezone according to ISO 8601
- // YYY-MM-DDThh:mm:ss.ssssss
- var dateRegex = /^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/; // If the date string does not specifiy a timezone, we must specifiy UTC. This is
- // expressed by ending with 'Z'
-
- if (dateRegex.test(str)) {
- str += 'Z';
- }
-
- return Date.parse(str);
- };
-
- var parsers = {
- /**
- * Specifies the duration of the entire Media Presentation. Format is a duration string
- * as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- mediaPresentationDuration: function mediaPresentationDuration(value) {
- return parseDuration(value);
- },
-
- /**
- * Specifies the Segment availability start time for all Segments referred to in this
- * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
- * time. Format is a date string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The date as seconds from unix epoch
- */
- availabilityStartTime: function availabilityStartTime(value) {
- return parseDate(value) / 1000;
- },
-
- /**
- * Specifies the smallest period between potential changes to the MPD. Format is a
- * duration string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- minimumUpdatePeriod: function minimumUpdatePeriod(value) {
- return parseDuration(value);
- },
-
- /**
- * Specifies the suggested presentation delay. Format is a
- * duration string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- suggestedPresentationDelay: function suggestedPresentationDelay(value) {
- return parseDuration(value);
- },
-
- /**
- * specifices the type of mpd. Can be either "static" or "dynamic"
- *
- * @param {string} value
- * value of attribute as a string
- *
- * @return {string}
- * The type as a string
- */
- type: function type(value) {
- return value;
- },
-
- /**
- * Specifies the duration of the smallest time shifting buffer for any Representation
- * in the MPD. Format is a duration string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- timeShiftBufferDepth: function timeShiftBufferDepth(value) {
- return parseDuration(value);
- },
-
- /**
- * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
- * Format is a duration string as specified in ISO 8601
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The duration in seconds
- */
- start: function start(value) {
- return parseDuration(value);
- },
-
- /**
- * Specifies the width of the visual presentation
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed width
- */
- width: function width(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the height of the visual presentation
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed height
- */
- height: function height(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the bitrate of the representation
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed bandwidth
- */
- bandwidth: function bandwidth(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the number of the first Media Segment in this Representation in the Period
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed number
- */
- startNumber: function startNumber(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the timescale in units per seconds
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed timescale
- */
- timescale: function timescale(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the presentationTimeOffset.
- *
- * @param {string} value
- * value of the attribute as a string
- *
- * @return {number}
- * The parsed presentationTimeOffset
- */
- presentationTimeOffset: function presentationTimeOffset(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the constant approximate Segment duration
- * NOTE: The element also contains an @duration attribute. This duration
- * specifies the duration of the Period. This attribute is currently not
- * supported by the rest of the parser, however we still check for it to prevent
- * errors.
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed duration
- */
- duration: function duration(value) {
- var parsedValue = parseInt(value, 10);
-
- if (isNaN(parsedValue)) {
- return parseDuration(value);
- }
-
- return parsedValue;
- },
-
- /**
- * Specifies the Segment duration, in units of the value of the @timescale.
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed duration
- */
- d: function d(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the MPD start time, in @timescale units, the first Segment in the series
- * starts relative to the beginning of the Period
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed time
- */
- t: function t(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Specifies the repeat count of the number of following contiguous Segments with the
- * same duration expressed by the value of @d
- *
- * @param {string} value
- * value of attribute as a string
- * @return {number}
- * The parsed number
- */
- r: function r(value) {
- return parseInt(value, 10);
- },
-
- /**
- * Default parser for all other attributes. Acts as a no-op and just returns the value
- * as a string
- *
- * @param {string} value
- * value of attribute as a string
- * @return {string}
- * Unparsed value
- */
- DEFAULT: function DEFAULT(value) {
- return value;
- }
- };
- /**
- * Gets all the attributes and values of the provided node, parses attributes with known
- * types, and returns an object with attribute names mapped to values.
- *
- * @param {Node} el
- * The node to parse attributes from
- * @return {Object}
- * Object with all attributes of el parsed
- */
-
- var parseAttributes = function parseAttributes(el) {
- if (!(el && el.attributes)) {
- return {};
- }
-
- return from(el.attributes).reduce(function (a, e) {
- var parseFn = parsers[e.name] || parsers.DEFAULT;
- a[e.name] = parseFn(e.value);
- return a;
- }, {});
- };
-
- var keySystemsMap = {
- 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',
- 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',
- 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',
- 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime'
- };
- /**
- * Builds a list of urls that is the product of the reference urls and BaseURL values
- *
- * @param {string[]} referenceUrls
- * List of reference urls to resolve to
- * @param {Node[]} baseUrlElements
- * List of BaseURL nodes from the mpd
- * @return {string[]}
- * List of resolved urls
- */
-
- var buildBaseUrls = function buildBaseUrls(referenceUrls, baseUrlElements) {
- if (!baseUrlElements.length) {
- return referenceUrls;
- }
-
- return flatten(referenceUrls.map(function (reference) {
- return baseUrlElements.map(function (baseUrlElement) {
- return resolveUrl$1(reference, getContent(baseUrlElement));
- });
- }));
- };
- /**
- * Contains all Segment information for its containing AdaptationSet
- *
- * @typedef {Object} SegmentInformation
- * @property {Object|undefined} template
- * Contains the attributes for the SegmentTemplate node
- * @property {Object[]|undefined} timeline
- * Contains a list of atrributes for each S node within the SegmentTimeline node
- * @property {Object|undefined} list
- * Contains the attributes for the SegmentList node
- * @property {Object|undefined} base
- * Contains the attributes for the SegmentBase node
- */
-
- /**
- * Returns all available Segment information contained within the AdaptationSet node
- *
- * @param {Node} adaptationSet
- * The AdaptationSet node to get Segment information from
- * @return {SegmentInformation}
- * The Segment information contained within the provided AdaptationSet
- */
-
-
- var getSegmentInformation = function getSegmentInformation(adaptationSet) {
- var segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];
- var segmentList = findChildren(adaptationSet, 'SegmentList')[0];
- var segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(function (s) {
- return merge({
- tag: 'SegmentURL'
- }, parseAttributes(s));
- });
- var segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];
- var segmentTimelineParentNode = segmentList || segmentTemplate;
- var segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];
- var segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
- var segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both
- // @initialization and an node. @initialization can be templated,
- // while the node can have a url and range specified. If the has
- // both @initialization and an subelement we opt to override with
- // the node, as this interaction is not defined in the spec.
-
- var template = segmentTemplate && parseAttributes(segmentTemplate);
-
- if (template && segmentInitialization) {
- template.initialization = segmentInitialization && parseAttributes(segmentInitialization);
- } else if (template && template.initialization) {
- // If it is @initialization we convert it to an object since this is the format that
- // later functions will rely on for the initialization segment. This is only valid
- // for
- template.initialization = {
- sourceURL: template.initialization
- };
- }
-
- var segmentInfo = {
- template: template,
- timeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(function (s) {
- return parseAttributes(s);
- }),
- list: segmentList && merge(parseAttributes(segmentList), {
- segmentUrls: segmentUrls,
- initialization: parseAttributes(segmentInitialization)
- }),
- base: segmentBase && merge(parseAttributes(segmentBase), {
- initialization: parseAttributes(segmentInitialization)
- })
- };
- Object.keys(segmentInfo).forEach(function (key) {
- if (!segmentInfo[key]) {
- delete segmentInfo[key];
- }
- });
- return segmentInfo;
- };
- /**
- * Contains Segment information and attributes needed to construct a Playlist object
- * from a Representation
- *
- * @typedef {Object} RepresentationInformation
- * @property {SegmentInformation} segmentInfo
- * Segment information for this Representation
- * @property {Object} attributes
- * Inherited attributes for this Representation
- */
-
- /**
- * Maps a Representation node to an object containing Segment information and attributes
- *
- * @name inheritBaseUrlsCallback
- * @function
- * @param {Node} representation
- * Representation node from the mpd
- * @return {RepresentationInformation}
- * Representation information needed to construct a Playlist object
- */
-
- /**
- * Returns a callback for Array.prototype.map for mapping Representation nodes to
- * Segment information and attributes using inherited BaseURL nodes.
- *
- * @param {Object} adaptationSetAttributes
- * Contains attributes inherited by the AdaptationSet
- * @param {string[]} adaptationSetBaseUrls
- * Contains list of resolved base urls inherited by the AdaptationSet
- * @param {SegmentInformation} adaptationSetSegmentInfo
- * Contains Segment information for the AdaptationSet
- * @return {inheritBaseUrlsCallback}
- * Callback map function
- */
-
-
- var inheritBaseUrls = function inheritBaseUrls(adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) {
- return function (representation) {
- var repBaseUrlElements = findChildren(representation, 'BaseURL');
- var repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
- var attributes = merge(adaptationSetAttributes, parseAttributes(representation));
- var representationSegmentInfo = getSegmentInformation(representation);
- return repBaseUrls.map(function (baseUrl) {
- return {
- segmentInfo: merge(adaptationSetSegmentInfo, representationSegmentInfo),
- attributes: merge(attributes, {
- baseUrl: baseUrl
- })
- };
- });
- };
- };
- /**
- * Tranforms a series of content protection nodes to
- * an object containing pssh data by key system
- *
- * @param {Node[]} contentProtectionNodes
- * Content protection nodes
- * @return {Object}
- * Object containing pssh data by key system
- */
-
-
- var generateKeySystemInformation = function generateKeySystemInformation(contentProtectionNodes) {
- return contentProtectionNodes.reduce(function (acc, node) {
- var attributes = parseAttributes(node);
- var keySystem = keySystemsMap[attributes.schemeIdUri];
-
- if (keySystem) {
- acc[keySystem] = {
- attributes: attributes
- };
- var psshNode = findChildren(node, 'cenc:pssh')[0];
-
- if (psshNode) {
- var pssh = getContent(psshNode);
- var psshBuffer = pssh && decodeB64ToUint8Array(pssh);
- acc[keySystem].pssh = psshBuffer;
- }
- }
-
- return acc;
- }, {});
- }; // defined in ANSI_SCTE 214-1 2016
-
-
- var parseCaptionServiceMetadata = function parseCaptionServiceMetadata(service) {
- // 608 captions
- if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {
- var values = service.value.split(';');
- return values.map(function (value) {
- var channel;
- var language; // default language to value
-
- language = value;
-
- if (/^CC\d=/.test(value)) {
- var _value$split = value.split('=');
-
- channel = _value$split[0];
- language = _value$split[1];
- } else if (/^CC\d$/.test(value)) {
- channel = value;
- }
-
- return {
- channel: channel,
- language: language
- };
- });
- } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {
- var _values = service.value.split(';');
-
- return _values.map(function (value) {
- var flags = {
- // service or channel number 1-63
- 'channel': undefined,
- // language is a 3ALPHA per ISO 639.2/B
- // field is required
- 'language': undefined,
- // BIT 1/0 or ?
- // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
- 'aspectRatio': 1,
- // BIT 1/0
- // easy reader flag indicated the text is tailed to the needs of beginning readers
- // default 0, or off
- 'easyReader': 0,
- // BIT 1/0
- // If 3d metadata is present (CEA-708.1) then 1
- // default 0
- '3D': 0
- };
-
- if (/=/.test(value)) {
- var _value$split2 = value.split('='),
- channel = _value$split2[0],
- _value$split2$ = _value$split2[1],
- opts = _value$split2$ === void 0 ? '' : _value$split2$;
-
- flags.channel = channel;
- flags.language = value;
- opts.split(',').forEach(function (opt) {
- var _opt$split = opt.split(':'),
- name = _opt$split[0],
- val = _opt$split[1];
-
- if (name === 'lang') {
- flags.language = val; // er for easyReadery
- } else if (name === 'er') {
- flags.easyReader = Number(val); // war for wide aspect ratio
- } else if (name === 'war') {
- flags.aspectRatio = Number(val);
- } else if (name === '3D') {
- flags['3D'] = Number(val);
- }
- });
- } else {
- flags.language = value;
- }
-
- if (flags.channel) {
- flags.channel = 'SERVICE' + flags.channel;
- }
-
- return flags;
- });
- }
- };
- /**
- * Maps an AdaptationSet node to a list of Representation information objects
- *
- * @name toRepresentationsCallback
- * @function
- * @param {Node} adaptationSet
- * AdaptationSet node from the mpd
- * @return {RepresentationInformation[]}
- * List of objects containing Representaion information
- */
-
- /**
- * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of
- * Representation information objects
- *
- * @param {Object} periodAttributes
- * Contains attributes inherited by the Period
- * @param {string[]} periodBaseUrls
- * Contains list of resolved base urls inherited by the Period
- * @param {string[]} periodSegmentInfo
- * Contains Segment Information at the period level
- * @return {toRepresentationsCallback}
- * Callback map function
- */
-
-
- var toRepresentations = function toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo) {
- return function (adaptationSet) {
- var adaptationSetAttributes = parseAttributes(adaptationSet);
- var adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));
- var role = findChildren(adaptationSet, 'Role')[0];
- var roleAttributes = {
- role: parseAttributes(role)
- };
- var attrs = merge(periodAttributes, adaptationSetAttributes, roleAttributes);
- var accessibility = findChildren(adaptationSet, 'Accessibility')[0];
- var captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));
-
- if (captionServices) {
- attrs = merge(attrs, {
- captionServices: captionServices
- });
- }
-
- var label = findChildren(adaptationSet, 'Label')[0];
-
- if (label && label.childNodes.length) {
- var labelVal = label.childNodes[0].nodeValue.trim();
- attrs = merge(attrs, {
- label: labelVal
- });
- }
-
- var contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));
-
- if (Object.keys(contentProtection).length) {
- attrs = merge(attrs, {
- contentProtection: contentProtection
- });
- }
-
- var segmentInfo = getSegmentInformation(adaptationSet);
- var representations = findChildren(adaptationSet, 'Representation');
- var adaptationSetSegmentInfo = merge(periodSegmentInfo, segmentInfo);
- return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
- };
- };
- /**
- * Maps an Period node to a list of Representation inforamtion objects for all
- * AdaptationSet nodes contained within the Period
- *
- * @name toAdaptationSetsCallback
- * @function
- * @param {Node} period
- * Period node from the mpd
- * @param {number} periodIndex
- * Index of the Period within the mpd
- * @return {RepresentationInformation[]}
- * List of objects containing Representaion information
- */
-
- /**
- * Returns a callback for Array.prototype.map for mapping Period nodes to a list of
- * Representation information objects
- *
- * @param {Object} mpdAttributes
- * Contains attributes inherited by the mpd
- * @param {string[]} mpdBaseUrls
- * Contains list of resolved base urls inherited by the mpd
- * @return {toAdaptationSetsCallback}
- * Callback map function
- */
-
-
- var toAdaptationSets = function toAdaptationSets(mpdAttributes, mpdBaseUrls) {
- return function (period, index) {
- var periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period, 'BaseURL'));
- var periodAtt = parseAttributes(period);
- var parsedPeriodId = parseInt(periodAtt.id, 10); // fallback to mapping index if Period@id is not a number
-
- var periodIndex = window__default['default'].isNaN(parsedPeriodId) ? index : parsedPeriodId;
- var periodAttributes = merge(mpdAttributes, {
- periodIndex: periodIndex
- });
- var adaptationSets = findChildren(period, 'AdaptationSet');
- var periodSegmentInfo = getSegmentInformation(period);
- return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
- };
- };
- /**
- * Traverses the mpd xml tree to generate a list of Representation information objects
- * that have inherited attributes from parent nodes
- *
- * @param {Node} mpd
- * The root node of the mpd
- * @param {Object} options
- * Available options for inheritAttributes
- * @param {string} options.manifestUri
- * The uri source of the mpd
- * @param {number} options.NOW
- * Current time per DASH IOP. Default is current time in ms since epoch
- * @param {number} options.clientOffset
- * Client time difference from NOW (in milliseconds)
- * @return {RepresentationInformation[]}
- * List of objects containing Representation information
- */
-
-
- var inheritAttributes = function inheritAttributes(mpd, options) {
- if (options === void 0) {
- options = {};
- }
-
- var _options = options,
- _options$manifestUri = _options.manifestUri,
- manifestUri = _options$manifestUri === void 0 ? '' : _options$manifestUri,
- _options$NOW = _options.NOW,
- NOW = _options$NOW === void 0 ? Date.now() : _options$NOW,
- _options$clientOffset = _options.clientOffset,
- clientOffset = _options$clientOffset === void 0 ? 0 : _options$clientOffset;
- var periods = findChildren(mpd, 'Period');
-
- if (!periods.length) {
- throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
- }
-
- var locations = findChildren(mpd, 'Location');
- var mpdAttributes = parseAttributes(mpd);
- var mpdBaseUrls = buildBaseUrls([manifestUri], findChildren(mpd, 'BaseURL'));
- mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
- mpdAttributes.NOW = NOW;
- mpdAttributes.clientOffset = clientOffset;
-
- if (locations.length) {
- mpdAttributes.locations = locations.map(getContent);
- }
-
- return {
- locations: mpdAttributes.locations,
- representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls)))
- };
- };
-
- var stringToMpdXml = function stringToMpdXml(manifestString) {
- if (manifestString === '') {
- throw new Error(errors.DASH_EMPTY_MANIFEST);
- }
-
- var parser = new xmldom.DOMParser();
- var xml;
- var mpd;
-
- try {
- xml = parser.parseFromString(manifestString, 'application/xml');
- mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;
- } catch (e) {// ie 11 throwsw on invalid xml
- }
-
- if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {
- throw new Error(errors.DASH_INVALID_XML);
- }
-
- return mpd;
- };
- /**
- * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
- *
- * @param {string} mpd
- * XML string of the MPD manifest
- * @return {Object|null}
- * Attributes of UTCTiming node specified in the manifest. Null if none found
- */
-
-
- var parseUTCTimingScheme = function parseUTCTimingScheme(mpd) {
- var UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];
-
- if (!UTCTimingNode) {
- return null;
- }
-
- var attributes = parseAttributes(UTCTimingNode);
-
- switch (attributes.schemeIdUri) {
- case 'urn:mpeg:dash:utc:http-head:2014':
- case 'urn:mpeg:dash:utc:http-head:2012':
- attributes.method = 'HEAD';
- break;
-
- case 'urn:mpeg:dash:utc:http-xsdate:2014':
- case 'urn:mpeg:dash:utc:http-iso:2014':
- case 'urn:mpeg:dash:utc:http-xsdate:2012':
- case 'urn:mpeg:dash:utc:http-iso:2012':
- attributes.method = 'GET';
- break;
-
- case 'urn:mpeg:dash:utc:direct:2014':
- case 'urn:mpeg:dash:utc:direct:2012':
- attributes.method = 'DIRECT';
- attributes.value = Date.parse(attributes.value);
- break;
-
- case 'urn:mpeg:dash:utc:http-ntp:2014':
- case 'urn:mpeg:dash:utc:ntp:2014':
- case 'urn:mpeg:dash:utc:sntp:2014':
- default:
- throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
- }
-
- return attributes;
- };
-
- var parse = function parse(manifestString, options) {
- if (options === void 0) {
- options = {};
- }
-
- var parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
- var playlists = toPlaylists(parsedManifestInfo.representationInfo);
- return toM3u8(playlists, parsedManifestInfo.locations, options.sidxMapping);
- };
- /**
- * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
- *
- * @param {string} manifestString
- * XML string of the MPD manifest
- * @return {Object|null}
- * Attributes of UTCTiming node specified in the manifest. Null if none found
- */
-
-
- var parseUTCTiming = function parseUTCTiming(manifestString) {
- return parseUTCTimingScheme(stringToMpdXml(manifestString));
- };
-
- var MAX_UINT32 = Math.pow(2, 32);
-
- var parseSidx = function parseSidx(data) {
- var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- references: [],
- referenceId: view.getUint32(4),
- timescale: view.getUint32(8)
- },
- i = 12;
-
- if (result.version === 0) {
- result.earliestPresentationTime = view.getUint32(i);
- result.firstOffset = view.getUint32(i + 4);
- i += 8;
- } else {
- // read 64 bits
- result.earliestPresentationTime = view.getUint32(i) * MAX_UINT32 + view.getUint32(i + 4);
- result.firstOffset = view.getUint32(i + 8) * MAX_UINT32 + view.getUint32(i + 12);
- i += 16;
- }
-
- i += 2; // reserved
-
- var referenceCount = view.getUint16(i);
- i += 2; // start of references
-
- for (; referenceCount > 0; i += 12, referenceCount--) {
- result.references.push({
- referenceType: (data[i] & 0x80) >>> 7,
- referencedSize: view.getUint32(i) & 0x7FFFFFFF,
- subsegmentDuration: view.getUint32(i + 4),
- startsWithSap: !!(data[i + 8] & 0x80),
- sapType: (data[i + 8] & 0x70) >>> 4,
- sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
- });
- }
-
- return result;
- };
-
- var parseSidx_1 = parseSidx;
-
- // we used to do this with log2 but BigInt does not support builtin math
- // Math.ceil(log2(x));
-
-
- var countBits = function countBits(x) {
- return x.toString(2).length;
- }; // count the number of whole bytes it would take to represent a number
-
- var countBytes = function countBytes(x) {
- return Math.ceil(countBits(x) / 8);
- };
- var isTypedArray = function isTypedArray(obj) {
- return ArrayBuffer.isView(obj);
- };
- var toUint8 = function toUint8(bytes) {
- if (bytes instanceof Uint8Array) {
- return bytes;
- }
-
- if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
- // any non-number or NaN leads to empty uint8array
- // eslint-disable-next-line
- if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
- bytes = 0;
- } else {
- bytes = [bytes];
- }
- }
-
- return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
- };
- var BigInt = window__default['default'].BigInt || Number;
- var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
- var bytesToNumber = function bytesToNumber(bytes, _temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- _ref$signed = _ref.signed,
- signed = _ref$signed === void 0 ? false : _ref$signed,
- _ref$le = _ref.le,
- le = _ref$le === void 0 ? false : _ref$le;
-
- bytes = toUint8(bytes);
- var fn = le ? 'reduce' : 'reduceRight';
- var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
- var number = obj.call(bytes, function (total, byte, i) {
- var exponent = le ? i : Math.abs(i + 1 - bytes.length);
- return total + BigInt(byte) * BYTE_TABLE[exponent];
- }, BigInt(0));
-
- if (signed) {
- var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
- number = BigInt(number);
-
- if (number > max) {
- number -= max;
- number -= max;
- number -= BigInt(2);
- }
- }
-
- return Number(number);
- };
- var numberToBytes = function numberToBytes(number, _temp2) {
- var _ref2 = _temp2 === void 0 ? {} : _temp2,
- _ref2$le = _ref2.le,
- le = _ref2$le === void 0 ? false : _ref2$le; // eslint-disable-next-line
-
-
- if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
- number = 0;
- }
-
- number = BigInt(number);
- var byteCount = countBytes(number);
- var bytes = new Uint8Array(new ArrayBuffer(byteCount));
-
- for (var i = 0; i < byteCount; i++) {
- var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
- bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
-
- if (number < 0) {
- bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
- bytes[byteIndex] -= i === 0 ? 1 : 2;
- }
- }
-
- return bytes;
- };
- var stringToBytes = function stringToBytes(string, stringIsBytes) {
- if (typeof string !== 'string' && string && typeof string.toString === 'function') {
- string = string.toString();
- }
-
- if (typeof string !== 'string') {
- return new Uint8Array();
- } // If the string already is bytes, we don't have to do this
- // otherwise we do this so that we split multi length characters
- // into individual bytes
-
-
- if (!stringIsBytes) {
- string = unescape(encodeURIComponent(string));
- }
-
- var view = new Uint8Array(string.length);
-
- for (var i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view;
- };
- var concatTypedArrays = function concatTypedArrays() {
- for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
- buffers[_key] = arguments[_key];
- }
-
- buffers = buffers.filter(function (b) {
- return b && (b.byteLength || b.length) && typeof b !== 'string';
- });
-
- if (buffers.length <= 1) {
- // for 0 length we will return empty uint8
- // for 1 length we return the first uint8
- return toUint8(buffers[0]);
- }
-
- var totalLen = buffers.reduce(function (total, buf, i) {
- return total + (buf.byteLength || buf.length);
- }, 0);
- var tempBuffer = new Uint8Array(totalLen);
- var offset = 0;
- buffers.forEach(function (buf) {
- buf = toUint8(buf);
- tempBuffer.set(buf, offset);
- offset += buf.byteLength;
- });
- return tempBuffer;
- };
- /**
- * Check if the bytes "b" are contained within bytes "a".
- *
- * @param {Uint8Array|Array} a
- * Bytes to check in
- *
- * @param {Uint8Array|Array} b
- * Bytes to check for
- *
- * @param {Object} options
- * options
- *
- * @param {Array|Uint8Array} [offset=0]
- * offset to use when looking at bytes in a
- *
- * @param {Array|Uint8Array} [mask=[]]
- * mask to use on bytes before comparison.
- *
- * @return {boolean}
- * If all bytes in b are inside of a, taking into account
- * bit masks.
- */
-
- var bytesMatch = function bytesMatch(a, b, _temp3) {
- var _ref3 = _temp3 === void 0 ? {} : _temp3,
- _ref3$offset = _ref3.offset,
- offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
- _ref3$mask = _ref3.mask,
- mask = _ref3$mask === void 0 ? [] : _ref3$mask;
-
- a = toUint8(a);
- b = toUint8(b); // ie 11 does not support uint8 every
-
- var fn = b.every ? b.every : Array.prototype.every;
- return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
- fn.call(b, function (bByte, i) {
- var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
- return bByte === aByte;
- });
- };
-
- var ID3 = toUint8([0x49, 0x44, 0x33]);
- var getId3Size = function getId3Size(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = toUint8(bytes);
- var flags = bytes[offset + 5];
- var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
- var footerPresent = (flags & 16) >> 4;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
- };
- var getId3Offset = function getId3Offset(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = toUint8(bytes);
-
- if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
- offset: offset
- })) {
- return offset;
- }
-
- offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
- // have multiple ID3 tag sections even though
- // they should not.
-
- return getId3Offset(bytes, offset);
- };
-
- var normalizePath$1 = function normalizePath(path) {
- if (typeof path === 'string') {
- return stringToBytes(path);
- }
-
- if (typeof path === 'number') {
- return path;
- }
-
- return path;
- };
-
- var normalizePaths$1 = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath$1(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath$1(p);
- });
- };
- /**
- * find any number of boxes by name given a path to it in an iso bmff
- * such as mp4.
- *
- * @param {TypedArray} bytes
- * bytes for the iso bmff to search for boxes in
- *
- * @param {Uint8Array[]|string[]|string|Uint8Array} name
- * An array of paths or a single path representing the name
- * of boxes to search through in bytes. Paths may be
- * uint8 (character codes) or strings.
- *
- * @param {boolean} [complete=false]
- * Should we search only for complete boxes on the final path.
- * This is very useful when you do not want to get back partial boxes
- * in the case of streaming files.
- *
- * @return {Uint8Array[]}
- * An array of the end paths that we found.
- */
-
- var findBox = function findBox(bytes, paths, complete) {
- if (complete === void 0) {
- complete = false;
- }
-
- paths = normalizePaths$1(paths);
- bytes = toUint8(bytes);
- var results = [];
-
- if (!paths.length) {
- // short-circuit the search for empty paths
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
- var type = bytes.subarray(i + 4, i + 8); // invalid box format.
-
- if (size === 0) {
- break;
- }
-
- var end = i + size;
-
- if (end > bytes.length) {
- // this box is bigger than the number of bytes we have
- // and complete is set, we cannot find any more boxes.
- if (complete) {
- break;
- }
-
- end = bytes.length;
- }
-
- var data = bytes.subarray(i + 8, end);
-
- if (bytesMatch(type, paths[0])) {
- if (paths.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next box along the path
- results.push.apply(results, findBox(data, paths.slice(1), complete));
- }
- }
-
- i = end;
- } // we've finished searching all of bytes
-
-
- return results;
- };
-
- // https://matroska-org.github.io/libebml/specs.html
- // https://www.matroska.org/technical/elements.html
- // https://www.webmproject.org/docs/container/
-
- var EBML_TAGS = {
- EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
- DocType: toUint8([0x42, 0x82]),
- Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
- SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
- Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
- Track: toUint8([0xAE]),
- TrackNumber: toUint8([0xd7]),
- DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
- TrackEntry: toUint8([0xAE]),
- TrackType: toUint8([0x83]),
- FlagDefault: toUint8([0x88]),
- CodecID: toUint8([0x86]),
- CodecPrivate: toUint8([0x63, 0xA2]),
- VideoTrack: toUint8([0xe0]),
- AudioTrack: toUint8([0xe1]),
- // Not used yet, but will be used for live webm/mkv
- // see https://www.matroska.org/technical/basics.html#block-structure
- // see https://www.matroska.org/technical/basics.html#simpleblock-structure
- Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
- Timestamp: toUint8([0xE7]),
- TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
- BlockGroup: toUint8([0xA0]),
- BlockDuration: toUint8([0x9B]),
- Block: toUint8([0xA1]),
- SimpleBlock: toUint8([0xA3])
- };
- /**
- * This is a simple table to determine the length
- * of things in ebml. The length is one based (starts at 1,
- * rather than zero) and for every zero bit before a one bit
- * we add one to length. We also need this table because in some
- * case we have to xor all the length bits from another value.
- */
-
- var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
-
- var getLength = function getLength(byte) {
- var len = 1;
-
- for (var i = 0; i < LENGTH_TABLE.length; i++) {
- if (byte & LENGTH_TABLE[i]) {
- break;
- }
-
- len++;
- }
-
- return len;
- }; // length in ebml is stored in the first 4 to 8 bits
- // of the first byte. 4 for the id length and 8 for the
- // data size length. Length is measured by converting the number to binary
- // then 1 + the number of zeros before a 1 is encountered starting
- // from the left.
-
-
- var getvint = function getvint(bytes, offset, removeLength, signed) {
- if (removeLength === void 0) {
- removeLength = true;
- }
-
- if (signed === void 0) {
- signed = false;
- }
-
- var length = getLength(bytes[offset]);
- var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
- // as they will be modified below to remove the dataSizeLen bits and we do not
- // want to modify the original data. normally we could just call slice on
- // uint8array but ie 11 does not support that...
-
- if (removeLength) {
- valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
- valueBytes[0] ^= LENGTH_TABLE[length - 1];
- }
-
- return {
- length: length,
- value: bytesToNumber(valueBytes, {
- signed: signed
- }),
- bytes: valueBytes
- };
- };
-
- var normalizePath = function normalizePath(path) {
- if (typeof path === 'string') {
- return path.match(/.{1,2}/g).map(function (p) {
- return normalizePath(p);
- });
- }
-
- if (typeof path === 'number') {
- return numberToBytes(path);
- }
-
- return path;
- };
-
- var normalizePaths = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath(p);
- });
- };
-
- var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
- if (offset >= bytes.length) {
- return bytes.length;
- }
-
- var innerid = getvint(bytes, offset, false);
-
- if (bytesMatch(id.bytes, innerid.bytes)) {
- return offset;
- }
-
- var dataHeader = getvint(bytes, offset + innerid.length);
- return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
- };
- /**
- * Notes on the EBLM format.
- *
- * EBLM uses "vints" tags. Every vint tag contains
- * two parts
- *
- * 1. The length from the first byte. You get this by
- * converting the byte to binary and counting the zeros
- * before a 1. Then you add 1 to that. Examples
- * 00011111 = length 4 because there are 3 zeros before a 1.
- * 00100000 = length 3 because there are 2 zeros before a 1.
- * 00000011 = length 7 because there are 6 zeros before a 1.
- *
- * 2. The bits used for length are removed from the first byte
- * Then all the bytes are merged into a value. NOTE: this
- * is not the case for id ebml tags as there id includes
- * length bits.
- *
- */
-
-
- var findEbml = function findEbml(bytes, paths) {
- paths = normalizePaths(paths);
- bytes = toUint8(bytes);
- var results = [];
-
- if (!paths.length) {
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var id = getvint(bytes, i, false);
- var dataHeader = getvint(bytes, i + id.length);
- var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
-
- if (dataHeader.value === 0x7f) {
- dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
-
- if (dataHeader.value !== bytes.length) {
- dataHeader.value -= dataStart;
- }
- }
-
- var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
- var data = bytes.subarray(dataStart, dataEnd);
-
- if (bytesMatch(paths[0], id.bytes)) {
- if (paths.length === 1) {
- // this is the end of the paths and we've found the tag we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next tag inside of the data
- // of this one
- results = results.concat(findEbml(data, paths.slice(1)));
- }
- }
-
- var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
-
- i += totalLength;
- }
-
- return results;
- }; // see https://www.matroska.org/technical/basics.html#block-structure
-
- var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
- var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
- var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
- /**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- *
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
- var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
- var positions = [];
- var i = 1; // Find all `Emulation Prevention Bytes`
-
- while (i < bytes.length - 2) {
- if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
- positions.push(i + 2);
- i++;
- }
-
- i++;
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (positions.length === 0) {
- return bytes;
- } // Create a new array to hold the NAL unit data
-
-
- var newLength = bytes.length - positions.length;
- var newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === positions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- positions.shift();
- }
-
- newData[i] = bytes[sourceIndex];
- }
-
- return newData;
- };
- var findNal = function findNal(bytes, dataType, types, nalLimit) {
- if (nalLimit === void 0) {
- nalLimit = Infinity;
- }
-
- bytes = toUint8(bytes);
- types = [].concat(types);
- var i = 0;
- var nalStart;
- var nalsFound = 0; // keep searching until:
- // we reach the end of bytes
- // we reach the maximum number of nals they want to seach
- // NOTE: that we disregard nalLimit when we have found the start
- // of the nal we want so that we can find the end of the nal we want.
-
- while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
- var nalOffset = void 0;
-
- if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
- nalOffset = 4;
- } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
- nalOffset = 3;
- } // we are unsynced,
- // find the next nal unit
-
-
- if (!nalOffset) {
- i++;
- continue;
- }
-
- nalsFound++;
-
- if (nalStart) {
- return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
- }
-
- var nalType = void 0;
-
- if (dataType === 'h264') {
- nalType = bytes[i + nalOffset] & 0x1f;
- } else if (dataType === 'h265') {
- nalType = bytes[i + nalOffset] >> 1 & 0x3f;
- }
-
- if (types.indexOf(nalType) !== -1) {
- nalStart = i + nalOffset;
- } // nal header is 1 length for h264, and 2 for h265
-
-
- i += nalOffset + (dataType === 'h264' ? 1 : 2);
- }
-
- return bytes.subarray(0, 0);
- };
- var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h264', type, nalLimit);
- };
- var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h265', type, nalLimit);
- };
-
- var CONSTANTS = {
- // "webm" string literal in hex
- 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
- // "matroska" string literal in hex
- 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
- // "fLaC" string literal in hex
- 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
- // "OggS" string literal in hex
- 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
- // ac-3 sync byte, also works for ec-3 as that is simply a codec
- // of ac-3
- 'ac3': toUint8([0x0b, 0x77]),
- // "RIFF" string literal in hex used for wav and avi
- 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
- // "AVI" string literal in hex
- 'avi': toUint8([0x41, 0x56, 0x49]),
- // "WAVE" string literal in hex
- 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
- // "ftyp3g" string literal in hex
- '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
- // "ftyp" string literal in hex
- 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
- // "styp" string literal in hex
- 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
- // "ftyp" string literal in hex
- 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74])
- };
- var _isLikely = {
- aac: function aac(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, [0xFF, 0x10], {
- offset: offset,
- mask: [0xFF, 0x16]
- });
- },
- mp3: function mp3(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, [0xFF, 0x02], {
- offset: offset,
- mask: [0xFF, 0x06]
- });
- },
- webm: function webm(bytes) {
- var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
-
- return bytesMatch(docType, CONSTANTS.webm);
- },
- mkv: function mkv(bytes) {
- var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
-
- return bytesMatch(docType, CONSTANTS.matroska);
- },
- mp4: function mp4(bytes) {
- return !_isLikely['3gp'](bytes) && !_isLikely.mov(bytes) && (bytesMatch(bytes, CONSTANTS.mp4, {
- offset: 4
- }) || bytesMatch(bytes, CONSTANTS.fmp4, {
- offset: 4
- }));
- },
- mov: function mov(bytes) {
- return bytesMatch(bytes, CONSTANTS.mov, {
- offset: 4
- });
- },
- '3gp': function gp(bytes) {
- return bytesMatch(bytes, CONSTANTS['3gp'], {
- offset: 4
- });
- },
- ac3: function ac3(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, CONSTANTS.ac3, {
- offset: offset
- });
- },
- ts: function ts(bytes) {
- if (bytes.length < 189 && bytes.length >= 1) {
- return bytes[0] === 0x47;
- }
-
- var i = 0; // check the first 376 bytes for two matching sync bytes
-
- while (i + 188 < bytes.length && i < 188) {
- if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
- return true;
- }
-
- i += 1;
- }
-
- return false;
- },
- flac: function flac(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, CONSTANTS.flac, {
- offset: offset
- });
- },
- ogg: function ogg(bytes) {
- return bytesMatch(bytes, CONSTANTS.ogg);
- },
- avi: function avi(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
- offset: 8
- });
- },
- wav: function wav(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
- offset: 8
- });
- },
- 'h264': function h264(bytes) {
- // find seq_parameter_set_rbsp
- return findH264Nal(bytes, 7, 3).length;
- },
- 'h265': function h265(bytes) {
- // find video_parameter_set_rbsp or seq_parameter_set_rbsp
- return findH265Nal(bytes, [32, 33], 3).length;
- }
- }; // get all the isLikely functions
- // but make sure 'ts' is above h264 and h265
- // but below everything else as it is the least specific
-
- var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
- .filter(function (t) {
- return t !== 'ts' && t !== 'h264' && t !== 'h265';
- }) // add it back to the bottom
- .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
-
- isLikelyTypes.forEach(function (type) {
- var isLikelyFn = _isLikely[type];
-
- _isLikely[type] = function (bytes) {
- return isLikelyFn(toUint8(bytes));
- };
- }); // export after wrapping
-
- var isLikely = _isLikely; // A useful list of file signatures can be found here
- // https://en.wikipedia.org/wiki/List_of_file_signatures
-
- var detectContainerForBytes = function detectContainerForBytes(bytes) {
- bytes = toUint8(bytes);
-
- for (var i = 0; i < isLikelyTypes.length; i++) {
- var type = isLikelyTypes[i];
-
- if (isLikely[type](bytes)) {
- return type;
- }
- }
-
- return '';
- }; // fmp4 is not a container
-
- var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
- return findBox(bytes, ['moof']).length > 0;
- };
-
- // which will only happen if the request is complete.
-
- var callbackOnCompleted = function callbackOnCompleted(request, cb) {
- if (request.readyState === 4) {
- return cb();
- }
-
- return;
- };
-
- var containerRequest = function containerRequest(uri, xhr, cb) {
- var bytes = [];
- var id3Offset;
- var finished = false;
-
- var endRequestAndCallback = function endRequestAndCallback(err, req, type, _bytes) {
- req.abort();
- finished = true;
- return cb(err, req, type, _bytes);
- };
-
- var progressListener = function progressListener(error, request) {
- if (finished) {
- return;
- }
-
- if (error) {
- return endRequestAndCallback(error, request, '', bytes);
- } // grap the new part of content that was just downloaded
-
-
- var newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
-
- bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
- id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
- // or we need at least two bytes after an id3Offset
-
- if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- }
-
- var type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
- // to see the second sync byte, wait until we have enough data
- // before declaring it ts
-
- if (type === 'ts' && bytes.length < 188) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- } // this may be an unsynced ts segment
- // wait for 376 bytes before detecting no container
-
-
- if (!type && bytes.length < 376) {
- return callbackOnCompleted(request, function () {
- return endRequestAndCallback(error, request, '', bytes);
- });
- }
-
- return endRequestAndCallback(null, request, type, bytes);
- };
-
- var options = {
- uri: uri,
- beforeSend: function beforeSend(request) {
- // this forces the browser to pass the bytes to us unprocessed
- request.overrideMimeType('text/plain; charset=x-user-defined');
- request.addEventListener('progress', function (_ref) {
- _ref.total;
- _ref.loaded;
- return callbackWrapper(request, null, {
- statusCode: request.status
- }, progressListener);
- });
- }
- };
- var request = xhr(options, function (error, response) {
- return callbackWrapper(request, error, response, progressListener);
- });
- return request;
- };
-
- var EventTarget = videojs__default['default'].EventTarget,
- mergeOptions = videojs__default['default'].mergeOptions;
-
- var dashPlaylistUnchanged = function dashPlaylistUnchanged(a, b) {
- if (!isPlaylistUnchanged(a, b)) {
- return false;
- } // for dash the above check will often return true in scenarios where
- // the playlist actually has changed because mediaSequence isn't a
- // dash thing, and we often set it to 1. So if the playlists have the same amount
- // of segments we return true.
- // So for dash we need to make sure that the underlying segments are different.
- // if sidx changed then the playlists are different.
-
-
- if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
- return false;
- } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
- return false;
- } // one or the other does not have segments
- // there was a change.
-
-
- if (a.segments && !b.segments || !a.segments && b.segments) {
- return false;
- } // neither has segments nothing changed
-
-
- if (!a.segments && !b.segments) {
- return true;
- } // check segments themselves
-
-
- for (var i = 0; i < a.segments.length; i++) {
- var aSegment = a.segments[i];
- var bSegment = b.segments[i]; // if uris are different between segments there was a change
-
- if (aSegment.uri !== bSegment.uri) {
- return false;
- } // neither segment has a byterange, there will be no byterange change.
-
-
- if (!aSegment.byterange && !bSegment.byterange) {
- continue;
- }
-
- var aByterange = aSegment.byterange;
- var bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
-
- if (aByterange && !bByterange || !aByterange && bByterange) {
- return false;
- } // if both segments have byterange with different offsets, there was a change.
-
-
- if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
- return false;
- }
- } // if everything was the same with segments, this is the same playlist.
-
-
- return true;
- };
- /**
- * Parses the master XML string and updates playlist URI references.
- *
- * @param {Object} config
- * Object of arguments
- * @param {string} config.masterXml
- * The mpd XML
- * @param {string} config.srcUrl
- * The mpd URL
- * @param {Date} config.clientOffset
- * A time difference between server and client
- * @param {Object} config.sidxMapping
- * SIDX mappings for moof/mdat URIs and byte ranges
- * @return {Object}
- * The parsed mpd manifest object
- */
-
-
- var parseMasterXml = function parseMasterXml(_ref) {
- var masterXml = _ref.masterXml,
- srcUrl = _ref.srcUrl,
- clientOffset = _ref.clientOffset,
- sidxMapping = _ref.sidxMapping;
- var master = parse(masterXml, {
- manifestUri: srcUrl,
- clientOffset: clientOffset,
- sidxMapping: sidxMapping
- });
- addPropertiesToMaster(master, srcUrl);
- return master;
- };
- /**
- * Returns a new master manifest that is the result of merging an updated master manifest
- * into the original version.
- *
- * @param {Object} oldMaster
- * The old parsed mpd object
- * @param {Object} newMaster
- * The updated parsed mpd object
- * @return {Object}
- * A new object representing the original master manifest with the updated media
- * playlists merged in
- */
-
- var updateMaster = function updateMaster(oldMaster, newMaster, sidxMapping) {
- var noChanges = true;
- var update = mergeOptions(oldMaster, {
- // These are top level properties that can be updated
- duration: newMaster.duration,
- minimumUpdatePeriod: newMaster.minimumUpdatePeriod
- }); // First update the playlists in playlist list
-
- for (var i = 0; i < newMaster.playlists.length; i++) {
- var playlist = newMaster.playlists[i];
-
- if (playlist.sidx) {
- var sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
-
- if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
- addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
- }
- }
-
- var playlistUpdate = updateMaster$1(update, playlist, dashPlaylistUnchanged);
-
- if (playlistUpdate) {
- update = playlistUpdate;
- noChanges = false;
- }
- } // Then update media group playlists
-
-
- forEachMediaGroup(newMaster, function (properties, type, group, label) {
- if (properties.playlists && properties.playlists.length) {
- var id = properties.playlists[0].id;
-
- var _playlistUpdate = updateMaster$1(update, properties.playlists[0], dashPlaylistUnchanged);
-
- if (_playlistUpdate) {
- update = _playlistUpdate; // update the playlist reference within media groups
-
- update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
- noChanges = false;
- }
- }
- });
-
- if (newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
- noChanges = false;
- }
-
- if (noChanges) {
- return null;
- }
-
- return update;
- }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
- // If the SIDXs have maps, the two maps should match,
- // both `a` and `b` missing SIDXs is considered matching.
- // If `a` or `b` but not both have a map, they aren't matching.
-
- var equivalentSidx = function equivalentSidx(a, b) {
- var neitherMap = Boolean(!a.map && !b.map);
- var equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
- return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
- }; // exported for testing
-
-
- var compareSidxEntry = function compareSidxEntry(playlists, oldSidxMapping) {
- var newSidxMapping = {};
-
- for (var id in playlists) {
- var playlist = playlists[id];
- var currentSidxInfo = playlist.sidx;
-
- if (currentSidxInfo) {
- var key = generateSidxKey(currentSidxInfo);
-
- if (!oldSidxMapping[key]) {
- break;
- }
-
- var savedSidxInfo = oldSidxMapping[key].sidxInfo;
-
- if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
- newSidxMapping[key] = oldSidxMapping[key];
- }
- }
- }
-
- return newSidxMapping;
- };
- /**
- * A function that filters out changed items as they need to be requested separately.
- *
- * The method is exported for testing
- *
- * @param {Object} master the parsed mpd XML returned via mpd-parser
- * @param {Object} oldSidxMapping the SIDX to compare against
- */
-
- var filterChangedSidxMappings = function filterChangedSidxMappings(master, oldSidxMapping) {
- var videoSidx = compareSidxEntry(master.playlists, oldSidxMapping);
- var mediaGroupSidx = videoSidx;
- forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
- if (properties.playlists && properties.playlists.length) {
- var playlists = properties.playlists;
- mediaGroupSidx = mergeOptions(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
- }
- });
- return mediaGroupSidx;
- };
-
- var DashPlaylistLoader = /*#__PURE__*/function (_EventTarget) {
- inheritsLoose(DashPlaylistLoader, _EventTarget);
-
- // DashPlaylistLoader must accept either a src url or a playlist because subsequent
- // playlist loader setups from media groups will expect to be able to pass a playlist
- // (since there aren't external URLs to media playlists with DASH)
- function DashPlaylistLoader(srcUrlOrPlaylist, vhs, options, masterPlaylistLoader) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _EventTarget.call(this) || this;
- _this.masterPlaylistLoader_ = masterPlaylistLoader || assertThisInitialized(_this);
-
- if (!masterPlaylistLoader) {
- _this.isMaster_ = true;
- }
-
- var _options = options,
- _options$withCredenti = _options.withCredentials,
- withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
- _options$handleManife = _options.handleManifestRedirects,
- handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
- _this.vhs_ = vhs;
- _this.withCredentials = withCredentials;
- _this.handleManifestRedirects = handleManifestRedirects;
-
- if (!srcUrlOrPlaylist) {
- throw new Error('A non-empty playlist URL or object is required');
- } // event naming?
-
-
- _this.on('minimumUpdatePeriod', function () {
- _this.refreshXml_();
- }); // live playlist staleness timeout
-
-
- _this.on('mediaupdatetimeout', function () {
- _this.refreshMedia_(_this.media().id);
- });
-
- _this.state = 'HAVE_NOTHING';
- _this.loadedPlaylists_ = {};
- _this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
- // The masterPlaylistLoader will be created with a string
-
- if (_this.isMaster_) {
- _this.masterPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
- // once multi-period is refactored
-
- _this.masterPlaylistLoader_.sidxMapping_ = {};
- } else {
- _this.childPlaylist_ = srcUrlOrPlaylist;
- }
-
- return _this;
- }
-
- var _proto = DashPlaylistLoader.prototype;
-
- _proto.requestErrored_ = function requestErrored_(err, request, startingState) {
- // disposed
- if (!this.request) {
- return true;
- } // pending request is cleared
-
-
- this.request = null;
-
- if (err) {
- // use the provided error object or create one
- // based on the request/response
- this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
- status: request.status,
- message: 'DASH request error at URL: ' + request.uri,
- response: request.response,
- // MEDIA_ERR_NETWORK
- code: 2
- };
-
- if (startingState) {
- this.state = startingState;
- }
-
- this.trigger('error');
- return true;
- }
- }
- /**
- * Verify that the container of the sidx segment can be parsed
- * and if it can, get and parse that segment.
- */
- ;
-
- _proto.addSidxSegments_ = function addSidxSegments_(playlist, startingState, cb) {
- var _this2 = this;
-
- var sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
-
- if (!playlist.sidx || !sidxKey || this.masterPlaylistLoader_.sidxMapping_[sidxKey]) {
- // keep this function async
- this.mediaRequest_ = window__default['default'].setTimeout(function () {
- return cb(false);
- }, 0);
- return;
- } // resolve the segment URL relative to the playlist
-
-
- var uri = resolveManifestRedirect(this.handleManifestRedirects, playlist.sidx.resolvedUri);
-
- var fin = function fin(err, request) {
- if (_this2.requestErrored_(err, request, startingState)) {
- return;
- }
-
- var sidxMapping = _this2.masterPlaylistLoader_.sidxMapping_;
- var sidx;
-
- try {
- sidx = parseSidx_1(toUint8(request.response).subarray(8));
- } catch (e) {
- // sidx parsing failed.
- _this2.requestErrored_(e, request, startingState);
-
- return;
- }
-
- sidxMapping[sidxKey] = {
- sidxInfo: playlist.sidx,
- sidx: sidx
- };
- addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
- return cb(true);
- };
-
- this.request = containerRequest(uri, this.vhs_.xhr, function (err, request, container, bytes) {
- if (err) {
- return fin(err, request);
- }
-
- if (!container || container !== 'mp4') {
- return fin({
- status: request.status,
- message: "Unsupported " + (container || 'unknown') + " container type for sidx segment at URL: " + uri,
- // response is just bytes in this case
- // but we really don't want to return that.
- response: '',
- playlist: playlist,
- internal: true,
- blacklistDuration: Infinity,
- // MEDIA_ERR_NETWORK
- code: 2
- }, request);
- } // if we already downloaded the sidx bytes in the container request, use them
-
-
- var _playlist$sidx$bytera = playlist.sidx.byterange,
- offset = _playlist$sidx$bytera.offset,
- length = _playlist$sidx$bytera.length;
-
- if (bytes.length >= length + offset) {
- return fin(err, {
- response: bytes.subarray(offset, offset + length),
- status: request.status,
- uri: request.uri
- });
- } // otherwise request sidx bytes
-
-
- _this2.request = _this2.vhs_.xhr({
- uri: uri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders({
- byterange: playlist.sidx.byterange
- })
- }, fin);
- });
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.stopRequest();
- this.loadedPlaylists_ = {};
- window__default['default'].clearTimeout(this.minimumUpdatePeriodTimeout_);
- window__default['default'].clearTimeout(this.mediaRequest_);
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- this.mediaRequest_ = null;
- this.minimumUpdatePeriodTimeout_ = null;
-
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
-
- this.off();
- };
-
- _proto.hasPendingRequest = function hasPendingRequest() {
- return this.request || this.mediaRequest_;
- };
-
- _proto.stopRequest = function stopRequest() {
- if (this.request) {
- var oldRequest = this.request;
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- };
-
- _proto.media = function media(playlist) {
- var _this3 = this;
-
- // getter
- if (!playlist) {
- return this.media_;
- } // setter
-
-
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- }
-
- var startingState = this.state; // find the playlist object if the target playlist has been specified by URI
-
- if (typeof playlist === 'string') {
- if (!this.masterPlaylistLoader_.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
-
- playlist = this.masterPlaylistLoader_.master.playlists[playlist];
- }
-
- var mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
-
- if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
- this.state = 'HAVE_METADATA';
- this.media_ = playlist; // trigger media change if the active media has been updated
-
- if (mediaChange) {
- this.trigger('mediachanging');
- this.trigger('mediachange');
- }
-
- return;
- } // switching to the active playlist is a no-op
-
-
- if (!mediaChange) {
- return;
- } // switching from an already loaded playlist
-
-
- if (this.media_) {
- this.trigger('mediachanging');
- }
-
- this.addSidxSegments_(playlist, startingState, function (sidxChanged) {
- // everything is ready just continue to haveMetadata
- _this3.haveMetadata({
- startingState: startingState,
- playlist: playlist
- });
- });
- };
-
- _proto.haveMetadata = function haveMetadata(_ref2) {
- var startingState = _ref2.startingState,
- playlist = _ref2.playlist;
- this.state = 'HAVE_METADATA';
- this.loadedPlaylists_[playlist.id] = playlist;
- this.mediaRequest_ = null; // This will trigger loadedplaylist
-
- this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
- // to resolve setup of media groups
-
- if (startingState === 'HAVE_MASTER') {
- this.trigger('loadedmetadata');
- } else {
- // trigger media change if the active media has been updated
- this.trigger('mediachange');
- }
- };
-
- _proto.pause = function pause() {
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
-
- this.stopRequest();
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
-
- if (this.isMaster_) {
- window__default['default'].clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_);
- this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
- }
-
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- }
- };
-
- _proto.load = function load(isFinalRendition) {
- var _this4 = this;
-
- window__default['default'].clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- var media = this.media();
-
- if (isFinalRendition) {
- var delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
- this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- return _this4.load();
- }, delay);
- return;
- } // because the playlists are internal to the manifest, load should either load the
- // main manifest, or do nothing but trigger an event
-
-
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- // Check to see if this is the master loader and the MUP was cleared (this happens
- // when the loader was paused). `media` should be set at this point since one is always
- // set during `start()`.
- if (this.isMaster_ && !this.minimumUpdatePeriodTimeout_) {
- // Trigger minimumUpdatePeriod to refresh the master manifest
- this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
-
- this.updateMinimumUpdatePeriodTimeout_();
- }
-
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- };
-
- _proto.start = function start() {
- var _this5 = this;
-
- this.started = true; // We don't need to request the master manifest again
- // Call this asynchronously to match the xhr request behavior below
-
- if (!this.isMaster_) {
- this.mediaRequest_ = window__default['default'].setTimeout(function () {
- return _this5.haveMaster_();
- }, 0);
- return;
- }
-
- this.requestMaster_(function (req, masterChanged) {
- _this5.haveMaster_();
-
- if (!_this5.hasPendingRequest() && !_this5.media_) {
- _this5.media(_this5.masterPlaylistLoader_.master.playlists[0]);
- }
- });
- };
-
- _proto.requestMaster_ = function requestMaster_(cb) {
- var _this6 = this;
-
- this.request = this.vhs_.xhr({
- uri: this.masterPlaylistLoader_.srcUrl,
- withCredentials: this.withCredentials
- }, function (error, req) {
- if (_this6.requestErrored_(error, req)) {
- if (_this6.state === 'HAVE_NOTHING') {
- _this6.started = false;
- }
-
- return;
- }
-
- var masterChanged = req.responseText !== _this6.masterPlaylistLoader_.masterXml_;
- _this6.masterPlaylistLoader_.masterXml_ = req.responseText;
-
- if (req.responseHeaders && req.responseHeaders.date) {
- _this6.masterLoaded_ = Date.parse(req.responseHeaders.date);
- } else {
- _this6.masterLoaded_ = Date.now();
- }
-
- _this6.masterPlaylistLoader_.srcUrl = resolveManifestRedirect(_this6.handleManifestRedirects, _this6.masterPlaylistLoader_.srcUrl, req);
-
- if (masterChanged) {
- _this6.handleMaster_();
-
- _this6.syncClientServerClock_(function () {
- return cb(req, masterChanged);
- });
-
- return;
- }
-
- return cb(req, masterChanged);
- });
- }
- /**
- * Parses the master xml for UTCTiming node to sync the client clock to the server
- * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
- *
- * @param {Function} done
- * Function to call when clock sync has completed
- */
- ;
-
- _proto.syncClientServerClock_ = function syncClientServerClock_(done) {
- var _this7 = this;
-
- var utcTiming = parseUTCTiming(this.masterPlaylistLoader_.masterXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
- // server clock
-
- if (utcTiming === null) {
- this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
- return done();
- }
-
- if (utcTiming.method === 'DIRECT') {
- this.masterPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
- return done();
- }
-
- this.request = this.vhs_.xhr({
- uri: resolveUrl(this.masterPlaylistLoader_.srcUrl, utcTiming.value),
- method: utcTiming.method,
- withCredentials: this.withCredentials
- }, function (error, req) {
- // disposed
- if (!_this7.request) {
- return;
- }
-
- if (error) {
- // sync request failed, fall back to using date header from mpd
- // TODO: log warning
- _this7.masterPlaylistLoader_.clientOffset_ = _this7.masterLoaded_ - Date.now();
- return done();
- }
-
- var serverTime;
-
- if (utcTiming.method === 'HEAD') {
- if (!req.responseHeaders || !req.responseHeaders.date) {
- // expected date header not preset, fall back to using date header from mpd
- // TODO: log warning
- serverTime = _this7.masterLoaded_;
- } else {
- serverTime = Date.parse(req.responseHeaders.date);
- }
- } else {
- serverTime = Date.parse(req.responseText);
- }
-
- _this7.masterPlaylistLoader_.clientOffset_ = serverTime - Date.now();
- done();
- });
- };
-
- _proto.haveMaster_ = function haveMaster_() {
- this.state = 'HAVE_MASTER';
-
- if (this.isMaster_) {
- // We have the master playlist at this point, so
- // trigger this to allow MasterPlaylistController
- // to make an initial playlist selection
- this.trigger('loadedplaylist');
- } else if (!this.media_) {
- // no media playlist was specifically selected so select
- // the one the child playlist loader was created with
- this.media(this.childPlaylist_);
- }
- };
-
- _proto.handleMaster_ = function handleMaster_() {
- // clear media request
- this.mediaRequest_ = null;
- var newMaster = parseMasterXml({
- masterXml: this.masterPlaylistLoader_.masterXml_,
- srcUrl: this.masterPlaylistLoader_.srcUrl,
- clientOffset: this.masterPlaylistLoader_.clientOffset_,
- sidxMapping: this.masterPlaylistLoader_.sidxMapping_
- });
- var oldMaster = this.masterPlaylistLoader_.master; // if we have an old master to compare the new master against
-
- if (oldMaster) {
- newMaster = updateMaster(oldMaster, newMaster, this.masterPlaylistLoader_.sidxMapping_);
- } // only update master if we have a new master
-
-
- this.masterPlaylistLoader_.master = newMaster ? newMaster : oldMaster;
- var location = this.masterPlaylistLoader_.master.locations && this.masterPlaylistLoader_.master.locations[0];
-
- if (location && location !== this.masterPlaylistLoader_.srcUrl) {
- this.masterPlaylistLoader_.srcUrl = location;
- }
-
- if (!oldMaster || newMaster && newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
- this.updateMinimumUpdatePeriodTimeout_();
- }
-
- return Boolean(newMaster);
- };
-
- _proto.updateMinimumUpdatePeriodTimeout_ = function updateMinimumUpdatePeriodTimeout_() {
- var mpl = this.masterPlaylistLoader_; // cancel any pending creation of mup on media
- // a new one will be added if needed.
-
- if (mpl.createMupOnMedia_) {
- mpl.off('loadedmetadata', mpl.createMupOnMedia_);
- mpl.createMupOnMedia_ = null;
- } // clear any pending timeouts
-
-
- if (mpl.minimumUpdatePeriodTimeout_) {
- window__default['default'].clearTimeout(mpl.minimumUpdatePeriodTimeout_);
- mpl.minimumUpdatePeriodTimeout_ = null;
- }
-
- var mup = mpl.master && mpl.master.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
- // MPD has no future validity, so a new one will need to be acquired when new
- // media segments are to be made available. Thus, we use the target duration
- // in this case
-
- if (mup === 0) {
- if (mpl.media()) {
- mup = mpl.media().targetDuration * 1000;
- } else {
- mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
- mpl.one('loadedmetadata', mpl.createMupOnMedia_);
- }
- } // if minimumUpdatePeriod is invalid or <= zero, which
- // can happen when a live video becomes VOD. skip timeout
- // creation.
-
-
- if (typeof mup !== 'number' || mup <= 0) {
- if (mup < 0) {
- this.logger_("found invalid minimumUpdatePeriod of " + mup + ", not setting a timeout");
- }
-
- return;
- }
-
- this.createMUPTimeout_(mup);
- };
-
- _proto.createMUPTimeout_ = function createMUPTimeout_(mup) {
- var mpl = this.masterPlaylistLoader_;
- mpl.minimumUpdatePeriodTimeout_ = window__default['default'].setTimeout(function () {
- mpl.minimumUpdatePeriodTimeout_ = null;
- mpl.trigger('minimumUpdatePeriod');
- mpl.createMUPTimeout_(mup);
- }, mup);
- }
- /**
- * Sends request to refresh the master xml and updates the parsed master manifest
- */
- ;
-
- _proto.refreshXml_ = function refreshXml_() {
- var _this8 = this;
-
- this.requestMaster_(function (req, masterChanged) {
- if (!masterChanged) {
- return;
- }
-
- if (_this8.media_) {
- _this8.media_ = _this8.masterPlaylistLoader_.master.playlists[_this8.media_.id];
- } // This will filter out updated sidx info from the mapping
-
-
- _this8.masterPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(_this8.masterPlaylistLoader_.master, _this8.masterPlaylistLoader_.sidxMapping_);
-
- _this8.addSidxSegments_(_this8.media(), _this8.state, function (sidxChanged) {
- // TODO: do we need to reload the current playlist?
- _this8.refreshMedia_(_this8.media().id);
- });
- });
- }
- /**
- * Refreshes the media playlist by re-parsing the master xml and updating playlist
- * references. If this is an alternate loader, the updated parsed manifest is retrieved
- * from the master loader.
- */
- ;
-
- _proto.refreshMedia_ = function refreshMedia_(mediaID) {
- var _this9 = this;
-
- if (!mediaID) {
- throw new Error('refreshMedia_ must take a media id');
- } // for master we have to reparse the master xml
- // to re-create segments based on current timing values
- // which may change media. We only skip updating master
- // if this is the first time this.media_ is being set.
- // as master was just parsed in that case.
-
-
- if (this.media_ && this.isMaster_) {
- this.handleMaster_();
- }
-
- var playlists = this.masterPlaylistLoader_.master.playlists;
- var mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
-
- if (mediaChanged) {
- this.media_ = playlists[mediaID];
- } else {
- this.trigger('playlistunchanged');
- }
-
- if (!this.mediaUpdateTimeout) {
- var createMediaUpdateTimeout = function createMediaUpdateTimeout() {
- if (_this9.media().endList) {
- return;
- }
-
- _this9.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
- _this9.trigger('mediaupdatetimeout');
-
- createMediaUpdateTimeout();
- }, refreshDelay(_this9.media(), Boolean(mediaChanged)));
- };
-
- createMediaUpdateTimeout();
- }
-
- this.trigger('loadedplaylist');
- };
-
- return DashPlaylistLoader;
- }(EventTarget);
-
- var Config = {
- GOAL_BUFFER_LENGTH: 30,
- MAX_GOAL_BUFFER_LENGTH: 60,
- BACK_BUFFER_LENGTH: 30,
- GOAL_BUFFER_LENGTH_RATE: 1,
- // 0.5 MB/s
- INITIAL_BANDWIDTH: 4194304,
- // A fudge factor to apply to advertised playlist bitrates to account for
- // temporary flucations in client bandwidth
- BANDWIDTH_VARIANCE: 1.2,
- // How much of the buffer must be filled before we consider upswitching
- BUFFER_LOW_WATER_LINE: 0,
- MAX_BUFFER_LOW_WATER_LINE: 30,
- // TODO: Remove this when experimentalBufferBasedABR is removed
- EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
- BUFFER_LOW_WATER_LINE_RATE: 1,
- // If the buffer is greater than the high water line, we won't switch down
- BUFFER_HIGH_WATER_LINE: 30
- };
-
- var stringToArrayBuffer = function stringToArrayBuffer(string) {
- var view = new Uint8Array(new ArrayBuffer(string.length));
-
- for (var i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view.buffer;
- };
-
- /* global Blob, BlobBuilder, Worker */
- // unify worker interface
- var browserWorkerPolyFill = function browserWorkerPolyFill(workerObj) {
- // node only supports on/off
- workerObj.on = workerObj.addEventListener;
- workerObj.off = workerObj.removeEventListener;
- return workerObj;
- };
-
- var createObjectURL = function createObjectURL(str) {
- try {
- return URL.createObjectURL(new Blob([str], {
- type: 'application/javascript'
- }));
- } catch (e) {
- var blob = new BlobBuilder();
- blob.append(str);
- return URL.createObjectURL(blob.getBlob());
- }
- };
-
- var factory = function factory(code) {
- return function () {
- var objectUrl = createObjectURL(code);
- var worker = browserWorkerPolyFill(new Worker(objectUrl));
- worker.objURL = objectUrl;
- var terminate = worker.terminate;
- worker.on = worker.addEventListener;
- worker.off = worker.removeEventListener;
-
- worker.terminate = function () {
- URL.revokeObjectURL(objectUrl);
- return terminate.call(this);
- };
-
- return worker;
- };
- };
- var transform = function transform(code) {
- return "var browserWorkerPolyFill = " + browserWorkerPolyFill.toString() + ";\n" + 'browserWorkerPolyFill(self);\n' + code;
- };
-
- var getWorkerString = function getWorkerString(fn) {
- return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
- };
-
- /* rollup-plugin-worker-factory start for worker!/Users/gkatsevman/p/http-streaming-release/src/transmuxer-worker.js */
- var workerCode$1 = transform(getWorkerString(function () {
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * A lightweight readable stream implemention that handles event dispatching.
- * Objects that inherit from streams should call init in their constructors.
- */
-
- var Stream = function Stream() {
- this.init = function () {
- var listeners = {};
- /**
- * Add a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} the callback to be invoked when an event of
- * the specified type occurs
- */
-
- this.on = function (type, listener) {
- if (!listeners[type]) {
- listeners[type] = [];
- }
-
- listeners[type] = listeners[type].concat(listener);
- };
- /**
- * Remove a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} a function previously registered for this
- * type of event through `on`
- */
-
-
- this.off = function (type, listener) {
- var index;
-
- if (!listeners[type]) {
- return false;
- }
-
- index = listeners[type].indexOf(listener);
- listeners[type] = listeners[type].slice();
- listeners[type].splice(index, 1);
- return index > -1;
- };
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- * @param type {string} the event name
- */
-
-
- this.trigger = function (type) {
- var callbacks, i, length, args;
- callbacks = listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- args = [];
- i = arguments.length;
-
- for (i = 1; i < arguments.length; ++i) {
- args.push(arguments[i]);
- }
-
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].apply(this, args);
- }
- }
- };
- /**
- * Destroys the stream and cleans up.
- */
-
-
- this.dispose = function () {
- listeners = {};
- };
- };
- };
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- * @param destination {stream} the stream that will receive all `data` events
- * @param autoFlush {boolean} if false, we will not call `flush` on the destination
- * when the current stream emits a 'done' event
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
-
-
- Stream.prototype.pipe = function (destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- this.on('done', function (flushSource) {
- destination.flush(flushSource);
- });
- this.on('partialdone', function (flushSource) {
- destination.partialFlush(flushSource);
- });
- this.on('endedtimeline', function (flushSource) {
- destination.endTimeline(flushSource);
- });
- this.on('reset', function (flushSource) {
- destination.reset(flushSource);
- });
- return destination;
- }; // Default stream functions that are expected to be overridden to perform
- // actual work. These are provided by the prototype as a sort of no-op
- // implementation so that we don't have to check for their existence in the
- // `pipe` function above.
-
-
- Stream.prototype.push = function (data) {
- this.trigger('data', data);
- };
-
- Stream.prototype.flush = function (flushSource) {
- this.trigger('done', flushSource);
- };
-
- Stream.prototype.partialFlush = function (flushSource) {
- this.trigger('partialdone', flushSource);
- };
-
- Stream.prototype.endTimeline = function (flushSource) {
- this.trigger('endedtimeline', flushSource);
- };
-
- Stream.prototype.reset = function (flushSource) {
- this.trigger('reset', flushSource);
- };
-
- var stream = Stream;
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Functions that generate fragmented MP4s suitable for use with Media
- * Source Extensions.
- */
-
- var UINT32_MAX = Math.pow(2, 32) - 1;
- var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants
-
- (function () {
- var i;
- types = {
- avc1: [],
- // codingname
- avcC: [],
- btrt: [],
- dinf: [],
- dref: [],
- esds: [],
- ftyp: [],
- hdlr: [],
- mdat: [],
- mdhd: [],
- mdia: [],
- mfhd: [],
- minf: [],
- moof: [],
- moov: [],
- mp4a: [],
- // codingname
- mvex: [],
- mvhd: [],
- pasp: [],
- sdtp: [],
- smhd: [],
- stbl: [],
- stco: [],
- stsc: [],
- stsd: [],
- stsz: [],
- stts: [],
- styp: [],
- tfdt: [],
- tfhd: [],
- traf: [],
- trak: [],
- trun: [],
- trex: [],
- tkhd: [],
- vmhd: []
- }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
- // don't throw an error
-
- if (typeof Uint8Array === 'undefined') {
- return;
- }
-
- for (i in types) {
- if (types.hasOwnProperty(i)) {
- types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
- }
- }
-
- MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
- AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
- MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
- VIDEO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
- ]);
- AUDIO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
- ]);
- HDLR_TYPES = {
- video: VIDEO_HDLR,
- audio: AUDIO_HDLR
- };
- DREF = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // entry_count
- 0x00, 0x00, 0x00, 0x0c, // entry_size
- 0x75, 0x72, 0x6c, 0x20, // 'url' type
- 0x00, // version 0
- 0x00, 0x00, 0x01 // entry_flags
- ]);
- SMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, // balance, 0 means centered
- 0x00, 0x00 // reserved
- ]);
- STCO = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00 // entry_count
- ]);
- STSC = STCO;
- STSZ = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // sample_size
- 0x00, 0x00, 0x00, 0x00 // sample_count
- ]);
- STTS = STCO;
- VMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x01, // flags
- 0x00, 0x00, // graphicsmode
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
- ]);
- })();
-
- box = function box(type) {
- var payload = [],
- size = 0,
- i,
- result,
- view;
-
- for (i = 1; i < arguments.length; i++) {
- payload.push(arguments[i]);
- }
-
- i = payload.length; // calculate the total size we need to allocate
-
- while (i--) {
- size += payload[i].byteLength;
- }
-
- result = new Uint8Array(size + 8);
- view = new DataView(result.buffer, result.byteOffset, result.byteLength);
- view.setUint32(0, result.byteLength);
- result.set(type, 4); // copy the payload into the result
-
- for (i = 0, size = 8; i < payload.length; i++) {
- result.set(payload[i], size);
- size += payload[i].byteLength;
- }
-
- return result;
- };
-
- dinf = function dinf() {
- return box(types.dinf, box(types.dref, DREF));
- };
-
- esds = function esds(track) {
- return box(types.esds, new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- // ES_Descriptor
- 0x03, // tag, ES_DescrTag
- 0x19, // length
- 0x00, 0x00, // ES_ID
- 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
- // DecoderConfigDescriptor
- 0x04, // tag, DecoderConfigDescrTag
- 0x11, // length
- 0x40, // object type
- 0x15, // streamType
- 0x00, 0x06, 0x00, // bufferSizeDB
- 0x00, 0x00, 0xda, 0xc0, // maxBitrate
- 0x00, 0x00, 0xda, 0xc0, // avgBitrate
- // DecoderSpecificInfo
- 0x05, // tag, DecoderSpecificInfoTag
- 0x02, // length
- // ISO/IEC 14496-3, AudioSpecificConfig
- // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
- track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
- ]));
- };
-
- ftyp = function ftyp() {
- return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
- };
-
- hdlr = function hdlr(type) {
- return box(types.hdlr, HDLR_TYPES[type]);
- };
-
- mdat = function mdat(data) {
- return box(types.mdat, data);
- };
-
- mdhd = function mdhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x02, // creation_time
- 0x00, 0x00, 0x00, 0x03, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
- 0x55, 0xc4, // 'und' language (undetermined)
- 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
- // defined. The sample rate can be parsed out of an ADTS header, for
- // instance.
-
- if (track.samplerate) {
- result[12] = track.samplerate >>> 24 & 0xFF;
- result[13] = track.samplerate >>> 16 & 0xFF;
- result[14] = track.samplerate >>> 8 & 0xFF;
- result[15] = track.samplerate & 0xFF;
- }
-
- return box(types.mdhd, result);
- };
-
- mdia = function mdia(track) {
- return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
- };
-
- mfhd = function mfhd(sequenceNumber) {
- return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
- (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
- ]));
- };
-
- minf = function minf(track) {
- return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
- };
-
- moof = function moof(sequenceNumber, tracks) {
- var trackFragments = [],
- i = tracks.length; // build traf boxes for each track fragment
-
- while (i--) {
- trackFragments[i] = traf(tracks[i]);
- }
-
- return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
- };
- /**
- * Returns a movie box.
- * @param tracks {array} the tracks associated with this movie
- * @see ISO/IEC 14496-12:2012(E), section 8.2.1
- */
-
-
- moov = function moov(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trak(tracks[i]);
- }
-
- return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
- };
-
- mvex = function mvex(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trex(tracks[i]);
- }
-
- return box.apply(null, [types.mvex].concat(boxes));
- };
-
- mvhd = function mvhd(duration) {
- var bytes = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // creation_time
- 0x00, 0x00, 0x00, 0x02, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
- 0x00, 0x01, 0x00, 0x00, // 1.0 rate
- 0x01, 0x00, // 1.0 volume
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0xff, 0xff, 0xff, 0xff // next_track_ID
- ]);
- return box(types.mvhd, bytes);
- };
-
- sdtp = function sdtp(track) {
- var samples = track.samples || [],
- bytes = new Uint8Array(4 + samples.length),
- flags,
- i; // leave the full box header (4 bytes) all zero
- // write the sample table
-
- for (i = 0; i < samples.length; i++) {
- flags = samples[i].flags;
- bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
- }
-
- return box(types.sdtp, bytes);
- };
-
- stbl = function stbl(track) {
- return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
- };
-
- (function () {
- var videoSample, audioSample;
-
- stsd = function stsd(track) {
- return box(types.stsd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
- };
-
- videoSample = function videoSample(track) {
- var sps = track.sps || [],
- pps = track.pps || [],
- sequenceParameterSets = [],
- pictureParameterSets = [],
- i,
- avc1Box; // assemble the SPSs
-
- for (i = 0; i < sps.length; i++) {
- sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
- sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
-
- sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
- } // assemble the PPSs
-
-
- for (i = 0; i < pps.length; i++) {
- pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
- pictureParameterSets.push(pps[i].byteLength & 0xFF);
- pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
- }
-
- avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- (track.width & 0xff00) >> 8, track.width & 0xff, // width
- (track.height & 0xff00) >> 8, track.height & 0xff, // height
- 0x00, 0x48, 0x00, 0x00, // horizresolution
- 0x00, 0x48, 0x00, 0x00, // vertresolution
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // frame_count
- 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
- 0x00, 0x18, // depth = 24
- 0x11, 0x11 // pre_defined = -1
- ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
- track.profileIdc, // AVCProfileIndication
- track.profileCompatibility, // profile_compatibility
- track.levelIdc, // AVCLevelIndication
- 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
- ].concat([sps.length], // numOfSequenceParameterSets
- sequenceParameterSets, // "SPS"
- [pps.length], // numOfPictureParameterSets
- pictureParameterSets // "PPS"
- ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
- 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
- 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
- ]))];
-
- if (track.sarRatio) {
- var hSpacing = track.sarRatio[0],
- vSpacing = track.sarRatio[1];
- avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 0xFF000000) >> 24, (hSpacing & 0xFF0000) >> 16, (hSpacing & 0xFF00) >> 8, hSpacing & 0xFF, (vSpacing & 0xFF000000) >> 24, (vSpacing & 0xFF0000) >> 16, (vSpacing & 0xFF00) >> 8, vSpacing & 0xFF])));
- }
-
- return box.apply(null, avc1Box);
- };
-
- audioSample = function audioSample(track) {
- return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- // AudioSampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
- (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
- // MP4AudioSampleEntry, ISO/IEC 14496-14
- ]), esds(track));
- };
- })();
-
- tkhd = function tkhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x07, // flags
- 0x00, 0x00, 0x00, 0x00, // creation_time
- 0x00, 0x00, 0x00, 0x00, // modification_time
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, // layer
- 0x00, 0x00, // alternate_group
- 0x01, 0x00, // non-audio track volume
- 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
- (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
- ]);
- return box(types.tkhd, result);
- };
- /**
- * Generate a track fragment (traf) box. A traf box collects metadata
- * about tracks in a movie fragment (moof) box.
- */
-
-
- traf = function traf(track) {
- var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
- trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x3a, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x00, 0x00, 0x00 // default_sample_flags
- ]));
- upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
- lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));
- trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
- 0x00, 0x00, 0x00, // flags
- // baseMediaDecodeTime
- upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])); // the data offset specifies the number of bytes from the start of
- // the containing moof to the first payload byte of the associated
- // mdat
-
- dataOffset = 32 + // tfhd
- 20 + // tfdt
- 8 + // traf header
- 16 + // mfhd
- 8 + // moof header
- 8; // mdat header
- // audio tracks require less metadata
-
- if (track.type === 'audio') {
- trackFragmentRun = trun$1(track, dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
- } // video tracks should contain an independent and disposable samples
- // box (sdtp)
- // generate one and adjust offsets to match
-
-
- sampleDependencyTable = sdtp(track);
- trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
- };
- /**
- * Generate a track box.
- * @param track {object} a track definition
- * @return {Uint8Array} the track box
- */
-
-
- trak = function trak(track) {
- track.duration = track.duration || 0xffffffff;
- return box(types.trak, tkhd(track), mdia(track));
- };
-
- trex = function trex(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x01, 0x00, 0x01 // default_sample_flags
- ]); // the last two bytes of default_sample_flags is the sample
- // degradation priority, a hint about the importance of this sample
- // relative to others. Lower the degradation priority for all sample
- // types other than video.
-
- if (track.type !== 'video') {
- result[result.length - 1] = 0x00;
- }
-
- return box(types.trex, result);
- };
-
- (function () {
- var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
- // duration is present for the first sample, it will be present for
- // all subsequent samples.
- // see ISO/IEC 14496-12:2012, Section 8.8.8.1
-
- trunHeader = function trunHeader(samples, offset) {
- var durationPresent = 0,
- sizePresent = 0,
- flagsPresent = 0,
- compositionTimeOffset = 0; // trun flag constants
-
- if (samples.length) {
- if (samples[0].duration !== undefined) {
- durationPresent = 0x1;
- }
-
- if (samples[0].size !== undefined) {
- sizePresent = 0x2;
- }
-
- if (samples[0].flags !== undefined) {
- flagsPresent = 0x4;
- }
-
- if (samples[0].compositionTimeOffset !== undefined) {
- compositionTimeOffset = 0x8;
- }
- }
-
- return [0x00, // version 0
- 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
- (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
- (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
- ];
- };
-
- videoTrun = function videoTrun(track, offset) {
- var bytesOffest, bytes, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 16 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 16);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
-
- bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
- bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
-
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
- }
-
- return box(types.trun, bytes);
- };
-
- audioTrun = function audioTrun(track, offset) {
- var bytes, bytesOffest, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 8 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 8);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
- }
-
- return box(types.trun, bytes);
- };
-
- trun$1 = function trun(track, offset) {
- if (track.type === 'audio') {
- return audioTrun(track, offset);
- }
-
- return videoTrun(track, offset);
- };
- })();
-
- var mp4Generator = {
- ftyp: ftyp,
- mdat: mdat,
- moof: moof,
- moov: moov,
- initSegment: function initSegment(tracks) {
- var fileType = ftyp(),
- movie = moov(tracks),
- result;
- result = new Uint8Array(fileType.byteLength + movie.byteLength);
- result.set(fileType);
- result.set(movie, fileType.byteLength);
- return result;
- }
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- // Convert an array of nal units into an array of frames with each frame being
- // composed of the nal units that make up that frame
- // Also keep track of cummulative data about the frame from the nal units such
- // as the frame duration, starting pts, etc.
-
- var groupNalsIntoFrames = function groupNalsIntoFrames(nalUnits) {
- var i,
- currentNal,
- currentFrame = [],
- frames = []; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength = 0;
- frames.nalCount = 0;
- frames.duration = 0;
- currentFrame.byteLength = 0;
-
- for (i = 0; i < nalUnits.length; i++) {
- currentNal = nalUnits[i]; // Split on 'aud'-type nal units
-
- if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
- // Since the very first nal unit is expected to be an AUD
- // only push to the frames array when currentFrame is not empty
- if (currentFrame.length) {
- currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- }
-
- currentFrame = [currentNal];
- currentFrame.byteLength = currentNal.data.byteLength;
- currentFrame.pts = currentNal.pts;
- currentFrame.dts = currentNal.dts;
- } else {
- // Specifically flag key frames for ease of use later
- if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
- currentFrame.keyFrame = true;
- }
-
- currentFrame.duration = currentNal.dts - currentFrame.dts;
- currentFrame.byteLength += currentNal.data.byteLength;
- currentFrame.push(currentNal);
- }
- } // For the last frame, use the duration of the previous frame if we
- // have nothing better to go on
-
-
- if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
- currentFrame.duration = frames[frames.length - 1].duration;
- } // Push the final frame
- // TODO added for LHLS, make sure this is OK
-
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- return frames;
- }; // Convert an array of frames into an array of Gop with each Gop being composed
- // of the frames that make up that Gop
- // Also keep track of cummulative data about the Gop from the frames such as the
- // Gop duration, starting pts, etc.
-
-
- var groupFramesIntoGops = function groupFramesIntoGops(frames) {
- var i,
- currentFrame,
- currentGop = [],
- gops = []; // We must pre-set some of the values on the Gop since we
- // keep running totals of these values
-
- currentGop.byteLength = 0;
- currentGop.nalCount = 0;
- currentGop.duration = 0;
- currentGop.pts = frames[0].pts;
- currentGop.dts = frames[0].dts; // store some metadata about all the Gops
-
- gops.byteLength = 0;
- gops.nalCount = 0;
- gops.duration = 0;
- gops.pts = frames[0].pts;
- gops.dts = frames[0].dts;
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
-
- if (currentFrame.keyFrame) {
- // Since the very first frame is expected to be an keyframe
- // only push to the gops array when currentGop is not empty
- if (currentGop.length) {
- gops.push(currentGop);
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration;
- }
-
- currentGop = [currentFrame];
- currentGop.nalCount = currentFrame.length;
- currentGop.byteLength = currentFrame.byteLength;
- currentGop.pts = currentFrame.pts;
- currentGop.dts = currentFrame.dts;
- currentGop.duration = currentFrame.duration;
- } else {
- currentGop.duration += currentFrame.duration;
- currentGop.nalCount += currentFrame.length;
- currentGop.byteLength += currentFrame.byteLength;
- currentGop.push(currentFrame);
- }
- }
-
- if (gops.length && currentGop.duration <= 0) {
- currentGop.duration = gops[gops.length - 1].duration;
- }
-
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration; // push the final Gop
-
- gops.push(currentGop);
- return gops;
- };
- /*
- * Search for the first keyframe in the GOPs and throw away all frames
- * until that keyframe. Then extend the duration of the pulled keyframe
- * and pull the PTS and DTS of the keyframe so that it covers the time
- * range of the frames that were disposed.
- *
- * @param {Array} gops video GOPs
- * @returns {Array} modified video GOPs
- */
-
-
- var extendFirstKeyFrame = function extendFirstKeyFrame(gops) {
- var currentGop;
-
- if (!gops[0][0].keyFrame && gops.length > 1) {
- // Remove the first GOP
- currentGop = gops.shift();
- gops.byteLength -= currentGop.byteLength;
- gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
- // first gop to cover the time period of the
- // frames we just removed
-
- gops[0][0].dts = currentGop.dts;
- gops[0][0].pts = currentGop.pts;
- gops[0][0].duration += currentGop.duration;
- }
-
- return gops;
- };
- /**
- * Default sample object
- * see ISO/IEC 14496-12:2012, section 8.6.4.3
- */
-
-
- var createDefaultSample = function createDefaultSample() {
- return {
- size: 0,
- flags: {
- isLeading: 0,
- dependsOn: 1,
- isDependedOn: 0,
- hasRedundancy: 0,
- degradationPriority: 0,
- isNonSyncSample: 1
- }
- };
- };
- /*
- * Collates information from a video frame into an object for eventual
- * entry into an MP4 sample table.
- *
- * @param {Object} frame the video frame
- * @param {Number} dataOffset the byte offset to position the sample
- * @return {Object} object containing sample table info for a frame
- */
-
-
- var sampleForFrame = function sampleForFrame(frame, dataOffset) {
- var sample = createDefaultSample();
- sample.dataOffset = dataOffset;
- sample.compositionTimeOffset = frame.pts - frame.dts;
- sample.duration = frame.duration;
- sample.size = 4 * frame.length; // Space for nal unit size
-
- sample.size += frame.byteLength;
-
- if (frame.keyFrame) {
- sample.flags.dependsOn = 2;
- sample.flags.isNonSyncSample = 0;
- }
-
- return sample;
- }; // generate the track's sample table from an array of gops
-
-
- var generateSampleTable$1 = function generateSampleTable(gops, baseDataOffset) {
- var h,
- i,
- sample,
- currentGop,
- currentFrame,
- dataOffset = baseDataOffset || 0,
- samples = [];
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h];
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i];
- sample = sampleForFrame(currentFrame, dataOffset);
- dataOffset += sample.size;
- samples.push(sample);
- }
- }
-
- return samples;
- }; // generate the track's raw mdat data from an array of gops
-
-
- var concatenateNalData = function concatenateNalData(gops) {
- var h,
- i,
- j,
- currentGop,
- currentFrame,
- currentNal,
- dataOffset = 0,
- nalsByteLength = gops.byteLength,
- numberOfNals = gops.nalCount,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each Gop..
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h]; // For each Frame..
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i]; // For each NAL..
-
- for (j = 0; j < currentFrame.length; j++) {
- currentNal = currentFrame[j];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
- }
- }
-
- return data;
- }; // generate the track's sample table from a frame
-
-
- var generateSampleTableForFrame = function generateSampleTableForFrame(frame, baseDataOffset) {
- var sample,
- dataOffset = baseDataOffset || 0,
- samples = [];
- sample = sampleForFrame(frame, dataOffset);
- samples.push(sample);
- return samples;
- }; // generate the track's raw mdat data from a frame
-
-
- var concatenateNalDataForFrame = function concatenateNalDataForFrame(frame) {
- var i,
- currentNal,
- dataOffset = 0,
- nalsByteLength = frame.byteLength,
- numberOfNals = frame.length,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each NAL..
-
- for (i = 0; i < frame.length; i++) {
- currentNal = frame[i];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
-
- return data;
- };
-
- var frameUtils = {
- groupNalsIntoFrames: groupNalsIntoFrames,
- groupFramesIntoGops: groupFramesIntoGops,
- extendFirstKeyFrame: extendFirstKeyFrame,
- generateSampleTable: generateSampleTable$1,
- concatenateNalData: concatenateNalData,
- generateSampleTableForFrame: generateSampleTableForFrame,
- concatenateNalDataForFrame: concatenateNalDataForFrame
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var highPrefix = [33, 16, 5, 32, 164, 27];
- var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
-
- var zeroFill = function zeroFill(count) {
- var a = [];
-
- while (count--) {
- a.push(0);
- }
-
- return a;
- };
-
- var makeTable = function makeTable(metaTable) {
- return Object.keys(metaTable).reduce(function (obj, key) {
- obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
- return arr.concat(part);
- }, []));
- return obj;
- }, {});
- };
-
- var silence;
-
- var silence_1 = function silence_1() {
- if (!silence) {
- // Frames-of-silence to use for filling in missing AAC frames
- var coneOfSilence = {
- 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
- 88200: [highPrefix, [231], zeroFill(170), [56]],
- 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
- 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
- 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
- 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
- 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
- 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
- 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
- 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
- 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
- };
- silence = makeTable(coneOfSilence);
- }
-
- return silence;
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
-
- var ONE_SECOND_IN_TS$4 = 90000,
- // 90kHz clock
- secondsToVideoTs,
- secondsToAudioTs,
- videoTsToSeconds,
- audioTsToSeconds,
- audioTsToVideoTs,
- videoTsToAudioTs,
- metadataTsToSeconds;
-
- secondsToVideoTs = function secondsToVideoTs(seconds) {
- return seconds * ONE_SECOND_IN_TS$4;
- };
-
- secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
- return seconds * sampleRate;
- };
-
- videoTsToSeconds = function videoTsToSeconds(timestamp) {
- return timestamp / ONE_SECOND_IN_TS$4;
- };
-
- audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
- return timestamp / sampleRate;
- };
-
- audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
- return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
- };
-
- videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
- return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
- };
- /**
- * Adjust ID3 tag or caption timing information by the timeline pts values
- * (if keepOriginalTimestamps is false) and convert to seconds
- */
-
-
- metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
- return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
- };
-
- var clock = {
- ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
- secondsToVideoTs: secondsToVideoTs,
- secondsToAudioTs: secondsToAudioTs,
- videoTsToSeconds: videoTsToSeconds,
- audioTsToSeconds: audioTsToSeconds,
- audioTsToVideoTs: audioTsToVideoTs,
- videoTsToAudioTs: videoTsToAudioTs,
- metadataTsToSeconds: metadataTsToSeconds
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- /**
- * Sum the `byteLength` properties of the data in each AAC frame
- */
-
- var sumFrameByteLengths = function sumFrameByteLengths(array) {
- var i,
- currentObj,
- sum = 0; // sum the byteLength's all each nal unit in the frame
-
- for (i = 0; i < array.length; i++) {
- currentObj = array[i];
- sum += currentObj.data.byteLength;
- }
-
- return sum;
- }; // Possibly pad (prefix) the audio track with silence if appending this track
- // would lead to the introduction of a gap in the audio buffer
-
-
- var prefixWithSilence = function prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
- var baseMediaDecodeTimeTs,
- frameDuration = 0,
- audioGapDuration = 0,
- audioFillFrameCount = 0,
- audioFillDuration = 0,
- silentFrame,
- i,
- firstFrame;
-
- if (!frames.length) {
- return;
- }
-
- baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
-
- frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
-
- if (audioAppendStartTs && videoBaseMediaDecodeTime) {
- // insert the shortest possible amount (audio gap or audio to video gap)
- audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
-
- audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
- audioFillDuration = audioFillFrameCount * frameDuration;
- } // don't attempt to fill gaps smaller than a single frame or larger
- // than a half second
-
-
- if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
- return;
- }
-
- silentFrame = silence_1()[track.samplerate];
-
- if (!silentFrame) {
- // we don't have a silent frame pregenerated for the sample rate, so use a frame
- // from the content instead
- silentFrame = frames[0].data;
- }
-
- for (i = 0; i < audioFillFrameCount; i++) {
- firstFrame = frames[0];
- frames.splice(0, 0, {
- data: silentFrame,
- dts: firstFrame.dts - frameDuration,
- pts: firstFrame.pts - frameDuration
- });
- }
-
- track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
- return audioFillDuration;
- }; // If the audio segment extends before the earliest allowed dts
- // value, remove AAC frames until starts at or after the earliest
- // allowed DTS so that we don't end up with a negative baseMedia-
- // DecodeTime for the audio track
-
-
- var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts) {
- if (track.minSegmentDts >= earliestAllowedDts) {
- return adtsFrames;
- } // We will need to recalculate the earliest segment Dts
-
-
- track.minSegmentDts = Infinity;
- return adtsFrames.filter(function (currentFrame) {
- // If this is an allowed frame, keep it and record it's Dts
- if (currentFrame.dts >= earliestAllowedDts) {
- track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
- track.minSegmentPts = track.minSegmentDts;
- return true;
- } // Otherwise, discard it
-
-
- return false;
- });
- }; // generate the track's raw mdat data from an array of frames
-
-
- var generateSampleTable = function generateSampleTable(frames) {
- var i,
- currentFrame,
- samples = [];
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- samples.push({
- size: currentFrame.data.byteLength,
- duration: 1024 // For AAC audio, all samples contain 1024 samples
-
- });
- }
-
- return samples;
- }; // generate the track's sample table from an array of frames
-
-
- var concatenateFrameData = function concatenateFrameData(frames) {
- var i,
- currentFrame,
- dataOffset = 0,
- data = new Uint8Array(sumFrameByteLengths(frames));
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- data.set(currentFrame.data, dataOffset);
- dataOffset += currentFrame.data.byteLength;
- }
-
- return data;
- };
-
- var audioFrameUtils = {
- prefixWithSilence: prefixWithSilence,
- trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
- generateSampleTable: generateSampleTable,
- concatenateFrameData: concatenateFrameData
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ONE_SECOND_IN_TS$3 = clock.ONE_SECOND_IN_TS;
- /**
- * Store information about the start and end of the track and the
- * duration for each frame/sample we process in order to calculate
- * the baseMediaDecodeTime
- */
-
- var collectDtsInfo = function collectDtsInfo(track, data) {
- if (typeof data.pts === 'number') {
- if (track.timelineStartInfo.pts === undefined) {
- track.timelineStartInfo.pts = data.pts;
- }
-
- if (track.minSegmentPts === undefined) {
- track.minSegmentPts = data.pts;
- } else {
- track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
- }
-
- if (track.maxSegmentPts === undefined) {
- track.maxSegmentPts = data.pts;
- } else {
- track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
- }
- }
-
- if (typeof data.dts === 'number') {
- if (track.timelineStartInfo.dts === undefined) {
- track.timelineStartInfo.dts = data.dts;
- }
-
- if (track.minSegmentDts === undefined) {
- track.minSegmentDts = data.dts;
- } else {
- track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
- }
-
- if (track.maxSegmentDts === undefined) {
- track.maxSegmentDts = data.dts;
- } else {
- track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
- }
- }
- };
- /**
- * Clear values used to calculate the baseMediaDecodeTime between
- * tracks
- */
-
-
- var clearDtsInfo = function clearDtsInfo(track) {
- delete track.minSegmentDts;
- delete track.maxSegmentDts;
- delete track.minSegmentPts;
- delete track.maxSegmentPts;
- };
- /**
- * Calculate the track's baseMediaDecodeTime based on the earliest
- * DTS the transmuxer has ever seen and the minimum DTS for the
- * current track
- * @param track {object} track metadata configuration
- * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime(track, keepOriginalTimestamps) {
- var baseMediaDecodeTime,
- scale,
- minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
-
- if (!keepOriginalTimestamps) {
- minSegmentDts -= track.timelineStartInfo.dts;
- } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
- // we want the start of the first segment to be placed
-
-
- baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
-
- baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
-
- baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
-
- if (track.type === 'audio') {
- // Audio has a different clock equal to the sampling_rate so we need to
- // scale the PTS values into the clock rate of the track
- scale = track.samplerate / ONE_SECOND_IN_TS$3;
- baseMediaDecodeTime *= scale;
- baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
- }
-
- return baseMediaDecodeTime;
- };
-
- var trackDecodeInfo = {
- clearDtsInfo: clearDtsInfo,
- calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
- collectDtsInfo: collectDtsInfo
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Reads in-band caption information from a video elementary
- * stream. Captions must follow the CEA-708 standard for injection
- * into an MPEG-2 transport streams.
- * @see https://en.wikipedia.org/wiki/CEA-708
- * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
- */
- // payload type field to indicate how they are to be
- // interpreted. CEAS-708 caption content is always transmitted with
- // payload type 0x04.
-
- var USER_DATA_REGISTERED_ITU_T_T35 = 4,
- RBSP_TRAILING_BITS = 128;
- /**
- * Parse a supplemental enhancement information (SEI) NAL unit.
- * Stops parsing once a message of type ITU T T35 has been found.
- *
- * @param bytes {Uint8Array} the bytes of a SEI NAL unit
- * @return {object} the parsed SEI payload
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- */
-
- var parseSei = function parseSei(bytes) {
- var i = 0,
- result = {
- payloadType: -1,
- payloadSize: 0
- },
- payloadType = 0,
- payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
-
- while (i < bytes.byteLength) {
- // stop once we have hit the end of the sei_rbsp
- if (bytes[i] === RBSP_TRAILING_BITS) {
- break;
- } // Parse payload type
-
-
- while (bytes[i] === 0xFF) {
- payloadType += 255;
- i++;
- }
-
- payloadType += bytes[i++]; // Parse payload size
-
- while (bytes[i] === 0xFF) {
- payloadSize += 255;
- i++;
- }
-
- payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
- // there can only ever be one caption message in a frame's sei
-
- if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
- var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
-
- if (userIdentifier === 'GA94') {
- result.payloadType = payloadType;
- result.payloadSize = payloadSize;
- result.payload = bytes.subarray(i, i + payloadSize);
- break;
- } else {
- result.payload = void 0;
- }
- } // skip the payload and parse the next message
-
-
- i += payloadSize;
- payloadType = 0;
- payloadSize = 0;
- }
-
- return result;
- }; // see ANSI/SCTE 128-1 (2013), section 8.1
-
-
- var parseUserData = function parseUserData(sei) {
- // itu_t_t35_contry_code must be 181 (United States) for
- // captions
- if (sei.payload[0] !== 181) {
- return null;
- } // itu_t_t35_provider_code should be 49 (ATSC) for captions
-
-
- if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
- return null;
- } // the user_identifier should be "GA94" to indicate ATSC1 data
-
-
- if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
- return null;
- } // finally, user_data_type_code should be 0x03 for caption data
-
-
- if (sei.payload[7] !== 0x03) {
- return null;
- } // return the user_data_type_structure and strip the trailing
- // marker bits
-
-
- return sei.payload.subarray(8, sei.payload.length - 1);
- }; // see CEA-708-D, section 4.4
-
-
- var parseCaptionPackets = function parseCaptionPackets(pts, userData) {
- var results = [],
- i,
- count,
- offset,
- data; // if this is just filler, return immediately
-
- if (!(userData[0] & 0x40)) {
- return results;
- } // parse out the cc_data_1 and cc_data_2 fields
-
-
- count = userData[0] & 0x1f;
-
- for (i = 0; i < count; i++) {
- offset = i * 3;
- data = {
- type: userData[offset + 2] & 0x03,
- pts: pts
- }; // capture cc data when cc_valid is 1
-
- if (userData[offset + 2] & 0x04) {
- data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
- results.push(data);
- }
- }
-
- return results;
- };
-
- var discardEmulationPreventionBytes$1 = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- }; // exports
-
-
- var captionPacketParser = {
- parseSei: parseSei,
- parseUserData: parseUserData,
- parseCaptionPackets: parseCaptionPackets,
- discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
- USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
- }; // Link To Transport
- // -----------------
-
- var CaptionStream$1 = function CaptionStream(options) {
- options = options || {};
- CaptionStream.prototype.init.call(this); // parse708captions flag, default to true
-
- this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
- this.captionPackets_ = [];
- this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
- ];
-
- if (this.parse708captions_) {
- this.cc708Stream_ = new Cea708Stream(); // eslint-disable-line no-use-before-define
- }
-
- this.reset(); // forward data and done events from CCs to this CaptionStream
-
- this.ccStreams_.forEach(function (cc) {
- cc.on('data', this.trigger.bind(this, 'data'));
- cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
- cc.on('done', this.trigger.bind(this, 'done'));
- }, this);
-
- if (this.parse708captions_) {
- this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
- this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
- this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
- }
- };
-
- CaptionStream$1.prototype = new stream();
-
- CaptionStream$1.prototype.push = function (event) {
- var sei, userData, newCaptionPackets; // only examine SEI NALs
-
- if (event.nalUnitType !== 'sei_rbsp') {
- return;
- } // parse the sei
-
-
- sei = captionPacketParser.parseSei(event.escapedRBSP); // no payload data, skip
-
- if (!sei.payload) {
- return;
- } // ignore everything but user_data_registered_itu_t_t35
-
-
- if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
- return;
- } // parse out the user data payload
-
-
- userData = captionPacketParser.parseUserData(sei); // ignore unrecognized userData
-
- if (!userData) {
- return;
- } // Sometimes, the same segment # will be downloaded twice. To stop the
- // caption data from being processed twice, we track the latest dts we've
- // received and ignore everything with a dts before that. However, since
- // data for a specific dts can be split across packets on either side of
- // a segment boundary, we need to make sure we *don't* ignore the packets
- // from the *next* segment that have dts === this.latestDts_. By constantly
- // tracking the number of packets received with dts === this.latestDts_, we
- // know how many should be ignored once we start receiving duplicates.
-
-
- if (event.dts < this.latestDts_) {
- // We've started getting older data, so set the flag.
- this.ignoreNextEqualDts_ = true;
- return;
- } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
- this.numSameDts_--;
-
- if (!this.numSameDts_) {
- // We've received the last duplicate packet, time to start processing again
- this.ignoreNextEqualDts_ = false;
- }
-
- return;
- } // parse out CC data packets and save them for later
-
-
- newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
- this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
-
- if (this.latestDts_ !== event.dts) {
- this.numSameDts_ = 0;
- }
-
- this.numSameDts_++;
- this.latestDts_ = event.dts;
- };
-
- CaptionStream$1.prototype.flushCCStreams = function (flushType) {
- this.ccStreams_.forEach(function (cc) {
- return flushType === 'flush' ? cc.flush() : cc.partialFlush();
- }, this);
- };
-
- CaptionStream$1.prototype.flushStream = function (flushType) {
- // make sure we actually parsed captions before proceeding
- if (!this.captionPackets_.length) {
- this.flushCCStreams(flushType);
- return;
- } // In Chrome, the Array#sort function is not stable so add a
- // presortIndex that we can use to ensure we get a stable-sort
-
-
- this.captionPackets_.forEach(function (elem, idx) {
- elem.presortIndex = idx;
- }); // sort caption byte-pairs based on their PTS values
-
- this.captionPackets_.sort(function (a, b) {
- if (a.pts === b.pts) {
- return a.presortIndex - b.presortIndex;
- }
-
- return a.pts - b.pts;
- });
- this.captionPackets_.forEach(function (packet) {
- if (packet.type < 2) {
- // Dispatch packet to the right Cea608Stream
- this.dispatchCea608Packet(packet);
- } else {
- // Dispatch packet to the Cea708Stream
- this.dispatchCea708Packet(packet);
- }
- }, this);
- this.captionPackets_.length = 0;
- this.flushCCStreams(flushType);
- };
-
- CaptionStream$1.prototype.flush = function () {
- return this.flushStream('flush');
- }; // Only called if handling partial data
-
-
- CaptionStream$1.prototype.partialFlush = function () {
- return this.flushStream('partialFlush');
- };
-
- CaptionStream$1.prototype.reset = function () {
- this.latestDts_ = null;
- this.ignoreNextEqualDts_ = false;
- this.numSameDts_ = 0;
- this.activeCea608Channel_ = [null, null];
- this.ccStreams_.forEach(function (ccStream) {
- ccStream.reset();
- });
- }; // From the CEA-608 spec:
-
- /*
- * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
- * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
- * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
- * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
- * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
- * to switch to captioning or Text.
- */
- // With that in mind, we ignore any data between an XDS control code and a
- // subsequent closed-captioning control code.
-
-
- CaptionStream$1.prototype.dispatchCea608Packet = function (packet) {
- // NOTE: packet.type is the CEA608 field
- if (this.setsTextOrXDSActive(packet)) {
- this.activeCea608Channel_[packet.type] = null;
- } else if (this.setsChannel1Active(packet)) {
- this.activeCea608Channel_[packet.type] = 0;
- } else if (this.setsChannel2Active(packet)) {
- this.activeCea608Channel_[packet.type] = 1;
- }
-
- if (this.activeCea608Channel_[packet.type] === null) {
- // If we haven't received anything to set the active channel, or the
- // packets are Text/XDS data, discard the data; we don't want jumbled
- // captions
- return;
- }
-
- this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
- };
-
- CaptionStream$1.prototype.setsChannel1Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1000;
- };
-
- CaptionStream$1.prototype.setsChannel2Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1800;
- };
-
- CaptionStream$1.prototype.setsTextOrXDSActive = function (packet) {
- return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
- };
-
- CaptionStream$1.prototype.dispatchCea708Packet = function (packet) {
- if (this.parse708captions_) {
- this.cc708Stream_.push(packet);
- }
- }; // ----------------------
- // Session to Application
- // ----------------------
- // This hash maps special and extended character codes to their
- // proper Unicode equivalent. The first one-byte key is just a
- // non-standard character code. The two-byte keys that follow are
- // the extended CEA708 character codes, along with the preceding
- // 0x10 extended character byte to distinguish these codes from
- // non-extended character codes. Every CEA708 character code that
- // is not in this object maps directly to a standard unicode
- // character code.
- // The transparent space and non-breaking transparent space are
- // technically not fully supported since there is no code to
- // make them transparent, so they have normal non-transparent
- // stand-ins.
- // The special closed caption (CC) character isn't a standard
- // unicode character, so a fairly similar unicode character was
- // chosen in it's place.
-
-
- var CHARACTER_TRANSLATION_708 = {
- 0x7f: 0x266a,
- // ♪
- 0x1020: 0x20,
- // Transparent Space
- 0x1021: 0xa0,
- // Nob-breaking Transparent Space
- 0x1025: 0x2026,
- // …
- 0x102a: 0x0160,
- // Š
- 0x102c: 0x0152,
- // Œ
- 0x1030: 0x2588,
- // █
- 0x1031: 0x2018,
- // ‘
- 0x1032: 0x2019,
- // ’
- 0x1033: 0x201c,
- // “
- 0x1034: 0x201d,
- // ”
- 0x1035: 0x2022,
- // •
- 0x1039: 0x2122,
- // ™
- 0x103a: 0x0161,
- // š
- 0x103c: 0x0153,
- // œ
- 0x103d: 0x2120,
- // ℠
- 0x103f: 0x0178,
- // Ÿ
- 0x1076: 0x215b,
- // ⅛
- 0x1077: 0x215c,
- // ⅜
- 0x1078: 0x215d,
- // ⅝
- 0x1079: 0x215e,
- // ⅞
- 0x107a: 0x23d0,
- // ⏐
- 0x107b: 0x23a4,
- // ⎤
- 0x107c: 0x23a3,
- // ⎣
- 0x107d: 0x23af,
- // ⎯
- 0x107e: 0x23a6,
- // ⎦
- 0x107f: 0x23a1,
- // ⎡
- 0x10a0: 0x3138 // ㄸ (CC char)
-
- };
-
- var get708CharFromCode = function get708CharFromCode(code) {
- var newCode = CHARACTER_TRANSLATION_708[code] || code;
-
- if (code & 0x1000 && code === newCode) {
- // Invalid extended code
- return '';
- }
-
- return String.fromCharCode(newCode);
- };
-
- var within708TextBlock = function within708TextBlock(b) {
- return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
- };
-
- var Cea708Window = function Cea708Window(windowNum) {
- this.windowNum = windowNum;
- this.reset();
- };
-
- Cea708Window.prototype.reset = function () {
- this.clearText();
- this.pendingNewLine = false;
- this.winAttr = {};
- this.penAttr = {};
- this.penLoc = {};
- this.penColor = {}; // These default values are arbitrary,
- // defineWindow will usually override them
-
- this.visible = 0;
- this.rowLock = 0;
- this.columnLock = 0;
- this.priority = 0;
- this.relativePositioning = 0;
- this.anchorVertical = 0;
- this.anchorHorizontal = 0;
- this.anchorPoint = 0;
- this.rowCount = 1;
- this.virtualRowCount = this.rowCount + 1;
- this.columnCount = 41;
- this.windowStyle = 0;
- this.penStyle = 0;
- };
-
- Cea708Window.prototype.getText = function () {
- return this.rows.join('\n');
- };
-
- Cea708Window.prototype.clearText = function () {
- this.rows = [''];
- this.rowIdx = 0;
- };
-
- Cea708Window.prototype.newLine = function (pts) {
- if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
- this.beforeRowOverflow(pts);
- }
-
- if (this.rows.length > 0) {
- this.rows.push('');
- this.rowIdx++;
- } // Show all virtual rows since there's no visible scrolling
-
-
- while (this.rows.length > this.virtualRowCount) {
- this.rows.shift();
- this.rowIdx--;
- }
- };
-
- Cea708Window.prototype.isEmpty = function () {
- if (this.rows.length === 0) {
- return true;
- } else if (this.rows.length === 1) {
- return this.rows[0] === '';
- }
-
- return false;
- };
-
- Cea708Window.prototype.addText = function (text) {
- this.rows[this.rowIdx] += text;
- };
-
- Cea708Window.prototype.backspace = function () {
- if (!this.isEmpty()) {
- var row = this.rows[this.rowIdx];
- this.rows[this.rowIdx] = row.substr(0, row.length - 1);
- }
- };
-
- var Cea708Service = function Cea708Service(serviceNum) {
- this.serviceNum = serviceNum;
- this.text = '';
- this.currentWindow = new Cea708Window(-1);
- this.windows = [];
- };
- /**
- * Initialize service windows
- * Must be run before service use
- *
- * @param {Integer} pts PTS value
- * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
- */
-
-
- Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
- this.startPts = pts;
-
- for (var win = 0; win < 8; win++) {
- this.windows[win] = new Cea708Window(win);
-
- if (typeof beforeRowOverflow === 'function') {
- this.windows[win].beforeRowOverflow = beforeRowOverflow;
- }
- }
- };
- /**
- * Set current window of service to be affected by commands
- *
- * @param {Integer} windowNum Window number
- */
-
-
- Cea708Service.prototype.setCurrentWindow = function (windowNum) {
- this.currentWindow = this.windows[windowNum];
- };
-
- var Cea708Stream = function Cea708Stream() {
- Cea708Stream.prototype.init.call(this);
- var self = this;
- this.current708Packet = null;
- this.services = {};
-
- this.push = function (packet) {
- if (packet.type === 3) {
- // 708 packet start
- self.new708Packet();
- self.add708Bytes(packet);
- } else {
- if (self.current708Packet === null) {
- // This should only happen at the start of a file if there's no packet start.
- self.new708Packet();
- }
-
- self.add708Bytes(packet);
- }
- };
- };
-
- Cea708Stream.prototype = new stream();
- /**
- * Push current 708 packet, create new 708 packet.
- */
-
- Cea708Stream.prototype.new708Packet = function () {
- if (this.current708Packet !== null) {
- this.push708Packet();
- }
-
- this.current708Packet = {
- data: [],
- ptsVals: []
- };
- };
- /**
- * Add pts and both bytes from packet into current 708 packet.
- */
-
-
- Cea708Stream.prototype.add708Bytes = function (packet) {
- var data = packet.ccData;
- var byte0 = data >>> 8;
- var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
- // that service blocks will always line up with byte pairs.
-
- this.current708Packet.ptsVals.push(packet.pts);
- this.current708Packet.data.push(byte0);
- this.current708Packet.data.push(byte1);
- };
- /**
- * Parse completed 708 packet into service blocks and push each service block.
- */
-
-
- Cea708Stream.prototype.push708Packet = function () {
- var packet708 = this.current708Packet;
- var packetData = packet708.data;
- var serviceNum = null;
- var blockSize = null;
- var i = 0;
- var b = packetData[i++];
- packet708.seq = b >> 6;
- packet708.sizeCode = b & 0x3f; // 0b00111111;
-
- for (; i < packetData.length; i++) {
- b = packetData[i++];
- serviceNum = b >> 5;
- blockSize = b & 0x1f; // 0b00011111
-
- if (serviceNum === 7 && blockSize > 0) {
- // Extended service num
- b = packetData[i++];
- serviceNum = b;
- }
-
- this.pushServiceBlock(serviceNum, i, blockSize);
-
- if (blockSize > 0) {
- i += blockSize - 1;
- }
- }
- };
- /**
- * Parse service block, execute commands, read text.
- *
- * Note: While many of these commands serve important purposes,
- * many others just parse out the parameters or attributes, but
- * nothing is done with them because this is not a full and complete
- * implementation of the entire 708 spec.
- *
- * @param {Integer} serviceNum Service number
- * @param {Integer} start Start index of the 708 packet data
- * @param {Integer} size Block size
- */
-
-
- Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
- var b;
- var i = start;
- var packetData = this.current708Packet.data;
- var service = this.services[serviceNum];
-
- if (!service) {
- service = this.initService(serviceNum, i);
- }
-
- for (; i < start + size && i < packetData.length; i++) {
- b = packetData[i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service);
- } else if (b === 0x10) {
- i = this.extendedCommands(i, service);
- } else if (0x80 <= b && b <= 0x87) {
- i = this.setCurrentWindow(i, service);
- } else if (0x98 <= b && b <= 0x9f) {
- i = this.defineWindow(i, service);
- } else if (b === 0x88) {
- i = this.clearWindows(i, service);
- } else if (b === 0x8c) {
- i = this.deleteWindows(i, service);
- } else if (b === 0x89) {
- i = this.displayWindows(i, service);
- } else if (b === 0x8a) {
- i = this.hideWindows(i, service);
- } else if (b === 0x8b) {
- i = this.toggleWindows(i, service);
- } else if (b === 0x97) {
- i = this.setWindowAttributes(i, service);
- } else if (b === 0x90) {
- i = this.setPenAttributes(i, service);
- } else if (b === 0x91) {
- i = this.setPenColor(i, service);
- } else if (b === 0x92) {
- i = this.setPenLocation(i, service);
- } else if (b === 0x8f) {
- service = this.reset(i, service);
- } else if (b === 0x08) {
- // BS: Backspace
- service.currentWindow.backspace();
- } else if (b === 0x0c) {
- // FF: Form feed
- service.currentWindow.clearText();
- } else if (b === 0x0d) {
- // CR: Carriage return
- service.currentWindow.pendingNewLine = true;
- } else if (b === 0x0e) {
- // HCR: Horizontal carriage return
- service.currentWindow.clearText();
- } else if (b === 0x8d) {
- // DLY: Delay, nothing to do
- i++;
- } else ;
- }
- };
- /**
- * Execute an extended command
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.extendedCommands = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service, true);
- }
-
- return i;
- };
- /**
- * Get PTS value of a given byte index
- *
- * @param {Integer} byteIndex Index of the byte
- * @return {Integer} PTS
- */
-
-
- Cea708Stream.prototype.getPts = function (byteIndex) {
- // There's 1 pts value per 2 bytes
- return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
- };
- /**
- * Initializes a service
- *
- * @param {Integer} serviceNum Service number
- * @return {Service} Initialized service object
- */
-
-
- Cea708Stream.prototype.initService = function (serviceNum, i) {
- var self = this;
- this.services[serviceNum] = new Cea708Service(serviceNum);
- this.services[serviceNum].init(this.getPts(i), function (pts) {
- self.flushDisplayed(pts, self.services[serviceNum]);
- });
- return this.services[serviceNum];
- };
- /**
- * Execute text writing to current window
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.handleText = function (i, service, isExtended) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var extended = isExtended ? 0x1000 : 0x0000;
- var char = get708CharFromCode(extended | b);
- var win = service.currentWindow;
-
- if (win.pendingNewLine && !win.isEmpty()) {
- win.newLine(this.getPts(i));
- }
-
- win.pendingNewLine = false;
- win.addText(char);
- return i;
- };
- /**
- * Parse and execute the CW# command.
- *
- * Set the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setCurrentWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- return i;
- };
- /**
- * Parse and execute the DF# command.
- *
- * Define a window and set it as the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.defineWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- var win = service.currentWindow;
- b = packetData[++i];
- win.visible = (b & 0x20) >> 5; // v
-
- win.rowLock = (b & 0x10) >> 4; // rl
-
- win.columnLock = (b & 0x08) >> 3; // cl
-
- win.priority = b & 0x07; // p
-
- b = packetData[++i];
- win.relativePositioning = (b & 0x80) >> 7; // rp
-
- win.anchorVertical = b & 0x7f; // av
-
- b = packetData[++i];
- win.anchorHorizontal = b; // ah
-
- b = packetData[++i];
- win.anchorPoint = (b & 0xf0) >> 4; // ap
-
- win.rowCount = b & 0x0f; // rc
-
- b = packetData[++i];
- win.columnCount = b & 0x3f; // cc
-
- b = packetData[++i];
- win.windowStyle = (b & 0x38) >> 3; // ws
-
- win.penStyle = b & 0x07; // ps
- // The spec says there are (rowCount+1) "virtual rows"
-
- win.virtualRowCount = win.rowCount + 1;
- return i;
- };
- /**
- * Parse and execute the SWA command.
- *
- * Set attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setWindowAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var winAttr = service.currentWindow.winAttr;
- b = packetData[++i];
- winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
-
- winAttr.fillRed = (b & 0x30) >> 4; // fr
-
- winAttr.fillGreen = (b & 0x0c) >> 2; // fg
-
- winAttr.fillBlue = b & 0x03; // fb
-
- b = packetData[++i];
- winAttr.borderType = (b & 0xc0) >> 6; // bt
-
- winAttr.borderRed = (b & 0x30) >> 4; // br
-
- winAttr.borderGreen = (b & 0x0c) >> 2; // bg
-
- winAttr.borderBlue = b & 0x03; // bb
-
- b = packetData[++i];
- winAttr.borderType += (b & 0x80) >> 5; // bt
-
- winAttr.wordWrap = (b & 0x40) >> 6; // ww
-
- winAttr.printDirection = (b & 0x30) >> 4; // pd
-
- winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
-
- winAttr.justify = b & 0x03; // j
-
- b = packetData[++i];
- winAttr.effectSpeed = (b & 0xf0) >> 4; // es
-
- winAttr.effectDirection = (b & 0x0c) >> 2; // ed
-
- winAttr.displayEffect = b & 0x03; // de
-
- return i;
- };
- /**
- * Gather text from all displayed windows and push a caption to output.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.flushDisplayed = function (pts, service) {
- var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
- // display text in the correct order, but sample files so far have not shown any issue.
-
- for (var winId = 0; winId < 8; winId++) {
- if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
- displayedText.push(service.windows[winId].getText());
- }
- }
-
- service.endPts = pts;
- service.text = displayedText.join('\n\n');
- this.pushCaption(service);
- service.startPts = pts;
- };
- /**
- * Push a caption to output if the caption contains text.
- *
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.pushCaption = function (service) {
- if (service.text !== '') {
- this.trigger('data', {
- startPts: service.startPts,
- endPts: service.endPts,
- text: service.text,
- stream: 'cc708_' + service.serviceNum
- });
- service.text = '';
- service.startPts = service.endPts;
- }
- };
- /**
- * Parse and execute the DSW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.displayWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the HDW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.hideWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 0;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the TGW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.toggleWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible ^= 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the CLW command.
- *
- * Clear text of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.clearWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].clearText();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the DLW command.
- *
- * Re-initialize windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.deleteWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].reset();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the SPA command.
- *
- * Set pen attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penAttr = service.currentWindow.penAttr;
- b = packetData[++i];
- penAttr.textTag = (b & 0xf0) >> 4; // tt
-
- penAttr.offset = (b & 0x0c) >> 2; // o
-
- penAttr.penSize = b & 0x03; // s
-
- b = packetData[++i];
- penAttr.italics = (b & 0x80) >> 7; // i
-
- penAttr.underline = (b & 0x40) >> 6; // u
-
- penAttr.edgeType = (b & 0x38) >> 3; // et
-
- penAttr.fontStyle = b & 0x07; // fs
-
- return i;
- };
- /**
- * Parse and execute the SPC command.
- *
- * Set pen color of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenColor = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penColor = service.currentWindow.penColor;
- b = packetData[++i];
- penColor.fgOpacity = (b & 0xc0) >> 6; // fo
-
- penColor.fgRed = (b & 0x30) >> 4; // fr
-
- penColor.fgGreen = (b & 0x0c) >> 2; // fg
-
- penColor.fgBlue = b & 0x03; // fb
-
- b = packetData[++i];
- penColor.bgOpacity = (b & 0xc0) >> 6; // bo
-
- penColor.bgRed = (b & 0x30) >> 4; // br
-
- penColor.bgGreen = (b & 0x0c) >> 2; // bg
-
- penColor.bgBlue = b & 0x03; // bb
-
- b = packetData[++i];
- penColor.edgeRed = (b & 0x30) >> 4; // er
-
- penColor.edgeGreen = (b & 0x0c) >> 2; // eg
-
- penColor.edgeBlue = b & 0x03; // eb
-
- return i;
- };
- /**
- * Parse and execute the SPL command.
- *
- * Set pen location of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenLocation = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
-
- service.currentWindow.pendingNewLine = true;
- b = packetData[++i];
- penLoc.row = b & 0x0f; // r
-
- b = packetData[++i];
- penLoc.column = b & 0x3f; // c
-
- return i;
- };
- /**
- * Execute the RST command.
- *
- * Reset service to a clean slate. Re-initialize.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Service} Re-initialized service
- */
-
-
- Cea708Stream.prototype.reset = function (i, service) {
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
- return this.initService(service.serviceNum, i);
- }; // This hash maps non-ASCII, special, and extended character codes to their
- // proper Unicode equivalent. The first keys that are only a single byte
- // are the non-standard ASCII characters, which simply map the CEA608 byte
- // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
- // character codes, but have their MSB bitmasked with 0x03 so that a lookup
- // can be performed regardless of the field and data channel on which the
- // character code was received.
-
-
- var CHARACTER_TRANSLATION = {
- 0x2a: 0xe1,
- // á
- 0x5c: 0xe9,
- // é
- 0x5e: 0xed,
- // í
- 0x5f: 0xf3,
- // ó
- 0x60: 0xfa,
- // ú
- 0x7b: 0xe7,
- // ç
- 0x7c: 0xf7,
- // ÷
- 0x7d: 0xd1,
- // Ñ
- 0x7e: 0xf1,
- // ñ
- 0x7f: 0x2588,
- // █
- 0x0130: 0xae,
- // ®
- 0x0131: 0xb0,
- // °
- 0x0132: 0xbd,
- // ½
- 0x0133: 0xbf,
- // ¿
- 0x0134: 0x2122,
- // ™
- 0x0135: 0xa2,
- // ¢
- 0x0136: 0xa3,
- // £
- 0x0137: 0x266a,
- // ♪
- 0x0138: 0xe0,
- // à
- 0x0139: 0xa0,
- //
- 0x013a: 0xe8,
- // è
- 0x013b: 0xe2,
- // â
- 0x013c: 0xea,
- // ê
- 0x013d: 0xee,
- // î
- 0x013e: 0xf4,
- // ô
- 0x013f: 0xfb,
- // û
- 0x0220: 0xc1,
- // Á
- 0x0221: 0xc9,
- // É
- 0x0222: 0xd3,
- // Ó
- 0x0223: 0xda,
- // Ú
- 0x0224: 0xdc,
- // Ü
- 0x0225: 0xfc,
- // ü
- 0x0226: 0x2018,
- // ‘
- 0x0227: 0xa1,
- // ¡
- 0x0228: 0x2a,
- // *
- 0x0229: 0x27,
- // '
- 0x022a: 0x2014,
- // —
- 0x022b: 0xa9,
- // ©
- 0x022c: 0x2120,
- // ℠
- 0x022d: 0x2022,
- // •
- 0x022e: 0x201c,
- // “
- 0x022f: 0x201d,
- // ”
- 0x0230: 0xc0,
- // À
- 0x0231: 0xc2,
- // Â
- 0x0232: 0xc7,
- // Ç
- 0x0233: 0xc8,
- // È
- 0x0234: 0xca,
- // Ê
- 0x0235: 0xcb,
- // Ë
- 0x0236: 0xeb,
- // ë
- 0x0237: 0xce,
- // Î
- 0x0238: 0xcf,
- // Ï
- 0x0239: 0xef,
- // ï
- 0x023a: 0xd4,
- // Ô
- 0x023b: 0xd9,
- // Ù
- 0x023c: 0xf9,
- // ù
- 0x023d: 0xdb,
- // Û
- 0x023e: 0xab,
- // «
- 0x023f: 0xbb,
- // »
- 0x0320: 0xc3,
- // Ã
- 0x0321: 0xe3,
- // ã
- 0x0322: 0xcd,
- // Í
- 0x0323: 0xcc,
- // Ì
- 0x0324: 0xec,
- // ì
- 0x0325: 0xd2,
- // Ò
- 0x0326: 0xf2,
- // ò
- 0x0327: 0xd5,
- // Õ
- 0x0328: 0xf5,
- // õ
- 0x0329: 0x7b,
- // {
- 0x032a: 0x7d,
- // }
- 0x032b: 0x5c,
- // \
- 0x032c: 0x5e,
- // ^
- 0x032d: 0x5f,
- // _
- 0x032e: 0x7c,
- // |
- 0x032f: 0x7e,
- // ~
- 0x0330: 0xc4,
- // Ä
- 0x0331: 0xe4,
- // ä
- 0x0332: 0xd6,
- // Ö
- 0x0333: 0xf6,
- // ö
- 0x0334: 0xdf,
- // ß
- 0x0335: 0xa5,
- // ¥
- 0x0336: 0xa4,
- // ¤
- 0x0337: 0x2502,
- // │
- 0x0338: 0xc5,
- // Å
- 0x0339: 0xe5,
- // å
- 0x033a: 0xd8,
- // Ø
- 0x033b: 0xf8,
- // ø
- 0x033c: 0x250c,
- // ┌
- 0x033d: 0x2510,
- // ┐
- 0x033e: 0x2514,
- // └
- 0x033f: 0x2518 // ┘
-
- };
-
- var getCharFromCode = function getCharFromCode(code) {
- if (code === null) {
- return '';
- }
-
- code = CHARACTER_TRANSLATION[code] || code;
- return String.fromCharCode(code);
- }; // the index of the last row in a CEA-608 display buffer
-
-
- var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
- // getting it through bit logic.
-
- var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // CEA-608 captions are rendered onto a 34x15 matrix of character
- // cells. The "bottom" row is the last element in the outer array.
-
- var createDisplayBuffer = function createDisplayBuffer() {
- var result = [],
- i = BOTTOM_ROW + 1;
-
- while (i--) {
- result.push('');
- }
-
- return result;
- };
-
- var Cea608Stream = function Cea608Stream(field, dataChannel) {
- Cea608Stream.prototype.init.call(this);
- this.field_ = field || 0;
- this.dataChannel_ = dataChannel || 0;
- this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
- this.setConstants();
- this.reset();
-
- this.push = function (packet) {
- var data, swap, char0, char1, text; // remove the parity bits
-
- data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
-
- if (data === this.lastControlCode_) {
- this.lastControlCode_ = null;
- return;
- } // Store control codes
-
-
- if ((data & 0xf000) === 0x1000) {
- this.lastControlCode_ = data;
- } else if (data !== this.PADDING_) {
- this.lastControlCode_ = null;
- }
-
- char0 = data >>> 8;
- char1 = data & 0xff;
-
- if (data === this.PADDING_) {
- return;
- } else if (data === this.RESUME_CAPTION_LOADING_) {
- this.mode_ = 'popOn';
- } else if (data === this.END_OF_CAPTION_) {
- // If an EOC is received while in paint-on mode, the displayed caption
- // text should be swapped to non-displayed memory as if it was a pop-on
- // caption. Because of that, we should explicitly switch back to pop-on
- // mode
- this.mode_ = 'popOn';
- this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
-
- this.flushDisplayed(packet.pts); // flip memory
-
- swap = this.displayed_;
- this.displayed_ = this.nonDisplayed_;
- this.nonDisplayed_ = swap; // start measuring the time to display the caption
-
- this.startPts_ = packet.pts;
- } else if (data === this.ROLL_UP_2_ROWS_) {
- this.rollUpRows_ = 2;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_3_ROWS_) {
- this.rollUpRows_ = 3;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_4_ROWS_) {
- this.rollUpRows_ = 4;
- this.setRollUp(packet.pts);
- } else if (data === this.CARRIAGE_RETURN_) {
- this.clearFormatting(packet.pts);
- this.flushDisplayed(packet.pts);
- this.shiftRowsUp_();
- this.startPts_ = packet.pts;
- } else if (data === this.BACKSPACE_) {
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- }
- } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
- this.nonDisplayed_ = createDisplayBuffer();
- } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
- if (this.mode_ !== 'paintOn') {
- // NOTE: This should be removed when proper caption positioning is
- // implemented
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- }
-
- this.mode_ = 'paintOn';
- this.startPts_ = packet.pts; // Append special characters to caption text
- } else if (this.isSpecialCharacter(char0, char1)) {
- // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Append extended characters to caption text
- } else if (this.isExtCharacter(char0, char1)) {
- // Extended characters always follow their "non-extended" equivalents.
- // IE if a "è" is desired, you'll always receive "eè"; non-compliant
- // decoders are supposed to drop the "è", while compliant decoders
- // backspace the "e" and insert "è".
- // Delete the previous character
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- } // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
-
-
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Process mid-row codes
- } else if (this.isMidRowCode(char0, char1)) {
- // Attributes are not additive, so clear all formatting
- this.clearFormatting(packet.pts); // According to the standard, mid-row codes
- // should be replaced with spaces, so add one now
-
- this[this.mode_](packet.pts, ' ');
- this.column_++;
-
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
-
- if ((char1 & 0x1) === 0x1) {
- this.addFormatting(packet.pts, ['u']);
- } // Detect offset control codes and adjust cursor
-
- } else if (this.isOffsetControlCode(char0, char1)) {
- // Cursor position is set by indent PAC (see below) in 4-column
- // increments, with an additional offset code of 1-3 to reach any
- // of the 32 columns specified by CEA-608. So all we need to do
- // here is increment the column cursor by the given offset.
- this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
- } else if (this.isPAC(char0, char1)) {
- // There's no logic for PAC -> row mapping, so we have to just
- // find the row code in an array and use its index :(
- var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
-
- if (this.mode_ === 'rollUp') {
- // This implies that the base row is incorrectly set.
- // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
- // of roll-up rows set.
- if (row - this.rollUpRows_ + 1 < 0) {
- row = this.rollUpRows_ - 1;
- }
-
- this.setRollUp(packet.pts, row);
- }
-
- if (row !== this.row_) {
- // formatting is only persistent for current row
- this.clearFormatting(packet.pts);
- this.row_ = row;
- } // All PACs can apply underline, so detect and apply
- // (All odd-numbered second bytes set underline)
-
-
- if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
- this.addFormatting(packet.pts, ['u']);
- }
-
- if ((data & 0x10) === 0x10) {
- // We've got an indent level code. Each successive even number
- // increments the column cursor by 4, so we can get the desired
- // column position by bit-shifting to the right (to get n/2)
- // and multiplying by 4.
- this.column_ = ((data & 0xe) >> 1) * 4;
- }
-
- if (this.isColorPAC(char1)) {
- // it's a color code, though we only support white, which
- // can be either normal or italicized. white italics can be
- // either 0x4e or 0x6e depending on the row, so we just
- // bitwise-and with 0xe to see if italics should be turned on
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
- } // We have a normal character in char0, and possibly one in char1
-
- } else if (this.isNormalChar(char0)) {
- if (char1 === 0x00) {
- char1 = null;
- }
-
- text = getCharFromCode(char0);
- text += getCharFromCode(char1);
- this[this.mode_](packet.pts, text);
- this.column_ += text.length;
- } // finish data processing
-
- };
- };
-
- Cea608Stream.prototype = new stream(); // Trigger a cue point that captures the current state of the
- // display buffer
-
- Cea608Stream.prototype.flushDisplayed = function (pts) {
- var content = this.displayed_ // remove spaces from the start and end of the string
- .map(function (row) {
- try {
- return row.trim();
- } catch (e) {
- // Ordinarily, this shouldn't happen. However, caption
- // parsing errors should not throw exceptions and
- // break playback.
- // eslint-disable-next-line no-console
- console.error('Skipping malformed caption.');
- return '';
- }
- }) // combine all text rows to display in one cue
- .join('\n') // and remove blank rows from the start and end, but not the middle
- .replace(/^\n+|\n+$/g, '');
-
- if (content.length) {
- this.trigger('data', {
- startPts: this.startPts_,
- endPts: pts,
- text: content,
- stream: this.name_
- });
- }
- };
- /**
- * Zero out the data, used for startup and on seek
- */
-
-
- Cea608Stream.prototype.reset = function () {
- this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
- // actually display captions. If a caption is shifted to a row
- // with a lower index than this, it is cleared from the display
- // buffer
-
- this.topRow_ = 0;
- this.startPts_ = 0;
- this.displayed_ = createDisplayBuffer();
- this.nonDisplayed_ = createDisplayBuffer();
- this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
-
- this.column_ = 0;
- this.row_ = BOTTOM_ROW;
- this.rollUpRows_ = 2; // This variable holds currently-applied formatting
-
- this.formatting_ = [];
- };
- /**
- * Sets up control code and related constants for this instance
- */
-
-
- Cea608Stream.prototype.setConstants = function () {
- // The following attributes have these uses:
- // ext_ : char0 for mid-row codes, and the base for extended
- // chars (ext_+0, ext_+1, and ext_+2 are char0s for
- // extended codes)
- // control_: char0 for control codes, except byte-shifted to the
- // left so that we can do this.control_ | CONTROL_CODE
- // offset_: char0 for tab offset codes
- //
- // It's also worth noting that control codes, and _only_ control codes,
- // differ between field 1 and field2. Field 2 control codes are always
- // their field 1 value plus 1. That's why there's the "| field" on the
- // control value.
- if (this.dataChannel_ === 0) {
- this.BASE_ = 0x10;
- this.EXT_ = 0x11;
- this.CONTROL_ = (0x14 | this.field_) << 8;
- this.OFFSET_ = 0x17;
- } else if (this.dataChannel_ === 1) {
- this.BASE_ = 0x18;
- this.EXT_ = 0x19;
- this.CONTROL_ = (0x1c | this.field_) << 8;
- this.OFFSET_ = 0x1f;
- } // Constants for the LSByte command codes recognized by Cea608Stream. This
- // list is not exhaustive. For a more comprehensive listing and semantics see
- // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
- // Padding
-
-
- this.PADDING_ = 0x0000; // Pop-on Mode
-
- this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
- this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
-
- this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
- this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
- this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
- this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
-
- this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
-
- this.BACKSPACE_ = this.CONTROL_ | 0x21;
- this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
- this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
- };
- /**
- * Detects if the 2-byte packet data is a special character
- *
- * Special characters have a second byte in the range 0x30 to 0x3f,
- * with the first byte being 0x11 (for data channel 1) or 0x19 (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an special character
- */
-
-
- Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet data is an extended character
- *
- * Extended characters have a second byte in the range 0x20 to 0x3f,
- * with the first byte being 0x12 or 0x13 (for data channel 1) or
- * 0x1a or 0x1b (for data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an extended character
- */
-
-
- Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
- return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet is a mid-row code
- *
- * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
- * the first byte being 0x11 (for data channel 1) or 0x19 (for data
- * channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a mid-row code
- */
-
-
- Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
- };
- /**
- * Detects if the 2-byte packet is an offset control code
- *
- * Offset control codes have a second byte in the range 0x21 to 0x23,
- * with the first byte being 0x17 (for data channel 1) or 0x1f (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an offset control code
- */
-
-
- Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
- return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
- };
- /**
- * Detects if the 2-byte packet is a Preamble Address Code
- *
- * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
- * or 0x18 to 0x1f (for data channel 2), with the second byte in the
- * range 0x40 to 0x7f.
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a PAC
- */
-
-
- Cea608Stream.prototype.isPAC = function (char0, char1) {
- return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
- };
- /**
- * Detects if a packet's second byte is in the range of a PAC color code
- *
- * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
- * 0x60 to 0x6f.
- *
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the byte is a color PAC
- */
-
-
- Cea608Stream.prototype.isColorPAC = function (char1) {
- return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
- };
- /**
- * Detects if a single byte is in the range of a normal character
- *
- * Normal text bytes are in the range 0x20 to 0x7f.
- *
- * @param {Integer} char The byte
- * @return {Boolean} Whether the byte is a normal character
- */
-
-
- Cea608Stream.prototype.isNormalChar = function (char) {
- return char >= 0x20 && char <= 0x7f;
- };
- /**
- * Configures roll-up
- *
- * @param {Integer} pts Current PTS
- * @param {Integer} newBaseRow Used by PACs to slide the current window to
- * a new position
- */
-
-
- Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
- // Reset the base row to the bottom row when switching modes
- if (this.mode_ !== 'rollUp') {
- this.row_ = BOTTOM_ROW;
- this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
-
- this.flushDisplayed(pts);
- this.nonDisplayed_ = createDisplayBuffer();
- this.displayed_ = createDisplayBuffer();
- }
-
- if (newBaseRow !== undefined && newBaseRow !== this.row_) {
- // move currently displayed captions (up or down) to the new base row
- for (var i = 0; i < this.rollUpRows_; i++) {
- this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
- this.displayed_[this.row_ - i] = '';
- }
- }
-
- if (newBaseRow === undefined) {
- newBaseRow = this.row_;
- }
-
- this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
- }; // Adds the opening HTML tag for the passed character to the caption text,
- // and keeps track of it for later closing
-
-
- Cea608Stream.prototype.addFormatting = function (pts, format) {
- this.formatting_ = this.formatting_.concat(format);
- var text = format.reduce(function (text, format) {
- return text + '<' + format + '>';
- }, '');
- this[this.mode_](pts, text);
- }; // Adds HTML closing tags for current formatting to caption text and
- // clears remembered formatting
-
-
- Cea608Stream.prototype.clearFormatting = function (pts) {
- if (!this.formatting_.length) {
- return;
- }
-
- var text = this.formatting_.reverse().reduce(function (text, format) {
- return text + '' + format + '>';
- }, '');
- this.formatting_ = [];
- this[this.mode_](pts, text);
- }; // Mode Implementations
-
-
- Cea608Stream.prototype.popOn = function (pts, text) {
- var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
-
- baseRow += text;
- this.nonDisplayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.rollUp = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.shiftRowsUp_ = function () {
- var i; // clear out inactive rows
-
- for (i = 0; i < this.topRow_; i++) {
- this.displayed_[i] = '';
- }
-
- for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
- this.displayed_[i] = '';
- } // shift displayed rows up
-
-
- for (i = this.topRow_; i < this.row_; i++) {
- this.displayed_[i] = this.displayed_[i + 1];
- } // clear out the bottom row
-
-
- this.displayed_[this.row_] = '';
- };
-
- Cea608Stream.prototype.paintOn = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- }; // exports
-
-
- var captionStream = {
- CaptionStream: CaptionStream$1,
- Cea608Stream: Cea608Stream,
- Cea708Stream: Cea708Stream
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var streamTypes = {
- H264_STREAM_TYPE: 0x1B,
- ADTS_STREAM_TYPE: 0x0F,
- METADATA_STREAM_TYPE: 0x15
- };
- var MAX_TS = 8589934592;
- var RO_THRESH = 4294967296;
- var TYPE_SHARED = 'shared';
-
- var handleRollover$1 = function handleRollover(value, reference) {
- var direction = 1;
-
- if (value > reference) {
- // If the current timestamp value is greater than our reference timestamp and we detect a
- // timestamp rollover, this means the roll over is happening in the opposite direction.
- // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
- // point will be set to a small number, e.g. 1. The user then seeks backwards over the
- // rollover point. In loading this segment, the timestamp values will be very large,
- // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
- // the time stamp to be `value - 2^33`.
- direction = -1;
- } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
- // cause an incorrect adjustment.
-
-
- while (Math.abs(reference - value) > RO_THRESH) {
- value += direction * MAX_TS;
- }
-
- return value;
- };
-
- var TimestampRolloverStream$1 = function TimestampRolloverStream(type) {
- var lastDTS, referenceDTS;
- TimestampRolloverStream.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
- // video and audio. We could use `undefined` here, but having a string
- // makes debugging a little clearer.
-
- this.type_ = type || TYPE_SHARED;
-
- this.push = function (data) {
- // Any "shared" rollover streams will accept _all_ data. Otherwise,
- // streams will only accept data that matches their type.
- if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
- return;
- }
-
- if (referenceDTS === undefined) {
- referenceDTS = data.dts;
- }
-
- data.dts = handleRollover$1(data.dts, referenceDTS);
- data.pts = handleRollover$1(data.pts, referenceDTS);
- lastDTS = data.dts;
- this.trigger('data', data);
- };
-
- this.flush = function () {
- referenceDTS = lastDTS;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.discontinuity = function () {
- referenceDTS = void 0;
- lastDTS = void 0;
- };
-
- this.reset = function () {
- this.discontinuity();
- this.trigger('reset');
- };
- };
-
- TimestampRolloverStream$1.prototype = new stream();
- var timestampRolloverStream = {
- TimestampRolloverStream: TimestampRolloverStream$1,
- handleRollover: handleRollover$1
- };
-
- var percentEncode$1 = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- },
- // return the string representation of the specified byte range,
- // interpreted as UTf-8.
- parseUtf8 = function parseUtf8(bytes, start, end) {
- return decodeURIComponent(percentEncode$1(bytes, start, end));
- },
- // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
- parseIso88591$1 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
- },
- parseSyncSafeInteger$1 = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- },
- tagParsers = {
- TXXX: function TXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the text fields
- tag.description = parseUtf8(tag.data, 1, i); // do not include the null terminator in the tag value
-
- tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
- break;
- }
- }
-
- tag.data = tag.value;
- },
- WXXX: function WXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.description = parseUtf8(tag.data, 1, i);
- tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
- break;
- }
- }
- },
- PRIV: function PRIV(tag) {
- var i;
-
- for (i = 0; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.owner = parseIso88591$1(tag.data, 0, i);
- break;
- }
- }
-
- tag.privateData = tag.data.subarray(i + 1);
- tag.data = tag.privateData;
- }
- },
- _MetadataStream;
-
- _MetadataStream = function MetadataStream(options) {
- var settings = {
- debug: !!(options && options.debug),
- // the bytes of the program-level descriptor field in MP2T
- // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
- // program element descriptors"
- descriptor: options && options.descriptor
- },
- // the total size in bytes of the ID3 tag being parsed
- tagSize = 0,
- // tag data that is not complete enough to be parsed
- buffer = [],
- // the total number of bytes currently in the buffer
- bufferSize = 0,
- i;
-
- _MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
- // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
-
-
- this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
-
- if (settings.descriptor) {
- for (i = 0; i < settings.descriptor.length; i++) {
- this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
- }
- }
-
- this.push = function (chunk) {
- var tag, frameStart, frameSize, frame, i, frameHeader;
-
- if (chunk.type !== 'timed-metadata') {
- return;
- } // if data_alignment_indicator is set in the PES header,
- // we must have the start of a new ID3 tag. Assume anything
- // remaining in the buffer was malformed and throw it out
-
-
- if (chunk.dataAlignmentIndicator) {
- bufferSize = 0;
- buffer.length = 0;
- } // ignore events that don't look like ID3 data
-
-
- if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) {
- if (settings.debug) {
- // eslint-disable-next-line no-console
- console.log('Skipping unrecognized metadata packet');
- }
-
- return;
- } // add this chunk to the data we've collected so far
-
-
- buffer.push(chunk);
- bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
-
- if (buffer.length === 1) {
- // the frame size is transmitted as a 28-bit integer in the
- // last four bytes of the ID3 header.
- // The most significant bit of each byte is dropped and the
- // results concatenated to recover the actual value.
- tagSize = parseSyncSafeInteger$1(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
- // convenient for our comparisons to include it
-
- tagSize += 10;
- } // if the entire frame has not arrived, wait for more data
-
-
- if (bufferSize < tagSize) {
- return;
- } // collect the entire frame so it can be parsed
-
-
- tag = {
- data: new Uint8Array(tagSize),
- frames: [],
- pts: buffer[0].pts,
- dts: buffer[0].dts
- };
-
- for (i = 0; i < tagSize;) {
- tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
- i += buffer[0].data.byteLength;
- bufferSize -= buffer[0].data.byteLength;
- buffer.shift();
- } // find the start of the first frame and the end of the tag
-
-
- frameStart = 10;
-
- if (tag.data[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger$1(tag.data.subarray(10, 14)); // clip any padding off the end
-
- tagSize -= parseSyncSafeInteger$1(tag.data.subarray(16, 20));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger$1(tag.data.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- // eslint-disable-next-line no-console
- return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
- }
-
- frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
- frame = {
- id: frameHeader,
- data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
- };
- frame.key = frame.id;
-
- if (tagParsers[frame.id]) {
- tagParsers[frame.id](frame); // handle the special PRIV frame used to indicate the start
- // time for raw AAC data
-
- if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.data,
- size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
- // on the value of this frame
- // we couldn't have known the appropriate pts and dts before
- // parsing this ID3 tag so set those values now
-
- if (tag.pts === undefined && tag.dts === undefined) {
- tag.pts = frame.timeStamp;
- tag.dts = frame.timeStamp;
- }
-
- this.trigger('timestamp', frame);
- }
- }
-
- tag.frames.push(frame);
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < tagSize);
-
- this.trigger('data', tag);
- };
- };
-
- _MetadataStream.prototype = new stream();
- var metadataStream = _MetadataStream;
- var TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
-
- var _TransportPacketStream, _TransportParseStream, _ElementaryStream; // constants
-
-
- var MP2T_PACKET_LENGTH$1 = 188,
- // bytes
- SYNC_BYTE$1 = 0x47;
- /**
- * Splits an incoming stream of binary data into MPEG-2 Transport
- * Stream packets.
- */
-
- _TransportPacketStream = function TransportPacketStream() {
- var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
- bytesInBuffer = 0;
-
- _TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
-
- /**
- * Split a stream of data into M2TS packets
- **/
-
-
- this.push = function (bytes) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH$1,
- everything; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (bytesInBuffer) {
- everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
- everything.set(buffer.subarray(0, bytesInBuffer));
- everything.set(bytes, bytesInBuffer);
- bytesInBuffer = 0;
- } else {
- everything = bytes;
- } // While we have enough data for a packet
-
-
- while (endIndex < everything.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
- // We found a packet so emit it and jump one whole packet forward in
- // the stream
- this.trigger('data', everything.subarray(startIndex, endIndex));
- startIndex += MP2T_PACKET_LENGTH$1;
- endIndex += MP2T_PACKET_LENGTH$1;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // If there was some data left over at the end of the segment that couldn't
- // possibly be a whole packet, keep it because it might be the start of a packet
- // that continues in the next segment
-
-
- if (startIndex < everything.byteLength) {
- buffer.set(everything.subarray(startIndex), 0);
- bytesInBuffer = everything.byteLength - startIndex;
- }
- };
- /**
- * Passes identified M2TS packets to the TransportParseStream to be parsed
- **/
-
-
- this.flush = function () {
- // If the buffer contains a whole packet when we are being flushed, emit it
- // and empty the buffer. Otherwise hold onto the data because it may be
- // important for decoding the next segment
- if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
- this.trigger('data', buffer);
- bytesInBuffer = 0;
- }
-
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.reset = function () {
- bytesInBuffer = 0;
- this.trigger('reset');
- };
- };
-
- _TransportPacketStream.prototype = new stream();
- /**
- * Accepts an MP2T TransportPacketStream and emits data events with parsed
- * forms of the individual transport stream packets.
- */
-
- _TransportParseStream = function TransportParseStream() {
- var parsePsi, parsePat, parsePmt, self;
-
- _TransportParseStream.prototype.init.call(this);
-
- self = this;
- this.packetsWaitingForPmt = [];
- this.programMapTable = undefined;
-
- parsePsi = function parsePsi(payload, psi) {
- var offset = 0; // PSI packets may be split into multiple sections and those
- // sections may be split into multiple packets. If a PSI
- // section starts in this packet, the payload_unit_start_indicator
- // will be true and the first byte of the payload will indicate
- // the offset from the current position to the start of the
- // section.
-
- if (psi.payloadUnitStartIndicator) {
- offset += payload[offset] + 1;
- }
-
- if (psi.type === 'pat') {
- parsePat(payload.subarray(offset), psi);
- } else {
- parsePmt(payload.subarray(offset), psi);
- }
- };
-
- parsePat = function parsePat(payload, pat) {
- pat.section_number = payload[7]; // eslint-disable-line camelcase
-
- pat.last_section_number = payload[8]; // eslint-disable-line camelcase
- // skip the PSI header and parse the first PMT entry
-
- self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
- pat.pmtPid = self.pmtPid;
- };
- /**
- * Parse out the relevant fields of a Program Map Table (PMT).
- * @param payload {Uint8Array} the PMT-specific portion of an MP2T
- * packet. The first byte in this array should be the table_id
- * field.
- * @param pmt {object} the object that should be decorated with
- * fields parsed from the PMT.
- */
-
-
- parsePmt = function parsePmt(payload, pmt) {
- var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
- // take effect. We don't believe this should ever be the case
- // for HLS but we'll ignore "forward" PMT declarations if we see
- // them. Future PMT declarations have the current_next_indicator
- // set to zero.
-
- if (!(payload[5] & 0x01)) {
- return;
- } // overwrite any existing program map table
-
-
- self.programMapTable = {
- video: null,
- audio: null,
- 'timed-metadata': {}
- }; // the mapping table ends at the end of the current section
-
- sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
- tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
- // long the program info descriptors are
-
- programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
-
- offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- var streamType = payload[offset];
- var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
- // TODO: should this be done for metadata too? for now maintain behavior of
- // multiple metadata streams
-
- if (streamType === streamTypes.H264_STREAM_TYPE && self.programMapTable.video === null) {
- self.programMapTable.video = pid;
- } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
- self.programMapTable.audio = pid;
- } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
- // map pid to stream type for metadata streams
- self.programMapTable['timed-metadata'][pid] = streamType;
- } // move to the next table entry
- // skip past the elementary stream descriptors, if present
-
-
- offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
- } // record the map on the packet as well
-
-
- pmt.programMapTable = self.programMapTable;
- };
- /**
- * Deliver a new MP2T packet to the next stream in the pipeline.
- */
-
-
- this.push = function (packet) {
- var result = {},
- offset = 4;
- result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
-
- result.pid = packet[1] & 0x1f;
- result.pid <<= 8;
- result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
- // fifth byte of the TS packet header. The adaptation field is
- // used to add stuffing to PES packets that don't fill a complete
- // TS packet, and to specify some forms of timing and control data
- // that we do not currently use.
-
- if ((packet[3] & 0x30) >>> 4 > 0x01) {
- offset += packet[offset] + 1;
- } // parse the rest of the packet based on the type
-
-
- if (result.pid === 0) {
- result.type = 'pat';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result);
- } else if (result.pid === this.pmtPid) {
- result.type = 'pmt';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
-
- while (this.packetsWaitingForPmt.length) {
- this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
- }
- } else if (this.programMapTable === undefined) {
- // When we have not seen a PMT yet, defer further processing of
- // PES packets until one has been parsed
- this.packetsWaitingForPmt.push([packet, offset, result]);
- } else {
- this.processPes_(packet, offset, result);
- }
- };
-
- this.processPes_ = function (packet, offset, result) {
- // set the appropriate stream type
- if (result.pid === this.programMapTable.video) {
- result.streamType = streamTypes.H264_STREAM_TYPE;
- } else if (result.pid === this.programMapTable.audio) {
- result.streamType = streamTypes.ADTS_STREAM_TYPE;
- } else {
- // if not video or audio, it is timed-metadata or unknown
- // if unknown, streamType will be undefined
- result.streamType = this.programMapTable['timed-metadata'][result.pid];
- }
-
- result.type = 'pes';
- result.data = packet.subarray(offset);
- this.trigger('data', result);
- };
- };
-
- _TransportParseStream.prototype = new stream();
- _TransportParseStream.STREAM_TYPES = {
- h264: 0x1b,
- adts: 0x0f
- };
- /**
- * Reconsistutes program elementary stream (PES) packets from parsed
- * transport stream packets. That is, if you pipe an
- * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
- * events will be events which capture the bytes for individual PES
- * packets plus relevant metadata that has been extracted from the
- * container.
- */
-
- _ElementaryStream = function ElementaryStream() {
- var self = this,
- // PES packet fragments
- video = {
- data: [],
- size: 0
- },
- audio = {
- data: [],
- size: 0
- },
- timedMetadata = {
- data: [],
- size: 0
- },
- programMapTable,
- parsePes = function parsePes(payload, pes) {
- var ptsDtsFlags;
- var startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
-
- pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
- // that are frame data that is continuing from the previous fragment. This
- // is to check that the pes data is the start of a new pes payload
-
- if (startPrefix !== 1) {
- return;
- } // get the packet length, this will be 0 for video
-
-
- pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
-
- pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
- // and a DTS value. Determine what combination of values is
- // available to work with.
-
- ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
- // performs all bitwise operations on 32-bit integers but javascript
- // supports a much greater range (52-bits) of integer using standard
- // mathematical operations.
- // We construct a 31-bit value using bitwise operators over the 31
- // most significant bits and then multiply by 4 (equal to a left-shift
- // of 2) before we add the final 2 least significant bits of the
- // timestamp (equal to an OR.)
-
- if (ptsDtsFlags & 0xC0) {
- // the PTS and DTS are not written out directly. For information
- // on how they are encoded, see
- // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
- pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
- pes.pts *= 4; // Left shift by 2
-
- pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
-
- pes.dts = pes.pts;
-
- if (ptsDtsFlags & 0x40) {
- pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
- pes.dts *= 4; // Left shift by 2
-
- pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
- }
- } // the data section starts immediately after the PES header.
- // pes_header_data_length specifies the number of header bytes
- // that follow the last byte of the field.
-
-
- pes.data = payload.subarray(9 + payload[8]);
- },
-
- /**
- * Pass completely parsed PES packets to the next stream in the pipeline
- **/
- flushStream = function flushStream(stream, type, forceFlush) {
- var packetData = new Uint8Array(stream.size),
- event = {
- type: type
- },
- i = 0,
- offset = 0,
- packetFlushable = false,
- fragment; // do nothing if there is not enough buffered data for a complete
- // PES header
-
- if (!stream.data.length || stream.size < 9) {
- return;
- }
-
- event.trackId = stream.data[0].pid; // reassemble the packet
-
- for (i = 0; i < stream.data.length; i++) {
- fragment = stream.data[i];
- packetData.set(fragment.data, offset);
- offset += fragment.data.byteLength;
- } // parse assembled packet's PES header
-
-
- parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
- // check that there is enough stream data to fill the packet
-
- packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
-
- if (forceFlush || packetFlushable) {
- stream.size = 0;
- stream.data.length = 0;
- } // only emit packets that are complete. this is to avoid assembling
- // incomplete PES packets due to poor segmentation
-
-
- if (packetFlushable) {
- self.trigger('data', event);
- }
- };
-
- _ElementaryStream.prototype.init.call(this);
- /**
- * Identifies M2TS packet types and parses PES packets using metadata
- * parsed from the PMT
- **/
-
-
- this.push = function (data) {
- ({
- pat: function pat() {// we have to wait for the PMT to arrive as well before we
- // have any meaningful metadata
- },
- pes: function pes() {
- var stream, streamType;
-
- switch (data.streamType) {
- case streamTypes.H264_STREAM_TYPE:
- stream = video;
- streamType = 'video';
- break;
-
- case streamTypes.ADTS_STREAM_TYPE:
- stream = audio;
- streamType = 'audio';
- break;
-
- case streamTypes.METADATA_STREAM_TYPE:
- stream = timedMetadata;
- streamType = 'timed-metadata';
- break;
-
- default:
- // ignore unknown stream types
- return;
- } // if a new packet is starting, we can flush the completed
- // packet
-
-
- if (data.payloadUnitStartIndicator) {
- flushStream(stream, streamType, true);
- } // buffer this fragment until we are sure we've received the
- // complete payload
-
-
- stream.data.push(data);
- stream.size += data.data.byteLength;
- },
- pmt: function pmt() {
- var event = {
- type: 'metadata',
- tracks: []
- };
- programMapTable = data.programMapTable; // translate audio and video streams to tracks
-
- if (programMapTable.video !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.video,
- codec: 'avc',
- type: 'video'
- });
- }
-
- if (programMapTable.audio !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.audio,
- codec: 'adts',
- type: 'audio'
- });
- }
-
- self.trigger('data', event);
- }
- })[data.type]();
- };
-
- this.reset = function () {
- video.size = 0;
- video.data.length = 0;
- audio.size = 0;
- audio.data.length = 0;
- this.trigger('reset');
- };
- /**
- * Flush any remaining input. Video PES packets may be of variable
- * length. Normally, the start of a new video packet can trigger the
- * finalization of the previous packet. That is not possible if no
- * more video is forthcoming, however. In that case, some other
- * mechanism (like the end of the file) has to be employed. When it is
- * clear that no additional data is forthcoming, calling this method
- * will flush the buffered packets.
- */
-
-
- this.flushStreams_ = function () {
- // !!THIS ORDER IS IMPORTANT!!
- // video first then audio
- flushStream(video, 'video');
- flushStream(audio, 'audio');
- flushStream(timedMetadata, 'timed-metadata');
- };
-
- this.flush = function () {
- this.flushStreams_();
- this.trigger('done');
- };
- };
-
- _ElementaryStream.prototype = new stream();
- var m2ts = {
- PAT_PID: 0x0000,
- MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
- TransportPacketStream: _TransportPacketStream,
- TransportParseStream: _TransportParseStream,
- ElementaryStream: _ElementaryStream,
- TimestampRolloverStream: TimestampRolloverStream,
- CaptionStream: captionStream.CaptionStream,
- Cea608Stream: captionStream.Cea608Stream,
- Cea708Stream: captionStream.Cea708Stream,
- MetadataStream: metadataStream
- };
-
- for (var type in streamTypes) {
- if (streamTypes.hasOwnProperty(type)) {
- m2ts[type] = streamTypes[type];
- }
- }
-
- var m2ts_1 = m2ts;
- var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
-
- var _AdtsStream;
-
- var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
- /*
- * Accepts a ElementaryStream and emits data events with parsed
- * AAC Audio Frames of the individual packets. Input audio in ADTS
- * format is unpacked and re-emitted as AAC frames.
- *
- * @see http://wiki.multimedia.cx/index.php?title=ADTS
- * @see http://wiki.multimedia.cx/?title=Understanding_AAC
- */
-
- _AdtsStream = function AdtsStream(handlePartialSegments) {
- var buffer,
- frameNum = 0;
-
- _AdtsStream.prototype.init.call(this);
-
- this.push = function (packet) {
- var i = 0,
- frameLength,
- protectionSkipBytes,
- frameEnd,
- oldBuffer,
- sampleCount,
- adtsFrameDuration;
-
- if (!handlePartialSegments) {
- frameNum = 0;
- }
-
- if (packet.type !== 'audio') {
- // ignore non-audio data
- return;
- } // Prepend any data in the buffer to the input data so that we can parse
- // aac frames the cross a PES packet boundary
-
-
- if (buffer) {
- oldBuffer = buffer;
- buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
- buffer.set(oldBuffer);
- buffer.set(packet.data, oldBuffer.byteLength);
- } else {
- buffer = packet.data;
- } // unpack any ADTS frames which have been fully received
- // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
-
-
- while (i + 5 < buffer.length) {
- // Look for the start of an ADTS header..
- if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- } // The protection skip bit tells us if we have 2 bytes of CRC data at the
- // end of the ADTS header
-
-
- protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
- // end of the sync sequence
-
- frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
- sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
- adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2];
- frameEnd = i + frameLength; // If we don't have enough data to actually finish this ADTS frame, return
- // and wait for more data
-
- if (buffer.byteLength < frameEnd) {
- return;
- } // Otherwise, deliver the complete AAC frame
-
-
- this.trigger('data', {
- pts: packet.pts + frameNum * adtsFrameDuration,
- dts: packet.dts + frameNum * adtsFrameDuration,
- sampleCount: sampleCount,
- audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
- channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
- samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
- samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
- // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
- samplesize: 16,
- data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
- });
- frameNum++; // If the buffer is empty, clear it and return
-
- if (buffer.byteLength === frameEnd) {
- buffer = undefined;
- return;
- } // Remove the finished frame from the buffer and start the process again
-
-
- buffer = buffer.subarray(frameEnd);
- }
- };
-
- this.flush = function () {
- frameNum = 0;
- this.trigger('done');
- };
-
- this.reset = function () {
- buffer = void 0;
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- buffer = void 0;
- this.trigger('endedtimeline');
- };
- };
-
- _AdtsStream.prototype = new stream();
- var adts = _AdtsStream;
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ExpGolomb;
- /**
- * Parser for exponential Golomb codes, a variable-bitwidth number encoding
- * scheme used by h264.
- */
-
- ExpGolomb = function ExpGolomb(workingData) {
- var // the number of bytes left to examine in workingData
- workingBytesAvailable = workingData.byteLength,
- // the current word being examined
- workingWord = 0,
- // :uint
- // the number of bits left to examine in the current word
- workingBitsAvailable = 0; // :uint;
- // ():uint
-
- this.length = function () {
- return 8 * workingBytesAvailable;
- }; // ():uint
-
-
- this.bitsAvailable = function () {
- return 8 * workingBytesAvailable + workingBitsAvailable;
- }; // ():void
-
-
- this.loadWord = function () {
- var position = workingData.byteLength - workingBytesAvailable,
- workingBytes = new Uint8Array(4),
- availableBytes = Math.min(4, workingBytesAvailable);
-
- if (availableBytes === 0) {
- throw new Error('no bytes available');
- }
-
- workingBytes.set(workingData.subarray(position, position + availableBytes));
- workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
-
- workingBitsAvailable = availableBytes * 8;
- workingBytesAvailable -= availableBytes;
- }; // (count:int):void
-
-
- this.skipBits = function (count) {
- var skipBytes; // :int
-
- if (workingBitsAvailable > count) {
- workingWord <<= count;
- workingBitsAvailable -= count;
- } else {
- count -= workingBitsAvailable;
- skipBytes = Math.floor(count / 8);
- count -= skipBytes * 8;
- workingBytesAvailable -= skipBytes;
- this.loadWord();
- workingWord <<= count;
- workingBitsAvailable -= count;
- }
- }; // (size:int):uint
-
-
- this.readBits = function (size) {
- var bits = Math.min(workingBitsAvailable, size),
- // :uint
- valu = workingWord >>> 32 - bits; // :uint
- // if size > 31, handle error
-
- workingBitsAvailable -= bits;
-
- if (workingBitsAvailable > 0) {
- workingWord <<= bits;
- } else if (workingBytesAvailable > 0) {
- this.loadWord();
- }
-
- bits = size - bits;
-
- if (bits > 0) {
- return valu << bits | this.readBits(bits);
- }
-
- return valu;
- }; // ():uint
-
-
- this.skipLeadingZeros = function () {
- var leadingZeroCount; // :uint
-
- for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
- if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
- // the first bit of working word is 1
- workingWord <<= leadingZeroCount;
- workingBitsAvailable -= leadingZeroCount;
- return leadingZeroCount;
- }
- } // we exhausted workingWord and still have not found a 1
-
-
- this.loadWord();
- return leadingZeroCount + this.skipLeadingZeros();
- }; // ():void
-
-
- this.skipUnsignedExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():void
-
-
- this.skipExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():uint
-
-
- this.readUnsignedExpGolomb = function () {
- var clz = this.skipLeadingZeros(); // :uint
-
- return this.readBits(clz + 1) - 1;
- }; // ():int
-
-
- this.readExpGolomb = function () {
- var valu = this.readUnsignedExpGolomb(); // :int
-
- if (0x01 & valu) {
- // the number is odd if the low order bit is set
- return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
- }
-
- return -1 * (valu >>> 1); // divide by two then make it negative
- }; // Some convenience functions
- // :Boolean
-
-
- this.readBoolean = function () {
- return this.readBits(1) === 1;
- }; // ():int
-
-
- this.readUnsignedByte = function () {
- return this.readBits(8);
- };
-
- this.loadWord();
- };
-
- var expGolomb = ExpGolomb;
-
- var _H264Stream, _NalByteStream;
-
- var PROFILES_WITH_OPTIONAL_SPS_DATA;
- /**
- * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
- */
-
- _NalByteStream = function NalByteStream() {
- var syncPoint = 0,
- i,
- buffer;
-
- _NalByteStream.prototype.init.call(this);
- /*
- * Scans a byte stream and triggers a data event with the NAL units found.
- * @param {Object} data Event received from H264Stream
- * @param {Uint8Array} data.data The h264 byte stream to be scanned
- *
- * @see H264Stream.push
- */
-
-
- this.push = function (data) {
- var swapBuffer;
-
- if (!buffer) {
- buffer = data.data;
- } else {
- swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
- swapBuffer.set(buffer);
- swapBuffer.set(data.data, buffer.byteLength);
- buffer = swapBuffer;
- }
-
- var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
- // scan for NAL unit boundaries
- // a match looks like this:
- // 0 0 1 .. NAL .. 0 0 1
- // ^ sync point ^ i
- // or this:
- // 0 0 1 .. NAL .. 0 0 0
- // ^ sync point ^ i
- // advance the sync point to a NAL start, if necessary
-
- for (; syncPoint < len - 3; syncPoint++) {
- if (buffer[syncPoint + 2] === 1) {
- // the sync point is properly aligned
- i = syncPoint + 5;
- break;
- }
- }
-
- while (i < len) {
- // look at the current byte to determine if we've hit the end of
- // a NAL unit boundary
- switch (buffer[i]) {
- case 0:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0) {
- i += 2;
- break;
- } else if (buffer[i - 2] !== 0) {
- i++;
- break;
- } // deliver the NAL unit if it isn't empty
-
-
- if (syncPoint + 3 !== i - 2) {
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- } // drop trailing zeroes
-
-
- do {
- i++;
- } while (buffer[i] !== 1 && i < len);
-
- syncPoint = i - 2;
- i += 3;
- break;
-
- case 1:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
- i += 3;
- break;
- } // deliver the NAL unit
-
-
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- syncPoint = i - 2;
- i += 3;
- break;
-
- default:
- // the current byte isn't a one or zero, so it cannot be part
- // of a sync sequence
- i += 3;
- break;
- }
- } // filter out the NAL units that were delivered
-
-
- buffer = buffer.subarray(syncPoint);
- i -= syncPoint;
- syncPoint = 0;
- };
-
- this.reset = function () {
- buffer = null;
- syncPoint = 0;
- this.trigger('reset');
- };
-
- this.flush = function () {
- // deliver the last buffered NAL unit
- if (buffer && buffer.byteLength > 3) {
- this.trigger('data', buffer.subarray(syncPoint + 3));
- } // reset the stream state
-
-
- buffer = null;
- syncPoint = 0;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
- };
-
- _NalByteStream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the SPS
- // see Recommendation ITU-T H.264 (4/2013),
- // 7.3.2.1.1 Sequence parameter set data syntax
-
- PROFILES_WITH_OPTIONAL_SPS_DATA = {
- 100: true,
- 110: true,
- 122: true,
- 244: true,
- 44: true,
- 83: true,
- 86: true,
- 118: true,
- 128: true,
- 138: true,
- 139: true,
- 134: true
- };
- /**
- * Accepts input from a ElementaryStream and produces H.264 NAL unit data
- * events.
- */
-
- _H264Stream = function H264Stream() {
- var nalByteStream = new _NalByteStream(),
- self,
- trackId,
- currentPts,
- currentDts,
- discardEmulationPreventionBytes,
- readSequenceParameterSet,
- skipScalingList;
-
- _H264Stream.prototype.init.call(this);
-
- self = this;
- /*
- * Pushes a packet from a stream onto the NalByteStream
- *
- * @param {Object} packet - A packet received from a stream
- * @param {Uint8Array} packet.data - The raw bytes of the packet
- * @param {Number} packet.dts - Decode timestamp of the packet
- * @param {Number} packet.pts - Presentation timestamp of the packet
- * @param {Number} packet.trackId - The id of the h264 track this packet came from
- * @param {('video'|'audio')} packet.type - The type of packet
- *
- */
-
- this.push = function (packet) {
- if (packet.type !== 'video') {
- return;
- }
-
- trackId = packet.trackId;
- currentPts = packet.pts;
- currentDts = packet.dts;
- nalByteStream.push(packet);
- };
- /*
- * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
- * for the NALUs to the next stream component.
- * Also, preprocess caption and sequence parameter NALUs.
- *
- * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
- * @see NalByteStream.push
- */
-
-
- nalByteStream.on('data', function (data) {
- var event = {
- trackId: trackId,
- pts: currentPts,
- dts: currentDts,
- data: data
- };
-
- switch (data[0] & 0x1f) {
- case 0x05:
- event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
- break;
-
- case 0x06:
- event.nalUnitType = 'sei_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- break;
-
- case 0x07:
- event.nalUnitType = 'seq_parameter_set_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- event.config = readSequenceParameterSet(event.escapedRBSP);
- break;
-
- case 0x08:
- event.nalUnitType = 'pic_parameter_set_rbsp';
- break;
-
- case 0x09:
- event.nalUnitType = 'access_unit_delimiter_rbsp';
- break;
- } // This triggers data on the H264Stream
-
-
- self.trigger('data', event);
- });
- nalByteStream.on('done', function () {
- self.trigger('done');
- });
- nalByteStream.on('partialdone', function () {
- self.trigger('partialdone');
- });
- nalByteStream.on('reset', function () {
- self.trigger('reset');
- });
- nalByteStream.on('endedtimeline', function () {
- self.trigger('endedtimeline');
- });
-
- this.flush = function () {
- nalByteStream.flush();
- };
-
- this.partialFlush = function () {
- nalByteStream.partialFlush();
- };
-
- this.reset = function () {
- nalByteStream.reset();
- };
-
- this.endTimeline = function () {
- nalByteStream.endTimeline();
- };
- /**
- * Advance the ExpGolomb decoder past a scaling list. The scaling
- * list is optionally transmitted as part of a sequence parameter
- * set and is not relevant to transmuxing.
- * @param count {number} the number of entries in this scaling list
- * @param expGolombDecoder {object} an ExpGolomb pointed to the
- * start of a scaling list
- * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
- */
-
-
- skipScalingList = function skipScalingList(count, expGolombDecoder) {
- var lastScale = 8,
- nextScale = 8,
- j,
- deltaScale;
-
- for (j = 0; j < count; j++) {
- if (nextScale !== 0) {
- deltaScale = expGolombDecoder.readExpGolomb();
- nextScale = (lastScale + deltaScale + 256) % 256;
- }
-
- lastScale = nextScale === 0 ? lastScale : nextScale;
- }
- };
- /**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
-
- discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- };
- /**
- * Read a sequence parameter set and return some interesting video
- * properties. A sequence parameter set is the H264 metadata that
- * describes the properties of upcoming video frames.
- * @param data {Uint8Array} the bytes of a sequence parameter set
- * @return {object} an object with configuration parsed from the
- * sequence parameter set, including the dimensions of the
- * associated video frames.
- */
-
-
- readSequenceParameterSet = function readSequenceParameterSet(data) {
- var frameCropLeftOffset = 0,
- frameCropRightOffset = 0,
- frameCropTopOffset = 0,
- frameCropBottomOffset = 0,
- sarScale = 1,
- expGolombDecoder,
- profileIdc,
- levelIdc,
- profileCompatibility,
- chromaFormatIdc,
- picOrderCntType,
- numRefFramesInPicOrderCntCycle,
- picWidthInMbsMinus1,
- picHeightInMapUnitsMinus1,
- frameMbsOnlyFlag,
- scalingListCount,
- sarRatio,
- aspectRatioIdc,
- i;
- expGolombDecoder = new expGolomb(data);
- profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
-
- profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
-
- levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
-
- expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
- // some profiles have more optional data we don't need
-
- if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
- chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
-
- if (chromaFormatIdc === 3) {
- expGolombDecoder.skipBits(1); // separate_colour_plane_flag
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
-
- expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
-
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_matrix_present_flag
- scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
-
- for (i = 0; i < scalingListCount; i++) {
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_list_present_flag[ i ]
- if (i < 6) {
- skipScalingList(16, expGolombDecoder);
- } else {
- skipScalingList(64, expGolombDecoder);
- }
- }
- }
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
-
- picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
-
- if (picOrderCntType === 0) {
- expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
- } else if (picOrderCntType === 1) {
- expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
-
- expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
-
- expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
-
- numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
-
- for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
- expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
-
- expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
-
- picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- frameMbsOnlyFlag = expGolombDecoder.readBits(1);
-
- if (frameMbsOnlyFlag === 0) {
- expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
- }
-
- expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
-
- if (expGolombDecoder.readBoolean()) {
- // frame_cropping_flag
- frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
- }
-
- if (expGolombDecoder.readBoolean()) {
- // vui_parameters_present_flag
- if (expGolombDecoder.readBoolean()) {
- // aspect_ratio_info_present_flag
- aspectRatioIdc = expGolombDecoder.readUnsignedByte();
-
- switch (aspectRatioIdc) {
- case 1:
- sarRatio = [1, 1];
- break;
-
- case 2:
- sarRatio = [12, 11];
- break;
-
- case 3:
- sarRatio = [10, 11];
- break;
-
- case 4:
- sarRatio = [16, 11];
- break;
-
- case 5:
- sarRatio = [40, 33];
- break;
-
- case 6:
- sarRatio = [24, 11];
- break;
-
- case 7:
- sarRatio = [20, 11];
- break;
-
- case 8:
- sarRatio = [32, 11];
- break;
-
- case 9:
- sarRatio = [80, 33];
- break;
-
- case 10:
- sarRatio = [18, 11];
- break;
-
- case 11:
- sarRatio = [15, 11];
- break;
-
- case 12:
- sarRatio = [64, 33];
- break;
-
- case 13:
- sarRatio = [160, 99];
- break;
-
- case 14:
- sarRatio = [4, 3];
- break;
-
- case 15:
- sarRatio = [3, 2];
- break;
-
- case 16:
- sarRatio = [2, 1];
- break;
-
- case 255:
- {
- sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
- break;
- }
- }
-
- if (sarRatio) {
- sarScale = sarRatio[0] / sarRatio[1];
- }
- }
- }
-
- return {
- profileIdc: profileIdc,
- levelIdc: levelIdc,
- profileCompatibility: profileCompatibility,
- width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
- height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
- sarRatio: sarRatio
- };
- };
- };
-
- _H264Stream.prototype = new stream();
- var h264 = {
- H264Stream: _H264Stream,
- NalByteStream: _NalByteStream
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Utilities to detect basic properties and metadata about Aac data.
- */
-
- var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
-
- var parseId3TagSize = function parseId3TagSize(header, byteIndex) {
- var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
- flags = header[byteIndex + 5],
- footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
-
- returnSize = returnSize >= 0 ? returnSize : 0;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
- };
-
- var getId3Offset = function getId3Offset(data, offset) {
- if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
- return offset;
- }
-
- offset += parseId3TagSize(data, offset);
- return getId3Offset(data, offset);
- }; // TODO: use vhs-utils
-
-
- var isLikelyAacData$1 = function isLikelyAacData(data) {
- var offset = getId3Offset(data, 0);
- return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
- // is not mp3 data but aac data.
- (data[offset + 1] & 0x16) === 0x10;
- };
-
- var parseSyncSafeInteger = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- }; // return a percent-encoded representation of the specified byte range
- // @see http://en.wikipedia.org/wiki/Percent-encoding
-
-
- var percentEncode = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- }; // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
-
-
- var parseIso88591 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
- };
-
- var parseAdtsSize = function parseAdtsSize(header, byteIndex) {
- var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
- middle = header[byteIndex + 4] << 3,
- highTwo = header[byteIndex + 3] & 0x3 << 11;
- return highTwo | middle | lowThree;
- };
-
- var parseType$2 = function parseType(header, byteIndex) {
- if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
- return 'timed-metadata';
- } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
- return 'audio';
- }
-
- return null;
- };
-
- var parseSampleRate = function parseSampleRate(packet) {
- var i = 0;
-
- while (i + 5 < packet.length) {
- if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- }
-
- return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
- }
-
- return null;
- };
-
- var parseAacTimestamp = function parseAacTimestamp(packet) {
- var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
-
- frameStart = 10;
-
- if (packet[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- return null;
- }
-
- frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
-
- if (frameHeader === 'PRIV') {
- frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
-
- for (var i = 0; i < frame.byteLength; i++) {
- if (frame[i] === 0) {
- var owner = parseIso88591(frame, 0, i);
-
- if (owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.subarray(i + 1);
- var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- return size;
- }
-
- break;
- }
- }
- }
-
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < packet.byteLength);
-
- return null;
- };
-
- var utils = {
- isLikelyAacData: isLikelyAacData$1,
- parseId3TagSize: parseId3TagSize,
- parseAdtsSize: parseAdtsSize,
- parseType: parseType$2,
- parseSampleRate: parseSampleRate,
- parseAacTimestamp: parseAacTimestamp
- };
-
- var _AacStream;
- /**
- * Splits an incoming stream of binary data into ADTS and ID3 Frames.
- */
-
-
- _AacStream = function AacStream() {
- var everything = new Uint8Array(),
- timeStamp = 0;
-
- _AacStream.prototype.init.call(this);
-
- this.setTimestamp = function (timestamp) {
- timeStamp = timestamp;
- };
-
- this.push = function (bytes) {
- var frameSize = 0,
- byteIndex = 0,
- bytesLeft,
- chunk,
- packet,
- tempLength; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (everything.length) {
- tempLength = everything.length;
- everything = new Uint8Array(bytes.byteLength + tempLength);
- everything.set(everything.subarray(0, tempLength));
- everything.set(bytes, tempLength);
- } else {
- everything = bytes;
- }
-
- while (everything.length - byteIndex >= 3) {
- if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
- // Exit early because we don't have enough to parse
- // the ID3 tag header
- if (everything.length - byteIndex < 10) {
- break;
- } // check framesize
-
-
- frameSize = utils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
- // Add to byteIndex to support multiple ID3 tags in sequence
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- chunk = {
- type: 'timed-metadata',
- data: everything.subarray(byteIndex, byteIndex + frameSize)
- };
- this.trigger('data', chunk);
- byteIndex += frameSize;
- continue;
- } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
- // Exit early because we don't have enough to parse
- // the ADTS frame header
- if (everything.length - byteIndex < 7) {
- break;
- }
-
- frameSize = utils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- packet = {
- type: 'audio',
- data: everything.subarray(byteIndex, byteIndex + frameSize),
- pts: timeStamp,
- dts: timeStamp
- };
- this.trigger('data', packet);
- byteIndex += frameSize;
- continue;
- }
-
- byteIndex++;
- }
-
- bytesLeft = everything.length - byteIndex;
-
- if (bytesLeft > 0) {
- everything = everything.subarray(byteIndex);
- } else {
- everything = new Uint8Array();
- }
- };
-
- this.reset = function () {
- everything = new Uint8Array();
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- everything = new Uint8Array();
- this.trigger('endedtimeline');
- };
- };
-
- _AacStream.prototype = new stream();
- var aac = _AacStream; // constants
-
- var AUDIO_PROPERTIES = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
- var audioProperties = AUDIO_PROPERTIES;
- var VIDEO_PROPERTIES = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
- var videoProperties = VIDEO_PROPERTIES;
- var H264Stream = h264.H264Stream;
- var isLikelyAacData = utils.isLikelyAacData;
- var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS; // object types
-
- var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
- /**
- * Compare two arrays (even typed) for same-ness
- */
-
-
- var arrayEquals = function arrayEquals(a, b) {
- var i;
-
- if (a.length !== b.length) {
- return false;
- } // compare the value of each element in the array
-
-
- for (i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) {
- return false;
- }
- }
-
- return true;
- };
-
- var generateSegmentTimingInfo = function generateSegmentTimingInfo(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
- var ptsOffsetFromDts = startPts - startDts,
- decodeDuration = endDts - startDts,
- presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
- // however, the player time values will reflect a start from the baseMediaDecodeTime.
- // In order to provide relevant values for the player times, base timing info on the
- // baseMediaDecodeTime and the DTS and PTS durations of the segment.
-
- return {
- start: {
- dts: baseMediaDecodeTime,
- pts: baseMediaDecodeTime + ptsOffsetFromDts
- },
- end: {
- dts: baseMediaDecodeTime + decodeDuration,
- pts: baseMediaDecodeTime + presentationDuration
- },
- prependedContentDuration: prependedContentDuration,
- baseMediaDecodeTime: baseMediaDecodeTime
- };
- };
- /**
- * Constructs a single-track, ISO BMFF media segment from AAC data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- _AudioSegmentStream = function AudioSegmentStream(track, options) {
- var adtsFrames = [],
- sequenceNumber = 0,
- earliestAllowedDts = 0,
- audioAppendStartTs = 0,
- videoBaseMediaDecodeTime = Infinity;
- options = options || {};
-
- _AudioSegmentStream.prototype.init.call(this);
-
- this.push = function (data) {
- trackDecodeInfo.collectDtsInfo(track, data);
-
- if (track) {
- audioProperties.forEach(function (prop) {
- track[prop] = data[prop];
- });
- } // buffer audio data until end() is called
-
-
- adtsFrames.push(data);
- };
-
- this.setEarliestDts = function (earliestDts) {
- earliestAllowedDts = earliestDts;
- };
-
- this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- videoBaseMediaDecodeTime = baseMediaDecodeTime;
- };
-
- this.setAudioAppendStart = function (timestamp) {
- audioAppendStartTs = timestamp;
- };
-
- this.flush = function () {
- var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
-
- if (adtsFrames.length === 0) {
- this.trigger('done', 'AudioSegmentStream');
- return;
- }
-
- frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
-
- videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
- // samples (that is, adts frames) in the audio data
-
- track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
-
- mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
- adtsFrames = [];
- moof = mp4Generator.moof(sequenceNumber, [track]);
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- trackDecodeInfo.clearDtsInfo(track);
- frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
- // tests) on adding the timingInfo event. However, it seems unlikely that there's a
- // valid use-case where an init segment/data should be triggered without associated
- // frames. Leaving for now, but should be looked into.
-
- if (frames.length) {
- segmentDuration = frames.length * frameDuration;
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
- // frame info is in video clock cycles. Convert to match expectation of
- // listeners (that all timestamps will be based on video clock cycles).
- clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
- frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
- this.trigger('timingInfo', {
- start: frames[0].pts,
- end: frames[0].pts + segmentDuration
- });
- }
-
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.trigger('done', 'AudioSegmentStream');
- };
-
- this.reset = function () {
- trackDecodeInfo.clearDtsInfo(track);
- adtsFrames = [];
- this.trigger('reset');
- };
- };
-
- _AudioSegmentStream.prototype = new stream();
- /**
- * Constructs a single-track, ISO BMFF media segment from H264 data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
- * gopsToAlignWith list when attempting to align gop pts
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
- _VideoSegmentStream = function VideoSegmentStream(track, options) {
- var sequenceNumber = 0,
- nalUnits = [],
- gopsToAlignWith = [],
- config,
- pps;
- options = options || {};
-
- _VideoSegmentStream.prototype.init.call(this);
-
- delete track.minPTS;
- this.gopCache_ = [];
- /**
- * Constructs a ISO BMFF segment given H264 nalUnits
- * @param {Object} nalUnit A data event representing a nalUnit
- * @param {String} nalUnit.nalUnitType
- * @param {Object} nalUnit.config Properties for a mp4 track
- * @param {Uint8Array} nalUnit.data The nalUnit bytes
- * @see lib/codecs/h264.js
- **/
-
- this.push = function (nalUnit) {
- trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
-
- if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
- config = nalUnit.config;
- track.sps = [nalUnit.data];
- videoProperties.forEach(function (prop) {
- track[prop] = config[prop];
- }, this);
- }
-
- if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
- pps = nalUnit.data;
- track.pps = [nalUnit.data];
- } // buffer video until flush() is called
-
-
- nalUnits.push(nalUnit);
- };
- /**
- * Pass constructed ISO BMFF track and boxes on to the
- * next stream in the pipeline
- **/
-
-
- this.flush = function () {
- var frames,
- gopForFusion,
- gops,
- moof,
- mdat,
- boxes,
- prependedContentDuration = 0,
- firstGop,
- lastGop; // Throw away nalUnits at the start of the byte stream until
- // we find the first AUD
-
- while (nalUnits.length) {
- if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
- break;
- }
-
- nalUnits.shift();
- } // Return early if no video data has been observed
-
-
- if (nalUnits.length === 0) {
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Organize the raw nal-units into arrays that represent
- // higher-level constructs such as frames and gops
- // (group-of-pictures)
-
-
- frames = frameUtils.groupNalsIntoFrames(nalUnits);
- gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
- // a problem since MSE (on Chrome) requires a leading keyframe.
- //
- // We have two approaches to repairing this situation:
- // 1) GOP-FUSION:
- // This is where we keep track of the GOPS (group-of-pictures)
- // from previous fragments and attempt to find one that we can
- // prepend to the current fragment in order to create a valid
- // fragment.
- // 2) KEYFRAME-PULLING:
- // Here we search for the first keyframe in the fragment and
- // throw away all the frames between the start of the fragment
- // and that keyframe. We then extend the duration and pull the
- // PTS of the keyframe forward so that it covers the time range
- // of the frames that were disposed of.
- //
- // #1 is far prefereable over #2 which can cause "stuttering" but
- // requires more things to be just right.
-
- if (!gops[0][0].keyFrame) {
- // Search for a gop for fusion from our gopCache
- gopForFusion = this.getGopForFusion_(nalUnits[0], track);
-
- if (gopForFusion) {
- // in order to provide more accurate timing information about the segment, save
- // the number of seconds prepended to the original segment due to GOP fusion
- prependedContentDuration = gopForFusion.duration;
- gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
- // new gop at the beginning
-
- gops.byteLength += gopForFusion.byteLength;
- gops.nalCount += gopForFusion.nalCount;
- gops.pts = gopForFusion.pts;
- gops.dts = gopForFusion.dts;
- gops.duration += gopForFusion.duration;
- } else {
- // If we didn't find a candidate gop fall back to keyframe-pulling
- gops = frameUtils.extendFirstKeyFrame(gops);
- }
- } // Trim gops to align with gopsToAlignWith
-
-
- if (gopsToAlignWith.length) {
- var alignedGops;
-
- if (options.alignGopsAtEnd) {
- alignedGops = this.alignGopsAtEnd_(gops);
- } else {
- alignedGops = this.alignGopsAtStart_(gops);
- }
-
- if (!alignedGops) {
- // save all the nals in the last GOP into the gop cache
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
-
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
- // when recalculated before sending off to CoalesceStream
-
-
- trackDecodeInfo.clearDtsInfo(track);
- gops = alignedGops;
- }
-
- trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
- // samples (that is, frames) in the video data
-
- track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
-
- mdat = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
- this.trigger('processedGopsInfo', gops.map(function (gop) {
- return {
- pts: gop.pts,
- dts: gop.dts,
- byteLength: gop.byteLength
- };
- }));
- firstGop = gops[0];
- lastGop = gops[gops.length - 1];
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
- this.trigger('timingInfo', {
- start: gops[0].pts,
- end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
- }); // save all the nals in the last GOP into the gop cache
-
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = [];
- this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
- this.trigger('timelineStartInfo', track.timelineStartInfo);
- moof = mp4Generator.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
- // throwing away hundreds of media segment fragments
-
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.resetStream_(); // Continue with the flush process now
-
- this.trigger('done', 'VideoSegmentStream');
- };
-
- this.reset = function () {
- this.resetStream_();
- nalUnits = [];
- this.gopCache_.length = 0;
- gopsToAlignWith.length = 0;
- this.trigger('reset');
- };
-
- this.resetStream_ = function () {
- trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
- // for instance, when we are rendition switching
-
- config = undefined;
- pps = undefined;
- }; // Search for a candidate Gop for gop-fusion from the gop cache and
- // return it or return null if no good candidate was found
-
-
- this.getGopForFusion_ = function (nalUnit) {
- var halfSecond = 45000,
- // Half-a-second in a 90khz clock
- allowableOverlap = 10000,
- // About 3 frames @ 30fps
- nearestDistance = Infinity,
- dtsDistance,
- nearestGopObj,
- currentGop,
- currentGopObj,
- i; // Search for the GOP nearest to the beginning of this nal unit
-
- for (i = 0; i < this.gopCache_.length; i++) {
- currentGopObj = this.gopCache_[i];
- currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
-
- if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
- continue;
- } // Reject Gops that would require a negative baseMediaDecodeTime
-
-
- if (currentGop.dts < track.timelineStartInfo.dts) {
- continue;
- } // The distance between the end of the gop and the start of the nalUnit
-
-
- dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
- // a half-second of the nal unit
-
- if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
- // Always use the closest GOP we found if there is more than
- // one candidate
- if (!nearestGopObj || nearestDistance > dtsDistance) {
- nearestGopObj = currentGopObj;
- nearestDistance = dtsDistance;
- }
- }
- }
-
- if (nearestGopObj) {
- return nearestGopObj.gop;
- }
-
- return null;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the START of the list
-
-
- this.alignGopsAtStart_ = function (gops) {
- var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
- byteLength = gops.byteLength;
- nalCount = gops.nalCount;
- duration = gops.duration;
- alignIndex = gopIndex = 0;
-
- while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- break;
- }
-
- if (gop.pts > align.pts) {
- // this current gop starts after the current gop we want to align on, so increment
- // align index
- alignIndex++;
- continue;
- } // current gop starts before the current gop we want to align on. so increment gop
- // index
-
-
- gopIndex++;
- byteLength -= gop.byteLength;
- nalCount -= gop.nalCount;
- duration -= gop.duration;
- }
-
- if (gopIndex === 0) {
- // no gops to trim
- return gops;
- }
-
- if (gopIndex === gops.length) {
- // all gops trimmed, skip appending all gops
- return null;
- }
-
- alignedGops = gops.slice(gopIndex);
- alignedGops.byteLength = byteLength;
- alignedGops.duration = duration;
- alignedGops.nalCount = nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the END of the list
-
-
- this.alignGopsAtEnd_ = function (gops) {
- var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
- alignIndex = gopsToAlignWith.length - 1;
- gopIndex = gops.length - 1;
- alignEndIndex = null;
- matchFound = false;
-
- while (alignIndex >= 0 && gopIndex >= 0) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- matchFound = true;
- break;
- }
-
- if (align.pts > gop.pts) {
- alignIndex--;
- continue;
- }
-
- if (alignIndex === gopsToAlignWith.length - 1) {
- // gop.pts is greater than the last alignment candidate. If no match is found
- // by the end of this loop, we still want to append gops that come after this
- // point
- alignEndIndex = gopIndex;
- }
-
- gopIndex--;
- }
-
- if (!matchFound && alignEndIndex === null) {
- return null;
- }
-
- var trimIndex;
-
- if (matchFound) {
- trimIndex = gopIndex;
- } else {
- trimIndex = alignEndIndex;
- }
-
- if (trimIndex === 0) {
- return gops;
- }
-
- var alignedGops = gops.slice(trimIndex);
- var metadata = alignedGops.reduce(function (total, gop) {
- total.byteLength += gop.byteLength;
- total.duration += gop.duration;
- total.nalCount += gop.nalCount;
- return total;
- }, {
- byteLength: 0,
- duration: 0,
- nalCount: 0
- });
- alignedGops.byteLength = metadata.byteLength;
- alignedGops.duration = metadata.duration;
- alignedGops.nalCount = metadata.nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- };
-
- this.alignGopsWith = function (newGopsToAlignWith) {
- gopsToAlignWith = newGopsToAlignWith;
- };
- };
-
- _VideoSegmentStream.prototype = new stream();
- /**
- * A Stream that can combine multiple streams (ie. audio & video)
- * into a single output segment for MSE. Also supports audio-only
- * and video-only streams.
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at media timeline start.
- */
-
- _CoalesceStream = function CoalesceStream(options, metadataStream) {
- // Number of Tracks per output segment
- // If greater than 1, we combine multiple
- // tracks into a single segment
- this.numberOfTracks = 0;
- this.metadataStream = metadataStream;
- options = options || {};
-
- if (typeof options.remux !== 'undefined') {
- this.remuxTracks = !!options.remux;
- } else {
- this.remuxTracks = true;
- }
-
- if (typeof options.keepOriginalTimestamps === 'boolean') {
- this.keepOriginalTimestamps = options.keepOriginalTimestamps;
- } else {
- this.keepOriginalTimestamps = false;
- }
-
- this.pendingTracks = [];
- this.videoTrack = null;
- this.pendingBoxes = [];
- this.pendingCaptions = [];
- this.pendingMetadata = [];
- this.pendingBytes = 0;
- this.emittedTracks = 0;
-
- _CoalesceStream.prototype.init.call(this); // Take output from multiple
-
-
- this.push = function (output) {
- // buffer incoming captions until the associated video segment
- // finishes
- if (output.text) {
- return this.pendingCaptions.push(output);
- } // buffer incoming id3 tags until the final flush
-
-
- if (output.frames) {
- return this.pendingMetadata.push(output);
- } // Add this track to the list of pending tracks and store
- // important information required for the construction of
- // the final segment
-
-
- this.pendingTracks.push(output.track);
- this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
- // We unshift audio and push video because
- // as of Chrome 75 when switching from
- // one init segment to another if the video
- // mdat does not appear after the audio mdat
- // only audio will play for the duration of our transmux.
-
- if (output.track.type === 'video') {
- this.videoTrack = output.track;
- this.pendingBoxes.push(output.boxes);
- }
-
- if (output.track.type === 'audio') {
- this.audioTrack = output.track;
- this.pendingBoxes.unshift(output.boxes);
- }
- };
- };
-
- _CoalesceStream.prototype = new stream();
-
- _CoalesceStream.prototype.flush = function (flushSource) {
- var offset = 0,
- event = {
- captions: [],
- captionStreams: {},
- metadata: [],
- info: {}
- },
- caption,
- id3,
- initSegment,
- timelineStartPts = 0,
- i;
-
- if (this.pendingTracks.length < this.numberOfTracks) {
- if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
- // Return because we haven't received a flush from a data-generating
- // portion of the segment (meaning that we have only recieved meta-data
- // or captions.)
- return;
- } else if (this.remuxTracks) {
- // Return until we have enough tracks from the pipeline to remux (if we
- // are remuxing audio and video into a single MP4)
- return;
- } else if (this.pendingTracks.length === 0) {
- // In the case where we receive a flush without any data having been
- // received we consider it an emitted track for the purposes of coalescing
- // `done` events.
- // We do this for the case where there is an audio and video track in the
- // segment but no audio data. (seen in several playlists with alternate
- // audio tracks and no audio present in the main TS segments.)
- this.emittedTracks++;
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
-
- return;
- }
- }
-
- if (this.videoTrack) {
- timelineStartPts = this.videoTrack.timelineStartInfo.pts;
- videoProperties.forEach(function (prop) {
- event.info[prop] = this.videoTrack[prop];
- }, this);
- } else if (this.audioTrack) {
- timelineStartPts = this.audioTrack.timelineStartInfo.pts;
- audioProperties.forEach(function (prop) {
- event.info[prop] = this.audioTrack[prop];
- }, this);
- }
-
- if (this.videoTrack || this.audioTrack) {
- if (this.pendingTracks.length === 1) {
- event.type = this.pendingTracks[0].type;
- } else {
- event.type = 'combined';
- }
-
- this.emittedTracks += this.pendingTracks.length;
- initSegment = mp4Generator.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
-
- event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
- // and track definitions
-
- event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
-
- event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
-
- for (i = 0; i < this.pendingBoxes.length; i++) {
- event.data.set(this.pendingBoxes[i], offset);
- offset += this.pendingBoxes[i].byteLength;
- } // Translate caption PTS times into second offsets to match the
- // video timeline for the segment, and add track info
-
-
- for (i = 0; i < this.pendingCaptions.length; i++) {
- caption = this.pendingCaptions[i];
- caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
- caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
- event.captionStreams[caption.stream] = true;
- event.captions.push(caption);
- } // Translate ID3 frame PTS times into second offsets to match the
- // video timeline for the segment
-
-
- for (i = 0; i < this.pendingMetadata.length; i++) {
- id3 = this.pendingMetadata[i];
- id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
- event.metadata.push(id3);
- } // We add this to every single emitted segment even though we only need
- // it for the first
-
-
- event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
-
- this.pendingTracks.length = 0;
- this.videoTrack = null;
- this.pendingBoxes.length = 0;
- this.pendingCaptions.length = 0;
- this.pendingBytes = 0;
- this.pendingMetadata.length = 0; // Emit the built segment
- // We include captions and ID3 tags for backwards compatibility,
- // ideally we should send only video and audio in the data event
-
- this.trigger('data', event); // Emit each caption to the outside world
- // Ideally, this would happen immediately on parsing captions,
- // but we need to ensure that video data is sent back first
- // so that caption timing can be adjusted to match video timing
-
- for (i = 0; i < event.captions.length; i++) {
- caption = event.captions[i];
- this.trigger('caption', caption);
- } // Emit each id3 tag to the outside world
- // Ideally, this would happen immediately on parsing the tag,
- // but we need to ensure that video data is sent back first
- // so that ID3 frame timing can be adjusted to match video timing
-
-
- for (i = 0; i < event.metadata.length; i++) {
- id3 = event.metadata[i];
- this.trigger('id3Frame', id3);
- }
- } // Only emit `done` if all tracks have been flushed and emitted
-
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
- };
-
- _CoalesceStream.prototype.setRemux = function (val) {
- this.remuxTracks = val;
- };
- /**
- * A Stream that expects MP2T binary data as input and produces
- * corresponding media segments, suitable for use with Media Source
- * Extension (MSE) implementations that support the ISO BMFF byte
- * stream format, like Chrome.
- */
-
-
- _Transmuxer = function Transmuxer(options) {
- var self = this,
- hasFlushed = true,
- videoTrack,
- audioTrack;
-
- _Transmuxer.prototype.init.call(this);
-
- options = options || {};
- this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
- this.transmuxPipeline_ = {};
-
- this.setupAacPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'aac';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.aacStream = new aac();
- pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('audio');
- pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('timed-metadata');
- pipeline.adtsStream = new adts();
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.aacStream;
- pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
- pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
- pipeline.metadataStream.on('timestamp', function (frame) {
- pipeline.aacStream.setTimestamp(frame.timeStamp);
- });
- pipeline.aacStream.on('data', function (data) {
- if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
- return;
- }
-
- audioTrack = audioTrack || {
- timelineStartInfo: {
- baseMediaDecodeTime: self.baseMediaDecodeTime
- },
- codec: 'adts',
- type: 'audio'
- }; // hook up the audio segment stream to the first track with aac data
-
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- };
-
- this.setupTsPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'ts';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.packetStream = new m2ts_1.TransportPacketStream();
- pipeline.parseStream = new m2ts_1.TransportParseStream();
- pipeline.elementaryStream = new m2ts_1.ElementaryStream();
- pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
- pipeline.adtsStream = new adts();
- pipeline.h264Stream = new H264Stream();
- pipeline.captionStream = new m2ts_1.CaptionStream(options);
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
-
- pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
- // demux the streams
-
- pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
- pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
- pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
-
- pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
- pipeline.elementaryStream.on('data', function (data) {
- var i;
-
- if (data.type === 'metadata') {
- i = data.tracks.length; // scan the tracks listed in the metadata
-
- while (i--) {
- if (!videoTrack && data.tracks[i].type === 'video') {
- videoTrack = data.tracks[i];
- videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- } else if (!audioTrack && data.tracks[i].type === 'audio') {
- audioTrack = data.tracks[i];
- audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- }
- } // hook up the video segment stream to the first track with h264 data
-
-
- if (videoTrack && !pipeline.videoSegmentStream) {
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
- pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
- // When video emits timelineStartInfo data after a flush, we forward that
- // info to the AudioSegmentStream, if it exists, because video timeline
- // data takes precedence. Do not do this if keepOriginalTimestamps is set,
- // because this is a particularly subtle form of timestamp alteration.
- if (audioTrack && !options.keepOriginalTimestamps) {
- audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
- // very earliest DTS we have seen in video because Chrome will
- // interpret any video track with a baseMediaDecodeTime that is
- // non-zero as a gap.
-
- pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
- pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
- pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
- if (audioTrack) {
- pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
-
- pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
- }
-
- if (audioTrack && !pipeline.audioSegmentStream) {
- // hook up the audio segment stream to the first track with aac data
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
- pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
- } // emit pmt info
-
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
- pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
- id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
- self.trigger('id3Frame', id3Frame);
- });
- pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- }; // hook up the segment streams once track metadata is delivered
-
-
- this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- var pipeline = this.transmuxPipeline_;
-
- if (!options.keepOriginalTimestamps) {
- this.baseMediaDecodeTime = baseMediaDecodeTime;
- }
-
- if (audioTrack) {
- audioTrack.timelineStartInfo.dts = undefined;
- audioTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(audioTrack);
-
- if (pipeline.audioTimestampRolloverStream) {
- pipeline.audioTimestampRolloverStream.discontinuity();
- }
- }
-
- if (videoTrack) {
- if (pipeline.videoSegmentStream) {
- pipeline.videoSegmentStream.gopCache_ = [];
- }
-
- videoTrack.timelineStartInfo.dts = undefined;
- videoTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(videoTrack);
- pipeline.captionStream.reset();
- }
-
- if (pipeline.timestampRolloverStream) {
- pipeline.timestampRolloverStream.discontinuity();
- }
- };
-
- this.setAudioAppendStart = function (timestamp) {
- if (audioTrack) {
- this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
- }
- };
-
- this.setRemux = function (val) {
- var pipeline = this.transmuxPipeline_;
- options.remux = val;
-
- if (pipeline && pipeline.coalesceStream) {
- pipeline.coalesceStream.setRemux(val);
- }
- };
-
- this.alignGopsWith = function (gopsToAlignWith) {
- if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
- this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
- }
- }; // feed incoming data to the front of the parsing pipeline
-
-
- this.push = function (data) {
- if (hasFlushed) {
- var isAac = isLikelyAacData(data);
-
- if (isAac && this.transmuxPipeline_.type !== 'aac') {
- this.setupAacPipeline();
- } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
- this.setupTsPipeline();
- }
-
- hasFlushed = false;
- }
-
- this.transmuxPipeline_.headOfPipeline.push(data);
- }; // flush any buffered data
-
-
- this.flush = function () {
- hasFlushed = true; // Start at the top of the pipeline and flush all pending work
-
- this.transmuxPipeline_.headOfPipeline.flush();
- };
-
- this.endTimeline = function () {
- this.transmuxPipeline_.headOfPipeline.endTimeline();
- };
-
- this.reset = function () {
- if (this.transmuxPipeline_.headOfPipeline) {
- this.transmuxPipeline_.headOfPipeline.reset();
- }
- }; // Caption data has to be reset when seeking outside buffered range
-
-
- this.resetCaptions = function () {
- if (this.transmuxPipeline_.captionStream) {
- this.transmuxPipeline_.captionStream.reset();
- }
- };
- };
-
- _Transmuxer.prototype = new stream();
- var transmuxer = {
- Transmuxer: _Transmuxer,
- VideoSegmentStream: _VideoSegmentStream,
- AudioSegmentStream: _AudioSegmentStream,
- AUDIO_PROPERTIES: audioProperties,
- VIDEO_PROPERTIES: videoProperties,
- // exported for testing
- generateSegmentTimingInfo: generateSegmentTimingInfo
- };
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var toUnsigned$3 = function toUnsigned(value) {
- return value >>> 0;
- };
-
- var toHexString$1 = function toHexString(value) {
- return ('00' + value.toString(16)).slice(-2);
- };
-
- var bin = {
- toUnsigned: toUnsigned$3,
- toHexString: toHexString$1
- };
-
- var parseType$1 = function parseType(buffer) {
- var result = '';
- result += String.fromCharCode(buffer[0]);
- result += String.fromCharCode(buffer[1]);
- result += String.fromCharCode(buffer[2]);
- result += String.fromCharCode(buffer[3]);
- return result;
- };
-
- var parseType_1 = parseType$1;
- var toUnsigned$2 = bin.toUnsigned;
-
- var findBox = function findBox(data, path) {
- var results = [],
- i,
- size,
- type,
- end,
- subresults;
-
- if (!path.length) {
- // short-circuit the search for empty paths
- return null;
- }
-
- for (i = 0; i < data.byteLength;) {
- size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
- type = parseType_1(data.subarray(i + 4, i + 8));
- end = size > 1 ? i + size : data.byteLength;
-
- if (type === path[0]) {
- if (path.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data.subarray(i + 8, end));
- } else {
- // recursively search for the next box along the path
- subresults = findBox(data.subarray(i + 8, end), path.slice(1));
-
- if (subresults.length) {
- results = results.concat(subresults);
- }
- }
- }
-
- i = end;
- } // we've finished searching all of data
-
-
- return results;
- };
-
- var findBox_1 = findBox;
- var toUnsigned$1 = bin.toUnsigned;
-
- var tfdt = function tfdt(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- baseMediaDecodeTime: toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7])
- };
-
- if (result.version === 1) {
- result.baseMediaDecodeTime *= Math.pow(2, 32);
- result.baseMediaDecodeTime += toUnsigned$1(data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11]);
- }
-
- return result;
- };
-
- var parseTfdt = tfdt;
-
- var parseSampleFlags = function parseSampleFlags(flags) {
- return {
- isLeading: (flags[0] & 0x0c) >>> 2,
- dependsOn: flags[0] & 0x03,
- isDependedOn: (flags[1] & 0xc0) >>> 6,
- hasRedundancy: (flags[1] & 0x30) >>> 4,
- paddingValue: (flags[1] & 0x0e) >>> 1,
- isNonSyncSample: flags[1] & 0x01,
- degradationPriority: flags[2] << 8 | flags[3]
- };
- };
-
- var parseSampleFlags_1 = parseSampleFlags;
-
- var trun = function trun(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- samples: []
- },
- view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- // Flag interpretation
- dataOffsetPresent = result.flags[2] & 0x01,
- // compare with 2nd byte of 0x1
- firstSampleFlagsPresent = result.flags[2] & 0x04,
- // compare with 2nd byte of 0x4
- sampleDurationPresent = result.flags[1] & 0x01,
- // compare with 2nd byte of 0x100
- sampleSizePresent = result.flags[1] & 0x02,
- // compare with 2nd byte of 0x200
- sampleFlagsPresent = result.flags[1] & 0x04,
- // compare with 2nd byte of 0x400
- sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
- // compare with 2nd byte of 0x800
- sampleCount = view.getUint32(4),
- offset = 8,
- sample;
-
- if (dataOffsetPresent) {
- // 32 bit signed integer
- result.dataOffset = view.getInt32(offset);
- offset += 4;
- } // Overrides the flags for the first sample only. The order of
- // optional values will be: duration, size, compositionTimeOffset
-
-
- if (firstSampleFlagsPresent && sampleCount) {
- sample = {
- flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
- };
- offset += 4;
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- sampleCount--;
- }
-
- while (sampleCount--) {
- sample = {};
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleFlagsPresent) {
- sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- }
-
- return result;
- };
-
- var parseTrun = trun;
-
- var tfhd = function tfhd(data) {
- var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- trackId: view.getUint32(4)
- },
- baseDataOffsetPresent = result.flags[2] & 0x01,
- sampleDescriptionIndexPresent = result.flags[2] & 0x02,
- defaultSampleDurationPresent = result.flags[2] & 0x08,
- defaultSampleSizePresent = result.flags[2] & 0x10,
- defaultSampleFlagsPresent = result.flags[2] & 0x20,
- durationIsEmpty = result.flags[0] & 0x010000,
- defaultBaseIsMoof = result.flags[0] & 0x020000,
- i;
- i = 8;
-
- if (baseDataOffsetPresent) {
- i += 4; // truncate top 4 bytes
- // FIXME: should we read the full 64 bits?
-
- result.baseDataOffset = view.getUint32(12);
- i += 4;
- }
-
- if (sampleDescriptionIndexPresent) {
- result.sampleDescriptionIndex = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleDurationPresent) {
- result.defaultSampleDuration = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleSizePresent) {
- result.defaultSampleSize = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleFlagsPresent) {
- result.defaultSampleFlags = view.getUint32(i);
- }
-
- if (durationIsEmpty) {
- result.durationIsEmpty = true;
- }
-
- if (!baseDataOffsetPresent && defaultBaseIsMoof) {
- result.baseDataOffsetIsMoof = true;
- }
-
- return result;
- };
-
- var parseTfhd = tfhd;
- var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
- var CaptionStream = captionStream.CaptionStream;
- /**
- * Maps an offset in the mdat to a sample based on the the size of the samples.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Number} offset - The offset into the mdat
- * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
- * @return {?Object} The matching sample, or null if no match was found.
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
- var mapToSample = function mapToSample(offset, samples) {
- var approximateOffset = offset;
-
- for (var i = 0; i < samples.length; i++) {
- var sample = samples[i];
-
- if (approximateOffset < sample.size) {
- return sample;
- }
-
- approximateOffset -= sample.size;
- }
-
- return null;
- };
- /**
- * Finds SEI nal units contained in a Media Data Box.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Uint8Array} avcStream - The bytes of the mdat
- * @param {Object[]} samples - The samples parsed out by `parseSamples`
- * @param {Number} trackId - The trackId of this video track
- * @return {Object[]} seiNals - the parsed SEI NALUs found.
- * The contents of the seiNal should match what is expected by
- * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
- *
- * @see ISO-BMFF-12/2015, Section 8.1.1
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- **/
-
-
- var findSeiNals = function findSeiNals(avcStream, samples, trackId) {
- var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
- result = [],
- seiNal,
- i,
- length,
- lastMatchedSample;
-
- for (i = 0; i + 4 < avcStream.length; i += length) {
- length = avcView.getUint32(i);
- i += 4; // Bail if this doesn't appear to be an H264 stream
-
- if (length <= 0) {
- continue;
- }
-
- switch (avcStream[i] & 0x1F) {
- case 0x06:
- var data = avcStream.subarray(i + 1, i + 1 + length);
- var matchingSample = mapToSample(i, samples);
- seiNal = {
- nalUnitType: 'sei_rbsp',
- size: length,
- data: data,
- escapedRBSP: discardEmulationPreventionBytes(data),
- trackId: trackId
- };
-
- if (matchingSample) {
- seiNal.pts = matchingSample.pts;
- seiNal.dts = matchingSample.dts;
- lastMatchedSample = matchingSample;
- } else if (lastMatchedSample) {
- // If a matching sample cannot be found, use the last
- // sample's values as they should be as close as possible
- seiNal.pts = lastMatchedSample.pts;
- seiNal.dts = lastMatchedSample.dts;
- } else {
- // eslint-disable-next-line no-console
- console.log("We've encountered a nal unit without data. See mux.js#233.");
- break;
- }
-
- result.push(seiNal);
- break;
- }
- }
-
- return result;
- };
- /**
- * Parses sample information out of Track Run Boxes and calculates
- * the absolute presentation and decode timestamps of each sample.
- *
- * @param {Array} truns - The Trun Run boxes to be parsed
- * @param {Number} baseMediaDecodeTime - base media decode time from tfdt
- @see ISO-BMFF-12/2015, Section 8.8.12
- * @param {Object} tfhd - The parsed Track Fragment Header
- * @see inspect.parseTfhd
- * @return {Object[]} the parsed samples
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
-
- var parseSamples = function parseSamples(truns, baseMediaDecodeTime, tfhd) {
- var currentDts = baseMediaDecodeTime;
- var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
- var defaultSampleSize = tfhd.defaultSampleSize || 0;
- var trackId = tfhd.trackId;
- var allSamples = [];
- truns.forEach(function (trun) {
- // Note: We currently do not parse the sample table as well
- // as the trun. It's possible some sources will require this.
- // moov > trak > mdia > minf > stbl
- var trackRun = parseTrun(trun);
- var samples = trackRun.samples;
- samples.forEach(function (sample) {
- if (sample.duration === undefined) {
- sample.duration = defaultSampleDuration;
- }
-
- if (sample.size === undefined) {
- sample.size = defaultSampleSize;
- }
-
- sample.trackId = trackId;
- sample.dts = currentDts;
-
- if (sample.compositionTimeOffset === undefined) {
- sample.compositionTimeOffset = 0;
- }
-
- sample.pts = currentDts + sample.compositionTimeOffset;
- currentDts += sample.duration;
- });
- allSamples = allSamples.concat(samples);
- });
- return allSamples;
- };
- /**
- * Parses out caption nals from an FMP4 segment's video tracks.
- *
- * @param {Uint8Array} segment - The bytes of a single segment
- * @param {Number} videoTrackId - The trackId of a video track in the segment
- * @return {Object.} A mapping of video trackId to
- * a list of seiNals found in that track
- **/
-
-
- var parseCaptionNals = function parseCaptionNals(segment, videoTrackId) {
- // To get the samples
- var trafs = findBox_1(segment, ['moof', 'traf']); // To get SEI NAL units
-
- var mdats = findBox_1(segment, ['mdat']);
- var captionNals = {};
- var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
-
- mdats.forEach(function (mdat, index) {
- var matchingTraf = trafs[index];
- mdatTrafPairs.push({
- mdat: mdat,
- traf: matchingTraf
- });
- });
- mdatTrafPairs.forEach(function (pair) {
- var mdat = pair.mdat;
- var traf = pair.traf;
- var tfhd = findBox_1(traf, ['tfhd']); // Exactly 1 tfhd per traf
-
- var headerInfo = parseTfhd(tfhd[0]);
- var trackId = headerInfo.trackId;
- var tfdt = findBox_1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
-
- var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
- var truns = findBox_1(traf, ['trun']);
- var samples;
- var seiNals; // Only parse video data for the chosen video track
-
- if (videoTrackId === trackId && truns.length > 0) {
- samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
- seiNals = findSeiNals(mdat, samples, trackId);
-
- if (!captionNals[trackId]) {
- captionNals[trackId] = [];
- }
-
- captionNals[trackId] = captionNals[trackId].concat(seiNals);
- }
- });
- return captionNals;
- };
- /**
- * Parses out inband captions from an MP4 container and returns
- * caption objects that can be used by WebVTT and the TextTrack API.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
- * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
- * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number} trackId - The id of the video track to parse
- * @param {Number} timescale - The timescale for the video track from the init segment
- *
- * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
- * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
- * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
- * @return {String} parsedCaptions[].text - The visible content of the caption
- **/
-
-
- var parseEmbeddedCaptions = function parseEmbeddedCaptions(segment, trackId, timescale) {
- var seiNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
-
- if (trackId === null) {
- return null;
- }
-
- seiNals = parseCaptionNals(segment, trackId);
- return {
- seiNals: seiNals[trackId],
- timescale: timescale
- };
- };
- /**
- * Converts SEI NALUs into captions that can be used by video.js
- **/
-
-
- var CaptionParser = function CaptionParser() {
- var isInitialized = false;
- var captionStream; // Stores segments seen before trackId and timescale are set
-
- var segmentCache; // Stores video track ID of the track being parsed
-
- var trackId; // Stores the timescale of the track being parsed
-
- var timescale; // Stores captions parsed so far
-
- var parsedCaptions; // Stores whether we are receiving partial data or not
-
- var parsingPartial;
- /**
- * A method to indicate whether a CaptionParser has been initalized
- * @returns {Boolean}
- **/
-
- this.isInitialized = function () {
- return isInitialized;
- };
- /**
- * Initializes the underlying CaptionStream, SEI NAL parsing
- * and management, and caption collection
- **/
-
-
- this.init = function (options) {
- captionStream = new CaptionStream();
- isInitialized = true;
- parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
-
- captionStream.on('data', function (event) {
- // Convert to seconds in the source's timescale
- event.startTime = event.startPts / timescale;
- event.endTime = event.endPts / timescale;
- parsedCaptions.captions.push(event);
- parsedCaptions.captionStreams[event.stream] = true;
- });
- };
- /**
- * Determines if a new video track will be selected
- * or if the timescale changed
- * @return {Boolean}
- **/
-
-
- this.isNewInit = function (videoTrackIds, timescales) {
- if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
- return false;
- }
-
- return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
- };
- /**
- * Parses out SEI captions and interacts with underlying
- * CaptionStream to return dispatched captions
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
- * @param {Object.} timescales - The timescales found in the init segment
- * @see parseEmbeddedCaptions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.parse = function (segment, videoTrackIds, timescales) {
- var parsedData;
-
- if (!this.isInitialized()) {
- return null; // This is not likely to be a video segment
- } else if (!videoTrackIds || !timescales) {
- return null;
- } else if (this.isNewInit(videoTrackIds, timescales)) {
- // Use the first video track only as there is no
- // mechanism to switch to other video tracks
- trackId = videoTrackIds[0];
- timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
- // data until we have one.
- // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
- } else if (trackId === null || !timescale) {
- segmentCache.push(segment);
- return null;
- } // Now that a timescale and trackId is set, parse cached segments
-
-
- while (segmentCache.length > 0) {
- var cachedSegment = segmentCache.shift();
- this.parse(cachedSegment, videoTrackIds, timescales);
- }
-
- parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
-
- if (parsedData === null || !parsedData.seiNals) {
- return null;
- }
-
- this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
-
- this.flushStream();
- return parsedCaptions;
- };
- /**
- * Pushes SEI NALUs onto CaptionStream
- * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
- * Assumes that `parseCaptionNals` has been called first
- * @see m2ts/caption-stream.js
- **/
-
-
- this.pushNals = function (nals) {
- if (!this.isInitialized() || !nals || nals.length === 0) {
- return null;
- }
-
- nals.forEach(function (nal) {
- captionStream.push(nal);
- });
- };
- /**
- * Flushes underlying CaptionStream to dispatch processed, displayable captions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.flushStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- if (!parsingPartial) {
- captionStream.flush();
- } else {
- captionStream.partialFlush();
- }
- };
- /**
- * Reset caption buckets for new data
- **/
-
-
- this.clearParsedCaptions = function () {
- parsedCaptions.captions = [];
- parsedCaptions.captionStreams = {};
- };
- /**
- * Resets underlying CaptionStream
- * @see m2ts/caption-stream.js
- **/
-
-
- this.resetCaptionStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- captionStream.reset();
- };
- /**
- * Convenience method to clear all captions flushed from the
- * CaptionStream and still being parsed
- * @see m2ts/caption-stream.js
- **/
-
-
- this.clearAllCaptions = function () {
- this.clearParsedCaptions();
- this.resetCaptionStream();
- };
- /**
- * Reset caption parser
- **/
-
-
- this.reset = function () {
- segmentCache = [];
- trackId = null;
- timescale = null;
-
- if (!parsedCaptions) {
- parsedCaptions = {
- captions: [],
- // CC1, CC2, CC3, CC4
- captionStreams: {}
- };
- } else {
- this.clearParsedCaptions();
- }
-
- this.resetCaptionStream();
- };
-
- this.reset();
- };
-
- var captionParser = CaptionParser;
- var toUnsigned = bin.toUnsigned;
- var toHexString = bin.toHexString;
- var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader;
- /**
- * Parses an MP4 initialization segment and extracts the timescale
- * values for any declared tracks. Timescale values indicate the
- * number of clock ticks per second to assume for time-based values
- * elsewhere in the MP4.
- *
- * To determine the start time of an MP4, you need two pieces of
- * information: the timescale unit and the earliest base media decode
- * time. Multiple timescales can be specified within an MP4 but the
- * base media decode time is always expressed in the timescale from
- * the media header box for the track:
- * ```
- * moov > trak > mdia > mdhd.timescale
- * ```
- * @param init {Uint8Array} the bytes of the init segment
- * @return {object} a hash of track ids to timescale values or null if
- * the init segment is malformed.
- */
-
- timescale = function timescale(init) {
- var result = {},
- traks = findBox_1(init, ['moov', 'trak']); // mdhd timescale
-
- return traks.reduce(function (result, trak) {
- var tkhd, version, index, id, mdhd;
- tkhd = findBox_1(trak, ['tkhd'])[0];
-
- if (!tkhd) {
- return null;
- }
-
- version = tkhd[0];
- index = version === 0 ? 12 : 20;
- id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
- mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
-
- if (!mdhd) {
- return null;
- }
-
- version = mdhd[0];
- index = version === 0 ? 12 : 20;
- result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
- return result;
- }, result);
- };
- /**
- * Determine the base media decode start time, in seconds, for an MP4
- * fragment. If multiple fragments are specified, the earliest time is
- * returned.
- *
- * The base media decode time can be parsed from track fragment
- * metadata:
- * ```
- * moof > traf > tfdt.baseMediaDecodeTime
- * ```
- * It requires the timescale value from the mdhd to interpret.
- *
- * @param timescale {object} a hash of track ids to timescale values.
- * @return {number} the earliest base media decode start time for the
- * fragment, in seconds
- */
-
-
- startTime = function startTime(timescale, fragment) {
- var trafs, baseTimes, result; // we need info from two childrend of each track fragment box
-
- trafs = findBox_1(fragment, ['moof', 'traf']); // determine the start times for each track
-
- baseTimes = [].concat.apply([], trafs.map(function (traf) {
- return findBox_1(traf, ['tfhd']).map(function (tfhd) {
- var id, scale, baseTime; // get the track id from the tfhd
-
- id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
-
- scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
-
- baseTime = findBox_1(traf, ['tfdt']).map(function (tfdt) {
- var version, result;
- version = tfdt[0];
- result = toUnsigned(tfdt[4] << 24 | tfdt[5] << 16 | tfdt[6] << 8 | tfdt[7]);
-
- if (version === 1) {
- result *= Math.pow(2, 32);
- result += toUnsigned(tfdt[8] << 24 | tfdt[9] << 16 | tfdt[10] << 8 | tfdt[11]);
- }
-
- return result;
- })[0];
- baseTime = typeof baseTime === 'number' && !isNaN(baseTime) ? baseTime : Infinity; // convert base time to seconds
-
- return baseTime / scale;
- });
- })); // return the minimum
-
- result = Math.min.apply(null, baseTimes);
- return isFinite(result) ? result : 0;
- };
- /**
- * Determine the composition start, in seconds, for an MP4
- * fragment.
- *
- * The composition start time of a fragment can be calculated using the base
- * media decode time, composition time offset, and timescale, as follows:
- *
- * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
- *
- * All of the aforementioned information is contained within a media fragment's
- * `traf` box, except for timescale info, which comes from the initialization
- * segment, so a track id (also contained within a `traf`) is also necessary to
- * associate it with a timescale
- *
- *
- * @param timescales {object} - a hash of track ids to timescale values.
- * @param fragment {Unit8Array} - the bytes of a media segment
- * @return {number} the composition start time for the fragment, in seconds
- **/
-
-
- compositionStartTime = function compositionStartTime(timescales, fragment) {
- var trafBoxes = findBox_1(fragment, ['moof', 'traf']);
- var baseMediaDecodeTime = 0;
- var compositionTimeOffset = 0;
- var trackId;
-
- if (trafBoxes && trafBoxes.length) {
- // The spec states that track run samples contained within a `traf` box are contiguous, but
- // it does not explicitly state whether the `traf` boxes themselves are contiguous.
- // We will assume that they are, so we only need the first to calculate start time.
- var tfhd = findBox_1(trafBoxes[0], ['tfhd'])[0];
- var trun = findBox_1(trafBoxes[0], ['trun'])[0];
- var tfdt = findBox_1(trafBoxes[0], ['tfdt'])[0];
-
- if (tfhd) {
- var parsedTfhd = parseTfhd(tfhd);
- trackId = parsedTfhd.trackId;
- }
-
- if (tfdt) {
- var parsedTfdt = parseTfdt(tfdt);
- baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
- }
-
- if (trun) {
- var parsedTrun = parseTrun(trun);
-
- if (parsedTrun.samples && parsedTrun.samples.length) {
- compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
- }
- }
- } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
- // specified.
-
-
- var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
-
- return (baseMediaDecodeTime + compositionTimeOffset) / timescale;
- };
- /**
- * Find the trackIds of the video tracks in this source.
- * Found by parsing the Handler Reference and Track Header Boxes:
- * moov > trak > mdia > hdlr
- * moov > trak > tkhd
- *
- * @param {Uint8Array} init - The bytes of the init segment for this source
- * @return {Number[]} A list of trackIds
- *
- * @see ISO-BMFF-12/2015, Section 8.4.3
- **/
-
-
- getVideoTrackIds = function getVideoTrackIds(init) {
- var traks = findBox_1(init, ['moov', 'trak']);
- var videoTrackIds = [];
- traks.forEach(function (trak) {
- var hdlrs = findBox_1(trak, ['mdia', 'hdlr']);
- var tkhds = findBox_1(trak, ['tkhd']);
- hdlrs.forEach(function (hdlr, index) {
- var handlerType = parseType_1(hdlr.subarray(8, 12));
- var tkhd = tkhds[index];
- var view;
- var version;
- var trackId;
-
- if (handlerType === 'vide') {
- view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- version = view.getUint8(0);
- trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
- videoTrackIds.push(trackId);
- }
- });
- });
- return videoTrackIds;
- };
-
- getTimescaleFromMediaHeader = function getTimescaleFromMediaHeader(mdhd) {
- // mdhd is a FullBox, meaning it will have its own version as the first byte
- var version = mdhd[0];
- var index = version === 0 ? 12 : 20;
- return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
- };
- /**
- * Get all the video, audio, and hint tracks from a non fragmented
- * mp4 segment
- */
-
-
- getTracks = function getTracks(init) {
- var traks = findBox_1(init, ['moov', 'trak']);
- var tracks = [];
- traks.forEach(function (trak) {
- var track = {};
- var tkhd = findBox_1(trak, ['tkhd'])[0];
- var view, tkhdVersion; // id
-
- if (tkhd) {
- view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- tkhdVersion = view.getUint8(0);
- track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
- }
-
- var hdlr = findBox_1(trak, ['mdia', 'hdlr'])[0]; // type
-
- if (hdlr) {
- var type = parseType_1(hdlr.subarray(8, 12));
-
- if (type === 'vide') {
- track.type = 'video';
- } else if (type === 'soun') {
- track.type = 'audio';
- } else {
- track.type = type;
- }
- } // codec
-
-
- var stsd = findBox_1(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
-
- if (stsd) {
- var sampleDescriptions = stsd.subarray(8); // gives the codec type string
-
- track.codec = parseType_1(sampleDescriptions.subarray(4, 8));
- var codecBox = findBox_1(sampleDescriptions, [track.codec])[0];
- var codecConfig, codecConfigType;
-
- if (codecBox) {
- // https://tools.ietf.org/html/rfc6381#section-3.3
- if (/^[a-z]vc[1-9]$/i.test(track.codec)) {
- // we don't need anything but the "config" parameter of the
- // avc1 codecBox
- codecConfig = codecBox.subarray(78);
- codecConfigType = parseType_1(codecConfig.subarray(4, 8));
-
- if (codecConfigType === 'avcC' && codecConfig.length > 11) {
- track.codec += '.'; // left padded with zeroes for single digit hex
- // profile idc
-
- track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
-
- track.codec += toHexString(codecConfig[10]); // level idc
-
- track.codec += toHexString(codecConfig[11]);
- } else {
- // TODO: show a warning that we couldn't parse the codec
- // and are using the default
- track.codec = 'avc1.4d400d';
- }
- } else if (/^mp4[a,v]$/i.test(track.codec)) {
- // we do not need anything but the streamDescriptor of the mp4a codecBox
- codecConfig = codecBox.subarray(28);
- codecConfigType = parseType_1(codecConfig.subarray(4, 8));
-
- if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
- track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
-
- track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
- } else {
- // TODO: show a warning that we couldn't parse the codec
- // and are using the default
- track.codec = 'mp4a.40.2';
- }
- } else {
- // flac, opus, etc
- track.codec = track.codec.toLowerCase();
- }
- }
- }
-
- var mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
-
- if (mdhd) {
- track.timescale = getTimescaleFromMediaHeader(mdhd);
- }
-
- tracks.push(track);
- });
- return tracks;
- };
-
- var probe$2 = {
- // export mp4 inspector's findBox and parseType for backwards compatibility
- findBox: findBox_1,
- parseType: parseType_1,
- timescale: timescale,
- startTime: startTime,
- compositionStartTime: compositionStartTime,
- videoTrackIds: getVideoTrackIds,
- tracks: getTracks,
- getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
- };
-
- var parsePid = function parsePid(packet) {
- var pid = packet[1] & 0x1f;
- pid <<= 8;
- pid |= packet[2];
- return pid;
- };
-
- var parsePayloadUnitStartIndicator = function parsePayloadUnitStartIndicator(packet) {
- return !!(packet[1] & 0x40);
- };
-
- var parseAdaptionField = function parseAdaptionField(packet) {
- var offset = 0; // if an adaption field is present, its length is specified by the
- // fifth byte of the TS packet header. The adaptation field is
- // used to add stuffing to PES packets that don't fill a complete
- // TS packet, and to specify some forms of timing and control data
- // that we do not currently use.
-
- if ((packet[3] & 0x30) >>> 4 > 0x01) {
- offset += packet[4] + 1;
- }
-
- return offset;
- };
-
- var parseType = function parseType(packet, pmtPid) {
- var pid = parsePid(packet);
-
- if (pid === 0) {
- return 'pat';
- } else if (pid === pmtPid) {
- return 'pmt';
- } else if (pmtPid) {
- return 'pes';
- }
-
- return null;
- };
-
- var parsePat = function parsePat(packet) {
- var pusi = parsePayloadUnitStartIndicator(packet);
- var offset = 4 + parseAdaptionField(packet);
-
- if (pusi) {
- offset += packet[offset] + 1;
- }
-
- return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
- };
-
- var parsePmt = function parsePmt(packet) {
- var programMapTable = {};
- var pusi = parsePayloadUnitStartIndicator(packet);
- var payloadOffset = 4 + parseAdaptionField(packet);
-
- if (pusi) {
- payloadOffset += packet[payloadOffset] + 1;
- } // PMTs can be sent ahead of the time when they should actually
- // take effect. We don't believe this should ever be the case
- // for HLS but we'll ignore "forward" PMT declarations if we see
- // them. Future PMT declarations have the current_next_indicator
- // set to zero.
-
-
- if (!(packet[payloadOffset + 5] & 0x01)) {
- return;
- }
-
- var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
-
- sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
- tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
- // long the program info descriptors are
-
- programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
-
- var offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
-
- programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
- // skip past the elementary stream descriptors, if present
-
- offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
- }
-
- return programMapTable;
- };
-
- var parsePesType = function parsePesType(packet, programMapTable) {
- var pid = parsePid(packet);
- var type = programMapTable[pid];
-
- switch (type) {
- case streamTypes.H264_STREAM_TYPE:
- return 'video';
-
- case streamTypes.ADTS_STREAM_TYPE:
- return 'audio';
-
- case streamTypes.METADATA_STREAM_TYPE:
- return 'timed-metadata';
-
- default:
- return null;
- }
- };
-
- var parsePesTime = function parsePesTime(packet) {
- var pusi = parsePayloadUnitStartIndicator(packet);
-
- if (!pusi) {
- return null;
- }
-
- var offset = 4 + parseAdaptionField(packet);
-
- if (offset >= packet.byteLength) {
- // From the H 222.0 MPEG-TS spec
- // "For transport stream packets carrying PES packets, stuffing is needed when there
- // is insufficient PES packet data to completely fill the transport stream packet
- // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
- // the sum of the lengths of the data elements in it, so that the payload bytes
- // remaining after the adaptation field exactly accommodates the available PES packet
- // data."
- //
- // If the offset is >= the length of the packet, then the packet contains no data
- // and instead is just adaption field stuffing bytes
- return null;
- }
-
- var pes = null;
- var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
- // and a DTS value. Determine what combination of values is
- // available to work with.
-
- ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
- // performs all bitwise operations on 32-bit integers but javascript
- // supports a much greater range (52-bits) of integer using standard
- // mathematical operations.
- // We construct a 31-bit value using bitwise operators over the 31
- // most significant bits and then multiply by 4 (equal to a left-shift
- // of 2) before we add the final 2 least significant bits of the
- // timestamp (equal to an OR.)
-
- if (ptsDtsFlags & 0xC0) {
- pes = {}; // the PTS and DTS are not written out directly. For information
- // on how they are encoded, see
- // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
-
- pes.pts = (packet[offset + 9] & 0x0E) << 27 | (packet[offset + 10] & 0xFF) << 20 | (packet[offset + 11] & 0xFE) << 12 | (packet[offset + 12] & 0xFF) << 5 | (packet[offset + 13] & 0xFE) >>> 3;
- pes.pts *= 4; // Left shift by 2
-
- pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
-
- pes.dts = pes.pts;
-
- if (ptsDtsFlags & 0x40) {
- pes.dts = (packet[offset + 14] & 0x0E) << 27 | (packet[offset + 15] & 0xFF) << 20 | (packet[offset + 16] & 0xFE) << 12 | (packet[offset + 17] & 0xFF) << 5 | (packet[offset + 18] & 0xFE) >>> 3;
- pes.dts *= 4; // Left shift by 2
-
- pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
- }
- }
-
- return pes;
- };
-
- var parseNalUnitType = function parseNalUnitType(type) {
- switch (type) {
- case 0x05:
- return 'slice_layer_without_partitioning_rbsp_idr';
-
- case 0x06:
- return 'sei_rbsp';
-
- case 0x07:
- return 'seq_parameter_set_rbsp';
-
- case 0x08:
- return 'pic_parameter_set_rbsp';
-
- case 0x09:
- return 'access_unit_delimiter_rbsp';
-
- default:
- return null;
- }
- };
-
- var videoPacketContainsKeyFrame = function videoPacketContainsKeyFrame(packet) {
- var offset = 4 + parseAdaptionField(packet);
- var frameBuffer = packet.subarray(offset);
- var frameI = 0;
- var frameSyncPoint = 0;
- var foundKeyFrame = false;
- var nalType; // advance the sync point to a NAL start, if necessary
-
- for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
- if (frameBuffer[frameSyncPoint + 2] === 1) {
- // the sync point is properly aligned
- frameI = frameSyncPoint + 5;
- break;
- }
- }
-
- while (frameI < frameBuffer.byteLength) {
- // look at the current byte to determine if we've hit the end of
- // a NAL unit boundary
- switch (frameBuffer[frameI]) {
- case 0:
- // skip past non-sync sequences
- if (frameBuffer[frameI - 1] !== 0) {
- frameI += 2;
- break;
- } else if (frameBuffer[frameI - 2] !== 0) {
- frameI++;
- break;
- }
-
- if (frameSyncPoint + 3 !== frameI - 2) {
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
- } // drop trailing zeroes
-
-
- do {
- frameI++;
- } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
-
- frameSyncPoint = frameI - 2;
- frameI += 3;
- break;
-
- case 1:
- // skip past non-sync sequences
- if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
- frameI += 3;
- break;
- }
-
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
-
- frameSyncPoint = frameI - 2;
- frameI += 3;
- break;
-
- default:
- // the current byte isn't a one or zero, so it cannot be part
- // of a sync sequence
- frameI += 3;
- break;
- }
- }
-
- frameBuffer = frameBuffer.subarray(frameSyncPoint);
- frameI -= frameSyncPoint;
- frameSyncPoint = 0; // parse the final nal
-
- if (frameBuffer && frameBuffer.byteLength > 3) {
- nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
-
- if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
- foundKeyFrame = true;
- }
- }
-
- return foundKeyFrame;
- };
-
- var probe$1 = {
- parseType: parseType,
- parsePat: parsePat,
- parsePmt: parsePmt,
- parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
- parsePesType: parsePesType,
- parsePesTime: parsePesTime,
- videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
- };
- var handleRollover = timestampRolloverStream.handleRollover;
- var probe = {};
- probe.ts = probe$1;
- probe.aac = utils;
- var ONE_SECOND_IN_TS = clock.ONE_SECOND_IN_TS;
- var MP2T_PACKET_LENGTH = 188,
- // bytes
- SYNC_BYTE = 0x47;
- /**
- * walks through segment data looking for pat and pmt packets to parse out
- * program map table information
- */
-
- var parsePsi_ = function parsePsi_(bytes, pmt) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type;
-
- while (endIndex < bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pat':
- pmt.pid = probe.ts.parsePat(packet);
- break;
-
- case 'pmt':
- var table = probe.ts.parsePmt(packet);
- pmt.table = pmt.table || {};
- Object.keys(table).forEach(function (key) {
- pmt.table[key] = table[key];
- });
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- }
- };
- /**
- * walks through the segment data from the start and end to get timing information
- * for the first and last audio pes packets
- */
-
-
- var parseAudioPes_ = function parseAudioPes_(bytes, pmt, result) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type,
- pesType,
- pusi,
- parsed;
- var endLoop = false; // Start walking from start of segment to get first audio packet
-
- while (endIndex <= bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'audio' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'audio';
- result.audio.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // Start walking from end of segment to get last audio packet
-
-
- endIndex = bytes.byteLength;
- startIndex = endIndex - MP2T_PACKET_LENGTH;
- endLoop = false;
-
- while (startIndex >= 0) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'audio' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'audio';
- result.audio.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex -= MP2T_PACKET_LENGTH;
- endIndex -= MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex--;
- endIndex--;
- }
- };
- /**
- * walks through the segment data from the start and end to get timing information
- * for the first and last video pes packets as well as timing information for the first
- * key frame.
- */
-
-
- var parseVideoPes_ = function parseVideoPes_(bytes, pmt, result) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- packet,
- type,
- pesType,
- pusi,
- parsed,
- frame,
- i,
- pes;
- var endLoop = false;
- var currentFrame = {
- data: [],
- size: 0
- }; // Start walking from start of segment to get first video packet
-
- while (endIndex < bytes.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'video') {
- if (pusi && !endLoop) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'video';
- result.video.push(parsed);
- endLoop = true;
- }
- }
-
- if (!result.firstKeyFrame) {
- if (pusi) {
- if (currentFrame.size !== 0) {
- frame = new Uint8Array(currentFrame.size);
- i = 0;
-
- while (currentFrame.data.length) {
- pes = currentFrame.data.shift();
- frame.set(pes, i);
- i += pes.byteLength;
- }
-
- if (probe.ts.videoPacketContainsKeyFrame(frame)) {
- var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
- // the keyframe seems to work fine with HLS playback
- // and definitely preferable to a crash with TypeError...
-
- if (firstKeyFrame) {
- result.firstKeyFrame = firstKeyFrame;
- result.firstKeyFrame.type = 'video';
- } else {
- // eslint-disable-next-line
- console.warn('Failed to extract PTS/DTS from PES at first keyframe. ' + 'This could be an unusual TS segment, or else mux.js did not ' + 'parse your TS segment correctly. If you know your TS ' + 'segments do contain PTS/DTS on keyframes please file a bug ' + 'report! You can try ffprobe to double check for yourself.');
- }
- }
-
- currentFrame.size = 0;
- }
- }
-
- currentFrame.data.push(packet);
- currentFrame.size += packet.byteLength;
- }
- }
-
- break;
- }
-
- if (endLoop && result.firstKeyFrame) {
- break;
- }
-
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // Start walking from end of segment to get last video packet
-
-
- endIndex = bytes.byteLength;
- startIndex = endIndex - MP2T_PACKET_LENGTH;
- endLoop = false;
-
- while (startIndex >= 0) {
- // Look for a pair of start and end sync bytes in the data..
- if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
- // We found a packet
- packet = bytes.subarray(startIndex, endIndex);
- type = probe.ts.parseType(packet, pmt.pid);
-
- switch (type) {
- case 'pes':
- pesType = probe.ts.parsePesType(packet, pmt.table);
- pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
-
- if (pesType === 'video' && pusi) {
- parsed = probe.ts.parsePesTime(packet);
-
- if (parsed) {
- parsed.type = 'video';
- result.video.push(parsed);
- endLoop = true;
- }
- }
-
- break;
- }
-
- if (endLoop) {
- break;
- }
-
- startIndex -= MP2T_PACKET_LENGTH;
- endIndex -= MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex--;
- endIndex--;
- }
- };
- /**
- * Adjusts the timestamp information for the segment to account for
- * rollover and convert to seconds based on pes packet timescale (90khz clock)
- */
-
-
- var adjustTimestamp_ = function adjustTimestamp_(segmentInfo, baseTimestamp) {
- if (segmentInfo.audio && segmentInfo.audio.length) {
- var audioBaseTimestamp = baseTimestamp;
-
- if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
- audioBaseTimestamp = segmentInfo.audio[0].dts;
- }
-
- segmentInfo.audio.forEach(function (info) {
- info.dts = handleRollover(info.dts, audioBaseTimestamp);
- info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
-
- info.dtsTime = info.dts / ONE_SECOND_IN_TS;
- info.ptsTime = info.pts / ONE_SECOND_IN_TS;
- });
- }
-
- if (segmentInfo.video && segmentInfo.video.length) {
- var videoBaseTimestamp = baseTimestamp;
-
- if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
- videoBaseTimestamp = segmentInfo.video[0].dts;
- }
-
- segmentInfo.video.forEach(function (info) {
- info.dts = handleRollover(info.dts, videoBaseTimestamp);
- info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
-
- info.dtsTime = info.dts / ONE_SECOND_IN_TS;
- info.ptsTime = info.pts / ONE_SECOND_IN_TS;
- });
-
- if (segmentInfo.firstKeyFrame) {
- var frame = segmentInfo.firstKeyFrame;
- frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
- frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
-
- frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
- frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
- }
- }
- };
- /**
- * inspects the aac data stream for start and end time information
- */
-
-
- var inspectAac_ = function inspectAac_(bytes) {
- var endLoop = false,
- audioCount = 0,
- sampleRate = null,
- timestamp = null,
- frameSize = 0,
- byteIndex = 0,
- packet;
-
- while (bytes.length - byteIndex >= 3) {
- var type = probe.aac.parseType(bytes, byteIndex);
-
- switch (type) {
- case 'timed-metadata':
- // Exit early because we don't have enough to parse
- // the ID3 tag header
- if (bytes.length - byteIndex < 10) {
- endLoop = true;
- break;
- }
-
- frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (frameSize > bytes.length) {
- endLoop = true;
- break;
- }
-
- if (timestamp === null) {
- packet = bytes.subarray(byteIndex, byteIndex + frameSize);
- timestamp = probe.aac.parseAacTimestamp(packet);
- }
-
- byteIndex += frameSize;
- break;
-
- case 'audio':
- // Exit early because we don't have enough to parse
- // the ADTS frame header
- if (bytes.length - byteIndex < 7) {
- endLoop = true;
- break;
- }
-
- frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (frameSize > bytes.length) {
- endLoop = true;
- break;
- }
-
- if (sampleRate === null) {
- packet = bytes.subarray(byteIndex, byteIndex + frameSize);
- sampleRate = probe.aac.parseSampleRate(packet);
- }
-
- audioCount++;
- byteIndex += frameSize;
- break;
-
- default:
- byteIndex++;
- break;
- }
-
- if (endLoop) {
- return null;
- }
- }
-
- if (sampleRate === null || timestamp === null) {
- return null;
- }
-
- var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
- var result = {
- audio: [{
- type: 'audio',
- dts: timestamp,
- pts: timestamp
- }, {
- type: 'audio',
- dts: timestamp + audioCount * 1024 * audioTimescale,
- pts: timestamp + audioCount * 1024 * audioTimescale
- }]
- };
- return result;
- };
- /**
- * inspects the transport stream segment data for start and end time information
- * of the audio and video tracks (when present) as well as the first key frame's
- * start time.
- */
-
-
- var inspectTs_ = function inspectTs_(bytes) {
- var pmt = {
- pid: null,
- table: null
- };
- var result = {};
- parsePsi_(bytes, pmt);
-
- for (var pid in pmt.table) {
- if (pmt.table.hasOwnProperty(pid)) {
- var type = pmt.table[pid];
-
- switch (type) {
- case streamTypes.H264_STREAM_TYPE:
- result.video = [];
- parseVideoPes_(bytes, pmt, result);
-
- if (result.video.length === 0) {
- delete result.video;
- }
-
- break;
-
- case streamTypes.ADTS_STREAM_TYPE:
- result.audio = [];
- parseAudioPes_(bytes, pmt, result);
-
- if (result.audio.length === 0) {
- delete result.audio;
- }
-
- break;
- }
- }
- }
-
- return result;
- };
- /**
- * Inspects segment byte data and returns an object with start and end timing information
- *
- * @param {Uint8Array} bytes The segment byte data
- * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
- * timestamps for rollover. This value must be in 90khz clock.
- * @return {Object} Object containing start and end frame timing info of segment.
- */
-
-
- var inspect = function inspect(bytes, baseTimestamp) {
- var isAacData = probe.aac.isLikelyAacData(bytes);
- var result;
-
- if (isAacData) {
- result = inspectAac_(bytes);
- } else {
- result = inspectTs_(bytes);
- }
-
- if (!result || !result.audio && !result.video) {
- return null;
- }
-
- adjustTimestamp_(result, baseTimestamp);
- return result;
- };
-
- var tsInspector = {
- inspect: inspect,
- parseAudioPes_: parseAudioPes_
- };
- /* global self */
-
- /**
- * Re-emits transmuxer events by converting them into messages to the
- * world outside the worker.
- *
- * @param {Object} transmuxer the transmuxer to wire events on
- * @private
- */
-
- var wireTransmuxerEvents = function wireTransmuxerEvents(self, transmuxer) {
- transmuxer.on('data', function (segment) {
- // transfer ownership of the underlying ArrayBuffer
- // instead of doing a copy to save memory
- // ArrayBuffers are transferable but generic TypedArrays are not
- // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
- var initArray = segment.initSegment;
- segment.initSegment = {
- data: initArray.buffer,
- byteOffset: initArray.byteOffset,
- byteLength: initArray.byteLength
- };
- var typedArray = segment.data;
- segment.data = typedArray.buffer;
- self.postMessage({
- action: 'data',
- segment: segment,
- byteOffset: typedArray.byteOffset,
- byteLength: typedArray.byteLength
- }, [segment.data]);
- });
- transmuxer.on('done', function (data) {
- self.postMessage({
- action: 'done'
- });
- });
- transmuxer.on('gopInfo', function (gopInfo) {
- self.postMessage({
- action: 'gopInfo',
- gopInfo: gopInfo
- });
- });
- transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
- var videoSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- videoSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'videoSegmentTimingInfo',
- videoSegmentTimingInfo: videoSegmentTimingInfo
- });
- });
- transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
- // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
- var audioSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- audioSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'audioSegmentTimingInfo',
- audioSegmentTimingInfo: audioSegmentTimingInfo
- });
- });
- transmuxer.on('id3Frame', function (id3Frame) {
- self.postMessage({
- action: 'id3Frame',
- id3Frame: id3Frame
- });
- });
- transmuxer.on('caption', function (caption) {
- self.postMessage({
- action: 'caption',
- caption: caption
- });
- });
- transmuxer.on('trackinfo', function (trackInfo) {
- self.postMessage({
- action: 'trackinfo',
- trackInfo: trackInfo
- });
- });
- transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
- // convert to video TS since we prioritize video time over audio
- self.postMessage({
- action: 'audioTimingInfo',
- audioTimingInfo: {
- start: clock.videoTsToSeconds(audioTimingInfo.start),
- end: clock.videoTsToSeconds(audioTimingInfo.end)
- }
- });
- });
- transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
- self.postMessage({
- action: 'videoTimingInfo',
- videoTimingInfo: {
- start: clock.videoTsToSeconds(videoTimingInfo.start),
- end: clock.videoTsToSeconds(videoTimingInfo.end)
- }
- });
- });
- };
- /**
- * All incoming messages route through this hash. If no function exists
- * to handle an incoming message, then we ignore the message.
- *
- * @class MessageHandlers
- * @param {Object} options the options to initialize with
- */
-
-
- var MessageHandlers = /*#__PURE__*/function () {
- function MessageHandlers(self, options) {
- this.options = options || {};
- this.self = self;
- this.init();
- }
- /**
- * initialize our web worker and wire all the events.
- */
-
-
- var _proto = MessageHandlers.prototype;
-
- _proto.init = function init() {
- if (this.transmuxer) {
- this.transmuxer.dispose();
- }
-
- this.transmuxer = new transmuxer.Transmuxer(this.options);
- wireTransmuxerEvents(this.self, this.transmuxer);
- };
-
- _proto.pushMp4Captions = function pushMp4Captions(data) {
- if (!this.captionParser) {
- this.captionParser = new captionParser();
- this.captionParser.init();
- }
-
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- var parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
- this.self.postMessage({
- action: 'mp4Captions',
- captions: parsed && parsed.captions || [],
- data: segment.buffer
- }, [segment.buffer]);
- };
-
- _proto.probeMp4StartTime = function probeMp4StartTime(_ref) {
- var timescales = _ref.timescales,
- data = _ref.data;
- var startTime = probe$2.startTime(timescales, data);
- this.self.postMessage({
- action: 'probeMp4StartTime',
- startTime: startTime,
- data: data
- }, [data.buffer]);
- };
-
- _proto.probeMp4Tracks = function probeMp4Tracks(_ref2) {
- var data = _ref2.data;
- var tracks = probe$2.tracks(data);
- this.self.postMessage({
- action: 'probeMp4Tracks',
- tracks: tracks,
- data: data
- }, [data.buffer]);
- }
- /**
- * Probe an mpeg2-ts segment to determine the start time of the segment in it's
- * internal "media time," as well as whether it contains video and/or audio.
- *
- * @private
- * @param {Uint8Array} bytes - segment bytes
- * @param {number} baseStartTime
- * Relative reference timestamp used when adjusting frame timestamps for rollover.
- * This value should be in seconds, as it's converted to a 90khz clock within the
- * function body.
- * @return {Object} The start time of the current segment in "media time" as well as
- * whether it contains video and/or audio
- */
- ;
-
- _proto.probeTs = function probeTs(_ref3) {
- var data = _ref3.data,
- baseStartTime = _ref3.baseStartTime;
- var tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock.ONE_SECOND_IN_TS : void 0;
- var timeInfo = tsInspector.inspect(data, tsStartTime);
- var result = null;
-
- if (timeInfo) {
- result = {
- // each type's time info comes back as an array of 2 times, start and end
- hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
- hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
- };
-
- if (result.hasVideo) {
- result.videoStart = timeInfo.video[0].ptsTime;
- }
-
- if (result.hasAudio) {
- result.audioStart = timeInfo.audio[0].ptsTime;
- }
- }
-
- this.self.postMessage({
- action: 'probeTs',
- result: result,
- data: data
- }, [data.buffer]);
- };
-
- _proto.clearAllMp4Captions = function clearAllMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearAllCaptions();
- }
- };
-
- _proto.clearParsedMp4Captions = function clearParsedMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearParsedCaptions();
- }
- }
- /**
- * Adds data (a ts segment) to the start of the transmuxer pipeline for
- * processing.
- *
- * @param {ArrayBuffer} data data to push into the muxer
- */
- ;
-
- _proto.push = function push(data) {
- // Cast array buffer to correct type for transmuxer
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- this.transmuxer.push(segment);
- }
- /**
- * Recreate the transmuxer so that the next segment added via `push`
- * start with a fresh transmuxer.
- */
- ;
-
- _proto.reset = function reset() {
- this.transmuxer.reset();
- }
- /**
- * Set the value that will be used as the `baseMediaDecodeTime` time for the
- * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
- * set relative to the first based on the PTS values.
- *
- * @param {Object} data used to set the timestamp offset in the muxer
- */
- ;
-
- _proto.setTimestampOffset = function setTimestampOffset(data) {
- var timestampOffset = data.timestampOffset || 0;
- this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset)));
- };
-
- _proto.setAudioAppendStart = function setAudioAppendStart(data) {
- this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));
- };
-
- _proto.setRemux = function setRemux(data) {
- this.transmuxer.setRemux(data.remux);
- }
- /**
- * Forces the pipeline to finish processing the last segment and emit it's
- * results.
- *
- * @param {Object} data event data, not really used
- */
- ;
-
- _proto.flush = function flush(data) {
- this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
-
- self.postMessage({
- action: 'done',
- type: 'transmuxed'
- });
- };
-
- _proto.endTimeline = function endTimeline() {
- this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
- // timelines
-
- self.postMessage({
- action: 'endedtimeline',
- type: 'transmuxed'
- });
- };
-
- _proto.alignGopsWith = function alignGopsWith(data) {
- this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
- };
-
- return MessageHandlers;
- }();
- /**
- * Our web worker interface so that things can talk to mux.js
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- *
- * @param {Object} self the scope for the web worker
- */
-
-
- self.onmessage = function (event) {
- if (event.data.action === 'init' && event.data.options) {
- this.messageHandlers = new MessageHandlers(self, event.data.options);
- return;
- }
-
- if (!this.messageHandlers) {
- this.messageHandlers = new MessageHandlers(self);
- }
-
- if (event.data && event.data.action && event.data.action !== 'init') {
- if (this.messageHandlers[event.data.action]) {
- this.messageHandlers[event.data.action](event.data);
- }
- }
- };
- }));
- var TransmuxWorker = factory(workerCode$1);
- /* rollup-plugin-worker-factory end for worker!/Users/gkatsevman/p/http-streaming-release/src/transmuxer-worker.js */
-
- var handleData_ = function handleData_(event, transmuxedData, callback) {
- var _event$data$segment = event.data.segment,
- type = _event$data$segment.type,
- initSegment = _event$data$segment.initSegment,
- captions = _event$data$segment.captions,
- captionStreams = _event$data$segment.captionStreams,
- metadata = _event$data$segment.metadata,
- videoFrameDtsTime = _event$data$segment.videoFrameDtsTime,
- videoFramePtsTime = _event$data$segment.videoFramePtsTime;
- transmuxedData.buffer.push({
- captions: captions,
- captionStreams: captionStreams,
- metadata: metadata
- });
- var boxes = event.data.segment.boxes || {
- data: event.data.segment.data
- };
- var result = {
- type: type,
- // cast ArrayBuffer to TypedArray
- data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
- initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
- };
-
- if (typeof videoFrameDtsTime !== 'undefined') {
- result.videoFrameDtsTime = videoFrameDtsTime;
- }
-
- if (typeof videoFramePtsTime !== 'undefined') {
- result.videoFramePtsTime = videoFramePtsTime;
- }
-
- callback(result);
- };
- var handleDone_ = function handleDone_(_ref) {
- var transmuxedData = _ref.transmuxedData,
- callback = _ref.callback;
- // Previously we only returned data on data events,
- // not on done events. Clear out the buffer to keep that consistent.
- transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
- // have received
-
- callback(transmuxedData);
- };
- var handleGopInfo_ = function handleGopInfo_(event, transmuxedData) {
- transmuxedData.gopInfo = event.data.gopInfo;
- };
- var processTransmux = function processTransmux(options) {
- var transmuxer = options.transmuxer,
- bytes = options.bytes,
- audioAppendStart = options.audioAppendStart,
- gopsToAlignWith = options.gopsToAlignWith,
- remux = options.remux,
- onData = options.onData,
- onTrackInfo = options.onTrackInfo,
- onAudioTimingInfo = options.onAudioTimingInfo,
- onVideoTimingInfo = options.onVideoTimingInfo,
- onVideoSegmentTimingInfo = options.onVideoSegmentTimingInfo,
- onAudioSegmentTimingInfo = options.onAudioSegmentTimingInfo,
- onId3 = options.onId3,
- onCaptions = options.onCaptions,
- onDone = options.onDone,
- onEndedTimeline = options.onEndedTimeline,
- isEndOfTimeline = options.isEndOfTimeline;
- var transmuxedData = {
- buffer: []
- };
- var waitForEndedTimelineEvent = isEndOfTimeline;
-
- var handleMessage = function handleMessage(event) {
- if (transmuxer.currentTransmux !== options) {
- // disposed
- return;
- }
-
- if (event.data.action === 'data') {
- handleData_(event, transmuxedData, onData);
- }
-
- if (event.data.action === 'trackinfo') {
- onTrackInfo(event.data.trackInfo);
- }
-
- if (event.data.action === 'gopInfo') {
- handleGopInfo_(event, transmuxedData);
- }
-
- if (event.data.action === 'audioTimingInfo') {
- onAudioTimingInfo(event.data.audioTimingInfo);
- }
-
- if (event.data.action === 'videoTimingInfo') {
- onVideoTimingInfo(event.data.videoTimingInfo);
- }
-
- if (event.data.action === 'videoSegmentTimingInfo') {
- onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
- }
-
- if (event.data.action === 'audioSegmentTimingInfo') {
- onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
- }
-
- if (event.data.action === 'id3Frame') {
- onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
- }
-
- if (event.data.action === 'caption') {
- onCaptions(event.data.caption);
- }
-
- if (event.data.action === 'endedtimeline') {
- waitForEndedTimelineEvent = false;
- onEndedTimeline();
- } // wait for the transmuxed event since we may have audio and video
-
-
- if (event.data.type !== 'transmuxed') {
- return;
- } // If the "endedtimeline" event has not yet fired, and this segment represents the end
- // of a timeline, that means there may still be data events before the segment
- // processing can be considerred complete. In that case, the final event should be
- // an "endedtimeline" event with the type "transmuxed."
-
-
- if (waitForEndedTimelineEvent) {
- return;
- }
-
- transmuxer.onmessage = null;
- handleDone_({
- transmuxedData: transmuxedData,
- callback: onDone
- });
- /* eslint-disable no-use-before-define */
-
- dequeue(transmuxer);
- /* eslint-enable */
- };
-
- transmuxer.onmessage = handleMessage;
-
- if (audioAppendStart) {
- transmuxer.postMessage({
- action: 'setAudioAppendStart',
- appendStart: audioAppendStart
- });
- } // allow empty arrays to be passed to clear out GOPs
-
-
- if (Array.isArray(gopsToAlignWith)) {
- transmuxer.postMessage({
- action: 'alignGopsWith',
- gopsToAlignWith: gopsToAlignWith
- });
- }
-
- if (typeof remux !== 'undefined') {
- transmuxer.postMessage({
- action: 'setRemux',
- remux: remux
- });
- }
-
- if (bytes.byteLength) {
- var buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
- var byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
- transmuxer.postMessage({
- action: 'push',
- // Send the typed-array of data as an ArrayBuffer so that
- // it can be sent as a "Transferable" and avoid the costly
- // memory copy
- data: buffer,
- // To recreate the original typed-array, we need information
- // about what portion of the ArrayBuffer it was a view into
- byteOffset: byteOffset,
- byteLength: bytes.byteLength
- }, [buffer]);
- }
-
- if (isEndOfTimeline) {
- transmuxer.postMessage({
- action: 'endTimeline'
- });
- } // even if we didn't push any bytes, we have to make sure we flush in case we reached
- // the end of the segment
-
-
- transmuxer.postMessage({
- action: 'flush'
- });
- };
- var dequeue = function dequeue(transmuxer) {
- transmuxer.currentTransmux = null;
-
- if (transmuxer.transmuxQueue.length) {
- transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
-
- if (typeof transmuxer.currentTransmux === 'function') {
- transmuxer.currentTransmux();
- } else {
- processTransmux(transmuxer.currentTransmux);
- }
- }
- };
- var processAction = function processAction(transmuxer, action) {
- transmuxer.postMessage({
- action: action
- });
- dequeue(transmuxer);
- };
- var enqueueAction = function enqueueAction(action, transmuxer) {
- if (!transmuxer.currentTransmux) {
- transmuxer.currentTransmux = action;
- processAction(transmuxer, action);
- return;
- }
-
- transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
- };
- var reset = function reset(transmuxer) {
- enqueueAction('reset', transmuxer);
- };
- var endTimeline = function endTimeline(transmuxer) {
- enqueueAction('endTimeline', transmuxer);
- };
- var transmux = function transmux(options) {
- if (!options.transmuxer.currentTransmux) {
- options.transmuxer.currentTransmux = options;
- processTransmux(options);
- return;
- }
-
- options.transmuxer.transmuxQueue.push(options);
- };
- var createTransmuxer = function createTransmuxer(options) {
- var transmuxer = new TransmuxWorker();
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue = [];
- var term = transmuxer.terminate;
-
- transmuxer.terminate = function () {
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue.length = 0;
- return term.call(transmuxer);
- };
-
- transmuxer.postMessage({
- action: 'init',
- options: options
- });
- return transmuxer;
- };
- var segmentTransmuxer = {
- reset: reset,
- endTimeline: endTimeline,
- transmux: transmux,
- createTransmuxer: createTransmuxer
- };
-
- var workerCallback = function workerCallback(options) {
- var transmuxer = options.transmuxer;
- var endAction = options.endAction || options.action;
- var callback = options.callback;
-
- var message = _extends_1({}, options, {
- endAction: null,
- transmuxer: null,
- callback: null
- });
-
- var listenForEndEvent = function listenForEndEvent(event) {
- if (event.data.action !== endAction) {
- return;
- }
-
- transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
-
- if (event.data.data) {
- event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
-
- if (options.data) {
- options.data = event.data.data;
- }
- }
-
- callback(event.data);
- };
-
- transmuxer.addEventListener('message', listenForEndEvent);
-
- if (options.data) {
- var isArrayBuffer = options.data instanceof ArrayBuffer;
- message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
- message.byteLength = options.data.byteLength;
- var transfers = [isArrayBuffer ? options.data : options.data.buffer];
- transmuxer.postMessage(message, transfers);
- } else {
- transmuxer.postMessage(message);
- }
- };
-
- var REQUEST_ERRORS = {
- FAILURE: 2,
- TIMEOUT: -101,
- ABORTED: -102
- };
- /**
- * Abort all requests
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- */
-
- var abortAll = function abortAll(activeXhrs) {
- activeXhrs.forEach(function (xhr) {
- xhr.abort();
- });
- };
- /**
- * Gather important bandwidth stats once a request has completed
- *
- * @param {Object} request - the XHR request from which to gather stats
- */
-
-
- var getRequestStats = function getRequestStats(request) {
- return {
- bandwidth: request.bandwidth,
- bytesReceived: request.bytesReceived || 0,
- roundTripTime: request.roundTripTime || 0
- };
- };
- /**
- * If possible gather bandwidth stats as a request is in
- * progress
- *
- * @param {Event} progressEvent - an event object from an XHR's progress event
- */
-
-
- var getProgressStats = function getProgressStats(progressEvent) {
- var request = progressEvent.target;
- var roundTripTime = Date.now() - request.requestTime;
- var stats = {
- bandwidth: Infinity,
- bytesReceived: 0,
- roundTripTime: roundTripTime || 0
- };
- stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
- // because we should only use bandwidth stats on progress to determine when
- // abort a request early due to insufficient bandwidth
-
- stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
- return stats;
- };
- /**
- * Handle all error conditions in one place and return an object
- * with all the information
- *
- * @param {Error|null} error - if non-null signals an error occured with the XHR
- * @param {Object} request - the XHR request that possibly generated the error
- */
-
-
- var handleErrors = function handleErrors(error, request) {
- if (request.timedout) {
- return {
- status: request.status,
- message: 'HLS request timed-out at URL: ' + request.uri,
- code: REQUEST_ERRORS.TIMEOUT,
- xhr: request
- };
- }
-
- if (request.aborted) {
- return {
- status: request.status,
- message: 'HLS request aborted at URL: ' + request.uri,
- code: REQUEST_ERRORS.ABORTED,
- xhr: request
- };
- }
-
- if (error) {
- return {
- status: request.status,
- message: 'HLS request errored at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
- return {
- status: request.status,
- message: 'Empty HLS response at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- return null;
- };
- /**
- * Handle responses for key data and convert the key data to the correct format
- * for the decryption step later
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Array} objects - objects to add the key bytes to.
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
- var handleKeyResponse = function handleKeyResponse(segment, objects, finishProcessingFn) {
- return function (error, request) {
- var response = request.response;
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- if (response.byteLength !== 16) {
- return finishProcessingFn({
- status: request.status,
- message: 'Invalid HLS key at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- }, segment);
- }
-
- var view = new DataView(response);
- var bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
-
- for (var i = 0; i < objects.length; i++) {
- objects[i].bytes = bytes;
- }
-
- return finishProcessingFn(null, segment);
- };
- };
-
- var parseInitSegment = function parseInitSegment(segment, _callback) {
- var type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
- // only know how to parse mp4 init segments at the moment
-
- if (type !== 'mp4') {
- var uri = segment.map.resolvedUri || segment.map.uri;
- return _callback({
- internal: true,
- message: "Found unsupported " + (type || 'unknown') + " container for initialization segment at URL: " + uri,
- code: REQUEST_ERRORS.FAILURE
- });
- }
-
- workerCallback({
- action: 'probeMp4Tracks',
- data: segment.map.bytes,
- transmuxer: segment.transmuxer,
- callback: function callback(_ref) {
- var tracks = _ref.tracks,
- data = _ref.data;
- // transfer bytes back to us
- segment.map.bytes = data;
- tracks.forEach(function (track) {
- segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
-
- if (segment.map.tracks[track.type]) {
- return;
- }
-
- segment.map.tracks[track.type] = track;
-
- if (typeof track.id === 'number' && track.timescale) {
- segment.map.timescales = segment.map.timescales || {};
- segment.map.timescales[track.id] = track.timescale;
- }
- });
- return _callback(null);
- }
- });
- };
- /**
- * Handle init-segment responses
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
- var handleInitSegmentResponse = function handleInitSegmentResponse(_ref2) {
- var segment = _ref2.segment,
- finishProcessingFn = _ref2.finishProcessingFn;
- return function (error, request) {
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- var bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
- // until the key request is done to decrypt.
-
- if (segment.map.key) {
- segment.map.encryptedBytes = bytes;
- return finishProcessingFn(null, segment);
- }
-
- segment.map.bytes = bytes;
- parseInitSegment(segment, function (parseError) {
- if (parseError) {
- parseError.xhr = request;
- parseError.status = request.status;
- return finishProcessingFn(parseError, segment);
- }
-
- finishProcessingFn(null, segment);
- });
- };
- };
- /**
- * Response handler for segment-requests being sure to set the correct
- * property depending on whether the segment is encryped or not
- * Also records and keeps track of stats that are used for ABR purposes
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-
-
- var handleSegmentResponse = function handleSegmentResponse(_ref3) {
- var segment = _ref3.segment,
- finishProcessingFn = _ref3.finishProcessingFn,
- responseType = _ref3.responseType;
- return function (error, request) {
- var errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- var newBytes = // although responseText "should" exist, this guard serves to prevent an error being
- // thrown for two primary cases:
- // 1. the mime type override stops working, or is not implemented for a specific
- // browser
- // 2. when using mock XHR libraries like sinon that do not allow the override behavior
- responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
- segment.stats = getRequestStats(request);
-
- if (segment.key) {
- segment.encryptedBytes = new Uint8Array(newBytes);
- } else {
- segment.bytes = new Uint8Array(newBytes);
- }
-
- return finishProcessingFn(null, segment);
- };
- };
-
- var transmuxAndNotify = function transmuxAndNotify(_ref4) {
- var segment = _ref4.segment,
- bytes = _ref4.bytes,
- trackInfoFn = _ref4.trackInfoFn,
- timingInfoFn = _ref4.timingInfoFn,
- videoSegmentTimingInfoFn = _ref4.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref4.audioSegmentTimingInfoFn,
- id3Fn = _ref4.id3Fn,
- captionsFn = _ref4.captionsFn,
- isEndOfTimeline = _ref4.isEndOfTimeline,
- endedTimelineFn = _ref4.endedTimelineFn,
- dataFn = _ref4.dataFn,
- doneFn = _ref4.doneFn;
- var fmp4Tracks = segment.map && segment.map.tracks || {};
- var isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
- // One reason for this is that in the case of full segments, we want to trust start
- // times from the probe, rather than the transmuxer.
-
- var audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
- var audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
- var videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
- var videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
-
- var finish = function finish() {
- return transmux({
- bytes: bytes,
- transmuxer: segment.transmuxer,
- audioAppendStart: segment.audioAppendStart,
- gopsToAlignWith: segment.gopsToAlignWith,
- remux: isMuxed,
- onData: function onData(result) {
- result.type = result.type === 'combined' ? 'video' : result.type;
- dataFn(segment, result);
- },
- onTrackInfo: function onTrackInfo(trackInfo) {
- if (trackInfoFn) {
- if (isMuxed) {
- trackInfo.isMuxed = true;
- }
-
- trackInfoFn(segment, trackInfo);
- }
- },
- onAudioTimingInfo: function onAudioTimingInfo(audioTimingInfo) {
- // we only want the first start value we encounter
- if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
- audioStartFn(audioTimingInfo.start);
- audioStartFn = null;
- } // we want to continually update the end time
-
-
- if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
- audioEndFn(audioTimingInfo.end);
- }
- },
- onVideoTimingInfo: function onVideoTimingInfo(videoTimingInfo) {
- // we only want the first start value we encounter
- if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
- videoStartFn(videoTimingInfo.start);
- videoStartFn = null;
- } // we want to continually update the end time
-
-
- if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
- videoEndFn(videoTimingInfo.end);
- }
- },
- onVideoSegmentTimingInfo: function onVideoSegmentTimingInfo(videoSegmentTimingInfo) {
- videoSegmentTimingInfoFn(videoSegmentTimingInfo);
- },
- onAudioSegmentTimingInfo: function onAudioSegmentTimingInfo(audioSegmentTimingInfo) {
- audioSegmentTimingInfoFn(audioSegmentTimingInfo);
- },
- onId3: function onId3(id3Frames, dispatchType) {
- id3Fn(segment, id3Frames, dispatchType);
- },
- onCaptions: function onCaptions(captions) {
- captionsFn(segment, [captions]);
- },
- isEndOfTimeline: isEndOfTimeline,
- onEndedTimeline: function onEndedTimeline() {
- endedTimelineFn();
- },
- onDone: function onDone(result) {
- if (!doneFn) {
- return;
- }
-
- result.type = result.type === 'combined' ? 'video' : result.type;
- doneFn(null, segment, result);
- }
- });
- }; // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
- // Meaning cached frame data may corrupt our notion of where this segment
- // really starts. To get around this, probe for the info needed.
-
-
- workerCallback({
- action: 'probeTs',
- transmuxer: segment.transmuxer,
- data: bytes,
- baseStartTime: segment.baseStartTime,
- callback: function callback(data) {
- segment.bytes = bytes = data.data;
- var probeResult = data.result;
-
- if (probeResult) {
- trackInfoFn(segment, {
- hasAudio: probeResult.hasAudio,
- hasVideo: probeResult.hasVideo,
- isMuxed: isMuxed
- });
- trackInfoFn = null;
-
- if (probeResult.hasAudio && !isMuxed) {
- audioStartFn(probeResult.audioStart);
- }
-
- if (probeResult.hasVideo) {
- videoStartFn(probeResult.videoStart);
- }
-
- audioStartFn = null;
- videoStartFn = null;
- }
-
- finish();
- }
- });
- };
-
- var handleSegmentBytes = function handleSegmentBytes(_ref5) {
- var segment = _ref5.segment,
- bytes = _ref5.bytes,
- trackInfoFn = _ref5.trackInfoFn,
- timingInfoFn = _ref5.timingInfoFn,
- videoSegmentTimingInfoFn = _ref5.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref5.audioSegmentTimingInfoFn,
- id3Fn = _ref5.id3Fn,
- captionsFn = _ref5.captionsFn,
- isEndOfTimeline = _ref5.isEndOfTimeline,
- endedTimelineFn = _ref5.endedTimelineFn,
- dataFn = _ref5.dataFn,
- doneFn = _ref5.doneFn;
- var bytesAsUint8Array = new Uint8Array(bytes); // TODO:
- // We should have a handler that fetches the number of bytes required
- // to check if something is fmp4. This will allow us to save bandwidth
- // because we can only blacklist a playlist and abort requests
- // by codec after trackinfo triggers.
-
- if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
- segment.isFmp4 = true;
- var tracks = segment.map.tracks;
- var trackInfo = {
- isFmp4: true,
- hasVideo: !!tracks.video,
- hasAudio: !!tracks.audio
- }; // if we have a audio track, with a codec that is not set to
- // encrypted audio
-
- if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
- trackInfo.audioCodec = tracks.audio.codec;
- } // if we have a video track, with a codec that is not set to
- // encrypted video
-
-
- if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
- trackInfo.videoCodec = tracks.video.codec;
- }
-
- if (tracks.video && tracks.audio) {
- trackInfo.isMuxed = true;
- } // since we don't support appending fmp4 data on progress, we know we have the full
- // segment here
-
-
- trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
- // time. The end time can be roughly calculated by the receiver using the duration.
- //
- // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
- // that is the true start of the segment (where the playback engine should begin
- // decoding).
-
- var finishLoading = function finishLoading(captions) {
- // if the track still has audio at this point it is only possible
- // for it to be audio only. See `tracks.video && tracks.audio` if statement
- // above.
- // we make sure to use segment.bytes here as that
- dataFn(segment, {
- data: bytesAsUint8Array,
- type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
- });
-
- if (captions && captions.length) {
- captionsFn(segment, captions);
- }
-
- doneFn(null, segment, {});
- };
-
- workerCallback({
- action: 'probeMp4StartTime',
- timescales: segment.map.timescales,
- data: bytesAsUint8Array,
- transmuxer: segment.transmuxer,
- callback: function callback(_ref6) {
- var data = _ref6.data,
- startTime = _ref6.startTime;
- // transfer bytes back to us
- bytes = data.buffer;
- segment.bytes = bytesAsUint8Array = data;
-
- if (trackInfo.hasAudio && !trackInfo.isMuxed) {
- timingInfoFn(segment, 'audio', 'start', startTime);
- }
-
- if (trackInfo.hasVideo) {
- timingInfoFn(segment, 'video', 'start', startTime);
- } // Run through the CaptionParser in case there are captions.
- // Initialize CaptionParser if it hasn't been yet
-
-
- if (!tracks.video || !data.byteLength || !segment.transmuxer) {
- finishLoading();
- return;
- }
-
- workerCallback({
- action: 'pushMp4Captions',
- endAction: 'mp4Captions',
- transmuxer: segment.transmuxer,
- data: bytesAsUint8Array,
- timescales: segment.map.timescales,
- trackIds: [tracks.video.id],
- callback: function callback(message) {
- // transfer bytes back to us
- bytes = message.data.buffer;
- segment.bytes = bytesAsUint8Array = message.data;
- finishLoading(message.captions);
- }
- });
- }
- });
- return;
- } // VTT or other segments that don't need processing
-
-
- if (!segment.transmuxer) {
- doneFn(null, segment, {});
- return;
- }
-
- if (typeof segment.container === 'undefined') {
- segment.container = detectContainerForBytes(bytesAsUint8Array);
- }
-
- if (segment.container !== 'ts' && segment.container !== 'aac') {
- trackInfoFn(segment, {
- hasAudio: false,
- hasVideo: false
- });
- doneFn(null, segment, {});
- return;
- } // ts or aac
-
-
- transmuxAndNotify({
- segment: segment,
- bytes: bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- };
-
- var decrypt = function decrypt(_ref7, callback) {
- var id = _ref7.id,
- key = _ref7.key,
- encryptedBytes = _ref7.encryptedBytes,
- decryptionWorker = _ref7.decryptionWorker;
-
- var decryptionHandler = function decryptionHandler(event) {
- if (event.data.source === id) {
- decryptionWorker.removeEventListener('message', decryptionHandler);
- var decrypted = event.data.decrypted;
- callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
- }
- };
-
- decryptionWorker.addEventListener('message', decryptionHandler);
- var keyBytes;
-
- if (key.bytes.slice) {
- keyBytes = key.bytes.slice();
- } else {
- keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
- } // incrementally decrypt the bytes
-
-
- decryptionWorker.postMessage(createTransferableMessage({
- source: id,
- encrypted: encryptedBytes,
- key: keyBytes,
- iv: key.iv
- }), [encryptedBytes.buffer, keyBytes.buffer]);
- };
- /**
- * Decrypt the segment via the decryption web worker
- *
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after decryption has completed
- */
-
-
- var decryptSegment = function decryptSegment(_ref8) {
- var decryptionWorker = _ref8.decryptionWorker,
- segment = _ref8.segment,
- trackInfoFn = _ref8.trackInfoFn,
- timingInfoFn = _ref8.timingInfoFn,
- videoSegmentTimingInfoFn = _ref8.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref8.audioSegmentTimingInfoFn,
- id3Fn = _ref8.id3Fn,
- captionsFn = _ref8.captionsFn,
- isEndOfTimeline = _ref8.isEndOfTimeline,
- endedTimelineFn = _ref8.endedTimelineFn,
- dataFn = _ref8.dataFn,
- doneFn = _ref8.doneFn;
- decrypt({
- id: segment.requestId,
- key: segment.key,
- encryptedBytes: segment.encryptedBytes,
- decryptionWorker: decryptionWorker
- }, function (decryptedBytes) {
- segment.bytes = decryptedBytes;
- handleSegmentBytes({
- segment: segment,
- bytes: segment.bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- });
- };
- /**
- * This function waits for all XHRs to finish (with either success or failure)
- * before continueing processing via it's callback. The function gathers errors
- * from each request into a single errors array so that the error status for
- * each request can be examined later.
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after all resources have been
- * downloaded and any decryption completed
- */
-
-
- var waitForCompletion = function waitForCompletion(_ref9) {
- var activeXhrs = _ref9.activeXhrs,
- decryptionWorker = _ref9.decryptionWorker,
- trackInfoFn = _ref9.trackInfoFn,
- timingInfoFn = _ref9.timingInfoFn,
- videoSegmentTimingInfoFn = _ref9.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref9.audioSegmentTimingInfoFn,
- id3Fn = _ref9.id3Fn,
- captionsFn = _ref9.captionsFn,
- isEndOfTimeline = _ref9.isEndOfTimeline,
- endedTimelineFn = _ref9.endedTimelineFn,
- dataFn = _ref9.dataFn,
- doneFn = _ref9.doneFn;
- var count = 0;
- var didError = false;
- return function (error, segment) {
- if (didError) {
- return;
- }
-
- if (error) {
- didError = true; // If there are errors, we have to abort any outstanding requests
-
- abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
- // handle the aborted events from those requests, there are some cases where we may
- // never get an aborted event. For instance, if the network connection is lost and
- // there were two requests, the first may have triggered an error immediately, while
- // the second request remains unsent. In that case, the aborted algorithm will not
- // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
- //
- // We also can't rely on the ready state of the XHR, since the request that
- // triggered the connection error may also show as a ready state of 0 (unsent).
- // Therefore, we have to finish this group of requests immediately after the first
- // seen error.
-
- return doneFn(error, segment);
- }
-
- count += 1;
-
- if (count === activeXhrs.length) {
- var segmentFinish = function segmentFinish() {
- if (segment.encryptedBytes) {
- return decryptSegment({
- decryptionWorker: decryptionWorker,
- segment: segment,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- } // Otherwise, everything is ready just continue
-
-
- handleSegmentBytes({
- segment: segment,
- bytes: segment.bytes,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- });
- }; // Keep track of when *all* of the requests have completed
-
-
- segment.endOfAllRequests = Date.now();
-
- if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
- return decrypt({
- decryptionWorker: decryptionWorker,
- // add -init to the "id" to differentiate between segment
- // and init segment decryption, just in case they happen
- // at the same time at some point in the future.
- id: segment.requestId + '-init',
- encryptedBytes: segment.map.encryptedBytes,
- key: segment.map.key
- }, function (decryptedBytes) {
- segment.map.bytes = decryptedBytes;
- parseInitSegment(segment, function (parseError) {
- if (parseError) {
- abortAll(activeXhrs);
- return doneFn(parseError, segment);
- }
-
- segmentFinish();
- });
- });
- }
-
- segmentFinish();
- }
- };
- };
- /**
- * Calls the abort callback if any request within the batch was aborted. Will only call
- * the callback once per batch of requests, even if multiple were aborted.
- *
- * @param {Object} loadendState - state to check to see if the abort function was called
- * @param {Function} abortFn - callback to call for abort
- */
-
-
- var handleLoadEnd = function handleLoadEnd(_ref10) {
- var loadendState = _ref10.loadendState,
- abortFn = _ref10.abortFn;
- return function (event) {
- var request = event.target;
-
- if (request.aborted && abortFn && !loadendState.calledAbortFn) {
- abortFn();
- loadendState.calledAbortFn = true;
- }
- };
- };
- /**
- * Simple progress event callback handler that gathers some stats before
- * executing a provided callback with the `segment` object
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} progressFn - a callback that is executed each time a progress event
- * is received
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Event} event - the progress event object from XMLHttpRequest
- */
-
-
- var handleProgress = function handleProgress(_ref11) {
- var segment = _ref11.segment,
- progressFn = _ref11.progressFn;
- _ref11.trackInfoFn;
- _ref11.timingInfoFn;
- _ref11.videoSegmentTimingInfoFn;
- _ref11.audioSegmentTimingInfoFn;
- _ref11.id3Fn;
- _ref11.captionsFn;
- _ref11.isEndOfTimeline;
- _ref11.endedTimelineFn;
- _ref11.dataFn;
- return function (event) {
- var request = event.target;
-
- if (request.aborted) {
- return;
- }
-
- segment.stats = videojs__default['default'].mergeOptions(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
-
- if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
- segment.stats.firstBytesReceivedAt = Date.now();
- }
-
- return progressFn(event, segment);
- };
- };
- /**
- * Load all resources and does any processing necessary for a media-segment
- *
- * Features:
- * decrypts the media-segment if it has a key uri and an iv
- * aborts *all* requests if *any* one request fails
- *
- * The segment object, at minimum, has the following format:
- * {
- * resolvedUri: String,
- * [transmuxer]: Object,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [key]: {
- * resolvedUri: String
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * iv: {
- * bytes: Uint32Array
- * }
- * },
- * [map]: {
- * resolvedUri: String,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [bytes]: Uint8Array
- * }
- * }
- * ...where [name] denotes optional properties
- *
- * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
- * @param {Object} xhrOptions - the base options to provide to all xhr requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
- * decryption routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} abortFn - a callback called (only once) if any piece of a request was
- * aborted
- * @param {Function} progressFn - a callback that receives progress events from the main
- * segment's xhr request
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that receives data from the main segment's xhr
- * request, transmuxed if needed
- * @param {Function} doneFn - a callback that is executed only once all requests have
- * succeeded or failed
- * @return {Function} a function that, when invoked, immediately aborts all
- * outstanding requests
- */
-
-
- var mediaSegmentRequest = function mediaSegmentRequest(_ref12) {
- var xhr = _ref12.xhr,
- xhrOptions = _ref12.xhrOptions,
- decryptionWorker = _ref12.decryptionWorker,
- segment = _ref12.segment,
- abortFn = _ref12.abortFn,
- progressFn = _ref12.progressFn,
- trackInfoFn = _ref12.trackInfoFn,
- timingInfoFn = _ref12.timingInfoFn,
- videoSegmentTimingInfoFn = _ref12.videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn = _ref12.audioSegmentTimingInfoFn,
- id3Fn = _ref12.id3Fn,
- captionsFn = _ref12.captionsFn,
- isEndOfTimeline = _ref12.isEndOfTimeline,
- endedTimelineFn = _ref12.endedTimelineFn,
- dataFn = _ref12.dataFn,
- doneFn = _ref12.doneFn;
- var activeXhrs = [];
- var finishProcessingFn = waitForCompletion({
- activeXhrs: activeXhrs,
- decryptionWorker: decryptionWorker,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn,
- doneFn: doneFn
- }); // optionally, request the decryption key
-
- if (segment.key && !segment.key.bytes) {
- var objects = [segment.key];
-
- if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
- objects.push(segment.map.key);
- }
-
- var keyRequestOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- var keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
- var keyXhr = xhr(keyRequestOptions, keyRequestCallback);
- activeXhrs.push(keyXhr);
- } // optionally, request the associated media init segment
-
-
- if (segment.map && !segment.map.bytes) {
- var differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
-
- if (differentMapKey) {
- var mapKeyRequestOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.map.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- var mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
- var mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
- activeXhrs.push(mapKeyXhr);
- }
-
- var initSegmentOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.map.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment.map)
- });
- var initSegmentRequestCallback = handleInitSegmentResponse({
- segment: segment,
- finishProcessingFn: finishProcessingFn
- });
- var initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
- activeXhrs.push(initSegmentXhr);
- }
-
- var segmentRequestOptions = videojs__default['default'].mergeOptions(xhrOptions, {
- uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment)
- });
- var segmentRequestCallback = handleSegmentResponse({
- segment: segment,
- finishProcessingFn: finishProcessingFn,
- responseType: segmentRequestOptions.responseType
- });
- var segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
- segmentXhr.addEventListener('progress', handleProgress({
- segment: segment,
- progressFn: progressFn,
- trackInfoFn: trackInfoFn,
- timingInfoFn: timingInfoFn,
- videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
- id3Fn: id3Fn,
- captionsFn: captionsFn,
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: endedTimelineFn,
- dataFn: dataFn
- }));
- activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
- // multiple times, provide a shared state object
-
- var loadendState = {};
- activeXhrs.forEach(function (activeXhr) {
- activeXhr.addEventListener('loadend', handleLoadEnd({
- loadendState: loadendState,
- abortFn: abortFn
- }));
- });
- return function () {
- return abortAll(activeXhrs);
- };
- };
-
- /**
- * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
- * codec strings, or translating codec strings into objects that can be examined.
- */
- var logFn$1 = logger('CodecUtils');
- /**
- * Returns a set of codec strings parsed from the playlist or the default
- * codec strings if no codecs were specified in the playlist
- *
- * @param {Playlist} media the current media playlist
- * @return {Object} an object with the video and audio codecs
- */
-
- var getCodecs = function getCodecs(media) {
- // if the codecs were explicitly specified, use them instead of the
- // defaults
- var mediaAttributes = media.attributes || {};
-
- if (mediaAttributes.CODECS) {
- return parseCodecs(mediaAttributes.CODECS);
- }
- };
-
- var isMaat = function isMaat(master, media) {
- var mediaAttributes = media.attributes || {};
- return master && master.mediaGroups && master.mediaGroups.AUDIO && mediaAttributes.AUDIO && master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
- };
- var isMuxed = function isMuxed(master, media) {
- if (!isMaat(master, media)) {
- return true;
- }
-
- var mediaAttributes = media.attributes || {};
- var audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
-
- for (var groupId in audioGroup) {
- // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
- // or there are listed playlists (the case for DASH, as the manifest will have already
- // provided all of the details necessary to generate the audio playlist, as opposed to
- // HLS' externally requested playlists), then the content is demuxed.
- if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
- return true;
- }
- }
-
- return false;
- };
- var unwrapCodecList = function unwrapCodecList(codecList) {
- var codecs = {};
- codecList.forEach(function (_ref) {
- var mediaType = _ref.mediaType,
- type = _ref.type,
- details = _ref.details;
- codecs[mediaType] = codecs[mediaType] || [];
- codecs[mediaType].push(translateLegacyCodec("" + type + details));
- });
- Object.keys(codecs).forEach(function (mediaType) {
- if (codecs[mediaType].length > 1) {
- logFn$1("multiple " + mediaType + " codecs found as attributes: " + codecs[mediaType].join(', ') + ". Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.");
- codecs[mediaType] = null;
- return;
- }
-
- codecs[mediaType] = codecs[mediaType][0];
- });
- return codecs;
- };
- var codecCount = function codecCount(codecObj) {
- var count = 0;
-
- if (codecObj.audio) {
- count++;
- }
-
- if (codecObj.video) {
- count++;
- }
-
- return count;
- };
- /**
- * Calculates the codec strings for a working configuration of
- * SourceBuffers to play variant streams in a master playlist. If
- * there is no possible working configuration, an empty object will be
- * returned.
- *
- * @param master {Object} the m3u8 object for the master playlist
- * @param media {Object} the m3u8 object for the variant playlist
- * @return {Object} the codec strings.
- *
- * @private
- */
-
- var codecsForPlaylist = function codecsForPlaylist(master, media) {
- var mediaAttributes = media.attributes || {};
- var codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
- // Put another way, there is no way to have a video-only multiple-audio HLS!
-
- if (isMaat(master, media) && !codecInfo.audio) {
- if (!isMuxed(master, media)) {
- // It is possible for codecs to be specified on the audio media group playlist but
- // not on the rendition playlist. This is mostly the case for DASH, where audio and
- // video are always separate (and separately specified).
- var defaultCodecs = unwrapCodecList(codecsFromDefault(master, mediaAttributes.AUDIO) || []);
-
- if (defaultCodecs.audio) {
- codecInfo.audio = defaultCodecs.audio;
- }
- }
- }
-
- return codecInfo;
- };
-
- var logFn = logger('PlaylistSelector');
-
- var representationToString = function representationToString(representation) {
- if (!representation || !representation.playlist) {
- return;
- }
-
- var playlist = representation.playlist;
- return JSON.stringify({
- id: playlist.id,
- bandwidth: representation.bandwidth,
- width: representation.width,
- height: representation.height,
- codecs: playlist.attributes && playlist.attributes.CODECS || ''
- });
- }; // Utilities
-
- /**
- * Returns the CSS value for the specified property on an element
- * using `getComputedStyle`. Firefox has a long-standing issue where
- * getComputedStyle() may return null when running in an iframe with
- * `display: none`.
- *
- * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
- * @param {HTMLElement} el the htmlelement to work on
- * @param {string} the proprety to get the style for
- */
-
-
- var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
- if (!el) {
- return '';
- }
-
- var result = window__default['default'].getComputedStyle(el);
-
- if (!result) {
- return '';
- }
-
- return result[property];
- };
- /**
- * Resuable stable sort function
- *
- * @param {Playlists} array
- * @param {Function} sortFn Different comparators
- * @function stableSort
- */
-
-
- var stableSort = function stableSort(array, sortFn) {
- var newArray = array.slice();
- array.sort(function (left, right) {
- var cmp = sortFn(left, right);
-
- if (cmp === 0) {
- return newArray.indexOf(left) - newArray.indexOf(right);
- }
-
- return cmp;
- });
- };
- /**
- * A comparator function to sort two playlist object by bandwidth.
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the bandwidth attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the bandwidth of right is greater than left and
- * exactly zero if the two are equal.
- */
-
-
- var comparePlaylistBandwidth = function comparePlaylistBandwidth(left, right) {
- var leftBandwidth;
- var rightBandwidth;
-
- if (left.attributes.BANDWIDTH) {
- leftBandwidth = left.attributes.BANDWIDTH;
- }
-
- leftBandwidth = leftBandwidth || window__default['default'].Number.MAX_VALUE;
-
- if (right.attributes.BANDWIDTH) {
- rightBandwidth = right.attributes.BANDWIDTH;
- }
-
- rightBandwidth = rightBandwidth || window__default['default'].Number.MAX_VALUE;
- return leftBandwidth - rightBandwidth;
- };
- /**
- * A comparator function to sort two playlist object by resolution (width).
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the resolution.width attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the resolution.width of right is greater than left and
- * exactly zero if the two are equal.
- */
-
- var comparePlaylistResolution = function comparePlaylistResolution(left, right) {
- var leftWidth;
- var rightWidth;
-
- if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
- leftWidth = left.attributes.RESOLUTION.width;
- }
-
- leftWidth = leftWidth || window__default['default'].Number.MAX_VALUE;
-
- if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
- rightWidth = right.attributes.RESOLUTION.width;
- }
-
- rightWidth = rightWidth || window__default['default'].Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
- // have the same media dimensions/ resolution
-
- if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
- return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
- }
-
- return leftWidth - rightWidth;
- };
- /**
- * Chooses the appropriate media playlist based on bandwidth and player size
- *
- * @param {Object} master
- * Object representation of the master manifest
- * @param {number} playerBandwidth
- * Current calculated bandwidth of the player
- * @param {number} playerWidth
- * Current width of the player element (should account for the device pixel ratio)
- * @param {number} playerHeight
- * Current height of the player element (should account for the device pixel ratio)
- * @param {boolean} limitRenditionByPlayerDimensions
- * True if the player width and height should be used during the selection, false otherwise
- * @param {Object} masterPlaylistController
- * the current masterPlaylistController object
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-
- var simpleSelector = function simpleSelector(master, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, masterPlaylistController) {
- // If we end up getting called before `master` is available, exit early
- if (!master) {
- return;
- }
-
- var options = {
- bandwidth: playerBandwidth,
- width: playerWidth,
- height: playerHeight,
- limitRenditionByPlayerDimensions: limitRenditionByPlayerDimensions
- };
- var playlists = master.playlists; // if playlist is audio only, select between currently active audio group playlists.
-
- if (Playlist.isAudioOnly(master)) {
- playlists = masterPlaylistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
- // at the buttom of this function for debugging.
-
- options.audioOnly = true;
- } // convert the playlists to an intermediary representation to make comparisons easier
-
-
- var sortedPlaylistReps = playlists.map(function (playlist) {
- var bandwidth;
- var width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
- var height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
- bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
- bandwidth = bandwidth || window__default['default'].Number.MAX_VALUE;
- return {
- bandwidth: bandwidth,
- width: width,
- height: height,
- playlist: playlist
- };
- });
- stableSort(sortedPlaylistReps, function (left, right) {
- return left.bandwidth - right.bandwidth;
- }); // filter out any playlists that have been excluded due to
- // incompatible configurations
-
- sortedPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return !Playlist.isIncompatible(rep.playlist);
- }); // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
-
- var enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return Playlist.isEnabled(rep.playlist);
- });
-
- if (!enabledPlaylistReps.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
- return !Playlist.isDisabled(rep.playlist);
- });
- } // filter out any variant that has greater effective bitrate
- // than the current estimated bandwidth
-
-
- var bandwidthPlaylistReps = enabledPlaylistReps.filter(function (rep) {
- return rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth;
- });
- var highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
- // and then taking the very first element
-
- var bandwidthBestRep = bandwidthPlaylistReps.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0]; // if we're not going to limit renditions by player size, make an early decision.
-
- if (limitRenditionByPlayerDimensions === false) {
- var _chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
-
- if (_chosenRep && _chosenRep.playlist) {
- var type = 'sortedPlaylistReps';
-
- if (bandwidthBestRep) {
- type = 'bandwidthBestRep';
- }
-
- if (enabledPlaylistReps[0]) {
- type = 'enabledPlaylistReps';
- }
-
- logFn("choosing " + representationToString(_chosenRep) + " using " + type + " with options", options);
- return _chosenRep.playlist;
- }
-
- logFn('could not choose a playlist with options', options);
- return null;
- } // filter out playlists without resolution information
-
-
- var haveResolution = bandwidthPlaylistReps.filter(function (rep) {
- return rep.width && rep.height;
- }); // sort variants by resolution
-
- stableSort(haveResolution, function (left, right) {
- return left.width - right.width;
- }); // if we have the exact resolution as the player use it
-
- var resolutionBestRepList = haveResolution.filter(function (rep) {
- return rep.width === playerWidth && rep.height === playerHeight;
- });
- highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
-
- var resolutionBestRep = resolutionBestRepList.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0];
- var resolutionPlusOneList;
- var resolutionPlusOneSmallest;
- var resolutionPlusOneRep; // find the smallest variant that is larger than the player
- // if there is no match of exact resolution
-
- if (!resolutionBestRep) {
- resolutionPlusOneList = haveResolution.filter(function (rep) {
- return rep.width > playerWidth || rep.height > playerHeight;
- }); // find all the variants have the same smallest resolution
-
- resolutionPlusOneSmallest = resolutionPlusOneList.filter(function (rep) {
- return rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height;
- }); // ensure that we also pick the highest bandwidth variant that
- // is just-larger-than the video player
-
- highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
- resolutionPlusOneRep = resolutionPlusOneSmallest.filter(function (rep) {
- return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
- })[0];
- } // fallback chain of variants
-
-
- var chosenRep = resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
-
- if (chosenRep && chosenRep.playlist) {
- var _type = 'sortedPlaylistReps';
-
- if (resolutionPlusOneRep) {
- _type = 'resolutionPlusOneRep';
- } else if (resolutionBestRep) {
- _type = 'resolutionBestRep';
- } else if (bandwidthBestRep) {
- _type = 'bandwidthBestRep';
- } else if (enabledPlaylistReps[0]) {
- _type = 'enabledPlaylistReps';
- }
-
- logFn("choosing " + representationToString(chosenRep) + " using " + _type + " with options", options);
- return chosenRep.playlist;
- }
-
- logFn('could not choose a playlist with options', options);
- return null;
- };
-
- /**
- * Chooses the appropriate media playlist based on the most recent
- * bandwidth estimate and the player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-
- var lastBandwidthSelector = function lastBandwidthSelector() {
- var pixelRatio = this.useDevicePixelRatio ? window__default['default'].devicePixelRatio || 1 : 1;
- return simpleSelector(this.playlists.master, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
- };
- /**
- * Chooses the appropriate media playlist based on an
- * exponential-weighted moving average of the bandwidth after
- * filtering for player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @param {number} decay - a number between 0 and 1. Higher values of
- * this parameter will cause previous bandwidth estimates to lose
- * significance more quickly.
- * @return {Function} a function which can be invoked to create a new
- * playlist selector function.
- * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
- */
-
- var movingAverageBandwidthSelector = function movingAverageBandwidthSelector(decay) {
- var average = -1;
- var lastSystemBandwidth = -1;
-
- if (decay < 0 || decay > 1) {
- throw new Error('Moving average bandwidth decay must be between 0 and 1.');
- }
-
- return function () {
- var pixelRatio = this.useDevicePixelRatio ? window__default['default'].devicePixelRatio || 1 : 1;
-
- if (average < 0) {
- average = this.systemBandwidth;
- lastSystemBandwidth = this.systemBandwidth;
- } // stop the average value from decaying for every 250ms
- // when the systemBandwidth is constant
- // and
- // stop average from setting to a very low value when the
- // systemBandwidth becomes 0 in case of chunk cancellation
-
-
- if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
- average = decay * this.systemBandwidth + (1 - decay) * average;
- lastSystemBandwidth = this.systemBandwidth;
- }
-
- return simpleSelector(this.playlists.master, average, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
- };
- };
- /**
- * Chooses the appropriate media playlist based on the potential to rebuffer
- *
- * @param {Object} settings
- * Object of information required to use this selector
- * @param {Object} settings.master
- * Object representation of the master manifest
- * @param {number} settings.currentTime
- * The current time of the player
- * @param {number} settings.bandwidth
- * Current measured bandwidth
- * @param {number} settings.duration
- * Duration of the media
- * @param {number} settings.segmentDuration
- * Segment duration to be used in round trip time calculations
- * @param {number} settings.timeUntilRebuffer
- * Time left in seconds until the player has to rebuffer
- * @param {number} settings.currentTimeline
- * The current timeline segments are being loaded from
- * @param {SyncController} settings.syncController
- * SyncController for determining if we have a sync point for a given playlist
- * @return {Object|null}
- * {Object} return.playlist
- * The highest bandwidth playlist with the least amount of rebuffering
- * {Number} return.rebufferingImpact
- * The amount of time in seconds switching to this playlist will rebuffer. A
- * negative value means that switching will cause zero rebuffering.
- */
-
- var minRebufferMaxBandwidthSelector = function minRebufferMaxBandwidthSelector(settings) {
- var master = settings.master,
- currentTime = settings.currentTime,
- bandwidth = settings.bandwidth,
- duration = settings.duration,
- segmentDuration = settings.segmentDuration,
- timeUntilRebuffer = settings.timeUntilRebuffer,
- currentTimeline = settings.currentTimeline,
- syncController = settings.syncController; // filter out any playlists that have been excluded due to
- // incompatible configurations
-
- var compatiblePlaylists = master.playlists.filter(function (playlist) {
- return !Playlist.isIncompatible(playlist);
- }); // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
-
- var enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
-
- if (!enabledPlaylists.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylists = compatiblePlaylists.filter(function (playlist) {
- return !Playlist.isDisabled(playlist);
- });
- }
-
- var bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
- var rebufferingEstimates = bandwidthPlaylists.map(function (playlist) {
- var syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
- // sync request first. This will double the request time
-
- var numRequests = syncPoint ? 1 : 2;
- var requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
- var rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
- return {
- playlist: playlist,
- rebufferingImpact: rebufferingImpact
- };
- });
- var noRebufferingPlaylists = rebufferingEstimates.filter(function (estimate) {
- return estimate.rebufferingImpact <= 0;
- }); // Sort by bandwidth DESC
-
- stableSort(noRebufferingPlaylists, function (a, b) {
- return comparePlaylistBandwidth(b.playlist, a.playlist);
- });
-
- if (noRebufferingPlaylists.length) {
- return noRebufferingPlaylists[0];
- }
-
- stableSort(rebufferingEstimates, function (a, b) {
- return a.rebufferingImpact - b.rebufferingImpact;
- });
- return rebufferingEstimates[0] || null;
- };
- /**
- * Chooses the appropriate media playlist, which in this case is the lowest bitrate
- * one with video. If no renditions with video exist, return the lowest audio rendition.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Object|null}
- * {Object} return.playlist
- * The lowest bitrate playlist that contains a video codec. If no such rendition
- * exists pick the lowest audio rendition.
- */
-
- var lowestBitrateCompatibleVariantSelector = function lowestBitrateCompatibleVariantSelector() {
- var _this = this;
-
- // filter out any playlists that have been excluded due to
- // incompatible configurations or playback errors
- var playlists = this.playlists.master.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
-
- stableSort(playlists, function (a, b) {
- return comparePlaylistBandwidth(a, b);
- }); // Parse and assume that playlists with no video codec have no video
- // (this is not necessarily true, although it is generally true).
- //
- // If an entire manifest has no valid videos everything will get filtered
- // out.
-
- var playlistsWithVideo = playlists.filter(function (playlist) {
- return !!codecsForPlaylist(_this.playlists.master, playlist).video;
- });
- return playlistsWithVideo[0] || null;
- };
-
- /**
- * Combine all segments into a single Uint8Array
- *
- * @param {Object} segmentObj
- * @return {Uint8Array} concatenated bytes
- * @private
- */
- var concatSegments = function concatSegments(segmentObj) {
- var offset = 0;
- var tempBuffer;
-
- if (segmentObj.bytes) {
- tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
-
- segmentObj.segments.forEach(function (segment) {
- tempBuffer.set(segment, offset);
- offset += segment.byteLength;
- });
- }
-
- return tempBuffer;
- };
-
- /**
- * @file text-tracks.js
- */
- /**
- * Create captions text tracks on video.js if they do not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {Object} tech the video.js tech
- * @param {Object} captionStream the caption stream to create
- * @private
- */
-
- var createCaptionsTrackIfNotExists = function createCaptionsTrackIfNotExists(inbandTextTracks, tech, captionStream) {
- if (!inbandTextTracks[captionStream]) {
- tech.trigger({
- type: 'usage',
- name: 'vhs-608'
- });
- tech.trigger({
- type: 'usage',
- name: 'hls-608'
- });
- var instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
-
- if (/^cc708_/.test(captionStream)) {
- instreamId = 'SERVICE' + captionStream.split('_')[1];
- }
-
- var track = tech.textTracks().getTrackById(instreamId);
-
- if (track) {
- // Resuse an existing track with a CC# id because this was
- // very likely created by videojs-contrib-hls from information
- // in the m3u8 for us to use
- inbandTextTracks[captionStream] = track;
- } else {
- // This section gets called when we have caption services that aren't specified in the manifest.
- // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
- var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
- var label = captionStream;
- var language = captionStream;
- var def = false;
- var captionService = captionServices[instreamId];
-
- if (captionService) {
- label = captionService.label;
- language = captionService.language;
- def = captionService.default;
- } // Otherwise, create a track with the default `CC#` label and
- // without a language
-
-
- inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
- kind: 'captions',
- id: instreamId,
- // TODO: investigate why this doesn't seem to turn the caption on by default
- default: def,
- label: label,
- language: language
- }, false).track;
- }
- }
- };
- /**
- * Add caption text track data to a source handler given an array of captions
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {Array} captionArray an array of caption data
- * @private
- */
-
- var addCaptionData = function addCaptionData(_ref) {
- var inbandTextTracks = _ref.inbandTextTracks,
- captionArray = _ref.captionArray,
- timestampOffset = _ref.timestampOffset;
-
- if (!captionArray) {
- return;
- }
-
- var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
- captionArray.forEach(function (caption) {
- var track = caption.stream;
- inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
- });
- };
- /**
- * Define properties on a cue for backwards compatability,
- * but warn the user that the way that they are using it
- * is depricated and will be removed at a later date.
- *
- * @param {Cue} cue the cue to add the properties on
- * @private
- */
-
- var deprecateOldCue = function deprecateOldCue(cue) {
- Object.defineProperties(cue.frame, {
- id: {
- get: function get() {
- videojs__default['default'].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
- return cue.value.key;
- }
- },
- value: {
- get: function get() {
- videojs__default['default'].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- },
- privateData: {
- get: function get() {
- videojs__default['default'].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- }
- });
- };
- /**
- * Add metadata text track data to a source handler given an array of metadata
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {Array} metadataArray an array of meta data
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {number} videoDuration the duration of the video
- * @private
- */
-
-
- var addMetadata = function addMetadata(_ref2) {
- var inbandTextTracks = _ref2.inbandTextTracks,
- metadataArray = _ref2.metadataArray,
- timestampOffset = _ref2.timestampOffset,
- videoDuration = _ref2.videoDuration;
-
- if (!metadataArray) {
- return;
- }
-
- var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
- var metadataTrack = inbandTextTracks.metadataTrack_;
-
- if (!metadataTrack) {
- return;
- }
-
- metadataArray.forEach(function (metadata) {
- var time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
- // ignore this bit of metadata.
- // This likely occurs when you have an non-timed ID3 tag like TIT2,
- // which is the "Title/Songname/Content description" frame
-
- if (typeof time !== 'number' || window__default['default'].isNaN(time) || time < 0 || !(time < Infinity)) {
- return;
- }
-
- metadata.frames.forEach(function (frame) {
- var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
- cue.frame = frame;
- cue.value = frame;
- deprecateOldCue(cue);
- metadataTrack.addCue(cue);
- });
- });
-
- if (!metadataTrack.cues || !metadataTrack.cues.length) {
- return;
- } // Updating the metadeta cues so that
- // the endTime of each cue is the startTime of the next cue
- // the endTime of last cue is the duration of the video
-
-
- var cues = metadataTrack.cues;
- var cuesArray = []; // Create a copy of the TextTrackCueList...
- // ...disregarding cues with a falsey value
-
- for (var i = 0; i < cues.length; i++) {
- if (cues[i]) {
- cuesArray.push(cues[i]);
- }
- } // Group cues by their startTime value
-
-
- var cuesGroupedByStartTime = cuesArray.reduce(function (obj, cue) {
- var timeSlot = obj[cue.startTime] || [];
- timeSlot.push(cue);
- obj[cue.startTime] = timeSlot;
- return obj;
- }, {}); // Sort startTimes by ascending order
-
- var sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort(function (a, b) {
- return Number(a) - Number(b);
- }); // Map each cue group's endTime to the next group's startTime
-
- sortedStartTimes.forEach(function (startTime, idx) {
- var cueGroup = cuesGroupedByStartTime[startTime];
- var nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
-
- cueGroup.forEach(function (cue) {
- cue.endTime = nextTime;
- });
- });
- };
- /**
- * Create metadata text track on video.js if it does not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {string} dispatchType the inband metadata track dispatch type
- * @param {Object} tech the video.js tech
- * @private
- */
-
- var createMetadataTrackIfNotExists = function createMetadataTrackIfNotExists(inbandTextTracks, dispatchType, tech) {
- if (inbandTextTracks.metadataTrack_) {
- return;
- }
-
- inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'Timed Metadata'
- }, false).track;
- inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
- };
- /**
- * Remove cues from a track on video.js.
- *
- * @param {Double} start start of where we should remove the cue
- * @param {Double} end end of where the we should remove the cue
- * @param {Object} track the text track to remove the cues from
- * @private
- */
-
- var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
- var i;
- var cue;
-
- if (!track) {
- return;
- }
-
- if (!track.cues) {
- return;
- }
-
- i = track.cues.length;
-
- while (i--) {
- cue = track.cues[i]; // Remove any cue within the provided start and end time
-
- if (cue.startTime >= start && cue.endTime <= end) {
- track.removeCue(cue);
- }
- }
- };
- /**
- * Remove duplicate cues from a track on video.js (a cue is considered a
- * duplicate if it has the same time interval and text as another)
- *
- * @param {Object} track the text track to remove the duplicate cues from
- * @private
- */
-
- var removeDuplicateCuesFromTrack = function removeDuplicateCuesFromTrack(track) {
- var cues = track.cues;
-
- if (!cues) {
- return;
- }
-
- for (var i = 0; i < cues.length; i++) {
- var duplicates = [];
- var occurrences = 0;
-
- for (var j = 0; j < cues.length; j++) {
- if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
- occurrences++;
-
- if (occurrences > 1) {
- duplicates.push(cues[j]);
- }
- }
- }
-
- if (duplicates.length) {
- duplicates.forEach(function (dupe) {
- return track.removeCue(dupe);
- });
- }
- }
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- var ONE_SECOND_IN_TS = 90000,
- // 90kHz clock
- secondsToVideoTs,
- secondsToAudioTs,
- videoTsToSeconds,
- audioTsToSeconds,
- audioTsToVideoTs,
- videoTsToAudioTs,
- metadataTsToSeconds;
-
- secondsToVideoTs = function secondsToVideoTs(seconds) {
- return seconds * ONE_SECOND_IN_TS;
- };
-
- secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
- return seconds * sampleRate;
- };
-
- videoTsToSeconds = function videoTsToSeconds(timestamp) {
- return timestamp / ONE_SECOND_IN_TS;
- };
-
- audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
- return timestamp / sampleRate;
- };
-
- audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
- return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
- };
-
- videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
- return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
- };
- /**
- * Adjust ID3 tag or caption timing information by the timeline pts values
- * (if keepOriginalTimestamps is false) and convert to seconds
- */
-
-
- metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
- return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
- };
-
- var clock = {
- ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
- secondsToVideoTs: secondsToVideoTs,
- secondsToAudioTs: secondsToAudioTs,
- videoTsToSeconds: videoTsToSeconds,
- audioTsToSeconds: audioTsToSeconds,
- audioTsToVideoTs: audioTsToVideoTs,
- videoTsToAudioTs: videoTsToAudioTs,
- metadataTsToSeconds: metadataTsToSeconds
- };
-
- /**
- * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
- * front of current time.
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {number} currentTime
- * The current time
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- * @return {Array}
- * List of gops considered safe to append over
- */
-
- var gopsSafeToAlignWith = function gopsSafeToAlignWith(buffer, currentTime, mapping) {
- if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
- return [];
- } // pts value for current time + 3 seconds to give a bit more wiggle room
-
-
- var currentTimePts = Math.ceil((currentTime - mapping + 3) * clock.ONE_SECOND_IN_TS);
- var i;
-
- for (i = 0; i < buffer.length; i++) {
- if (buffer[i].pts > currentTimePts) {
- break;
- }
- }
-
- return buffer.slice(i);
- };
- /**
- * Appends gop information (timing and byteLength) received by the transmuxer for the
- * gops appended in the last call to appendBuffer
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Array} gops
- * List of new gop information
- * @param {boolean} replace
- * If true, replace the buffer with the new gop information. If false, append the
- * new gop information to the buffer in the right location of time.
- * @return {Array}
- * Updated list of gop information
- */
-
- var updateGopBuffer = function updateGopBuffer(buffer, gops, replace) {
- if (!gops.length) {
- return buffer;
- }
-
- if (replace) {
- // If we are in safe append mode, then completely overwrite the gop buffer
- // with the most recent appeneded data. This will make sure that when appending
- // future segments, we only try to align with gops that are both ahead of current
- // time and in the last segment appended.
- return gops.slice();
- }
-
- var start = gops[0].pts;
- var i = 0;
-
- for (i; i < buffer.length; i++) {
- if (buffer[i].pts >= start) {
- break;
- }
- }
-
- return buffer.slice(0, i).concat(gops);
- };
- /**
- * Removes gop information in buffer that overlaps with provided start and end
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Double} start
- * position to start the remove at
- * @param {Double} end
- * position to end the remove at
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- */
-
- var removeGopBuffer = function removeGopBuffer(buffer, start, end, mapping) {
- var startPts = Math.ceil((start - mapping) * clock.ONE_SECOND_IN_TS);
- var endPts = Math.ceil((end - mapping) * clock.ONE_SECOND_IN_TS);
- var updatedBuffer = buffer.slice();
- var i = buffer.length;
-
- while (i--) {
- if (buffer[i].pts <= endPts) {
- break;
- }
- }
-
- if (i === -1) {
- // no removal because end of remove range is before start of buffer
- return updatedBuffer;
- }
-
- var j = i + 1;
-
- while (j--) {
- if (buffer[j].pts <= startPts) {
- break;
- }
- } // clamp remove range start to 0 index
-
-
- j = Math.max(j, 0);
- updatedBuffer.splice(j, i - j + 1);
- return updatedBuffer;
- };
-
- var shallowEqual = function shallowEqual(a, b) {
- // if both are undefined
- // or one or the other is undefined
- // they are not equal
- if (!a && !b || !a && b || a && !b) {
- return false;
- } // they are the same object and thus, equal
-
-
- if (a === b) {
- return true;
- } // sort keys so we can make sure they have
- // all the same keys later.
-
-
- var akeys = Object.keys(a).sort();
- var bkeys = Object.keys(b).sort(); // different number of keys, not equal
-
- if (akeys.length !== bkeys.length) {
- return false;
- }
-
- for (var i = 0; i < akeys.length; i++) {
- var key = akeys[i]; // different sorted keys, not equal
-
- if (key !== bkeys[i]) {
- return false;
- } // different values, not equal
-
-
- if (a[key] !== b[key]) {
- return false;
- }
- }
-
- return true;
- };
-
- // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
- var QUOTA_EXCEEDED_ERR = 22;
-
- /**
- * The segment loader has no recourse except to fetch a segment in the
- * current playlist and use the internal timestamps in that segment to
- * generate a syncPoint. This function returns a good candidate index
- * for that process.
- *
- * @param {Array} segments - the segments array from a playlist.
- * @return {number} An index of a segment from the playlist to load
- */
-
- var getSyncSegmentCandidate = function getSyncSegmentCandidate(currentTimeline, segments, targetTime) {
- segments = segments || [];
- var timelineSegments = [];
- var time = 0;
-
- for (var i = 0; i < segments.length; i++) {
- var segment = segments[i];
-
- if (currentTimeline === segment.timeline) {
- timelineSegments.push(i);
- time += segment.duration;
-
- if (time > targetTime) {
- return i;
- }
- }
- }
-
- if (timelineSegments.length === 0) {
- return 0;
- } // default to the last timeline segment
-
-
- return timelineSegments[timelineSegments.length - 1];
- }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
- // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
- // as a start to prevent any potential issues with removing content too close to the
- // playhead.
-
- var MIN_BACK_BUFFER = 1; // in ms
-
- var CHECK_BUFFER_DELAY = 500;
-
- var finite = function finite(num) {
- return typeof num === 'number' && isFinite(num);
- }; // With most content hovering around 30fps, if a segment has a duration less than a half
- // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
- // not accurately reflect the rest of the content.
-
-
- var MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
- var illegalMediaSwitch = function illegalMediaSwitch(loaderType, startingMedia, trackInfo) {
- // Although these checks should most likely cover non 'main' types, for now it narrows
- // the scope of our checks.
- if (loaderType !== 'main' || !startingMedia || !trackInfo) {
- return null;
- }
-
- if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
- return 'Neither audio nor video found in segment.';
- }
-
- if (startingMedia.hasVideo && !trackInfo.hasVideo) {
- return 'Only audio found in segment when we expected video.' + ' We can\'t switch to audio only from a stream that had video.' + ' To get rid of this message, please add codec information to the manifest.';
- }
-
- if (!startingMedia.hasVideo && trackInfo.hasVideo) {
- return 'Video found in segment when we expected only audio.' + ' We can\'t switch to a stream with video from an audio only stream.' + ' To get rid of this message, please add codec information to the manifest.';
- }
-
- return null;
- };
- /**
- * Calculates a time value that is safe to remove from the back buffer without interrupting
- * playback.
- *
- * @param {TimeRange} seekable
- * The current seekable range
- * @param {number} currentTime
- * The current time of the player
- * @param {number} targetDuration
- * The target duration of the current playlist
- * @return {number}
- * Time that is safe to remove from the back buffer without interrupting playback
- */
-
- var safeBackBufferTrimTime = function safeBackBufferTrimTime(seekable, currentTime, targetDuration) {
- // 30 seconds before the playhead provides a safe default for trimming.
- //
- // Choosing a reasonable default is particularly important for high bitrate content and
- // VOD videos/live streams with large windows, as the buffer may end up overfilled and
- // throw an APPEND_BUFFER_ERR.
- var trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
-
- if (seekable.length) {
- // Some live playlists may have a shorter window of content than the full allowed back
- // buffer. For these playlists, don't save content that's no longer within the window.
- trimTime = Math.max(trimTime, seekable.start(0));
- } // Don't remove within target duration of the current time to avoid the possibility of
- // removing the GOP currently being played, as removing it can cause playback stalls.
-
-
- var maxTrimTime = currentTime - targetDuration;
- return Math.min(maxTrimTime, trimTime);
- };
-
- var segmentInfoString = function segmentInfoString(segmentInfo) {
- var startOfSegment = segmentInfo.startOfSegment,
- duration = segmentInfo.duration,
- segment = segmentInfo.segment,
- part = segmentInfo.part,
- _segmentInfo$playlist = segmentInfo.playlist,
- seq = _segmentInfo$playlist.mediaSequence,
- id = _segmentInfo$playlist.id,
- _segmentInfo$playlist2 = _segmentInfo$playlist.segments,
- segments = _segmentInfo$playlist2 === void 0 ? [] : _segmentInfo$playlist2,
- index = segmentInfo.mediaIndex,
- partIndex = segmentInfo.partIndex,
- timeline = segmentInfo.timeline;
- var segmentLen = segments.length - 1;
- var selection = 'mediaIndex/partIndex increment';
-
- if (segmentInfo.getMediaInfoForTime) {
- selection = "getMediaInfoForTime (" + segmentInfo.getMediaInfoForTime + ")";
- } else if (segmentInfo.isSyncRequest) {
- selection = 'getSyncSegmentCandidate (isSyncRequest)';
- }
-
- var hasPartIndex = typeof partIndex === 'number';
- var name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
- var zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
- preloadSegment: segment
- }) - 1 : 0;
- return name + " [" + (seq + index) + "/" + (seq + segmentLen) + "]" + (hasPartIndex ? " part [" + partIndex + "/" + zeroBasedPartCount + "]" : '') + (" segment start/end [" + segment.start + " => " + segment.end + "]") + (hasPartIndex ? " part start/end [" + part.start + " => " + part.end + "]" : '') + (" startOfSegment [" + startOfSegment + "]") + (" duration [" + duration + "]") + (" timeline [" + timeline + "]") + (" selected by [" + selection + "]") + (" playlist [" + id + "]");
- };
-
- var timingInfoPropertyForMedia = function timingInfoPropertyForMedia(mediaType) {
- return mediaType + "TimingInfo";
- };
- /**
- * Returns the timestamp offset to use for the segment.
- *
- * @param {number} segmentTimeline
- * The timeline of the segment
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} startOfSegment
- * The estimated segment start
- * @param {TimeRange[]} buffered
- * The loader's buffer
- * @param {boolean} overrideCheck
- * If true, no checks are made to see if the timestamp offset value should be set,
- * but sets it directly to a value.
- *
- * @return {number|null}
- * Either a number representing a new timestamp offset, or null if the segment is
- * part of the same timeline
- */
-
-
- var timestampOffsetForSegment = function timestampOffsetForSegment(_ref) {
- var segmentTimeline = _ref.segmentTimeline,
- currentTimeline = _ref.currentTimeline,
- startOfSegment = _ref.startOfSegment,
- buffered = _ref.buffered,
- overrideCheck = _ref.overrideCheck;
-
- // Check to see if we are crossing a discontinuity to see if we need to set the
- // timestamp offset on the transmuxer and source buffer.
- //
- // Previously, we changed the timestampOffset if the start of this segment was less than
- // the currently set timestampOffset, but this isn't desirable as it can produce bad
- // behavior, especially around long running live streams.
- if (!overrideCheck && segmentTimeline === currentTimeline) {
- return null;
- } // When changing renditions, it's possible to request a segment on an older timeline. For
- // instance, given two renditions with the following:
- //
- // #EXTINF:10
- // segment1
- // #EXT-X-DISCONTINUITY
- // #EXTINF:10
- // segment2
- // #EXTINF:10
- // segment3
- //
- // And the current player state:
- //
- // current time: 8
- // buffer: 0 => 20
- //
- // The next segment on the current rendition would be segment3, filling the buffer from
- // 20s onwards. However, if a rendition switch happens after segment2 was requested,
- // then the next segment to be requested will be segment1 from the new rendition in
- // order to fill time 8 and onwards. Using the buffered end would result in repeated
- // content (since it would position segment1 of the new rendition starting at 20s). This
- // case can be identified when the new segment's timeline is a prior value. Instead of
- // using the buffered end, the startOfSegment can be used, which, hopefully, will be
- // more accurate to the actual start time of the segment.
-
-
- if (segmentTimeline < currentTimeline) {
- return startOfSegment;
- } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
- // value uses the end of the last segment if it is available. While this value
- // should often be correct, it's better to rely on the buffered end, as the new
- // content post discontinuity should line up with the buffered end as if it were
- // time 0 for the new content.
-
-
- return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
- };
- /**
- * Returns whether or not the loader should wait for a timeline change from the timeline
- * change controller before processing the segment.
- *
- * Primary timing in VHS goes by video. This is different from most media players, as
- * audio is more often used as the primary timing source. For the foreseeable future, VHS
- * will continue to use video as the primary timing source, due to the current logic and
- * expectations built around it.
-
- * Since the timing follows video, in order to maintain sync, the video loader is
- * responsible for setting both audio and video source buffer timestamp offsets.
- *
- * Setting different values for audio and video source buffers could lead to
- * desyncing. The following examples demonstrate some of the situations where this
- * distinction is important. Note that all of these cases involve demuxed content. When
- * content is muxed, the audio and video are packaged together, therefore syncing
- * separate media playlists is not an issue.
- *
- * CASE 1: Audio prepares to load a new timeline before video:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the audio loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the video loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the audio loader goes ahead and loads and appends the 6th segment before the video
- * loader crosses the discontinuity, then when appended, the 6th audio segment will use
- * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
- * the audio loader must provide the audioAppendStart value to trim the content in the
- * transmuxer, and that value relies on the audio timestamp offset. Since the audio
- * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
- * segment until that value is provided.
- *
- * CASE 2: Video prepares to load a new timeline before audio:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the video loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the audio loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the video loader goes ahead and loads and appends the 6th segment, then once the
- * segment is loaded and processed, both the video and audio timestamp offsets will be
- * set, since video is used as the primary timing source. This is to ensure content lines
- * up appropriately, as any modifications to the video timing are reflected by audio when
- * the video loader sets the audio and video timestamp offsets to the same value. However,
- * setting the timestamp offset for audio before audio has had a chance to change
- * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
- * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
- *
- * CASE 3: When seeking, audio prepares to load a new timeline before video
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, both audio and video loaders are loading segments from timeline
- * 0, but imagine that the seek originated from timeline 1.
- *
- * When seeking to a new timeline, the timestamp offset will be set based on the expected
- * segment start of the loaded video segment. In order to maintain sync, the audio loader
- * must wait for the video loader to load its segment and update both the audio and video
- * timestamp offsets before it may load and append its own segment. This is the case
- * whether the seek results in a mismatched segment request (e.g., the audio loader
- * chooses to load segment 3 and the video loader chooses to load segment 4) or the
- * loaders choose to load the same segment index from each playlist, as the segments may
- * not be aligned perfectly, even for matching segment indexes.
- *
- * @param {Object} timelinechangeController
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} segmentTimeline
- * The timeline of the segment being loaded
- * @param {('main'|'audio')} loaderType
- * The loader type
- * @param {boolean} audioDisabled
- * Whether the audio is disabled for the loader. This should only be true when the
- * loader may have muxed audio in its segment, but should not append it, e.g., for
- * the main loader when an alternate audio playlist is active.
- *
- * @return {boolean}
- * Whether the loader should wait for a timeline change from the timeline change
- * controller before processing the segment
- */
-
- var shouldWaitForTimelineChange = function shouldWaitForTimelineChange(_ref2) {
- var timelineChangeController = _ref2.timelineChangeController,
- currentTimeline = _ref2.currentTimeline,
- segmentTimeline = _ref2.segmentTimeline,
- loaderType = _ref2.loaderType,
- audioDisabled = _ref2.audioDisabled;
-
- if (currentTimeline === segmentTimeline) {
- return false;
- }
-
- if (loaderType === 'audio') {
- var lastMainTimelineChange = timelineChangeController.lastTimelineChange({
- type: 'main'
- }); // Audio loader should wait if:
- //
- // * main hasn't had a timeline change yet (thus has not loaded its first segment)
- // * main hasn't yet changed to the timeline audio is looking to load
-
- return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
- } // The main loader only needs to wait for timeline changes if there's demuxed audio.
- // Otherwise, there's nothing to wait for, since audio would be muxed into the main
- // loader's segments (or the content is audio/video only and handled by the main
- // loader).
-
-
- if (loaderType === 'main' && audioDisabled) {
- var pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
- type: 'audio'
- }); // Main loader should wait for the audio loader if audio is not pending a timeline
- // change to the current timeline.
- //
- // Since the main loader is responsible for setting the timestamp offset for both
- // audio and video, the main loader must wait for audio to be about to change to its
- // timeline before setting the offset, otherwise, if audio is behind in loading,
- // segments from the previous timeline would be adjusted by the new timestamp offset.
- //
- // This requirement means that video will not cross a timeline until the audio is
- // about to cross to it, so that way audio and video will always cross the timeline
- // together.
- //
- // In addition to normal timeline changes, these rules also apply to the start of a
- // stream (going from a non-existent timeline, -1, to timeline 0). It's important
- // that these rules apply to the first timeline change because if they did not, it's
- // possible that the main loader will cross two timelines before the audio loader has
- // crossed one. Logic may be implemented to handle the startup as a special case, but
- // it's easier to simply treat all timeline changes the same.
-
- if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
- return false;
- }
-
- return true;
- }
-
- return false;
- };
- var mediaDuration = function mediaDuration(audioTimingInfo, videoTimingInfo) {
- var audioDuration = audioTimingInfo && typeof audioTimingInfo.start === 'number' && typeof audioTimingInfo.end === 'number' ? audioTimingInfo.end - audioTimingInfo.start : 0;
- var videoDuration = videoTimingInfo && typeof videoTimingInfo.start === 'number' && typeof videoTimingInfo.end === 'number' ? videoTimingInfo.end - videoTimingInfo.start : 0;
- return Math.max(audioDuration, videoDuration);
- };
- var segmentTooLong = function segmentTooLong(_ref3) {
- var segmentDuration = _ref3.segmentDuration,
- maxDuration = _ref3.maxDuration;
-
- // 0 duration segments are most likely due to metadata only segments or a lack of
- // information.
- if (!segmentDuration) {
- return false;
- } // For HLS:
- //
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
- // The EXTINF duration of each Media Segment in the Playlist
- // file, when rounded to the nearest integer, MUST be less than or equal
- // to the target duration; longer segments can trigger playback stalls
- // or other errors.
- //
- // For DASH, the mpd-parser uses the largest reported segment duration as the target
- // duration. Although that reported duration is occasionally approximate (i.e., not
- // exact), a strict check may report that a segment is too long more often in DASH.
-
-
- return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
- };
- var getTroublesomeSegmentDurationMessage = function getTroublesomeSegmentDurationMessage(segmentInfo, sourceType) {
- // Right now we aren't following DASH's timing model exactly, so only perform
- // this check for HLS content.
- if (sourceType !== 'hls') {
- return null;
- }
-
- var segmentDuration = mediaDuration(segmentInfo.audioTimingInfo, segmentInfo.videoTimingInfo); // Don't report if we lack information.
- //
- // If the segment has a duration of 0 it is either a lack of information or a
- // metadata only segment and shouldn't be reported here.
-
- if (!segmentDuration) {
- return null;
- }
-
- var targetDuration = segmentInfo.playlist.targetDuration;
- var isSegmentWayTooLong = segmentTooLong({
- segmentDuration: segmentDuration,
- maxDuration: targetDuration * 2
- });
- var isSegmentSlightlyTooLong = segmentTooLong({
- segmentDuration: segmentDuration,
- maxDuration: targetDuration
- });
- var segmentTooLongMessage = "Segment with index " + segmentInfo.mediaIndex + " " + ("from playlist " + segmentInfo.playlist.id + " ") + ("has a duration of " + segmentDuration + " ") + ("when the reported duration is " + segmentInfo.duration + " ") + ("and the target duration is " + targetDuration + ". ") + 'For HLS content, a duration in excess of the target duration may result in ' + 'playback issues. See the HLS specification section on EXT-X-TARGETDURATION for ' + 'more details: ' + 'https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1';
-
- if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
- return {
- severity: isSegmentWayTooLong ? 'warn' : 'info',
- message: segmentTooLongMessage
- };
- }
-
- return null;
- };
- /**
- * An object that manages segment loading and appending.
- *
- * @class SegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-
- var SegmentLoader = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(SegmentLoader, _videojs$EventTarget);
-
- function SegmentLoader(settings, options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this; // check pre-conditions
-
- if (!settings) {
- throw new TypeError('Initialization settings are required');
- }
-
- if (typeof settings.currentTime !== 'function') {
- throw new TypeError('No currentTime getter specified');
- }
-
- if (!settings.mediaSource) {
- throw new TypeError('No MediaSource specified');
- } // public properties
-
-
- _this.bandwidth = settings.bandwidth;
- _this.throughput = {
- rate: 0,
- count: 0
- };
- _this.roundTrip = NaN;
-
- _this.resetStats_();
-
- _this.mediaIndex = null;
- _this.partIndex = null; // private settings
-
- _this.hasPlayed_ = settings.hasPlayed;
- _this.currentTime_ = settings.currentTime;
- _this.seekable_ = settings.seekable;
- _this.seeking_ = settings.seeking;
- _this.duration_ = settings.duration;
- _this.mediaSource_ = settings.mediaSource;
- _this.vhs_ = settings.vhs;
- _this.loaderType_ = settings.loaderType;
- _this.currentMediaInfo_ = void 0;
- _this.startingMediaInfo_ = void 0;
- _this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
- _this.goalBufferLength_ = settings.goalBufferLength;
- _this.sourceType_ = settings.sourceType;
- _this.sourceUpdater_ = settings.sourceUpdater;
- _this.inbandTextTracks_ = settings.inbandTextTracks;
- _this.state_ = 'INIT';
- _this.timelineChangeController_ = settings.timelineChangeController;
- _this.shouldSaveSegmentTimingInfo_ = true;
- _this.parse708captions_ = settings.parse708captions; // private instance variables
-
- _this.checkBufferTimeout_ = null;
- _this.error_ = void 0;
- _this.currentTimeline_ = -1;
- _this.pendingSegment_ = null;
- _this.xhrOptions_ = null;
- _this.pendingSegments_ = [];
- _this.audioDisabled_ = false;
- _this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
-
- _this.gopBuffer_ = [];
- _this.timeMapping_ = 0;
- _this.safeAppend_ = videojs__default['default'].browser.IE_VERSION >= 11;
- _this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- _this.playlistOfLastInitSegment_ = {
- audio: null,
- video: null
- };
- _this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
- // information yet to start the loading process (e.g., if the audio loader wants to
- // load a segment from the next timeline but the main loader hasn't yet crossed that
- // timeline), then the load call will be added to the queue until it is ready to be
- // processed.
-
- _this.loadQueue_ = [];
- _this.metadataQueue_ = {
- id3: [],
- caption: []
- };
- _this.waitingOnRemove_ = false;
- _this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
-
- _this.activeInitSegmentId_ = null;
- _this.initSegments_ = {}; // HLSe playback
-
- _this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
- _this.keyCache_ = {};
- _this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
- // between a time in the display time and a segment index within
- // a playlist
-
- _this.syncController_ = settings.syncController;
- _this.syncPoint_ = {
- segmentIndex: 0,
- time: 0
- };
- _this.transmuxer_ = _this.createTransmuxer_();
-
- _this.triggerSyncInfoUpdate_ = function () {
- return _this.trigger('syncinfoupdate');
- };
-
- _this.syncController_.on('syncinfoupdate', _this.triggerSyncInfoUpdate_);
-
- _this.mediaSource_.addEventListener('sourceopen', function () {
- if (!_this.isEndOfStream_()) {
- _this.ended_ = false;
- }
- }); // ...for determining the fetch location
-
-
- _this.fetchAtBuffer_ = false;
- _this.logger_ = logger("SegmentLoader[" + _this.loaderType_ + "]");
- Object.defineProperty(assertThisInitialized(_this), 'state', {
- get: function get() {
- return this.state_;
- },
- set: function set(newState) {
- if (newState !== this.state_) {
- this.logger_(this.state_ + " -> " + newState);
- this.state_ = newState;
- this.trigger('statechange');
- }
- }
- });
-
- _this.sourceUpdater_.on('ready', function () {
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- }); // Only the main loader needs to listen for pending timeline changes, as the main
- // loader should wait for audio to be ready to change its timeline so that both main
- // and audio timelines change together. For more details, see the
- // shouldWaitForTimelineChange function.
-
-
- if (_this.loaderType_ === 'main') {
- _this.timelineChangeController_.on('pendingtimelinechange', function () {
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- });
- } // The main loader only listens on pending timeline changes, but the audio loader,
- // since its loads follow main, needs to listen on timeline changes. For more details,
- // see the shouldWaitForTimelineChange function.
-
-
- if (_this.loaderType_ === 'audio') {
- _this.timelineChangeController_.on('timelinechange', function () {
- if (_this.hasEnoughInfoToLoad_()) {
- _this.processLoadQueue_();
- }
-
- if (_this.hasEnoughInfoToAppend_()) {
- _this.processCallQueue_();
- }
- });
- }
-
- return _this;
- }
-
- var _proto = SegmentLoader.prototype;
-
- _proto.createTransmuxer_ = function createTransmuxer_() {
- return segmentTransmuxer.createTransmuxer({
- remux: false,
- alignGopsAtEnd: this.safeAppend_,
- keepOriginalTimestamps: true,
- parse708captions: this.parse708captions_
- });
- }
- /**
- * reset all of our media stats
- *
- * @private
- */
- ;
-
- _proto.resetStats_ = function resetStats_() {
- this.mediaBytesTransferred = 0;
- this.mediaRequests = 0;
- this.mediaRequestsAborted = 0;
- this.mediaRequestsTimedout = 0;
- this.mediaRequestsErrored = 0;
- this.mediaTransferDuration = 0;
- this.mediaSecondsLoaded = 0;
- this.mediaAppends = 0;
- }
- /**
- * dispose of the SegmentLoader and reset to the default state
- */
- ;
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.state = 'DISPOSED';
- this.pause();
- this.abort_();
-
- if (this.transmuxer_) {
- this.transmuxer_.terminate();
- }
-
- this.resetStats_();
-
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- }
-
- if (this.syncController_ && this.triggerSyncInfoUpdate_) {
- this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
- }
-
- this.off();
- };
-
- _proto.setAudio = function setAudio(enable) {
- this.audioDisabled_ = !enable;
-
- if (enable) {
- this.appendInitSegment_.audio = true;
- } else {
- // remove current track audio if it gets disabled
- this.sourceUpdater_.removeAudio(0, this.duration_());
- }
- }
- /**
- * abort anything that is currently doing on with the SegmentLoader
- * and reset to a default state
- */
- ;
-
- _proto.abort = function abort() {
- if (this.state !== 'WAITING') {
- if (this.pendingSegment_) {
- this.pendingSegment_ = null;
- }
-
- return;
- }
-
- this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
- // since we are no longer "waiting" on any requests. XHR callback is not always run
- // when the request is aborted. This will prevent the loader from being stuck in the
- // WAITING state indefinitely.
-
- this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
- // next segment
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
- /**
- * abort all pending xhr requests and null any pending segements
- *
- * @private
- */
- ;
-
- _proto.abort_ = function abort_() {
- if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
- this.pendingSegment_.abortRequests();
- } // clear out the segment being processed
-
-
- this.pendingSegment_ = null;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
- this.waitingOnRemove_ = false;
- window__default['default'].clearTimeout(this.quotaExceededErrorRetryTimeout_);
- this.quotaExceededErrorRetryTimeout_ = null;
- };
-
- _proto.checkForAbort_ = function checkForAbort_(requestId) {
- // If the state is APPENDING, then aborts will not modify the state, meaning the first
- // callback that happens should reset the state to READY so that loading can continue.
- if (this.state === 'APPENDING' && !this.pendingSegment_) {
- this.state = 'READY';
- return true;
- }
-
- if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
- return true;
- }
-
- return false;
- }
- /**
- * set an error on the segment loader and null out any pending segements
- *
- * @param {Error} error the error to set on the SegmentLoader
- * @return {Error} the error that was set or that is currently set
- */
- ;
-
- _proto.error = function error(_error) {
- if (typeof _error !== 'undefined') {
- this.logger_('error occurred:', _error);
- this.error_ = _error;
- }
-
- this.pendingSegment_ = null;
- return this.error_;
- };
-
- _proto.endOfStream = function endOfStream() {
- this.ended_ = true;
-
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
-
- this.gopBuffer_.length = 0;
- this.pause();
- this.trigger('ended');
- }
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- ;
-
- _proto.buffered_ = function buffered_() {
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- return videojs__default['default'].createTimeRanges();
- }
-
- if (this.loaderType_ === 'main') {
- var _this$startingMediaIn = this.startingMediaInfo_,
- hasAudio = _this$startingMediaIn.hasAudio,
- hasVideo = _this$startingMediaIn.hasVideo,
- isMuxed = _this$startingMediaIn.isMuxed;
-
- if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
- return this.sourceUpdater_.buffered();
- }
-
- if (hasVideo) {
- return this.sourceUpdater_.videoBuffered();
- }
- } // One case that can be ignored for now is audio only with alt audio,
- // as we don't yet have proper support for that.
-
-
- return this.sourceUpdater_.audioBuffered();
- }
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- ;
-
- _proto.initSegmentForMap = function initSegmentForMap(map, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!map) {
- return null;
- }
-
- var id = initSegmentId(map);
- var storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: map.bytes,
- tracks: map.tracks,
- timescales: map.timescales
- };
- }
-
- return storedMap || map;
- }
- /**
- * Gets and sets key for the provided key
- *
- * @param {Object} key
- * The key object representing the key to get or set
- * @param {boolean=} set
- * If true, the key for the provided key should be saved
- * @return {Object}
- * Key object for desired key
- */
- ;
-
- _proto.segmentKey = function segmentKey(key, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!key) {
- return null;
- }
-
- var id = segmentKeyId(key);
- var storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
-
- if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
- this.keyCache_[id] = storedKey = {
- resolvedUri: key.resolvedUri,
- bytes: key.bytes
- };
- }
-
- var result = {
- resolvedUri: (storedKey || key).resolvedUri
- };
-
- if (storedKey) {
- result.bytes = storedKey.bytes;
- }
-
- return result;
- }
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- ;
-
- _proto.couldBeginLoading_ = function couldBeginLoading_() {
- return this.playlist_ && !this.paused();
- }
- /**
- * load a playlist and start to fill the buffer
- */
- ;
-
- _proto.load = function load() {
- // un-pause
- this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
- // specified
-
- if (!this.playlist_) {
- return;
- } // if all the configuration is ready, initialize and begin loading
-
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- } // if we're in the middle of processing a segment already, don't
- // kick off an additional segment request
-
-
- if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
- return;
- }
-
- this.state = 'READY';
- }
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- ;
-
- _proto.init_ = function init_() {
- this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
- // audio data from the muxed content should be removed
-
- this.resetEverything();
- return this.monitorBuffer_();
- }
- /**
- * set a playlist on the segment loader
- *
- * @param {PlaylistLoader} media the playlist to set on the segment loader
- */
- ;
-
- _proto.playlist = function playlist(newPlaylist, options) {
- if (options === void 0) {
- options = {};
- }
-
- if (!newPlaylist) {
- return;
- }
-
- var oldPlaylist = this.playlist_;
- var segmentInfo = this.pendingSegment_;
- this.playlist_ = newPlaylist;
- this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
- // is always our zero-time so force a sync update each time the playlist
- // is refreshed from the server
- //
- // Use the INIT state to determine if playback has started, as the playlist sync info
- // should be fixed once requests begin (as sync points are generated based on sync
- // info), but not before then.
-
- if (this.state === 'INIT') {
- newPlaylist.syncInfo = {
- mediaSequence: newPlaylist.mediaSequence,
- time: 0
- }; // Setting the date time mapping means mapping the program date time (if available)
- // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
- // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
- // be updated as the playlist is refreshed before the loader starts loading, the
- // program date time mapping needs to be updated as well.
- //
- // This mapping is only done for the main loader because a program date time should
- // map equivalently between playlists.
-
- if (this.loaderType_ === 'main') {
- this.syncController_.setDateTimeMappingForStart(newPlaylist);
- }
- }
-
- var oldId = null;
-
- if (oldPlaylist) {
- if (oldPlaylist.id) {
- oldId = oldPlaylist.id;
- } else if (oldPlaylist.uri) {
- oldId = oldPlaylist.uri;
- }
- }
-
- this.logger_("playlist update [" + oldId + " => " + (newPlaylist.id || newPlaylist.uri) + "]"); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
- // in LIVE, we always want to update with new playlists (including refreshes)
-
- this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
- // buffering now
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- }
-
- if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
- if (this.mediaIndex !== null) {
- // we must "resync" the segment loader when we switch renditions and
- // the segment loader is already synced to the previous rendition
- this.resyncLoader();
- }
-
- this.currentMediaInfo_ = void 0;
- this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
-
- return;
- } // we reloaded the same playlist so we are in a live scenario
- // and we will likely need to adjust the mediaIndex
-
-
- var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
- this.logger_("live window shift [" + mediaSequenceDiff + "]"); // update the mediaIndex on the SegmentLoader
- // this is important because we can abort a request and this value must be
- // equal to the last appended mediaIndex
-
- if (this.mediaIndex !== null) {
- this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
- // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
- // new playlist was incremented by 1.
-
- if (this.mediaIndex < 0) {
- this.mediaIndex = null;
- this.partIndex = null;
- } else {
- var segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
- // unless parts fell off of the playlist for this segment.
- // In that case we need to reset partIndex and resync
-
- if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
- var mediaIndex = this.mediaIndex;
- this.logger_("currently processing part (index " + this.partIndex + ") no longer exists.");
- this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
- // as the part was dropped from our current playlists segment.
- // The mediaIndex will still be valid so keep that around.
-
- this.mediaIndex = mediaIndex;
- }
- }
- } // update the mediaIndex on the SegmentInfo object
- // this is important because we will update this.mediaIndex with this value
- // in `handleAppendsDone_` after the segment has been successfully appended
-
-
- if (segmentInfo) {
- segmentInfo.mediaIndex -= mediaSequenceDiff;
-
- if (segmentInfo.mediaIndex < 0) {
- segmentInfo.mediaIndex = null;
- segmentInfo.partIndex = null;
- } else {
- // we need to update the referenced segment so that timing information is
- // saved for the new playlist's segment, however, if the segment fell off the
- // playlist, we can leave the old reference and just lose the timing info
- if (segmentInfo.mediaIndex >= 0) {
- segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
- }
-
- if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
- segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
- }
- }
- }
-
- this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
- }
- /**
- * Prevent the loader from fetching additional segments. If there
- * is a segment request outstanding, it will finish processing
- * before the loader halts. A segment loader can be unpaused by
- * calling load().
- */
- ;
-
- _proto.pause = function pause() {
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- this.checkBufferTimeout_ = null;
- }
- }
- /**
- * Returns whether the segment loader is fetching additional
- * segments when given the opportunity. This property can be
- * modified through calls to pause() and load().
- */
- ;
-
- _proto.paused = function paused() {
- return this.checkBufferTimeout_ === null;
- }
- /**
- * Delete all the buffered data and reset the SegmentLoader
- *
- * @param {Function} [done] an optional callback to be executed when the remove
- * operation is complete
- */
- ;
-
- _proto.resetEverything = function resetEverything(done) {
- this.ended_ = false;
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
- // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
- // we then clamp the value to duration if necessary.
-
- this.remove(0, Infinity, done); // clears fmp4 captions
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
- /**
- * Force the SegmentLoader to resync and start loading around the currentTime instead
- * of starting at the end of the buffer
- *
- * Useful for fast quality changes
- */
- ;
-
- _proto.resetLoader = function resetLoader() {
- this.fetchAtBuffer_ = false;
- this.resyncLoader();
- }
- /**
- * Force the SegmentLoader to restart synchronization and make a conservative guess
- * before returning to the simple walk-forward method
- */
- ;
-
- _proto.resyncLoader = function resyncLoader() {
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
-
- this.mediaIndex = null;
- this.partIndex = null;
- this.syncPoint_ = null;
- this.isPendingTimestampOffset_ = false;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.abort();
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- }
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- * @param {Function} [done] - an optional callback to be executed when the remove
- * @param {boolean} force - force all remove operations to happen
- * operation is complete
- */
- ;
-
- _proto.remove = function remove(start, end, done, force) {
- if (done === void 0) {
- done = function done() {};
- }
-
- if (force === void 0) {
- force = false;
- }
-
- // clamp end to duration if we need to remove everything.
- // This is due to a browser bug that causes issues if we remove to Infinity.
- // videojs/videojs-contrib-hls#1225
- if (end === Infinity) {
- end = this.duration_();
- } // skip removes that would throw an error
- // commonly happens during a rendition switch at the start of a video
- // from start 0 to end 0
-
-
- if (end <= start) {
- this.logger_('skipping remove because end ${end} is <= start ${start}');
- return;
- }
-
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
-
- return;
- } // set it to one to complete this function's removes
-
-
- var removesRemaining = 1;
-
- var removeFinished = function removeFinished() {
- removesRemaining--;
-
- if (removesRemaining === 0) {
- done();
- }
- };
-
- if (force || !this.audioDisabled_) {
- removesRemaining++;
- this.sourceUpdater_.removeAudio(start, end, removeFinished);
- } // While it would be better to only remove video if the main loader has video, this
- // should be safe with audio only as removeVideo will call back even if there's no
- // video buffer.
- //
- // In theory we can check to see if there's video before calling the remove, but in
- // the event that we're switching between renditions and from video to audio only
- // (when we add support for that), we may need to clear the video contents despite
- // what the new media will contain.
-
-
- if (force || this.loaderType_ === 'main') {
- this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
- removesRemaining++;
- this.sourceUpdater_.removeVideo(start, end, removeFinished);
- } // remove any captions and ID3 tags
-
-
- for (var track in this.inbandTextTracks_) {
- removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
-
- removeFinished();
- }
- /**
- * (re-)schedule monitorBufferTick_ to run as soon as possible
- *
- * @private
- */
- ;
-
- _proto.monitorBuffer_ = function monitorBuffer_() {
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window__default['default'].setTimeout(this.monitorBufferTick_.bind(this), 1);
- }
- /**
- * As long as the SegmentLoader is in the READY state, periodically
- * invoke fillBuffer_().
- *
- * @private
- */
- ;
-
- _proto.monitorBufferTick_ = function monitorBufferTick_() {
- if (this.state === 'READY') {
- this.fillBuffer_();
- }
-
- if (this.checkBufferTimeout_) {
- window__default['default'].clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window__default['default'].setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
- }
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- ;
-
- _proto.fillBuffer_ = function fillBuffer_() {
- // TODO since the source buffer maintains a queue, and we shouldn't call this function
- // except when we're ready for the next segment, this check can most likely be removed
- if (this.sourceUpdater_.updating()) {
- return;
- } // see if we need to begin loading immediately
-
-
- var segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- this.isPendingTimestampOffset_ = false;
- this.timelineChangeController_.pendingTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
-
- this.loadSegment_(segmentInfo);
- }
- /**
- * Determines if we should call endOfStream on the media source based
- * on the state of the buffer or if appened segment was the final
- * segment in the playlist.
- *
- * @param {number} [mediaIndex] the media index of segment we last appended
- * @param {Object} [playlist] a media playlist object
- * @return {boolean} do we need to call endOfStream on the MediaSource
- */
- ;
-
- _proto.isEndOfStream_ = function isEndOfStream_(mediaIndex, playlist, partIndex) {
- if (mediaIndex === void 0) {
- mediaIndex = this.mediaIndex;
- }
-
- if (playlist === void 0) {
- playlist = this.playlist_;
- }
-
- if (partIndex === void 0) {
- partIndex = this.partIndex;
- }
-
- if (!playlist || !this.mediaSource_) {
- return false;
- }
-
- var segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
-
- var appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
-
- var appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endOfStream
- // so that MediaSources can trigger the `ended` event when it runs out of
- // buffered data instead of waiting for me
-
- return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
- }
- /**
- * Determines what request should be made given current segment loader state.
- *
- * @return {Object} a request object that describes the segment/part to load
- */
- ;
-
- _proto.chooseNextRequest_ = function chooseNextRequest_() {
- var bufferedEnd = lastBufferedEnd(this.buffered_()) || 0;
- var bufferedTime = Math.max(0, bufferedEnd - this.currentTime_());
- var preloaded = !this.hasPlayed_() && bufferedTime >= 1;
- var haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
- var segments = this.playlist_.segments; // return no segment if:
- // 1. we don't have segments
- // 2. The video has not yet played and we already downloaded a segment
- // 3. we already have enough buffered time
-
- if (!segments.length || preloaded || haveEnoughBuffer) {
- return null;
- }
-
- this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
- var next = {
- partIndex: null,
- mediaIndex: null,
- startOfSegment: null,
- playlist: this.playlist_,
- isSyncRequest: Boolean(!this.syncPoint_)
- };
-
- if (next.isSyncRequest) {
- next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
- } else if (this.mediaIndex !== null) {
- var segment = segments[this.mediaIndex];
- var partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
- next.startOfSegment = segment.end ? segment.end : bufferedEnd;
-
- if (segment.parts && segment.parts[partIndex + 1]) {
- next.mediaIndex = this.mediaIndex;
- next.partIndex = partIndex + 1;
- } else {
- next.mediaIndex = this.mediaIndex + 1;
- }
- } else {
- // Find the segment containing the end of the buffer or current time.
- var _Playlist$getMediaInf = Playlist.getMediaInfoForTime({
- playlist: this.playlist_,
- currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
- startingPartIndex: this.syncPoint_.partIndex,
- startingSegmentIndex: this.syncPoint_.segmentIndex,
- startTime: this.syncPoint_.time
- }),
- segmentIndex = _Playlist$getMediaInf.segmentIndex,
- startTime = _Playlist$getMediaInf.startTime,
- _partIndex = _Playlist$getMediaInf.partIndex;
-
- next.getMediaInfoForTime = this.fetchAtBuffer_ ? 'bufferedEnd' : 'currentTime';
- next.mediaIndex = segmentIndex;
- next.startOfSegment = startTime;
- next.partIndex = _partIndex;
- }
-
- var nextSegment = segments[next.mediaIndex];
- var nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
- // the next partIndex is invalid do not choose a next segment.
-
- if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
- return null;
- } // if the next segment has parts, and we don't have a partIndex.
- // Set partIndex to 0
-
-
- if (typeof next.partIndex !== 'number' && nextSegment.parts) {
- next.partIndex = 0;
- }
-
- var ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
- // 1. this is the last segment in the playlist
- // 2. end of stream has been called on the media source already
- // 3. the player is not seeking
-
- if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
- return null;
- }
-
- return this.generateSegmentInfo_(next);
- };
-
- _proto.generateSegmentInfo_ = function generateSegmentInfo_(options) {
- var playlist = options.playlist,
- mediaIndex = options.mediaIndex,
- startOfSegment = options.startOfSegment,
- isSyncRequest = options.isSyncRequest,
- partIndex = options.partIndex,
- forceTimestampOffset = options.forceTimestampOffset,
- getMediaInfoForTime = options.getMediaInfoForTime;
- var segment = playlist.segments[mediaIndex];
- var part = typeof partIndex === 'number' && segment.parts[partIndex];
- var segmentInfo = {
- requestId: 'segment-loader-' + Math.random(),
- // resolve the segment URL relative to the playlist
- uri: part && part.resolvedUri || segment.resolvedUri,
- // the segment's mediaIndex at the time it was requested
- mediaIndex: mediaIndex,
- partIndex: part ? partIndex : null,
- // whether or not to update the SegmentLoader's state with this
- // segment's mediaIndex
- isSyncRequest: isSyncRequest,
- startOfSegment: startOfSegment,
- // the segment's playlist
- playlist: playlist,
- // unencrypted bytes of the segment
- bytes: null,
- // when a key is defined for this segment, the encrypted bytes
- encryptedBytes: null,
- // The target timestampOffset for this segment when we append it
- // to the source buffer
- timestampOffset: null,
- // The timeline that the segment is in
- timeline: segment.timeline,
- // The expected duration of the segment in seconds
- duration: part && part.duration || segment.duration,
- // retain the segment in case the playlist updates while doing an async process
- segment: segment,
- part: part,
- byteLength: 0,
- transmuxer: this.transmuxer_,
- // type of getMediaInfoForTime that was used to get this segment
- getMediaInfoForTime: getMediaInfoForTime
- };
- var overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
- segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
- segmentTimeline: segment.timeline,
- currentTimeline: this.currentTimeline_,
- startOfSegment: startOfSegment,
- buffered: this.buffered_(),
- overrideCheck: overrideCheck
- });
- var audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
-
- if (typeof audioBufferedEnd === 'number') {
- // since the transmuxer is using the actual timing values, but the buffer is
- // adjusted by the timestamp offset, we must adjust the value here
- segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
- }
-
- if (this.sourceUpdater_.videoBuffered().length) {
- segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
- // adjusted by the timestmap offset, we must adjust the value here
- this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
- }
-
- return segmentInfo;
- } // get the timestampoffset for a segment,
- // added so that vtt segment loader can override and prevent
- // adding timestamp offsets.
- ;
-
- _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_(options) {
- return timestampOffsetForSegment(options);
- }
- /**
- * Determines if the network has enough bandwidth to complete the current segment
- * request in a timely manner. If not, the request will be aborted early and bandwidth
- * updated to trigger a playlist switch.
- *
- * @param {Object} stats
- * Object containing stats about the request timing and size
- * @private
- */
- ;
-
- _proto.earlyAbortWhenNeeded_ = function earlyAbortWhenNeeded_(stats) {
- if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
- // TODO: Replace using timeout with a boolean indicating whether this playlist is
- // the lowestEnabledRendition.
- !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
- !this.playlist_.attributes.BANDWIDTH) {
- return;
- } // Wait at least 1 second since the first byte of data has been received before
- // using the calculated bandwidth from the progress event to allow the bitrate
- // to stabilize
-
-
- if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
- return;
- }
-
- var currentTime = this.currentTime_();
- var measuredBandwidth = stats.bandwidth;
- var segmentDuration = this.pendingSegment_.duration;
- var requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
- // if we are only left with less than 1 second when the request completes.
- // A negative timeUntilRebuffering indicates we are already rebuffering
-
- var timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
- // is larger than the estimated time until the player runs out of forward buffer
-
- if (requestTimeRemaining <= timeUntilRebuffer$1) {
- return;
- }
-
- var switchCandidate = minRebufferMaxBandwidthSelector({
- master: this.vhs_.playlists.master,
- currentTime: currentTime,
- bandwidth: measuredBandwidth,
- duration: this.duration_(),
- segmentDuration: segmentDuration,
- timeUntilRebuffer: timeUntilRebuffer$1,
- currentTimeline: this.currentTimeline_,
- syncController: this.syncController_
- });
-
- if (!switchCandidate) {
- return;
- }
-
- var rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
- var timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
- var minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
- // potential round trip time of the new request so that we are not too aggressive
- // with switching to a playlist that might save us a fraction of a second.
-
- if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
- minimumTimeSaving = 1;
- }
-
- if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
- return;
- } // set the bandwidth to that of the desired playlist being sure to scale by
- // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
- // don't trigger a bandwidthupdate as the bandwidth is artifial
-
-
- this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
- this.trigger('earlyabort');
- };
-
- _proto.handleAbort_ = function handleAbort_(segmentInfo) {
- this.logger_("Aborting " + segmentInfoString(segmentInfo));
- this.mediaRequestsAborted += 1;
- }
- /**
- * XHR `progress` event handler
- *
- * @param {Event}
- * The XHR `progress` event
- * @param {Object} simpleSegment
- * A simplified segment object copy
- * @private
- */
- ;
-
- _proto.handleProgress_ = function handleProgress_(event, simpleSegment) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- this.trigger('progress');
- };
-
- _proto.handleTrackInfo_ = function handleTrackInfo_(simpleSegment, trackInfo) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- if (this.checkForIllegalMediaSwitch(trackInfo)) {
- return;
- }
-
- trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
- // Guard against cases where we're not getting track info at all until we are
- // certain that all streams will provide it.
-
- if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.startingMediaInfo_ = trackInfo;
- this.currentMediaInfo_ = trackInfo;
- this.logger_('trackinfo update', trackInfo);
- this.trigger('trackinfo');
- } // trackinfo may cause an abort if the trackinfo
- // causes a codec change to an unsupported codec.
-
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // set trackinfo on the pending segment so that
- // it can append.
-
-
- this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
-
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- };
-
- _proto.handleTimingInfo_ = function handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- var segmentInfo = this.pendingSegment_;
- var timingInfoProperty = timingInfoPropertyForMedia(mediaType);
- segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
- segmentInfo[timingInfoProperty][timeType] = time;
- this.logger_("timinginfo: " + mediaType + " - " + timeType + " - " + time); // check if any calls were waiting on the timing info
-
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- };
-
- _proto.handleCaptions_ = function handleCaptions_(simpleSegment, captionData) {
- var _this2 = this;
-
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // This could only happen with fmp4 segments, but
- // should still not happen in general
-
-
- if (captionData.length === 0) {
- this.logger_('SegmentLoader received no captions from a caption event');
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
- // can be adjusted by the timestamp offset
-
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
- return;
- }
-
- var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
- var captionTracks = {}; // get total start/end and captions for each track/stream
-
- captionData.forEach(function (caption) {
- // caption.stream is actually a track name...
- // set to the existing values in tracks or default values
- captionTracks[caption.stream] = captionTracks[caption.stream] || {
- // Infinity, as any other value will be less than this
- startTime: Infinity,
- captions: [],
- // 0 as an other value will be more than this
- endTime: 0
- };
- var captionTrack = captionTracks[caption.stream];
- captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
- captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
- captionTrack.captions.push(caption);
- });
- Object.keys(captionTracks).forEach(function (trackName) {
- var _captionTracks$trackN = captionTracks[trackName],
- startTime = _captionTracks$trackN.startTime,
- endTime = _captionTracks$trackN.endTime,
- captions = _captionTracks$trackN.captions;
- var inbandTextTracks = _this2.inbandTextTracks_;
-
- _this2.logger_("adding cues from " + startTime + " -> " + endTime + " for " + trackName);
-
- createCaptionsTrackIfNotExists(inbandTextTracks, _this2.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
- // We do this because a rendition change that also changes the timescale for captions
- // will result in captions being re-parsed for certain segments. If we add them again
- // without clearing we will have two of the same captions visible.
-
- removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
- addCaptionData({
- captionArray: captions,
- inbandTextTracks: inbandTextTracks,
- timestampOffset: timestampOffset
- });
- }); // Reset stored captions since we added parsed
- // captions to a text track at this point
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- };
-
- _proto.handleId3_ = function handleId3_(simpleSegment, id3Frames, dispatchType) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
-
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
- return;
- }
-
- var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
- // audio/video source with a metadata track, and an alt audio with a metadata track.
- // However, this probably won't happen, and if it does it can be handled then.
-
- createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
- addMetadata({
- inbandTextTracks: this.inbandTextTracks_,
- metadataArray: id3Frames,
- timestampOffset: timestampOffset,
- videoDuration: this.duration_()
- });
- };
-
- _proto.processMetadataQueue_ = function processMetadataQueue_() {
- this.metadataQueue_.id3.forEach(function (fn) {
- return fn();
- });
- this.metadataQueue_.caption.forEach(function (fn) {
- return fn();
- });
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- };
-
- _proto.processCallQueue_ = function processCallQueue_() {
- var callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
-
- this.callQueue_ = [];
- callQueue.forEach(function (fun) {
- return fun();
- });
- };
-
- _proto.processLoadQueue_ = function processLoadQueue_() {
- var loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
-
- this.loadQueue_ = [];
- loadQueue.forEach(function (fun) {
- return fun();
- });
- }
- /**
- * Determines whether the loader has enough info to load the next segment.
- *
- * @return {boolean}
- * Whether or not the loader has enough info to load the next segment
- */
- ;
-
- _proto.hasEnoughInfoToLoad_ = function hasEnoughInfoToLoad_() {
- // Since primary timing goes by video, only the audio loader potentially needs to wait
- // to load.
- if (this.loaderType_ !== 'audio') {
- return true;
- }
-
- var segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
- // enough info to load.
-
- if (!segmentInfo) {
- return false;
- } // The first segment can and should be loaded immediately so that source buffers are
- // created together (before appending). Source buffer creation uses the presence of
- // audio and video data to determine whether to create audio/video source buffers, and
- // uses processed (transmuxed or parsed) media to determine the types required.
-
-
- if (!this.currentMediaInfo_) {
- return true;
- }
-
- if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
- // can be requested and downloaded and only wait before it is transmuxed or parsed.
- // But in practice, there are a few reasons why it is better to wait until a loader
- // is ready to append that segment before requesting and downloading:
- //
- // 1. Because audio and main loaders cross discontinuities together, if this loader
- // is waiting for the other to catch up, then instead of requesting another
- // segment and using up more bandwidth, by not yet loading, more bandwidth is
- // allotted to the loader currently behind.
- // 2. media-segment-request doesn't have to have logic to consider whether a segment
- // is ready to be processed or not, isolating the queueing behavior to the loader.
- // 3. The audio loader bases some of its segment properties on timing information
- // provided by the main loader, meaning that, if the logic for waiting on
- // processing was in media-segment-request, then it would also need to know how
- // to re-generate the segment information after the main loader caught up.
- shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })) {
- return false;
- }
-
- return true;
- };
-
- _proto.hasEnoughInfoToAppend_ = function hasEnoughInfoToAppend_() {
- if (!this.sourceUpdater_.ready()) {
- return false;
- } // If content needs to be removed or the loader is waiting on an append reattempt,
- // then no additional content should be appended until the prior append is resolved.
-
-
- if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
- return false;
- }
-
- var segmentInfo = this.pendingSegment_; // no segment to append any data for or
- // we do not have information on this specific
- // segment yet
-
- if (!segmentInfo || !segmentInfo.trackInfo) {
- return false;
- }
-
- var _this$currentMediaInf = this.currentMediaInfo_,
- hasAudio = _this$currentMediaInf.hasAudio,
- hasVideo = _this$currentMediaInf.hasVideo,
- isMuxed = _this$currentMediaInf.isMuxed;
-
- if (hasVideo && !segmentInfo.videoTimingInfo) {
- return false;
- } // muxed content only relies on video timing information for now.
-
-
- if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
- return false;
- }
-
- if (shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })) {
- return false;
- }
-
- return true;
- };
-
- _proto.handleData_ = function handleData_(simpleSegment, result) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- } // If there's anything in the call queue, then this data came later and should be
- // executed after the calls currently queued.
-
-
- if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
- this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
-
- this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
-
- this.updateMediaSecondsLoaded_(segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
- // logic may change behavior depending on the state, and changing state too early may
- // inflate our estimates of bandwidth. In the future this should be re-examined to
- // note more granular states.
- // don't process and append data if the mediaSource is closed
-
- if (this.mediaSource_.readyState === 'closed') {
- return;
- } // if this request included an initialization segment, save that data
- // to the initSegment cache
-
-
- if (simpleSegment.map) {
- simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
-
- segmentInfo.segment.map = simpleSegment.map;
- } // if this request included a segment key, save that data in the cache
-
-
- if (simpleSegment.key) {
- this.segmentKey(simpleSegment.key, true);
- }
-
- segmentInfo.isFmp4 = simpleSegment.isFmp4;
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
-
- if (segmentInfo.isFmp4) {
- this.trigger('fmp4');
- segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
- } else {
- var useVideoTimingInfo = this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- var firstVideoFrameTimeForData;
-
- if (useVideoTimingInfo) {
- firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
- } // Segment loader knows more about segment timing than the transmuxer (in certain
- // aspects), so make any changes required for a more accurate start time.
- // Don't set the end time yet, as the segment may not be finished processing.
-
-
- segmentInfo.timingInfo.start = this.trueSegmentStart_({
- currentStart: segmentInfo.timingInfo.start,
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex,
- currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
- useVideoTimingInfo: useVideoTimingInfo,
- firstVideoFrameTimeForData: firstVideoFrameTimeForData,
- videoTimingInfo: segmentInfo.videoTimingInfo,
- audioTimingInfo: segmentInfo.audioTimingInfo
- });
- } // Init segments for audio and video only need to be appended in certain cases. Now
- // that data is about to be appended, we can check the final cases to determine
- // whether we should append an init segment.
-
-
- this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
- // as we use the start of the segment to offset the best guess (playlist provided)
- // timestamp offset.
-
- this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
- // be appended or not.
-
- if (segmentInfo.isSyncRequest) {
- // first save/update our timing info for this segment.
- // this is what allows us to choose an accurate segment
- // and the main reason we make a sync request.
- this.updateTimingInfoEnd_(segmentInfo);
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo: segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
- var next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
- // after taking into account its timing info, do not append it.
-
- if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
- this.logger_('sync segment was incorrect, not appending');
- return;
- } // otherwise append it like any other segment as our guess was correct.
-
-
- this.logger_('sync segment was correct, appending');
- } // Save some state so that in the future anything waiting on first append (and/or
- // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
- // we need some notion of whether the timestamp offset or other relevant information
- // has had a chance to be set.
-
-
- segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
-
- this.processMetadataQueue_();
- this.appendData_(segmentInfo, result);
- };
-
- _proto.updateAppendInitSegmentStatus = function updateAppendInitSegmentStatus(segmentInfo, type) {
- // alt audio doesn't manage timestamp offset
- if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' && // in the case that we're handling partial data, we don't want to append an init
- // segment for each chunk
- !segmentInfo.changedTimestampOffset) {
- // if the timestamp offset changed, the timeline may have changed, so we have to re-
- // append init segments
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- }
-
- if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
- // make sure we append init segment on playlist changes, in case the media config
- // changed
- this.appendInitSegment_[type] = true;
- }
- };
-
- _proto.getInitSegmentAndUpdateState_ = function getInitSegmentAndUpdateState_(_ref4) {
- var type = _ref4.type,
- initSegment = _ref4.initSegment,
- map = _ref4.map,
- playlist = _ref4.playlist;
-
- // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
- // (Section 3) required to parse the applicable Media Segments. It applies to every
- // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
- // or until the end of the playlist."
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
- if (map) {
- var id = initSegmentId(map);
-
- if (this.activeInitSegmentId_ === id) {
- // don't need to re-append the init segment if the ID matches
- return null;
- } // a map-specified init segment takes priority over any transmuxed (or otherwise
- // obtained) init segment
- //
- // this also caches the init segment for later use
-
-
- initSegment = this.initSegmentForMap(map, true).bytes;
- this.activeInitSegmentId_ = id;
- } // We used to always prepend init segments for video, however, that shouldn't be
- // necessary. Instead, we should only append on changes, similar to what we've always
- // done for audio. This is more important (though may not be that important) for
- // frame-by-frame appending for LHLS, simply because of the increased quantity of
- // appends.
-
-
- if (initSegment && this.appendInitSegment_[type]) {
- // Make sure we track the playlist that we last used for the init segment, so that
- // we can re-append the init segment in the event that we get data from a new
- // playlist. Discontinuities and track changes are handled in other sections.
- this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
-
- this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
- // we are appending the muxer init segment
-
- this.activeInitSegmentId_ = null;
- return initSegment;
- }
-
- return null;
- };
-
- _proto.handleQuotaExceededError_ = function handleQuotaExceededError_(_ref5, error) {
- var _this3 = this;
-
- var segmentInfo = _ref5.segmentInfo,
- type = _ref5.type,
- bytes = _ref5.bytes;
- var audioBuffered = this.sourceUpdater_.audioBuffered();
- var videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
- // should be cleared out during the buffer removals. However, log in case it helps
- // debug.
-
- if (audioBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
- }
-
- if (videoBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
- }
-
- var audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
- var audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
- var videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
- var videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
-
- if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
- // Can't remove enough buffer to make room for new segment (or the browser doesn't
- // allow for appends of segments this size). In the future, it may be possible to
- // split up the segment and append in pieces, but for now, error out this playlist
- // in an attempt to switch to a more manageable rendition.
- this.logger_('On QUOTA_EXCEEDED_ERR, single segment too large to append to ' + 'buffer, triggering an error. ' + ("Appended byte length: " + bytes.byteLength + ", ") + ("audio buffer: " + timeRangesToArray(audioBuffered).join(', ') + ", ") + ("video buffer: " + timeRangesToArray(videoBuffered).join(', ') + ", "));
- this.error({
- message: 'Quota exceeded error with append of a single segment of content',
- excludeUntil: Infinity
- });
- this.trigger('error');
- return;
- } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
- // that the segment-loader should block on future events until this one is handled, so
- // that it doesn't keep moving onto further segments. Adding the call to the call
- // queue will prevent further appends until waitingOnRemove_ and
- // quotaExceededErrorRetryTimeout_ are cleared.
- //
- // Note that this will only block the current loader. In the case of demuxed content,
- // the other load may keep filling as fast as possible. In practice, this should be
- // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
- // source buffer, or video fills without enough room for audio to append (and without
- // the availability of clearing out seconds of back buffer to make room for audio).
- // But it might still be good to handle this case in the future as a TODO.
-
-
- this.waitingOnRemove_ = true;
- this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }));
- var currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
- // before retrying.
-
- var timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
- this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to " + timeToRemoveUntil);
- this.remove(0, timeToRemoveUntil, function () {
- _this3.logger_("On QUOTA_EXCEEDED_ERR, retrying append in " + MIN_BACK_BUFFER + "s");
-
- _this3.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
- // attempts (since we can't clear less than the minimum)
-
- _this3.quotaExceededErrorRetryTimeout_ = window__default['default'].setTimeout(function () {
- _this3.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
-
- _this3.quotaExceededErrorRetryTimeout_ = null;
-
- _this3.processCallQueue_();
- }, MIN_BACK_BUFFER * 1000);
- }, true);
- };
-
- _proto.handleAppendError_ = function handleAppendError_(_ref6, error) {
- var segmentInfo = _ref6.segmentInfo,
- type = _ref6.type,
- bytes = _ref6.bytes;
-
- // if there's no error, nothing to do
- if (!error) {
- return;
- }
-
- if (error.code === QUOTA_EXCEEDED_ERR) {
- this.handleQuotaExceededError_({
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }); // A quota exceeded error should be recoverable with a future re-append, so no need
- // to trigger an append error.
-
- return;
- }
-
- this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
- this.error(type + " append of " + bytes.length + "b failed for segment " + ("#" + segmentInfo.mediaIndex + " in playlist " + segmentInfo.playlist.id)); // If an append errors, we often can't recover.
- // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
- //
- // Trigger a special error so that it can be handled separately from normal,
- // recoverable errors.
-
- this.trigger('appenderror');
- };
-
- _proto.appendToSourceBuffer_ = function appendToSourceBuffer_(_ref7) {
- var segmentInfo = _ref7.segmentInfo,
- type = _ref7.type,
- initSegment = _ref7.initSegment,
- data = _ref7.data,
- bytes = _ref7.bytes;
-
- // If this is a re-append, bytes were already created and don't need to be recreated
- if (!bytes) {
- var segments = [data];
- var byteLength = data.byteLength;
-
- if (initSegment) {
- // if the media initialization segment is changing, append it before the content
- // segment
- segments.unshift(initSegment);
- byteLength += initSegment.byteLength;
- } // Technically we should be OK appending the init segment separately, however, we
- // haven't yet tested that, and prepending is how we have always done things.
-
-
- bytes = concatSegments({
- bytes: byteLength,
- segments: segments
- });
- }
-
- this.sourceUpdater_.appendBuffer({
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }, this.handleAppendError_.bind(this, {
- segmentInfo: segmentInfo,
- type: type,
- bytes: bytes
- }));
- };
-
- _proto.handleSegmentTimingInfo_ = function handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
- if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
- return;
- }
-
- var segment = this.pendingSegment_.segment;
- var timingInfoProperty = type + "TimingInfo";
-
- if (!segment[timingInfoProperty]) {
- segment[timingInfoProperty] = {};
- }
-
- segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
- segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
- segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
- segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
- segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
-
- segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
- };
-
- _proto.appendData_ = function appendData_(segmentInfo, result) {
- var type = result.type,
- data = result.data;
-
- if (!data || !data.byteLength) {
- return;
- }
-
- if (type === 'audio' && this.audioDisabled_) {
- return;
- }
-
- var initSegment = this.getInitSegmentAndUpdateState_({
- type: type,
- initSegment: result.initSegment,
- playlist: segmentInfo.playlist,
- map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
- });
- this.appendToSourceBuffer_({
- segmentInfo: segmentInfo,
- type: type,
- initSegment: initSegment,
- data: data
- });
- }
- /**
- * load a specific segment from a request into the buffer
- *
- * @private
- */
- ;
-
- _proto.loadSegment_ = function loadSegment_(segmentInfo) {
- var _this4 = this;
-
- this.state = 'WAITING';
- this.pendingSegment_ = segmentInfo;
- this.trimBackBuffer_(segmentInfo);
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
-
- if (!this.hasEnoughInfoToLoad_()) {
- this.loadQueue_.push(function () {
- // regenerate the audioAppendStart, timestampOffset, etc as they
- // may have changed since this function was added to the queue.
- var options = _extends_1({}, segmentInfo, {
- forceTimestampOffset: true
- });
-
- _extends_1(segmentInfo, _this4.generateSegmentInfo_(options));
-
- _this4.isPendingTimestampOffset_ = false;
-
- _this4.updateTransmuxerAndRequestSegment_(segmentInfo);
- });
- return;
- }
-
- this.updateTransmuxerAndRequestSegment_(segmentInfo);
- };
-
- _proto.updateTransmuxerAndRequestSegment_ = function updateTransmuxerAndRequestSegment_(segmentInfo) {
- var _this5 = this;
-
- // We'll update the source buffer's timestamp offset once we have transmuxed data, but
- // the transmuxer still needs to be updated before then.
- //
- // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
- // offset must be passed to the transmuxer for stream correcting adjustments.
- if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
- this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
-
- segmentInfo.gopsToAlignWith = [];
- this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
-
- this.transmuxer_.postMessage({
- action: 'reset'
- });
- this.transmuxer_.postMessage({
- action: 'setTimestampOffset',
- timestampOffset: segmentInfo.timestampOffset
- });
- }
-
- var simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
- var isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
- var isWalkingForward = this.mediaIndex !== null;
- var isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
- // the first timeline
- segmentInfo.timeline > 0;
- var isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
- this.logger_("Requesting " + segmentInfoString(segmentInfo)); // If there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),
- // then this init segment has never been seen before and should be appended.
- //
- // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
- // both to true and leave the decision of whether to append the init segment to append time.
-
- if (simpleSegment.map && !simpleSegment.map.bytes) {
- this.logger_('going to request init segment.');
- this.appendInitSegment_ = {
- video: true,
- audio: true
- };
- }
-
- segmentInfo.abortRequests = mediaSegmentRequest({
- xhr: this.vhs_.xhr,
- xhrOptions: this.xhrOptions_,
- decryptionWorker: this.decrypter_,
- segment: simpleSegment,
- abortFn: this.handleAbort_.bind(this, segmentInfo),
- progressFn: this.handleProgress_.bind(this),
- trackInfoFn: this.handleTrackInfo_.bind(this),
- timingInfoFn: this.handleTimingInfo_.bind(this),
- videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
- audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
- captionsFn: this.handleCaptions_.bind(this),
- isEndOfTimeline: isEndOfTimeline,
- endedTimelineFn: function endedTimelineFn() {
- _this5.logger_('received endedtimeline callback');
- },
- id3Fn: this.handleId3_.bind(this),
- dataFn: this.handleData_.bind(this),
- doneFn: this.segmentRequestFinished_.bind(this)
- });
- }
- /**
- * trim the back buffer so that we don't have too much data
- * in the source buffer
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- */
- ;
-
- _proto.trimBackBuffer_ = function trimBackBuffer_(segmentInfo) {
- var removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
- // buffer and a very conservative "garbage collector"
- // We manually clear out the old buffer to ensure
- // we don't trigger the QuotaExceeded error
- // on the source buffer during subsequent appends
-
- if (removeToTime > 0) {
- this.remove(0, removeToTime);
- }
- }
- /**
- * created a simplified copy of the segment object with just the
- * information necessary to perform the XHR and decryption
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- * @return {Object} a simplified segment object copy
- */
- ;
-
- _proto.createSimplifiedSegmentObj_ = function createSimplifiedSegmentObj_(segmentInfo) {
- var segment = segmentInfo.segment;
- var part = segmentInfo.part;
- var simpleSegment = {
- resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
- byterange: part ? part.byterange : segment.byterange,
- requestId: segmentInfo.requestId,
- transmuxer: segmentInfo.transmuxer,
- audioAppendStart: segmentInfo.audioAppendStart,
- gopsToAlignWith: segmentInfo.gopsToAlignWith,
- part: segmentInfo.part
- };
- var previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
-
- if (previousSegment && previousSegment.timeline === segment.timeline) {
- // The baseStartTime of a segment is used to handle rollover when probing the TS
- // segment to retrieve timing information. Since the probe only looks at the media's
- // times (e.g., PTS and DTS values of the segment), and doesn't consider the
- // player's time (e.g., player.currentTime()), baseStartTime should reflect the
- // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
- // seconds of media time, so should be used here. The previous segment is used since
- // the end of the previous segment should represent the beginning of the current
- // segment, so long as they are on the same timeline.
- if (previousSegment.videoTimingInfo) {
- simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
- } else if (previousSegment.audioTimingInfo) {
- simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
- }
- }
-
- if (segment.key) {
- // if the media sequence is greater than 2^32, the IV will be incorrect
- // assuming 10s segments, that would be about 1300 years
- var iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
- simpleSegment.key = this.segmentKey(segment.key);
- simpleSegment.key.iv = iv;
- }
-
- if (segment.map) {
- simpleSegment.map = this.initSegmentForMap(segment.map);
- }
-
- return simpleSegment;
- };
-
- _proto.saveTransferStats_ = function saveTransferStats_(stats) {
- // every request counts as a media request even if it has been aborted
- // or canceled due to a timeout
- this.mediaRequests += 1;
-
- if (stats) {
- this.mediaBytesTransferred += stats.bytesReceived;
- this.mediaTransferDuration += stats.roundTripTime;
- }
- };
-
- _proto.saveBandwidthRelatedStats_ = function saveBandwidthRelatedStats_(duration, stats) {
- // byteLength will be used for throughput, and should be based on bytes receieved,
- // which we only know at the end of the request and should reflect total bytes
- // downloaded rather than just bytes processed from components of the segment
- this.pendingSegment_.byteLength = stats.bytesReceived;
-
- if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_("Ignoring segment's bandwidth because its duration of " + duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
- return;
- }
-
- this.bandwidth = stats.bandwidth;
- this.roundTrip = stats.roundTripTime;
- };
-
- _proto.handleTimeout_ = function handleTimeout_() {
- // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functinality between segment loaders
- this.mediaRequestsTimedout += 1;
- this.bandwidth = 1;
- this.roundTrip = NaN;
- this.trigger('bandwidthupdate');
- }
- /**
- * Handle the callback from the segmentRequest function and set the
- * associated SegmentLoader state and errors if necessary
- *
- * @private
- */
- ;
-
- _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
- // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
- // check the call queue directly since this function doesn't need to deal with any
- // data, and can continue even if the source buffers are not set up and we didn't get
- // any data from the segment
- if (this.callQueue_.length) {
- this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
-
- if (!this.pendingSegment_) {
- return;
- } // the request was aborted and the SegmentLoader has already started
- // another request. this can happen when the timeout for an aborted
- // request triggers due to a limitation in the XHR library
- // do not count this as any sort of request or we risk double-counting
-
-
- if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
- return;
- } // an error occurred from the active pendingSegment_ so reset everything
-
-
- if (error) {
- this.pendingSegment_ = null;
- this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
-
- if (error.code === REQUEST_ERRORS.ABORTED) {
- return;
- }
-
- this.pause(); // the error is really just that at least one of the requests timed-out
- // set the bandwidth to a very low value and trigger an ABR switch to
- // take emergency action
-
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- return;
- } // if control-flow has arrived here, then the error is real
- // emit an error event to blacklist the current playlist
-
-
- this.mediaRequestsErrored += 1;
- this.error(error);
- this.trigger('error');
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
- // generated for ABR purposes
-
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
- segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
-
- if (result.gopInfo) {
- this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
- } // Although we may have already started appending on progress, we shouldn't switch the
- // state away from loading until we are officially done loading the segment data.
-
-
- this.state = 'APPENDING'; // used for testing
-
- this.trigger('appending');
- this.waitForAppendsToComplete_(segmentInfo);
- };
-
- _proto.setTimeMapping_ = function setTimeMapping_(timeline) {
- var timelineMapping = this.syncController_.mappingForTimeline(timeline);
-
- if (timelineMapping !== null) {
- this.timeMapping_ = timelineMapping;
- }
- };
-
- _proto.updateMediaSecondsLoaded_ = function updateMediaSecondsLoaded_(segment) {
- if (typeof segment.start === 'number' && typeof segment.end === 'number') {
- this.mediaSecondsLoaded += segment.end - segment.start;
- } else {
- this.mediaSecondsLoaded += segment.duration;
- }
- };
-
- _proto.shouldUpdateTransmuxerTimestampOffset_ = function shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
- if (timestampOffset === null) {
- return false;
- } // note that we're potentially using the same timestamp offset for both video and
- // audio
-
-
- if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- return true;
- }
-
- if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- return true;
- }
-
- return false;
- };
-
- _proto.trueSegmentStart_ = function trueSegmentStart_(_ref8) {
- var currentStart = _ref8.currentStart,
- playlist = _ref8.playlist,
- mediaIndex = _ref8.mediaIndex,
- firstVideoFrameTimeForData = _ref8.firstVideoFrameTimeForData,
- currentVideoTimestampOffset = _ref8.currentVideoTimestampOffset,
- useVideoTimingInfo = _ref8.useVideoTimingInfo,
- videoTimingInfo = _ref8.videoTimingInfo,
- audioTimingInfo = _ref8.audioTimingInfo;
-
- if (typeof currentStart !== 'undefined') {
- // if start was set once, keep using it
- return currentStart;
- }
-
- if (!useVideoTimingInfo) {
- return audioTimingInfo.start;
- }
-
- var previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
- // within that segment. Since the transmuxer maintains a cache of incomplete data
- // from and/or the last frame seen, the start time may reflect a frame that starts
- // in the previous segment. Check for that case and ensure the start time is
- // accurate for the segment.
-
- if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
- return firstVideoFrameTimeForData;
- }
-
- return videoTimingInfo.start;
- };
-
- _proto.waitForAppendsToComplete_ = function waitForAppendsToComplete_(segmentInfo) {
- if (!this.currentMediaInfo_) {
- this.error({
- message: 'No starting media returned, likely due to an unsupported media format.',
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return;
- } // Although transmuxing is done, appends may not yet be finished. Throw a marker
- // on each queue this loader is responsible for to ensure that the appends are
- // complete.
-
-
- var _this$currentMediaInf2 = this.currentMediaInfo_,
- hasAudio = _this$currentMediaInf2.hasAudio,
- hasVideo = _this$currentMediaInf2.hasVideo,
- isMuxed = _this$currentMediaInf2.isMuxed;
- var waitForVideo = this.loaderType_ === 'main' && hasVideo;
- var waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
- segmentInfo.waitingOnAppends = 0; // segments with no data
-
- if (!segmentInfo.hasAppendedData_) {
- if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
- // When there's no audio or video data in the segment, there's no audio or video
- // timing information.
- //
- // If there's no audio or video timing information, then the timestamp offset
- // can't be adjusted to the appropriate value for the transmuxer and source
- // buffers.
- //
- // Therefore, the next segment should be used to set the timestamp offset.
- this.isPendingTimestampOffset_ = true;
- } // override settings for metadata only segments
-
-
- segmentInfo.timingInfo = {
- start: 0
- };
- segmentInfo.waitingOnAppends++;
-
- if (!this.isPendingTimestampOffset_) {
- // update the timestampoffset
- this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
- // no video/audio data.
-
- this.processMetadataQueue_();
- } // append is "done" instantly with no data.
-
-
- this.checkAppendsDone_(segmentInfo);
- return;
- } // Since source updater could call back synchronously, do the increments first.
-
-
- if (waitForVideo) {
- segmentInfo.waitingOnAppends++;
- }
-
- if (waitForAudio) {
- segmentInfo.waitingOnAppends++;
- }
-
- if (waitForVideo) {
- this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
-
- if (waitForAudio) {
- this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
- };
-
- _proto.checkAppendsDone_ = function checkAppendsDone_(segmentInfo) {
- if (this.checkForAbort_(segmentInfo.requestId)) {
- return;
- }
-
- segmentInfo.waitingOnAppends--;
-
- if (segmentInfo.waitingOnAppends === 0) {
- this.handleAppendsDone_();
- }
- };
-
- _proto.checkForIllegalMediaSwitch = function checkForIllegalMediaSwitch(trackInfo) {
- var illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.currentMediaInfo_, trackInfo);
-
- if (illegalMediaSwitchError) {
- this.error({
- message: illegalMediaSwitchError,
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return true;
- }
-
- return false;
- };
-
- _proto.updateSourceBufferTimestampOffset_ = function updateSourceBufferTimestampOffset_(segmentInfo) {
- if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
- // priority, timing-wise, so we must wait
- typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
- segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
- this.loaderType_ !== 'main') {
- return;
- }
-
- var didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
- // the timing info here comes from video. In the event that the audio is longer than
- // the video, this will trim the start of the audio.
- // This also trims any offset from 0 at the beginning of the media
-
- segmentInfo.timestampOffset -= segmentInfo.timingInfo.start; // In the event that there are part segment downloads, each will try to update the
- // timestamp offset. Retaining this bit of state prevents us from updating in the
- // future (within the same segment), however, there may be a better way to handle it.
-
- segmentInfo.changedTimestampOffset = true;
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (didChange) {
- this.trigger('timestampoffset');
- }
- };
-
- _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_(segmentInfo) {
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
- var useVideoTimingInfo = this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- var prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
-
- if (!prioritizedTimingInfo) {
- return;
- }
-
- segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
- // current example is the case of fmp4), so use the rough duration to calculate an
- // end time.
- prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
- }
- /**
- * callback to run when appendBuffer is finished. detects if we are
- * in a good state to do things with the data we got, or if we need
- * to wait for more
- *
- * @private
- */
- ;
-
- _proto.handleAppendsDone_ = function handleAppendsDone_() {
- // appendsdone can cause an abort
- if (this.pendingSegment_) {
- this.trigger('appendsdone');
- }
-
- if (!this.pendingSegment_) {
- this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
- // all appending cases?
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
-
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
- // best to wait until all appends are done so we're sure that the primary media is
- // finished (and we have its end time).
-
- this.updateTimingInfoEnd_(segmentInfo);
-
- if (this.shouldSaveSegmentTimingInfo_) {
- // Timeline mappings should only be saved for the main loader. This is for multiple
- // reasons:
- //
- // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
- // and the main loader try to save the timeline mapping, whichever comes later
- // will overwrite the first. In theory this is OK, as the mappings should be the
- // same, however, it breaks for (2)
- // 2) In the event of a live stream, the initial live point will make for a somewhat
- // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
- // the mapping will be off for one of the streams, dependent on which one was
- // first saved (see (1)).
- // 3) Primary timing goes by video in VHS, so the mapping should be video.
- //
- // Since the audio loader will wait for the main loader to load the first segment,
- // the main loader will save the first timeline mapping, and ensure that there won't
- // be a case where audio loads two segments without saving a mapping (thus leading
- // to missing segment timing info).
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo: segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
- }
-
- var segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
-
- if (segmentDurationMessage) {
- if (segmentDurationMessage.severity === 'warn') {
- videojs__default['default'].log.warn(segmentDurationMessage.message);
- } else {
- this.logger_(segmentDurationMessage.message);
- }
- }
-
- this.recordThroughput_(segmentInfo);
- this.pendingSegment_ = null;
- this.state = 'READY';
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate'); // if the sync request was not appended
- // then it was not the correct segment.
- // throw it away and use the data it gave us
- // to get the correct one.
-
- if (!segmentInfo.hasAppendedData_) {
- this.logger_("Throwing away un-appended sync request " + segmentInfoString(segmentInfo));
- return;
- }
- }
-
- this.logger_("Appended " + segmentInfoString(segmentInfo));
- this.addSegmentMetadataCue_(segmentInfo);
- this.fetchAtBuffer_ = true;
-
- if (this.currentTimeline_ !== segmentInfo.timeline) {
- this.timelineChangeController_.lastTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- }); // If audio is not disabled, the main segment loader is responsible for updating
- // the audio timeline as well. If the content is video only, this won't have any
- // impact.
-
- if (this.loaderType_ === 'main' && !this.audioDisabled_) {
- this.timelineChangeController_.lastTimelineChange({
- type: 'audio',
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
- }
-
- this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
- // the following conditional otherwise it may consider this a bad "guess"
- // and attempt to resync when the post-update seekable window and live
- // point would mean that this was the perfect segment to fetch
-
- this.trigger('syncinfoupdate');
- var segment = segmentInfo.segment; // If we previously appended a segment that ends more than 3 targetDurations before
- // the currentTime_ that means that our conservative guess was too conservative.
- // In that case, reset the loader state so that we try to use any information gained
- // from the previous request to create a new, more accurate, sync-point.
-
- if (segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3) {
- this.resetEverything();
- return;
- }
-
- var isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
- // and conservatively guess
-
- if (isWalkingForward) {
- this.trigger('bandwidthupdate');
- }
-
- this.trigger('progress');
- this.mediaIndex = segmentInfo.mediaIndex;
- this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
- // buffer, end the stream. this ensures the "ended" event will
- // fire if playback reaches that point.
-
- if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
- this.endOfStream();
- } // used for testing
-
-
- this.trigger('appended');
-
- if (segmentInfo.hasAppendedData_) {
- this.mediaAppends++;
- }
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
- /**
- * Records the current throughput of the decrypt, transmux, and append
- * portion of the semgment pipeline. `throughput.rate` is a the cumulative
- * moving average of the throughput. `throughput.count` is the number of
- * data points in the average.
- *
- * @private
- * @param {Object} segmentInfo the object returned by loadSegment
- */
- ;
-
- _proto.recordThroughput_ = function recordThroughput_(segmentInfo) {
- if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_("Ignoring segment's throughput because its duration of " + segmentInfo.duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
- return;
- }
-
- var rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
- // by zero in the case where the throughput is ridiculously high
-
- var segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
-
- var segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
- // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
-
- this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
- }
- /**
- * Adds a cue to the segment-metadata track with some metadata information about the
- * segment
- *
- * @private
- * @param {Object} segmentInfo
- * the object returned by loadSegment
- * @method addSegmentMetadataCue_
- */
- ;
-
- _proto.addSegmentMetadataCue_ = function addSegmentMetadataCue_(segmentInfo) {
- if (!this.segmentMetadataTrack_) {
- return;
- }
-
- var segment = segmentInfo.segment;
- var start = segment.start;
- var end = segment.end; // Do not try adding the cue if the start and end times are invalid.
-
- if (!finite(start) || !finite(end)) {
- return;
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
- var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
- var value = {
- custom: segment.custom,
- dateTimeObject: segment.dateTimeObject,
- dateTimeString: segment.dateTimeString,
- bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
- resolution: segmentInfo.playlist.attributes.RESOLUTION,
- codecs: segmentInfo.playlist.attributes.CODECS,
- byteLength: segmentInfo.byteLength,
- uri: segmentInfo.uri,
- timeline: segmentInfo.timeline,
- playlist: segmentInfo.playlist.id,
- start: start,
- end: end
- };
- var data = JSON.stringify(value);
- var cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
- // the differences of WebKitDataCue in safari and VTTCue in other browsers
-
- cue.value = value;
- this.segmentMetadataTrack_.addCue(cue);
- };
-
- return SegmentLoader;
- }(videojs__default['default'].EventTarget);
-
- function noop() {}
-
- var toTitleCase = function toTitleCase(string) {
- if (typeof string !== 'string') {
- return string;
- }
-
- return string.replace(/./, function (w) {
- return w.toUpperCase();
- });
- };
-
- var bufferTypes = ['video', 'audio'];
-
- var _updating = function updating(type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
- };
-
- var nextQueueIndexOfType = function nextQueueIndexOfType(type, queue) {
- for (var i = 0; i < queue.length; i++) {
- var queueEntry = queue[i];
-
- if (queueEntry.type === 'mediaSource') {
- // If the next entry is a media source entry (uses multiple source buffers), block
- // processing to allow it to go through first.
- return null;
- }
-
- if (queueEntry.type === type) {
- return i;
- }
- }
-
- return null;
- };
-
- var shiftQueue = function shiftQueue(type, sourceUpdater) {
- if (sourceUpdater.queue.length === 0) {
- return;
- }
-
- var queueIndex = 0;
- var queueEntry = sourceUpdater.queue[queueIndex];
-
- if (queueEntry.type === 'mediaSource') {
- if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
- sourceUpdater.queue.shift();
- queueEntry.action(sourceUpdater);
-
- if (queueEntry.doneFn) {
- queueEntry.doneFn();
- } // Only specific source buffer actions must wait for async updateend events. Media
- // Source actions process synchronously. Therefore, both audio and video source
- // buffers are now clear to process the next queue entries.
-
-
- shiftQueue('audio', sourceUpdater);
- shiftQueue('video', sourceUpdater);
- } // Media Source actions require both source buffers, so if the media source action
- // couldn't process yet (because one or both source buffers are busy), block other
- // queue actions until both are available and the media source action can process.
-
-
- return;
- }
-
- if (type === 'mediaSource') {
- // If the queue was shifted by a media source action (this happens when pushing a
- // media source action onto the queue), then it wasn't from an updateend event from an
- // audio or video source buffer, so there's no change from previous state, and no
- // processing should be done.
- return;
- } // Media source queue entries don't need to consider whether the source updater is
- // started (i.e., source buffers are created) as they don't need the source buffers, but
- // source buffer queue entries do.
-
-
- if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || _updating(type, sourceUpdater)) {
- return;
- }
-
- if (queueEntry.type !== type) {
- queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
-
- if (queueIndex === null) {
- // Either there's no queue entry that uses this source buffer type in the queue, or
- // there's a media source queue entry before the next entry of this type, in which
- // case wait for that action to process first.
- return;
- }
-
- queueEntry = sourceUpdater.queue[queueIndex];
- }
-
- sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
- //
- // The queue pending operation must be set before the action is performed in the event
- // that the action results in a synchronous event that is acted upon. For instance, if
- // an exception is thrown that can be handled, it's possible that new actions will be
- // appended to an empty queue and immediately executed, but would not have the correct
- // pending information if this property was set after the action was performed.
-
- sourceUpdater.queuePending[type] = queueEntry;
- queueEntry.action(type, sourceUpdater);
-
- if (!queueEntry.doneFn) {
- // synchronous operation, process next entry
- sourceUpdater.queuePending[type] = null;
- shiftQueue(type, sourceUpdater);
- return;
- }
- };
-
- var cleanupBuffer = function cleanupBuffer(type, sourceUpdater) {
- var buffer = sourceUpdater[type + "Buffer"];
- var titleType = toTitleCase(type);
-
- if (!buffer) {
- return;
- }
-
- buffer.removeEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
- buffer.removeEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
- sourceUpdater.codecs[type] = null;
- sourceUpdater[type + "Buffer"] = null;
- };
-
- var inSourceBuffers = function inSourceBuffers(mediaSource, sourceBuffer) {
- return mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
- };
-
- var actions = {
- appendBuffer: function appendBuffer(bytes, segmentInfo, onError) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Appending segment " + segmentInfo.mediaIndex + "'s " + bytes.length + " bytes to " + type + "Buffer");
-
- try {
- sourceBuffer.appendBuffer(bytes);
- } catch (e) {
- sourceUpdater.logger_("Error with code " + e.code + " " + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + ("when appending segment " + segmentInfo.mediaIndex + " to " + type + "Buffer"));
- sourceUpdater.queuePending[type] = null;
- onError(e);
- }
- };
- },
- remove: function remove(start, end) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Removing " + start + " to " + end + " from " + type + "Buffer");
-
- try {
- sourceBuffer.remove(start, end);
- } catch (e) {
- sourceUpdater.logger_("Remove " + start + " to " + end + " from " + type + "Buffer failed");
- }
- };
- },
- timestampOffset: function timestampOffset(offset) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Setting " + type + "timestampOffset to " + offset);
- sourceBuffer.timestampOffset = offset;
- };
- },
- callback: function callback(_callback) {
- return function (type, sourceUpdater) {
- _callback();
- };
- },
- endOfStream: function endOfStream(error) {
- return function (sourceUpdater) {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
-
- sourceUpdater.logger_("Calling mediaSource endOfStream(" + (error || '') + ")");
-
- try {
- sourceUpdater.mediaSource.endOfStream(error);
- } catch (e) {
- videojs__default['default'].log.warn('Failed to call media source endOfStream', e);
- }
- };
- },
- duration: function duration(_duration) {
- return function (sourceUpdater) {
- sourceUpdater.logger_("Setting mediaSource duration to " + _duration);
-
- try {
- sourceUpdater.mediaSource.duration = _duration;
- } catch (e) {
- videojs__default['default'].log.warn('Failed to set media source duration', e);
- }
- };
- },
- abort: function abort() {
- return function (type, sourceUpdater) {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
-
- var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("calling abort on " + type + "Buffer");
-
- try {
- sourceBuffer.abort();
- } catch (e) {
- videojs__default['default'].log.warn("Failed to abort on " + type + "Buffer", e);
- }
- };
- },
- addSourceBuffer: function addSourceBuffer(type, codec) {
- return function (sourceUpdater) {
- var titleType = toTitleCase(type);
- var mime = getMimeForCodec(codec);
- sourceUpdater.logger_("Adding " + type + "Buffer with codec " + codec + " to mediaSource");
- var sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
- sourceBuffer.addEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
- sourceBuffer.addEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
- sourceUpdater.codecs[type] = codec;
- sourceUpdater[type + "Buffer"] = sourceBuffer;
- };
- },
- removeSourceBuffer: function removeSourceBuffer(type) {
- return function (sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_("Removing " + type + "Buffer with codec " + sourceUpdater.codecs[type] + " from mediaSource");
-
- try {
- sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
- } catch (e) {
- videojs__default['default'].log.warn("Failed to removeSourceBuffer " + type + "Buffer", e);
- }
- };
- },
- changeType: function changeType(codec) {
- return function (type, sourceUpdater) {
- var sourceBuffer = sourceUpdater[type + "Buffer"];
- var mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
-
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- } // do not update codec if we don't need to.
-
-
- if (sourceUpdater.codecs[type] === codec) {
- return;
- }
-
- sourceUpdater.logger_("changing " + type + "Buffer codec from " + sourceUpdater.codecs[type] + " to " + codec);
- sourceBuffer.changeType(mime);
- sourceUpdater.codecs[type] = codec;
- };
- }
- };
-
- var pushQueue = function pushQueue(_ref) {
- var type = _ref.type,
- sourceUpdater = _ref.sourceUpdater,
- action = _ref.action,
- doneFn = _ref.doneFn,
- name = _ref.name;
- sourceUpdater.queue.push({
- type: type,
- action: action,
- doneFn: doneFn,
- name: name
- });
- shiftQueue(type, sourceUpdater);
- };
-
- var onUpdateend = function onUpdateend(type, sourceUpdater) {
- return function (e) {
- // Although there should, in theory, be a pending action for any updateend receieved,
- // there are some actions that may trigger updateend events without set definitions in
- // the w3c spec. For instance, setting the duration on the media source may trigger
- // updateend events on source buffers. This does not appear to be in the spec. As such,
- // if we encounter an updateend without a corresponding pending action from our queue
- // for that source buffer type, process the next action.
- if (sourceUpdater.queuePending[type]) {
- var doneFn = sourceUpdater.queuePending[type].doneFn;
- sourceUpdater.queuePending[type] = null;
-
- if (doneFn) {
- // if there's an error, report it
- doneFn(sourceUpdater[type + "Error_"]);
- }
- }
-
- shiftQueue(type, sourceUpdater);
- };
- };
- /**
- * A queue of callbacks to be serialized and applied when a
- * MediaSource and its associated SourceBuffers are not in the
- * updating state. It is used by the segment loader to update the
- * underlying SourceBuffers when new data is loaded, for instance.
- *
- * @class SourceUpdater
- * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
- * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
- */
-
-
- var SourceUpdater = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(SourceUpdater, _videojs$EventTarget);
-
- function SourceUpdater(mediaSource) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- _this.mediaSource = mediaSource;
-
- _this.sourceopenListener_ = function () {
- return shiftQueue('mediaSource', assertThisInitialized(_this));
- };
-
- _this.mediaSource.addEventListener('sourceopen', _this.sourceopenListener_);
-
- _this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
-
- _this.audioTimestampOffset_ = 0;
- _this.videoTimestampOffset_ = 0;
- _this.queue = [];
- _this.queuePending = {
- audio: null,
- video: null
- };
- _this.delayedAudioAppendQueue_ = [];
- _this.videoAppendQueued_ = false;
- _this.codecs = {};
- _this.onVideoUpdateEnd_ = onUpdateend('video', assertThisInitialized(_this));
- _this.onAudioUpdateEnd_ = onUpdateend('audio', assertThisInitialized(_this));
-
- _this.onVideoError_ = function (e) {
- // used for debugging
- _this.videoError_ = e;
- };
-
- _this.onAudioError_ = function (e) {
- // used for debugging
- _this.audioError_ = e;
- };
-
- _this.createdSourceBuffers_ = false;
- _this.initializedEme_ = false;
- _this.triggeredReady_ = false;
- return _this;
- }
-
- var _proto = SourceUpdater.prototype;
-
- _proto.initializedEme = function initializedEme() {
- this.initializedEme_ = true;
- this.triggerReady();
- };
-
- _proto.hasCreatedSourceBuffers = function hasCreatedSourceBuffers() {
- // if false, likely waiting on one of the segment loaders to get enough data to create
- // source buffers
- return this.createdSourceBuffers_;
- };
-
- _proto.hasInitializedAnyEme = function hasInitializedAnyEme() {
- return this.initializedEme_;
- };
-
- _proto.ready = function ready() {
- return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
- };
-
- _proto.createSourceBuffers = function createSourceBuffers(codecs) {
- if (this.hasCreatedSourceBuffers()) {
- // already created them before
- return;
- } // the intial addOrChangeSourceBuffers will always be
- // two add buffers.
-
-
- this.addOrChangeSourceBuffers(codecs);
- this.createdSourceBuffers_ = true;
- this.trigger('createdsourcebuffers');
- this.triggerReady();
- };
-
- _proto.triggerReady = function triggerReady() {
- // only allow ready to be triggered once, this prevents the case
- // where:
- // 1. we trigger createdsourcebuffers
- // 2. ie 11 synchronously initializates eme
- // 3. the synchronous initialization causes us to trigger ready
- // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
- if (this.ready() && !this.triggeredReady_) {
- this.triggeredReady_ = true;
- this.trigger('ready');
- }
- }
- /**
- * Add a type of source buffer to the media source.
- *
- * @param {string} type
- * The type of source buffer to add.
- *
- * @param {string} codec
- * The codec to add the source buffer with.
- */
- ;
-
- _proto.addSourceBuffer = function addSourceBuffer(type, codec) {
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.addSourceBuffer(type, codec),
- name: 'addSourceBuffer'
- });
- }
- /**
- * call abort on a source buffer.
- *
- * @param {string} type
- * The type of source buffer to call abort on.
- */
- ;
-
- _proto.abort = function abort(type) {
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.abort(type),
- name: 'abort'
- });
- }
- /**
- * Call removeSourceBuffer and remove a specific type
- * of source buffer on the mediaSource.
- *
- * @param {string} type
- * The type of source buffer to remove.
- */
- ;
-
- _proto.removeSourceBuffer = function removeSourceBuffer(type) {
- if (!this.canRemoveSourceBuffer()) {
- videojs__default['default'].log.error('removeSourceBuffer is not supported!');
- return;
- }
-
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.removeSourceBuffer(type),
- name: 'removeSourceBuffer'
- });
- }
- /**
- * Whether or not the removeSourceBuffer function is supported
- * on the mediaSource.
- *
- * @return {boolean}
- * if removeSourceBuffer can be called.
- */
- ;
-
- _proto.canRemoveSourceBuffer = function canRemoveSourceBuffer() {
- // IE reports that it supports removeSourceBuffer, but often throws
- // errors when attempting to use the function. So we report that it
- // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
- // throws errors, so we report that it does not support this as well.
- return !videojs__default['default'].browser.IE_VERSION && !videojs__default['default'].browser.IS_FIREFOX && window__default['default'].MediaSource && window__default['default'].MediaSource.prototype && typeof window__default['default'].MediaSource.prototype.removeSourceBuffer === 'function';
- }
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- ;
-
- SourceUpdater.canChangeType = function canChangeType() {
- return window__default['default'].SourceBuffer && window__default['default'].SourceBuffer.prototype && typeof window__default['default'].SourceBuffer.prototype.changeType === 'function';
- }
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- ;
-
- _proto.canChangeType = function canChangeType() {
- return this.constructor.canChangeType();
- }
- /**
- * Call the changeType function on a source buffer, given the code and type.
- *
- * @param {string} type
- * The type of source buffer to call changeType on.
- *
- * @param {string} codec
- * The codec string to change type with on the source buffer.
- */
- ;
-
- _proto.changeType = function changeType(type, codec) {
- if (!this.canChangeType()) {
- videojs__default['default'].log.error('changeType is not supported!');
- return;
- }
-
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.changeType(codec),
- name: 'changeType'
- });
- }
- /**
- * Add source buffers with a codec or, if they are already created,
- * call changeType on source buffers using changeType.
- *
- * @param {Object} codecs
- * Codecs to switch to
- */
- ;
-
- _proto.addOrChangeSourceBuffers = function addOrChangeSourceBuffers(codecs) {
- var _this2 = this;
-
- if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
- throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
- }
-
- Object.keys(codecs).forEach(function (type) {
- var codec = codecs[type];
-
- if (!_this2.hasCreatedSourceBuffers()) {
- return _this2.addSourceBuffer(type, codec);
- }
-
- if (_this2.canChangeType()) {
- _this2.changeType(type, codec);
- }
- });
- }
- /**
- * Queue an update to append an ArrayBuffer.
- *
- * @param {MediaObject} object containing audioBytes and/or videoBytes
- * @param {Function} done the function to call when done
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
- */
- ;
-
- _proto.appendBuffer = function appendBuffer(options, doneFn) {
- var _this3 = this;
-
- var segmentInfo = options.segmentInfo,
- type = options.type,
- bytes = options.bytes;
- this.processedAppend_ = true;
-
- if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
- this.delayedAudioAppendQueue_.push([options, doneFn]);
- this.logger_("delayed audio append of " + bytes.length + " until video append");
- return;
- } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
- // not be fired. This means that the queue will be blocked until the next action
- // taken by the segment-loader. Provide a mechanism for segment-loader to handle
- // these errors by calling the doneFn with the specific error.
-
-
- var onError = doneFn;
- pushQueue({
- type: type,
- sourceUpdater: this,
- action: actions.appendBuffer(bytes, segmentInfo || {
- mediaIndex: -1
- }, onError),
- doneFn: doneFn,
- name: 'appendBuffer'
- });
-
- if (type === 'video') {
- this.videoAppendQueued_ = true;
-
- if (!this.delayedAudioAppendQueue_.length) {
- return;
- }
-
- var queue = this.delayedAudioAppendQueue_.slice();
- this.logger_("queuing delayed audio " + queue.length + " appendBuffers");
- this.delayedAudioAppendQueue_.length = 0;
- queue.forEach(function (que) {
- _this3.appendBuffer.apply(_this3, que);
- });
- }
- }
- /**
- * Get the audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The audio buffer's buffered time range
- */
- ;
-
- _proto.audioBuffered = function audioBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
- return videojs__default['default'].createTimeRange();
- }
-
- return this.audioBuffer.buffered ? this.audioBuffer.buffered : videojs__default['default'].createTimeRange();
- }
- /**
- * Get the video buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The video buffer's buffered time range
- */
- ;
-
- _proto.videoBuffered = function videoBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
- return videojs__default['default'].createTimeRange();
- }
-
- return this.videoBuffer.buffered ? this.videoBuffer.buffered : videojs__default['default'].createTimeRange();
- }
- /**
- * Get a combined video/audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * the combined time range
- */
- ;
-
- _proto.buffered = function buffered() {
- var video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
- var audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
-
- if (audio && !video) {
- return this.audioBuffered();
- }
-
- if (video && !audio) {
- return this.videoBuffered();
- }
-
- return bufferIntersection(this.audioBuffered(), this.videoBuffered());
- }
- /**
- * Add a callback to the queue that will set duration on the mediaSource.
- *
- * @param {number} duration
- * The duration to set
- *
- * @param {Function} [doneFn]
- * function to run after duration has been set.
- */
- ;
-
- _proto.setDuration = function setDuration(duration, doneFn) {
- if (doneFn === void 0) {
- doneFn = noop;
- }
-
- // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.duration(duration),
- name: 'duration',
- doneFn: doneFn
- });
- }
- /**
- * Add a mediaSource endOfStream call to the queue
- *
- * @param {Error} [error]
- * Call endOfStream with an error
- *
- * @param {Function} [doneFn]
- * A function that should be called when the
- * endOfStream call has finished.
- */
- ;
-
- _proto.endOfStream = function endOfStream(error, doneFn) {
- if (error === void 0) {
- error = null;
- }
-
- if (doneFn === void 0) {
- doneFn = noop;
- }
-
- if (typeof error !== 'string') {
- error = undefined;
- } // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
-
-
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.endOfStream(error),
- name: 'endOfStream',
- doneFn: doneFn
- });
- }
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- ;
-
- _proto.removeAudio = function removeAudio(start, end, done) {
- if (done === void 0) {
- done = noop;
- }
-
- if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- ;
-
- _proto.removeVideo = function removeVideo(start, end, done) {
- if (done === void 0) {
- done = noop;
- }
-
- if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
- /**
- * Whether the underlying sourceBuffer is updating or not
- *
- * @return {boolean} the updating status of the SourceBuffer
- */
- ;
-
- _proto.updating = function updating() {
- // the audio/video source buffer is updating
- if (_updating('audio', this) || _updating('video', this)) {
- return true;
- }
-
- return false;
- }
- /**
- * Set/get the timestampoffset on the audio SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- ;
-
- _proto.audioTimestampOffset = function audioTimestampOffset(offset) {
- if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
- this.audioTimestampOffset_ !== offset) {
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.audioTimestampOffset_ = offset;
- }
-
- return this.audioTimestampOffset_;
- }
- /**
- * Set/get the timestampoffset on the video SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- ;
-
- _proto.videoTimestampOffset = function videoTimestampOffset(offset) {
- if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
- this.videoTimestampOffset !== offset) {
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.videoTimestampOffset_ = offset;
- }
-
- return this.videoTimestampOffset_;
- }
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the audio queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- ;
-
- _proto.audioQueueCallback = function audioQueueCallback(callback) {
- if (!this.audioBuffer) {
- return;
- }
-
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the video queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- ;
-
- _proto.videoQueueCallback = function videoQueueCallback(callback) {
- if (!this.videoBuffer) {
- return;
- }
-
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
- /**
- * dispose of the source updater and the underlying sourceBuffer
- */
- ;
-
- _proto.dispose = function dispose() {
- var _this4 = this;
-
- this.trigger('dispose');
- bufferTypes.forEach(function (type) {
- _this4.abort(type);
-
- if (_this4.canRemoveSourceBuffer()) {
- _this4.removeSourceBuffer(type);
- } else {
- _this4[type + "QueueCallback"](function () {
- return cleanupBuffer(type, _this4);
- });
- }
- });
- this.videoAppendQueued_ = false;
- this.delayedAudioAppendQueue_.length = 0;
-
- if (this.sourceopenListener_) {
- this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
- }
-
- this.off();
- };
-
- return SourceUpdater;
- }(videojs__default['default'].EventTarget);
-
- var uint8ToUtf8 = function uint8ToUtf8(uintArray) {
- return decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
- };
-
- var VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(function (char) {
- return char.charCodeAt(0);
- }));
- /**
- * An object that manages segment loading and appending.
- *
- * @class VTTSegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-
- var VTTSegmentLoader = /*#__PURE__*/function (_SegmentLoader) {
- inheritsLoose(VTTSegmentLoader, _SegmentLoader);
-
- function VTTSegmentLoader(settings, options) {
- var _this;
-
- if (options === void 0) {
- options = {};
- }
-
- _this = _SegmentLoader.call(this, settings, options) || this; // SegmentLoader requires a MediaSource be specified or it will throw an error;
- // however, VTTSegmentLoader has no need of a media source, so delete the reference
-
- _this.mediaSource_ = null;
- _this.subtitlesTrack_ = null;
- _this.loaderType_ = 'subtitle';
- _this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
- // the sync controller leads to improper behavior.
-
- _this.shouldSaveSegmentTimingInfo_ = false;
- return _this;
- }
-
- var _proto = VTTSegmentLoader.prototype;
-
- _proto.createTransmuxer_ = function createTransmuxer_() {
- // don't need to transmux any subtitles
- return null;
- }
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- ;
-
- _proto.buffered_ = function buffered_() {
- if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
- return videojs__default['default'].createTimeRanges();
- }
-
- var cues = this.subtitlesTrack_.cues;
- var start = cues[0].startTime;
- var end = cues[cues.length - 1].startTime;
- return videojs__default['default'].createTimeRanges([[start, end]]);
- }
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- ;
-
- _proto.initSegmentForMap = function initSegmentForMap(map, set) {
- if (set === void 0) {
- set = false;
- }
-
- if (!map) {
- return null;
- }
-
- var id = initSegmentId(map);
- var storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- // append WebVTT line terminators to the media initialization segment if it exists
- // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
- // requires two or more WebVTT line terminators between the WebVTT header and the
- // rest of the file
- var combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
- var combinedSegment = new Uint8Array(combinedByteLength);
- combinedSegment.set(map.bytes);
- combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: combinedSegment
- };
- }
-
- return storedMap || map;
- }
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- ;
-
- _proto.couldBeginLoading_ = function couldBeginLoading_() {
- return this.playlist_ && this.subtitlesTrack_ && !this.paused();
- }
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- ;
-
- _proto.init_ = function init_() {
- this.state = 'READY';
- this.resetEverything();
- return this.monitorBuffer_();
- }
- /**
- * Set a subtitle track on the segment loader to add subtitles to
- *
- * @param {TextTrack=} track
- * The text track to add loaded subtitles to
- * @return {TextTrack}
- * Returns the subtitles track
- */
- ;
-
- _proto.track = function track(_track) {
- if (typeof _track === 'undefined') {
- return this.subtitlesTrack_;
- }
-
- this.subtitlesTrack_ = _track; // if we were unpaused but waiting for a sourceUpdater, start
- // buffering now
-
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- this.init_();
- }
-
- return this.subtitlesTrack_;
- }
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- */
- ;
-
- _proto.remove = function remove(start, end) {
- removeCuesFromTrack(start, end, this.subtitlesTrack_);
- }
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- ;
-
- _proto.fillBuffer_ = function fillBuffer_() {
- var _this2 = this;
-
- // see if we need to begin loading immediately
- var segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
- // We don't have the timestamp offset that we need to sync subtitles.
- // Rerun on a timestamp offset or user interaction.
- var checkTimestampOffset = function checkTimestampOffset() {
- _this2.state = 'READY';
-
- if (!_this2.paused()) {
- // if not paused, queue a buffer check as soon as possible
- _this2.monitorBuffer_();
- }
- };
-
- this.syncController_.one('timestampoffset', checkTimestampOffset);
- this.state = 'WAITING_ON_TIMELINE';
- return;
- }
-
- this.loadSegment_(segmentInfo);
- } // never set a timestamp offset for vtt segments.
- ;
-
- _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_() {
- return null;
- };
-
- _proto.chooseNextRequest_ = function chooseNextRequest_() {
- return this.skipEmptySegments_(_SegmentLoader.prototype.chooseNextRequest_.call(this));
- }
- /**
- * Prevents the segment loader from requesting segments we know contain no subtitles
- * by walking forward until we find the next segment that we don't know whether it is
- * empty or not.
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @return {Object}
- * a segment info object that describes the current segment
- */
- ;
-
- _proto.skipEmptySegments_ = function skipEmptySegments_(segmentInfo) {
- while (segmentInfo && segmentInfo.segment.empty) {
- // stop at the last possible segmentInfo
- if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
- segmentInfo = null;
- break;
- }
-
- segmentInfo = this.generateSegmentInfo_({
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex + 1,
- startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
- isSyncRequest: segmentInfo.isSyncRequest
- });
- }
-
- return segmentInfo;
- };
-
- _proto.stopForError = function stopForError(error) {
- this.error(error);
- this.state = 'READY';
- this.pause();
- this.trigger('error');
- }
- /**
- * append a decrypted segement to the SourceBuffer through a SourceUpdater
- *
- * @private
- */
- ;
-
- _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
- var _this3 = this;
-
- if (!this.subtitlesTrack_) {
- this.state = 'READY';
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats); // the request was aborted
-
- if (!this.pendingSegment_) {
- this.state = 'READY';
- this.mediaRequestsAborted += 1;
- return;
- }
-
- if (error) {
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- }
-
- if (error.code === REQUEST_ERRORS.ABORTED) {
- this.mediaRequestsAborted += 1;
- } else {
- this.mediaRequestsErrored += 1;
- }
-
- this.stopForError(error);
- return;
- }
-
- var segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functionality between segment loaders
-
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
- this.state = 'APPENDING'; // used for tests
-
- this.trigger('appending');
- var segment = segmentInfo.segment;
-
- if (segment.map) {
- segment.map.bytes = simpleSegment.map.bytes;
- }
-
- segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, wait till it finished loading
-
- if (typeof window__default['default'].WebVTT !== 'function' && this.subtitlesTrack_ && this.subtitlesTrack_.tech_) {
- var loadHandler;
-
- var errorHandler = function errorHandler() {
- _this3.subtitlesTrack_.tech_.off('vttjsloaded', loadHandler);
-
- _this3.stopForError({
- message: 'Error loading vtt.js'
- });
-
- return;
- };
-
- loadHandler = function loadHandler() {
- _this3.subtitlesTrack_.tech_.off('vttjserror', errorHandler);
-
- _this3.segmentRequestFinished_(error, simpleSegment, result);
- };
-
- this.state = 'WAITING_ON_VTTJS';
- this.subtitlesTrack_.tech_.one('vttjsloaded', loadHandler);
- this.subtitlesTrack_.tech_.one('vttjserror', errorHandler);
- return;
- }
-
- segment.requested = true;
-
- try {
- this.parseVTTCues_(segmentInfo);
- } catch (e) {
- this.stopForError({
- message: e.message
- });
- return;
- }
-
- this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
-
- if (segmentInfo.cues.length) {
- segmentInfo.timingInfo = {
- start: segmentInfo.cues[0].startTime,
- end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
- };
- } else {
- segmentInfo.timingInfo = {
- start: segmentInfo.startOfSegment,
- end: segmentInfo.startOfSegment + segmentInfo.duration
- };
- }
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate');
- this.pendingSegment_ = null;
- this.state = 'READY';
- return;
- }
-
- segmentInfo.byteLength = segmentInfo.bytes.byteLength;
- this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
- // the subtitle track
-
- segmentInfo.cues.forEach(function (cue) {
- _this3.subtitlesTrack_.addCue(_this3.featuresNativeTextTracks_ ? new window__default['default'].VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
- }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
- // cues to have identical time-intervals, but if the text is also identical
- // we can safely assume it is a duplicate that can be removed (ex. when a cue
- // "overlaps" VTT segments)
-
- removeDuplicateCuesFromTrack(this.subtitlesTrack_);
- this.handleAppendsDone_();
- };
-
- _proto.handleData_ = function handleData_() {// noop as we shouldn't be getting video/audio data captions
- // that we do not support here.
- };
-
- _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_() {// noop
- }
- /**
- * Uses the WebVTT parser to parse the segment response
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @private
- */
- ;
-
- _proto.parseVTTCues_ = function parseVTTCues_(segmentInfo) {
- var decoder;
- var decodeBytesToString = false;
-
- if (typeof window__default['default'].TextDecoder === 'function') {
- decoder = new window__default['default'].TextDecoder('utf8');
- } else {
- decoder = window__default['default'].WebVTT.StringDecoder();
- decodeBytesToString = true;
- }
-
- var parser = new window__default['default'].WebVTT.Parser(window__default['default'], window__default['default'].vttjs, decoder);
- segmentInfo.cues = [];
- segmentInfo.timestampmap = {
- MPEGTS: 0,
- LOCAL: 0
- };
- parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
-
- parser.ontimestampmap = function (map) {
- segmentInfo.timestampmap = map;
- };
-
- parser.onparsingerror = function (error) {
- videojs__default['default'].log.warn('Error encountered when parsing cues: ' + error.message);
- };
-
- if (segmentInfo.segment.map) {
- var mapData = segmentInfo.segment.map.bytes;
-
- if (decodeBytesToString) {
- mapData = uint8ToUtf8(mapData);
- }
-
- parser.parse(mapData);
- }
-
- var segmentData = segmentInfo.bytes;
-
- if (decodeBytesToString) {
- segmentData = uint8ToUtf8(segmentData);
- }
-
- parser.parse(segmentData);
- parser.flush();
- }
- /**
- * Updates the start and end times of any cues parsed by the WebVTT parser using
- * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
- * from the SyncController
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @param {Object} mappingObj
- * object containing a mapping from TS to media time
- * @param {Object} playlist
- * the playlist object containing the segment
- * @private
- */
- ;
-
- _proto.updateTimeMapping_ = function updateTimeMapping_(segmentInfo, mappingObj, playlist) {
- var segment = segmentInfo.segment;
-
- if (!mappingObj) {
- // If the sync controller does not have a mapping of TS to Media Time for the
- // timeline, then we don't have enough information to update the cue
- // start/end times
- return;
- }
-
- if (!segmentInfo.cues.length) {
- // If there are no cues, we also do not have enough information to figure out
- // segment timing. Mark that the segment contains no cues so we don't re-request
- // an empty segment.
- segment.empty = true;
- return;
- }
-
- var timestampmap = segmentInfo.timestampmap;
- var diff = timestampmap.MPEGTS / clock.ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
- segmentInfo.cues.forEach(function (cue) {
- // First convert cue time to TS time using the timestamp-map provided within the vtt
- cue.startTime += diff;
- cue.endTime += diff;
- });
-
- if (!playlist.syncInfo) {
- var firstStart = segmentInfo.cues[0].startTime;
- var lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
- playlist.syncInfo = {
- mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
- time: Math.min(firstStart, lastStart - segment.duration)
- };
- }
- };
-
- return VTTSegmentLoader;
- }(SegmentLoader);
-
- /**
- * @file ad-cue-tags.js
- */
- /**
- * Searches for an ad cue that overlaps with the given mediaTime
- *
- * @param {Object} track
- * the track to find the cue for
- *
- * @param {number} mediaTime
- * the time to find the cue at
- *
- * @return {Object|null}
- * the found cue or null
- */
-
- var findAdCue = function findAdCue(track, mediaTime) {
- var cues = track.cues;
-
- for (var i = 0; i < cues.length; i++) {
- var cue = cues[i];
-
- if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
- return cue;
- }
- }
-
- return null;
- };
- var updateAdCues = function updateAdCues(media, track, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- if (!media.segments) {
- return;
- }
-
- var mediaTime = offset;
- var cue;
-
- for (var i = 0; i < media.segments.length; i++) {
- var segment = media.segments[i];
-
- if (!cue) {
- // Since the cues will span for at least the segment duration, adding a fudge
- // factor of half segment duration will prevent duplicate cues from being
- // created when timing info is not exact (e.g. cue start time initialized
- // at 10.006677, but next call mediaTime is 10.003332 )
- cue = findAdCue(track, mediaTime + segment.duration / 2);
- }
-
- if (cue) {
- if ('cueIn' in segment) {
- // Found a CUE-IN so end the cue
- cue.endTime = mediaTime;
- cue.adEndTime = mediaTime;
- mediaTime += segment.duration;
- cue = null;
- continue;
- }
-
- if (mediaTime < cue.endTime) {
- // Already processed this mediaTime for this cue
- mediaTime += segment.duration;
- continue;
- } // otherwise extend cue until a CUE-IN is found
-
-
- cue.endTime += segment.duration;
- } else {
- if ('cueOut' in segment) {
- cue = new window__default['default'].VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
- cue.adStartTime = mediaTime; // Assumes tag format to be
- // #EXT-X-CUE-OUT:30
-
- cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
- track.addCue(cue);
- }
-
- if ('cueOutCont' in segment) {
- // Entered into the middle of an ad cue
- // Assumes tag formate to be
- // #EXT-X-CUE-OUT-CONT:10/30
- var _segment$cueOutCont$s = segment.cueOutCont.split('/').map(parseFloat),
- adOffset = _segment$cueOutCont$s[0],
- adTotal = _segment$cueOutCont$s[1];
-
- cue = new window__default['default'].VTTCue(mediaTime, mediaTime + segment.duration, '');
- cue.adStartTime = mediaTime - adOffset;
- cue.adEndTime = cue.adStartTime + adTotal;
- track.addCue(cue);
- }
- }
-
- mediaTime += segment.duration;
- }
- };
-
- var syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
- // the equivalence display-time 0 === segment-index 0
- {
- name: 'VOD',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (duration !== Infinity) {
- var syncPoint = {
- time: 0,
- segmentIndex: 0,
- partIndex: null
- };
- return syncPoint;
- }
-
- return null;
- }
- }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
- {
- name: 'ProgramDateTime',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
- return null;
- }
-
- var syncPoint = null;
- var lastDistance = null;
- var partsAndSegments = getPartsAndSegments(playlist);
- currentTime = currentTime || 0;
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
- var partAndSegment = partsAndSegments[index];
- var segment = partAndSegment.segment;
- var datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
-
- if (!datetimeMapping) {
- continue;
- }
-
- if (segment.dateTimeObject) {
- var segmentTime = segment.dateTimeObject.getTime() / 1000;
- var start = segmentTime + datetimeMapping; // take part duration into account.
-
- if (segment.parts && typeof partAndSegment.partIndex === 'number') {
- for (var z = 0; z < partAndSegment.partIndex; z++) {
- start += segment.parts[z].duration;
- }
- }
-
- var distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
- break;
- }
-
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
- }
-
- return syncPoint;
- }
- }, // Stategy "Segment": We have a known time mapping for a timeline and a
- // segment in the current timeline with timing data
- {
- name: 'Segment',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- var syncPoint = null;
- var lastDistance = null;
- currentTime = currentTime || 0;
- var partsAndSegments = getPartsAndSegments(playlist);
-
- for (var i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
- var partAndSegment = partsAndSegments[index];
- var segment = partAndSegment.segment;
- var start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
-
- if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
- var distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
- }
- }
-
- return syncPoint;
- }
- }, // Stategy "Discontinuity": We have a discontinuity with a known
- // display-time
- {
- name: 'Discontinuity',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- var syncPoint = null;
- currentTime = currentTime || 0;
-
- if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- var lastDistance = null;
-
- for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
- var segmentIndex = playlist.discontinuityStarts[i];
- var discontinuity = playlist.discontinuitySequence + i + 1;
- var discontinuitySync = syncController.discontinuities[discontinuity];
-
- if (discontinuitySync) {
- var distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
-
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: discontinuitySync.time,
- segmentIndex: segmentIndex,
- partIndex: null
- };
- }
- }
- }
- }
-
- return syncPoint;
- }
- }, // Stategy "Playlist": We have a playlist with a known mapping of
- // segment index to display time
- {
- name: 'Playlist',
- run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
- if (playlist.syncInfo) {
- var syncPoint = {
- time: playlist.syncInfo.time,
- segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
- partIndex: null
- };
- return syncPoint;
- }
-
- return null;
- }
- }];
-
- var SyncController = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(SyncController, _videojs$EventTarget);
-
- function SyncController(options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this; // ...for synching across variants
-
- _this.timelines = [];
- _this.discontinuities = [];
- _this.timelineToDatetimeMappings = {};
- _this.logger_ = logger('SyncController');
- return _this;
- }
- /**
- * Find a sync-point for the playlist specified
- *
- * A sync-point is defined as a known mapping from display-time to
- * a segment-index in the current playlist.
- *
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinite if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Object}
- * A sync-point object
- */
-
-
- var _proto = SyncController.prototype;
-
- _proto.getSyncPoint = function getSyncPoint(playlist, duration, currentTimeline, currentTime) {
- var syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
-
- if (!syncPoints.length) {
- // Signal that we need to attempt to get a sync-point manually
- // by fetching a segment in the playlist and constructing
- // a sync-point from that information
- return null;
- } // Now find the sync-point that is closest to the currentTime because
- // that should result in the most accurate guess about which segment
- // to fetch
-
-
- return this.selectSyncPoint_(syncPoints, {
- key: 'time',
- value: currentTime
- });
- }
- /**
- * Calculate the amount of time that has expired off the playlist during playback
- *
- * @param {Playlist} playlist
- * Playlist object to calculate expired from
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playling a live source)
- * @return {number|null}
- * The amount of time that has expired off the playlist during playback. Null
- * if no sync-points for the playlist can be found.
- */
- ;
-
- _proto.getExpiredTime = function getExpiredTime(playlist, duration) {
- if (!playlist || !playlist.segments) {
- return null;
- }
-
- var syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
-
- if (!syncPoints.length) {
- return null;
- }
-
- var syncPoint = this.selectSyncPoint_(syncPoints, {
- key: 'segmentIndex',
- value: 0
- }); // If the sync-point is beyond the start of the playlist, we want to subtract the
- // duration from index 0 to syncPoint.segmentIndex instead of adding.
-
- if (syncPoint.segmentIndex > 0) {
- syncPoint.time *= -1;
- }
-
- return Math.abs(syncPoint.time + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: syncPoint.segmentIndex,
- endIndex: 0
- }));
- }
- /**
- * Runs each sync-point strategy and returns a list of sync-points returned by the
- * strategies
- *
- * @private
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Array}
- * A list of sync-point objects
- */
- ;
-
- _proto.runStrategies_ = function runStrategies_(playlist, duration, currentTimeline, currentTime) {
- var syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
-
- for (var i = 0; i < syncPointStrategies.length; i++) {
- var strategy = syncPointStrategies[i];
- var syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
-
- if (syncPoint) {
- syncPoint.strategy = strategy.name;
- syncPoints.push({
- strategy: strategy.name,
- syncPoint: syncPoint
- });
- }
- }
-
- return syncPoints;
- }
- /**
- * Selects the sync-point nearest the specified target
- *
- * @private
- * @param {Array} syncPoints
- * List of sync-points to select from
- * @param {Object} target
- * Object specifying the property and value we are targeting
- * @param {string} target.key
- * Specifies the property to target. Must be either 'time' or 'segmentIndex'
- * @param {number} target.value
- * The value to target for the specified key.
- * @return {Object}
- * The sync-point nearest the target
- */
- ;
-
- _proto.selectSyncPoint_ = function selectSyncPoint_(syncPoints, target) {
- var bestSyncPoint = syncPoints[0].syncPoint;
- var bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
- var bestStrategy = syncPoints[0].strategy;
-
- for (var i = 1; i < syncPoints.length; i++) {
- var newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
-
- if (newDistance < bestDistance) {
- bestDistance = newDistance;
- bestSyncPoint = syncPoints[i].syncPoint;
- bestStrategy = syncPoints[i].strategy;
- }
- }
-
- this.logger_("syncPoint for [" + target.key + ": " + target.value + "] chosen with strategy" + (" [" + bestStrategy + "]: [time:" + bestSyncPoint.time + ",") + (" segmentIndex:" + bestSyncPoint.segmentIndex) + (typeof bestSyncPoint.partIndex === 'number' ? ",partIndex:" + bestSyncPoint.partIndex : '') + ']');
- return bestSyncPoint;
- }
- /**
- * Save any meta-data present on the segments when segments leave
- * the live window to the playlist to allow for synchronization at the
- * playlist level later.
- *
- * @param {Playlist} oldPlaylist - The previous active playlist
- * @param {Playlist} newPlaylist - The updated and most current playlist
- */
- ;
-
- _proto.saveExpiredSegmentInfo = function saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
- var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // When a segment expires from the playlist and it has a start time
- // save that information as a possible sync-point reference in future
-
- for (var i = mediaSequenceDiff - 1; i >= 0; i--) {
- var lastRemovedSegment = oldPlaylist.segments[i];
-
- if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
- newPlaylist.syncInfo = {
- mediaSequence: oldPlaylist.mediaSequence + i,
- time: lastRemovedSegment.start
- };
- this.logger_("playlist refresh sync: [time:" + newPlaylist.syncInfo.time + "," + (" mediaSequence: " + newPlaylist.syncInfo.mediaSequence + "]"));
- this.trigger('syncinfoupdate');
- break;
- }
- }
- }
- /**
- * Save the mapping from playlist's ProgramDateTime to display. This should only happen
- * before segments start to load.
- *
- * @param {Playlist} playlist - The currently active playlist
- */
- ;
-
- _proto.setDateTimeMappingForStart = function setDateTimeMappingForStart(playlist) {
- // It's possible for the playlist to be updated before playback starts, meaning time
- // zero is not yet set. If, during these playlist refreshes, a discontinuity is
- // crossed, then the old time zero mapping (for the prior timeline) would be retained
- // unless the mappings are cleared.
- this.timelineToDatetimeMappings = {};
-
- if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
- var firstSegment = playlist.segments[0];
- var playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
- this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
- }
- }
- /**
- * Calculates and saves timeline mappings, playlist sync info, and segment timing values
- * based on the latest timing information.
- *
- * @param {Object} options
- * Options object
- * @param {SegmentInfo} options.segmentInfo
- * The current active request information
- * @param {boolean} options.shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved for timeline mapping and program date time mappings.
- */
- ;
-
- _proto.saveSegmentTimingInfo = function saveSegmentTimingInfo(_ref) {
- var segmentInfo = _ref.segmentInfo,
- shouldSaveTimelineMapping = _ref.shouldSaveTimelineMapping;
- var didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
- var segment = segmentInfo.segment;
-
- if (didCalculateSegmentTimeMapping) {
- this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
- // now with segment timing information
-
- if (!segmentInfo.playlist.syncInfo) {
- segmentInfo.playlist.syncInfo = {
- mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
- time: segment.start
- };
- }
- }
-
- var dateTime = segment.dateTimeObject;
-
- if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
- this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
- }
- };
-
- _proto.timestampOffsetForTimeline = function timestampOffsetForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
-
- return this.timelines[timeline].time;
- };
-
- _proto.mappingForTimeline = function mappingForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
-
- return this.timelines[timeline].mapping;
- }
- /**
- * Use the "media time" for a segment to generate a mapping to "display time" and
- * save that display time to the segment.
- *
- * @private
- * @param {SegmentInfo} segmentInfo
- * The current active request information
- * @param {Object} timingInfo
- * The start and end time of the current segment in "media time"
- * @param {boolean} shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved in timelines.
- * @return {boolean}
- * Returns false if segment time mapping could not be calculated
- */
- ;
-
- _proto.calculateSegmentTimeMapping_ = function calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
- // TODO: remove side effects
- var segment = segmentInfo.segment;
- var part = segmentInfo.part;
- var mappingObj = this.timelines[segmentInfo.timeline];
- var start;
- var end;
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- mappingObj = {
- time: segmentInfo.startOfSegment,
- mapping: segmentInfo.startOfSegment - timingInfo.start
- };
-
- if (shouldSaveTimelineMapping) {
- this.timelines[segmentInfo.timeline] = mappingObj;
- this.trigger('timestampoffset');
- this.logger_("time mapping for timeline " + segmentInfo.timeline + ": " + ("[time: " + mappingObj.time + "] [mapping: " + mappingObj.mapping + "]"));
- }
-
- start = segmentInfo.startOfSegment;
- end = timingInfo.end + mappingObj.mapping;
- } else if (mappingObj) {
- start = timingInfo.start + mappingObj.mapping;
- end = timingInfo.end + mappingObj.mapping;
- } else {
- return false;
- }
-
- if (part) {
- part.start = start;
- part.end = end;
- } // If we don't have a segment start yet or the start value we got
- // is less than our current segment.start value, save a new start value.
- // We have to do this because parts will have segment timing info saved
- // multiple times and we want segment start to be the earliest part start
- // value for that segment.
-
-
- if (!segment.start || start < segment.start) {
- segment.start = start;
- }
-
- segment.end = end;
- return true;
- }
- /**
- * Each time we have discontinuity in the playlist, attempt to calculate the location
- * in display of the start of the discontinuity and save that. We also save an accuracy
- * value so that we save values with the most accuracy (closest to 0.)
- *
- * @private
- * @param {SegmentInfo} segmentInfo - The current active request information
- */
- ;
-
- _proto.saveDiscontinuitySyncInfo_ = function saveDiscontinuitySyncInfo_(segmentInfo) {
- var playlist = segmentInfo.playlist;
- var segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
- // the start of the range and it's accuracy is 0 (greater accuracy values
- // mean more approximation)
-
- if (segment.discontinuity) {
- this.discontinuities[segment.timeline] = {
- time: segment.start,
- accuracy: 0
- };
- } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- // Search for future discontinuities that we can provide better timing
- // information for and save that information for sync purposes
- for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
- var segmentIndex = playlist.discontinuityStarts[i];
- var discontinuity = playlist.discontinuitySequence + i + 1;
- var mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
- var accuracy = Math.abs(mediaIndexDiff);
-
- if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
- var time = void 0;
-
- if (mediaIndexDiff < 0) {
- time = segment.start - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex,
- endIndex: segmentIndex
- });
- } else {
- time = segment.end + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex + 1,
- endIndex: segmentIndex
- });
- }
-
- this.discontinuities[discontinuity] = {
- time: time,
- accuracy: accuracy
- };
- }
- }
- }
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.off();
- };
-
- return SyncController;
- }(videojs__default['default'].EventTarget);
-
- /**
- * The TimelineChangeController acts as a source for segment loaders to listen for and
- * keep track of latest and pending timeline changes. This is useful to ensure proper
- * sync, as each loader may need to make a consideration for what timeline the other
- * loader is on before making changes which could impact the other loader's media.
- *
- * @class TimelineChangeController
- * @extends videojs.EventTarget
- */
-
- var TimelineChangeController = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(TimelineChangeController, _videojs$EventTarget);
-
- function TimelineChangeController() {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- _this.pendingTimelineChanges_ = {};
- _this.lastTimelineChanges_ = {};
- return _this;
- }
-
- var _proto = TimelineChangeController.prototype;
-
- _proto.clearPendingTimelineChange = function clearPendingTimelineChange(type) {
- this.pendingTimelineChanges_[type] = null;
- this.trigger('pendingtimelinechange');
- };
-
- _proto.pendingTimelineChange = function pendingTimelineChange(_ref) {
- var type = _ref.type,
- from = _ref.from,
- to = _ref.to;
-
- if (typeof from === 'number' && typeof to === 'number') {
- this.pendingTimelineChanges_[type] = {
- type: type,
- from: from,
- to: to
- };
- this.trigger('pendingtimelinechange');
- }
-
- return this.pendingTimelineChanges_[type];
- };
-
- _proto.lastTimelineChange = function lastTimelineChange(_ref2) {
- var type = _ref2.type,
- from = _ref2.from,
- to = _ref2.to;
-
- if (typeof from === 'number' && typeof to === 'number') {
- this.lastTimelineChanges_[type] = {
- type: type,
- from: from,
- to: to
- };
- delete this.pendingTimelineChanges_[type];
- this.trigger('timelinechange');
- }
-
- return this.lastTimelineChanges_[type];
- };
-
- _proto.dispose = function dispose() {
- this.trigger('dispose');
- this.pendingTimelineChanges_ = {};
- this.lastTimelineChanges_ = {};
- this.off();
- };
-
- return TimelineChangeController;
- }(videojs__default['default'].EventTarget);
-
- /* rollup-plugin-worker-factory start for worker!/Users/gkatsevman/p/http-streaming-release/src/decrypter-worker.js */
- var workerCode = transform(getWorkerString(function () {
-
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function require(path, base) {
- return commonjsRequire(path, base === undefined || base === null ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
-
- function commonjsRequire() {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
-
- var createClass = createCommonjsModule(function (module) {
- 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);
- }
- }
-
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
-
- module.exports = _createClass;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- var setPrototypeOf = createCommonjsModule(function (module) {
- function _setPrototypeOf(o, p) {
- module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
-
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- return _setPrototypeOf(o, p);
- }
-
- module.exports = _setPrototypeOf;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- var inheritsLoose = createCommonjsModule(function (module) {
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- setPrototypeOf(subClass, superClass);
- }
-
- module.exports = _inheritsLoose;
- module.exports["default"] = module.exports, module.exports.__esModule = true;
- });
- /**
- * @file stream.js
- */
-
- /**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
-
- var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
- }();
- /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
-
- /**
- * Returns the subarray of a Uint8Array without PKCS#7 padding.
- *
- * @param padded {Uint8Array} unencrypted bytes that have been padded
- * @return {Uint8Array} the unpadded bytes
- * @see http://tools.ietf.org/html/rfc5652
- */
-
-
- function unpad(padded) {
- return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
- }
- /*! @name aes-decrypter @version 3.1.2 @license Apache-2.0 */
-
- /**
- * @file aes.js
- *
- * This file contains an adaptation of the AES decryption algorithm
- * from the Standford Javascript Cryptography Library. That work is
- * covered by the following copyright and permissions notice:
- *
- * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. 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 AUTHORS ``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 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.
- *
- * The views and conclusions contained in the software and documentation
- * are those of the authors and should not be interpreted as representing
- * official policies, either expressed or implied, of the authors.
- */
-
- /**
- * Expand the S-box tables.
- *
- * @private
- */
-
-
- var precompute = function precompute() {
- var tables = [[[], [], [], [], []], [[], [], [], [], []]];
- var encTable = tables[0];
- var decTable = tables[1];
- var sbox = encTable[4];
- var sboxInv = decTable[4];
- var i;
- var x;
- var xInv;
- var d = [];
- var th = [];
- var x2;
- var x4;
- var x8;
- var s;
- var tEnc;
- var tDec; // Compute double and third tables
-
- for (i = 0; i < 256; i++) {
- th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
- }
-
- for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
- // Compute sbox
- s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
- s = s >> 8 ^ s & 255 ^ 99;
- sbox[x] = s;
- sboxInv[s] = x; // Compute MixColumns
-
- x8 = d[x4 = d[x2 = d[x]]];
- tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- tEnc = d[s] * 0x101 ^ s * 0x1010100;
-
- for (i = 0; i < 4; i++) {
- encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
- decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
- }
- } // Compactify. Considerable speedup on Firefox.
-
-
- for (i = 0; i < 5; i++) {
- encTable[i] = encTable[i].slice(0);
- decTable[i] = decTable[i].slice(0);
- }
-
- return tables;
- };
-
- var aesTables = null;
- /**
- * Schedule out an AES key for both encryption and decryption. This
- * is a low-level class. Use a cipher mode to do bulk encryption.
- *
- * @class AES
- * @param key {Array} The key as an array of 4, 6 or 8 words.
- */
-
- var AES = /*#__PURE__*/function () {
- function AES(key) {
- /**
- * The expanded S-box and inverse S-box tables. These will be computed
- * on the client so that we don't have to send them down the wire.
- *
- * There are two tables, _tables[0] is for encryption and
- * _tables[1] is for decryption.
- *
- * The first 4 sub-tables are the expanded S-box with MixColumns. The
- * last (_tables[01][4]) is the S-box itself.
- *
- * @private
- */
- // if we have yet to precompute the S-box tables
- // do so now
- if (!aesTables) {
- aesTables = precompute();
- } // then make a copy of that object for use
-
-
- this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
- var i;
- var j;
- var tmp;
- var sbox = this._tables[0][4];
- var decTable = this._tables[1];
- var keyLen = key.length;
- var rcon = 1;
-
- if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
- throw new Error('Invalid aes key size');
- }
-
- var encKey = key.slice(0);
- var decKey = [];
- this._key = [encKey, decKey]; // schedule encryption keys
-
- for (i = keyLen; i < 4 * keyLen + 28; i++) {
- tmp = encKey[i - 1]; // apply sbox
-
- if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
- tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
-
- if (i % keyLen === 0) {
- tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
- rcon = rcon << 1 ^ (rcon >> 7) * 283;
- }
- }
-
- encKey[i] = encKey[i - keyLen] ^ tmp;
- } // schedule decryption keys
-
-
- for (j = 0; i; j++, i--) {
- tmp = encKey[j & 3 ? i : i - 4];
-
- if (i <= 4 || j < 4) {
- decKey[j] = tmp;
- } else {
- decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
- }
- }
- }
- /**
- * Decrypt 16 bytes, specified as four 32-bit words.
- *
- * @param {number} encrypted0 the first word to decrypt
- * @param {number} encrypted1 the second word to decrypt
- * @param {number} encrypted2 the third word to decrypt
- * @param {number} encrypted3 the fourth word to decrypt
- * @param {Int32Array} out the array to write the decrypted words
- * into
- * @param {number} offset the offset into the output array to start
- * writing results
- * @return {Array} The plaintext.
- */
-
-
- var _proto = AES.prototype;
-
- _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
- var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
-
- var a = encrypted0 ^ key[0];
- var b = encrypted3 ^ key[1];
- var c = encrypted2 ^ key[2];
- var d = encrypted1 ^ key[3];
- var a2;
- var b2;
- var c2; // key.length === 2 ?
-
- var nInnerRounds = key.length / 4 - 2;
- var i;
- var kIndex = 4;
- var table = this._tables[1]; // load up the tables
-
- var table0 = table[0];
- var table1 = table[1];
- var table2 = table[2];
- var table3 = table[3];
- var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
-
- for (i = 0; i < nInnerRounds; i++) {
- a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
- b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
- c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
- d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
- kIndex += 4;
- a = a2;
- b = b2;
- c = c2;
- } // Last round.
-
-
- for (i = 0; i < 4; i++) {
- out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
- a2 = a;
- a = b;
- b = c;
- c = d;
- d = a2;
- }
- };
-
- return AES;
- }();
- /**
- * A wrapper around the Stream class to use setTimeout
- * and run stream "jobs" Asynchronously
- *
- * @class AsyncStream
- * @extends Stream
- */
-
-
- var AsyncStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(AsyncStream, _Stream);
-
- function AsyncStream() {
- var _this;
-
- _this = _Stream.call(this, Stream) || this;
- _this.jobs = [];
- _this.delay = 1;
- _this.timeout_ = null;
- return _this;
- }
- /**
- * process an async job
- *
- * @private
- */
-
-
- var _proto = AsyncStream.prototype;
-
- _proto.processJob_ = function processJob_() {
- this.jobs.shift()();
-
- if (this.jobs.length) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- } else {
- this.timeout_ = null;
- }
- }
- /**
- * push a job into the stream
- *
- * @param {Function} job the job to push into the stream
- */
- ;
-
- _proto.push = function push(job) {
- this.jobs.push(job);
-
- if (!this.timeout_) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- }
- };
-
- return AsyncStream;
- }(Stream);
- /**
- * Convert network-order (big-endian) bytes into their little-endian
- * representation.
- */
-
-
- var ntoh = function ntoh(word) {
- return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
- };
- /**
- * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * use for the first round of CBC.
- * @return {Uint8Array} the decrypted bytes
- *
- * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
- * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
- * @see https://tools.ietf.org/html/rfc2315
- */
-
-
- var decrypt = function decrypt(encrypted, key, initVector) {
- // word-level access to the encrypted bytes
- var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
- var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
-
- var decrypted = new Uint8Array(encrypted.byteLength);
- var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
- // decrypted data
-
- var init0;
- var init1;
- var init2;
- var init3;
- var encrypted0;
- var encrypted1;
- var encrypted2;
- var encrypted3; // iteration variable
-
- var wordIx; // pull out the words of the IV to ensure we don't modify the
- // passed-in reference and easier access
-
- init0 = initVector[0];
- init1 = initVector[1];
- init2 = initVector[2];
- init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
- // to each decrypted block
-
- for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
- // convert big-endian (network order) words into little-endian
- // (javascript order)
- encrypted0 = ntoh(encrypted32[wordIx]);
- encrypted1 = ntoh(encrypted32[wordIx + 1]);
- encrypted2 = ntoh(encrypted32[wordIx + 2]);
- encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
-
- decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
- // plaintext
-
- decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
- decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
- decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
- decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
-
- init0 = encrypted0;
- init1 = encrypted1;
- init2 = encrypted2;
- init3 = encrypted3;
- }
-
- return decrypted;
- };
- /**
- * The `Decrypter` class that manages decryption of AES
- * data through `AsyncStream` objects and the `decrypt`
- * function
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * @param {Function} done the function to run when done
- * @class Decrypter
- */
-
-
- var Decrypter = /*#__PURE__*/function () {
- function Decrypter(encrypted, key, initVector, done) {
- var step = Decrypter.STEP;
- var encrypted32 = new Int32Array(encrypted.buffer);
- var decrypted = new Uint8Array(encrypted.byteLength);
- var i = 0;
- this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
-
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
-
- for (i = step; i < encrypted32.length; i += step) {
- initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
- } // invoke the done() callback when everything is finished
-
-
- this.asyncStream_.push(function () {
- // remove pkcs#7 padding from the decrypted bytes
- done(null, unpad(decrypted));
- });
- }
- /**
- * a getter for step the maximum number of bytes to process at one time
- *
- * @return {number} the value of step 32000
- */
-
-
- var _proto = Decrypter.prototype;
- /**
- * @private
- */
-
- _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
- return function () {
- var bytes = decrypt(encrypted, key, initVector);
- decrypted.set(bytes, encrypted.byteOffset);
- };
- };
-
- createClass(Decrypter, null, [{
- key: "STEP",
- get: function get() {
- // 4 * 8000;
- return 32000;
- }
- }]);
- return Decrypter;
- }();
- /**
- * @file bin-utils.js
- */
-
- /**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-
-
- var createTransferableMessage = function createTransferableMessage(message) {
- var transferable = {};
- Object.keys(message).forEach(function (key) {
- var value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
- return transferable;
- };
- /* global self */
-
- /**
- * Our web worker interface so that things can talk to aes-decrypter
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- */
-
-
- self.onmessage = function (event) {
- var data = event.data;
- var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
- var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
- var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
- /* eslint-disable no-new, handle-callback-err */
-
- new Decrypter(encrypted, key, iv, function (err, bytes) {
- self.postMessage(createTransferableMessage({
- source: data.source,
- decrypted: bytes
- }), [bytes.buffer]);
- });
- /* eslint-enable */
- };
- }));
- var Decrypter = factory(workerCode);
- /* rollup-plugin-worker-factory end for worker!/Users/gkatsevman/p/http-streaming-release/src/decrypter-worker.js */
-
- /**
- * Convert the properties of an HLS track into an audioTrackKind.
- *
- * @private
- */
-
- var audioTrackKind_ = function audioTrackKind_(properties) {
- var kind = properties.default ? 'main' : 'alternative';
-
- if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
- kind = 'main-desc';
- }
-
- return kind;
- };
- /**
- * Pause provided segment loader and playlist loader if active
- *
- * @param {SegmentLoader} segmentLoader
- * SegmentLoader to pause
- * @param {Object} mediaType
- * Active media type
- * @function stopLoaders
- */
-
-
- var stopLoaders = function stopLoaders(segmentLoader, mediaType) {
- segmentLoader.abort();
- segmentLoader.pause();
-
- if (mediaType && mediaType.activePlaylistLoader) {
- mediaType.activePlaylistLoader.pause();
- mediaType.activePlaylistLoader = null;
- }
- };
- /**
- * Start loading provided segment loader and playlist loader
- *
- * @param {PlaylistLoader} playlistLoader
- * PlaylistLoader to start loading
- * @param {Object} mediaType
- * Active media type
- * @function startLoaders
- */
-
- var startLoaders = function startLoaders(playlistLoader, mediaType) {
- // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
- // playlist loader
- mediaType.activePlaylistLoader = playlistLoader;
- playlistLoader.load();
- };
- /**
- * Returns a function to be called when the media group changes. It performs a
- * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
- * change of group is merely a rendition switch of the same content at another encoding,
- * rather than a change of content, such as switching audio from English to Spanish.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a non-destructive resync of SegmentLoader when the active media
- * group changes.
- * @function onGroupChanged
- */
-
- var onGroupChanged = function onGroupChanged(type, settings) {
- return function () {
- var _settings$segmentLoad = settings.segmentLoaders,
- segmentLoader = _settings$segmentLoad[type],
- mainSegmentLoader = _settings$segmentLoad.main,
- mediaType = settings.mediaTypes[type];
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.getActiveGroup();
- var previousActiveLoader = mediaType.activePlaylistLoader;
- var lastGroup = mediaType.lastGroup_; // the group did not change do nothing
-
- if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup || activeGroup.isMasterPlaylist) {
- // there is no group active or active group is a main playlist and won't change
- return;
- }
-
- if (!activeGroup.playlistLoader) {
- if (previousActiveLoader) {
- // The previous group had a playlist loader but the new active group does not
- // this means we are switching from demuxed to muxed audio. In this case we want to
- // do a destructive reset of the main segment loader and not restart the audio
- // loaders.
- mainSegmentLoader.resetEverything();
- }
-
- return;
- } // Non-destructive resync
-
-
- segmentLoader.resyncLoader();
- startLoaders(activeGroup.playlistLoader, mediaType);
- };
- };
- var onGroupChanging = function onGroupChanging(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- mediaType.lastGroup_ = null;
- segmentLoader.abort();
- segmentLoader.pause();
- };
- };
- /**
- * Returns a function to be called when the media track changes. It performs a
- * destructive reset of the SegmentLoader to ensure we start loading as close to
- * currentTime as possible.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a destructive reset of SegmentLoader when the active media
- * track changes.
- * @function onTrackChanged
- */
-
- var onTrackChanged = function onTrackChanged(type, settings) {
- return function () {
- var masterPlaylistLoader = settings.masterPlaylistLoader,
- _settings$segmentLoad2 = settings.segmentLoaders,
- segmentLoader = _settings$segmentLoad2[type],
- mainSegmentLoader = _settings$segmentLoad2.main,
- mediaType = settings.mediaTypes[type];
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.getActiveGroup();
- var previousActiveLoader = mediaType.activePlaylistLoader;
- var lastTrack = mediaType.lastTrack_; // track did not change, do nothing
-
- if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup) {
- // there is no group active so we do not want to restart loaders
- return;
- }
-
- if (activeGroup.isMasterPlaylist) {
- // track did not change, do nothing
- if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
- return;
- }
-
- var mpc = settings.vhs.masterPlaylistController_;
- var newPlaylist = mpc.selectPlaylist(); // media will not change do nothing
-
- if (mpc.media() === newPlaylist) {
- return;
- }
-
- mediaType.logger_("track change. Switching master audio from " + lastTrack.id + " to " + activeTrack.id);
- masterPlaylistLoader.pause();
- mainSegmentLoader.resetEverything();
- mpc.fastQualityChange_(newPlaylist);
- return;
- }
-
- if (type === 'AUDIO') {
- if (!activeGroup.playlistLoader) {
- // when switching from demuxed audio/video to muxed audio/video (noted by no
- // playlist loader for the audio group), we want to do a destructive reset of the
- // main segment loader and not restart the audio loaders
- mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
- // it should be stopped
-
- mainSegmentLoader.resetEverything();
- return;
- } // although the segment loader is an audio segment loader, call the setAudio
- // function to ensure it is prepared to re-append the init segment (or handle other
- // config changes)
-
-
- segmentLoader.setAudio(true);
- mainSegmentLoader.setAudio(false);
- }
-
- if (previousActiveLoader === activeGroup.playlistLoader) {
- // Nothing has actually changed. This can happen because track change events can fire
- // multiple times for a "single" change. One for enabling the new active track, and
- // one for disabling the track that was active
- startLoaders(activeGroup.playlistLoader, mediaType);
- return;
- }
-
- if (segmentLoader.track) {
- // For WebVTT, set the new text track in the segmentloader
- segmentLoader.track(activeTrack);
- } // destructive reset
-
-
- segmentLoader.resetEverything();
- startLoaders(activeGroup.playlistLoader, mediaType);
- };
- };
- var onError = {
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning (or error if the playlist is blacklisted) to
- * console and switches back to default audio track.
- * @function onError.AUDIO
- */
- AUDIO: function AUDIO(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type],
- blacklistCurrentPlaylist = settings.blacklistCurrentPlaylist;
- stopLoaders(segmentLoader, mediaType); // switch back to default audio track
-
- var activeTrack = mediaType.activeTrack();
- var activeGroup = mediaType.activeGroup();
- var id = (activeGroup.filter(function (group) {
- return group.default;
- })[0] || activeGroup[0]).id;
- var defaultTrack = mediaType.tracks[id];
-
- if (activeTrack === defaultTrack) {
- // Default track encountered an error. All we can do now is blacklist the current
- // rendition and hope another will switch audio groups
- blacklistCurrentPlaylist({
- message: 'Problem encountered loading the default audio track.'
- });
- return;
- }
-
- videojs__default['default'].log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
-
- for (var trackId in mediaType.tracks) {
- mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
- }
-
- mediaType.onTrackChanged();
- };
- },
-
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning to console and disables the active subtitle track
- * @function onError.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, settings) {
- return function () {
- var segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- videojs__default['default'].log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
- stopLoaders(segmentLoader, mediaType);
- var track = mediaType.activeTrack();
-
- if (track) {
- track.mode = 'disabled';
- }
-
- mediaType.onTrackChanged();
- };
- }
- };
- var setupListeners = {
- /**
- * Setup event listeners for audio playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.AUDIO
- */
- AUDIO: function AUDIO(type, playlistLoader, settings) {
- if (!playlistLoader) {
- // no playlist loader means audio will be muxed with the video
- return;
- }
-
- var tech = settings.tech,
- requestOptions = settings.requestOptions,
- segmentLoader = settings.segmentLoaders[type];
- playlistLoader.on('loadedmetadata', function () {
- var media = playlistLoader.media();
- segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
-
- if (!tech.paused() || media.endList && tech.preload() !== 'none') {
- segmentLoader.load();
- }
- });
- playlistLoader.on('loadedplaylist', function () {
- segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
-
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
- playlistLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup event listeners for subtitle playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, playlistLoader, settings) {
- var tech = settings.tech,
- requestOptions = settings.requestOptions,
- segmentLoader = settings.segmentLoaders[type],
- mediaType = settings.mediaTypes[type];
- playlistLoader.on('loadedmetadata', function () {
- var media = playlistLoader.media();
- segmentLoader.playlist(media, requestOptions);
- segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
-
- if (!tech.paused() || media.endList && tech.preload() !== 'none') {
- segmentLoader.load();
- }
- });
- playlistLoader.on('loadedplaylist', function () {
- segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
-
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
- playlistLoader.on('error', onError[type](type, settings));
- }
- };
- var initialize = {
- /**
- * Setup PlaylistLoaders and AudioTracks for the audio groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.AUDIO
- */
- 'AUDIO': function AUDIO(type, settings) {
- var vhs = settings.vhs,
- sourceType = settings.sourceType,
- segmentLoader = settings.segmentLoaders[type],
- requestOptions = settings.requestOptions,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$ = settings.mediaTypes[type],
- groups = _settings$mediaTypes$.groups,
- tracks = _settings$mediaTypes$.tracks,
- logger_ = _settings$mediaTypes$.logger_,
- masterPlaylistLoader = settings.masterPlaylistLoader;
- var audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master); // force a default if we have none
-
- if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
- mediaGroups[type] = {
- main: {
- default: {
- default: true
- }
- }
- };
- }
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- var properties = mediaGroups[type][groupId][variantLabel];
- var playlistLoader = void 0;
-
- if (audioOnlyMaster) {
- logger_("AUDIO group '" + groupId + "' label '" + variantLabel + "' is a master playlist");
- properties.isMasterPlaylist = true;
- playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
- // use the resolved media playlist object
- } else if (sourceType === 'vhs-json' && properties.playlists) {
- playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
- } else if (properties.resolvedUri) {
- playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
- // should we even have properties.playlists in this check.
- } else if (properties.playlists && sourceType === 'dash') {
- playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
- } else {
- // no resolvedUri means the audio is muxed with the video when using this
- // audio track
- playlistLoader = null;
- }
-
- properties = videojs__default['default'].mergeOptions({
- id: variantLabel,
- playlistLoader: playlistLoader
- }, properties);
- setupListeners[type](type, properties.playlistLoader, settings);
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = new videojs__default['default'].AudioTrack({
- id: variantLabel,
- kind: audioTrackKind_(properties),
- enabled: false,
- language: properties.language,
- default: properties.default,
- label: variantLabel
- });
- tracks[variantLabel] = track;
- }
- }
- } // setup single error event handler for the segment loader
-
-
- segmentLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup PlaylistLoaders and TextTracks for the subtitle groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.SUBTITLES
- */
- 'SUBTITLES': function SUBTITLES(type, settings) {
- var tech = settings.tech,
- vhs = settings.vhs,
- sourceType = settings.sourceType,
- segmentLoader = settings.segmentLoaders[type],
- requestOptions = settings.requestOptions,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$2 = settings.mediaTypes[type],
- groups = _settings$mediaTypes$2.groups,
- tracks = _settings$mediaTypes$2.tracks,
- masterPlaylistLoader = settings.masterPlaylistLoader;
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- if (mediaGroups[type][groupId][variantLabel].forced) {
- // Subtitle playlists with the forced attribute are not selectable in Safari.
- // According to Apple's HLS Authoring Specification:
- // If content has forced subtitles and regular subtitles in a given language,
- // the regular subtitles track in that language MUST contain both the forced
- // subtitles and the regular subtitles for that language.
- // Because of this requirement and that Safari does not add forced subtitles,
- // forced subtitles are skipped here to maintain consistent experience across
- // all platforms
- continue;
- }
-
- var properties = mediaGroups[type][groupId][variantLabel];
- var playlistLoader = void 0;
-
- if (sourceType === 'hls') {
- playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
- } else if (sourceType === 'dash') {
- var playlists = properties.playlists.filter(function (p) {
- return p.excludeUntil !== Infinity;
- });
-
- if (!playlists.length) {
- return;
- }
-
- playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
- } else if (sourceType === 'vhs-json') {
- playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
- // as provided, otherwise use the resolved URI to load the playlist
- properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
- }
-
- properties = videojs__default['default'].mergeOptions({
- id: variantLabel,
- playlistLoader: playlistLoader
- }, properties);
- setupListeners[type](type, properties.playlistLoader, settings);
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = tech.addRemoteTextTrack({
- id: variantLabel,
- kind: 'subtitles',
- default: properties.default && properties.autoselect,
- language: properties.language,
- label: variantLabel
- }, false).track;
- tracks[variantLabel] = track;
- }
- }
- } // setup single error event handler for the segment loader
-
-
- segmentLoader.on('error', onError[type](type, settings));
- },
-
- /**
- * Setup TextTracks for the closed-caption groups
- *
- * @param {String} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize['CLOSED-CAPTIONS']
- */
- 'CLOSED-CAPTIONS': function CLOSEDCAPTIONS(type, settings) {
- var tech = settings.tech,
- mediaGroups = settings.master.mediaGroups,
- _settings$mediaTypes$3 = settings.mediaTypes[type],
- groups = _settings$mediaTypes$3.groups,
- tracks = _settings$mediaTypes$3.tracks;
-
- for (var groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (var variantLabel in mediaGroups[type][groupId]) {
- var properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
-
- if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
- continue;
- }
-
- var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
- var newProps = {
- label: variantLabel,
- language: properties.language,
- instreamId: properties.instreamId,
- default: properties.default && properties.autoselect
- };
-
- if (captionServices[newProps.instreamId]) {
- newProps = videojs__default['default'].mergeOptions(newProps, captionServices[newProps.instreamId]);
- }
-
- if (newProps.default === undefined) {
- delete newProps.default;
- } // No PlaylistLoader is required for Closed-Captions because the captions are
- // embedded within the video stream
-
-
- groups[groupId].push(videojs__default['default'].mergeOptions({
- id: variantLabel
- }, properties));
-
- if (typeof tracks[variantLabel] === 'undefined') {
- var track = tech.addRemoteTextTrack({
- id: newProps.instreamId,
- kind: 'captions',
- default: newProps.default,
- language: newProps.language,
- label: newProps.label
- }, false).track;
- tracks[variantLabel] = track;
- }
- }
- }
- }
- };
-
- var groupMatch = function groupMatch(list, media) {
- for (var i = 0; i < list.length; i++) {
- if (playlistMatch(media, list[i])) {
- return true;
- }
-
- if (list[i].playlists && groupMatch(list[i].playlists, media)) {
- return true;
- }
- }
-
- return false;
- };
- /**
- * Returns a function used to get the active group of the provided type
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media group for the provided type. Takes an
- * optional parameter {TextTrack} track. If no track is provided, a list of all
- * variants in the group, otherwise the variant corresponding to the provided
- * track is returned.
- * @function activeGroup
- */
-
-
- var activeGroup = function activeGroup(type, settings) {
- return function (track) {
- var masterPlaylistLoader = settings.masterPlaylistLoader,
- groups = settings.mediaTypes[type].groups;
- var media = masterPlaylistLoader.media();
-
- if (!media) {
- return null;
- }
-
- var variants = null; // set to variants to main media active group
-
- if (media.attributes[type]) {
- variants = groups[media.attributes[type]];
- }
-
- var groupKeys = Object.keys(groups);
-
- if (!variants) {
- // find the masterPlaylistLoader media
- // that is in a media group if we are dealing
- // with audio only
- if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.master)) {
- for (var i = 0; i < groupKeys.length; i++) {
- var groupPropertyList = groups[groupKeys[i]];
-
- if (groupMatch(groupPropertyList, media)) {
- variants = groupPropertyList;
- break;
- }
- } // use the main group if it exists
-
- } else if (groups.main) {
- variants = groups.main; // only one group, use that one
- } else if (groupKeys.length === 1) {
- variants = groups[groupKeys[0]];
- }
- }
-
- if (typeof track === 'undefined') {
- return variants;
- }
-
- if (track === null || !variants) {
- // An active track was specified so a corresponding group is expected. track === null
- // means no track is currently active so there is no corresponding group
- return null;
- }
-
- return variants.filter(function (props) {
- return props.id === track.id;
- })[0] || null;
- };
- };
- var activeTrack = {
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.AUDIO
- */
- AUDIO: function AUDIO(type, settings) {
- return function () {
- var tracks = settings.mediaTypes[type].tracks;
-
- for (var id in tracks) {
- if (tracks[id].enabled) {
- return tracks[id];
- }
- }
-
- return null;
- };
- },
-
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.SUBTITLES
- */
- SUBTITLES: function SUBTITLES(type, settings) {
- return function () {
- var tracks = settings.mediaTypes[type].tracks;
-
- for (var id in tracks) {
- if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
- return tracks[id];
- }
- }
-
- return null;
- };
- }
- };
- var getActiveGroup = function getActiveGroup(type, _ref) {
- var mediaTypes = _ref.mediaTypes;
- return function () {
- var activeTrack_ = mediaTypes[type].activeTrack();
-
- if (!activeTrack_) {
- return null;
- }
-
- return mediaTypes[type].activeGroup(activeTrack_);
- };
- };
- /**
- * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
- * Closed-Captions) specified in the master manifest.
- *
- * @param {Object} settings
- * Object containing required information for setting up the media groups
- * @param {Tech} settings.tech
- * The tech of the player
- * @param {Object} settings.requestOptions
- * XHR request options used by the segment loaders
- * @param {PlaylistLoader} settings.masterPlaylistLoader
- * PlaylistLoader for the master source
- * @param {VhsHandler} settings.vhs
- * VHS SourceHandler
- * @param {Object} settings.master
- * The parsed master manifest
- * @param {Object} settings.mediaTypes
- * Object to store the loaders, tracks, and utility methods for each media type
- * @param {Function} settings.blacklistCurrentPlaylist
- * Blacklists the current rendition and forces a rendition switch.
- * @function setupMediaGroups
- */
-
- var setupMediaGroups = function setupMediaGroups(settings) {
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
- initialize[type](type, settings);
- });
- var mediaTypes = settings.mediaTypes,
- masterPlaylistLoader = settings.masterPlaylistLoader,
- tech = settings.tech,
- vhs = settings.vhs,
- _settings$segmentLoad3 = settings.segmentLoaders,
- audioSegmentLoader = _settings$segmentLoad3['AUDIO'],
- mainSegmentLoader = _settings$segmentLoad3.main; // setup active group and track getters and change event handlers
-
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- mediaTypes[type].activeGroup = activeGroup(type, settings);
- mediaTypes[type].activeTrack = activeTrack[type](type, settings);
- mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
- mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
- mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
- mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
- }); // DO NOT enable the default subtitle or caption track.
- // DO enable the default audio track
-
- var audioGroup = mediaTypes.AUDIO.activeGroup();
-
- if (audioGroup) {
- var groupId = (audioGroup.filter(function (group) {
- return group.default;
- })[0] || audioGroup[0]).id;
- mediaTypes.AUDIO.tracks[groupId].enabled = true;
- mediaTypes.AUDIO.onGroupChanged();
- mediaTypes.AUDIO.onTrackChanged();
- var activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
- // track is changed, but needs to be handled here since the track may not be considered
- // changed on the first call to onTrackChanged
-
- if (!activeAudioGroup.playlistLoader) {
- // either audio is muxed with video or the stream is audio only
- mainSegmentLoader.setAudio(true);
- } else {
- // audio is demuxed
- mainSegmentLoader.setAudio(false);
- audioSegmentLoader.setAudio(true);
- }
- }
-
- masterPlaylistLoader.on('mediachange', function () {
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- return mediaTypes[type].onGroupChanged();
- });
- });
- masterPlaylistLoader.on('mediachanging', function () {
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- return mediaTypes[type].onGroupChanging();
- });
- }); // custom audio track change event handler for usage event
-
- var onAudioTrackChanged = function onAudioTrackChanged() {
- mediaTypes.AUDIO.onTrackChanged();
- tech.trigger({
- type: 'usage',
- name: 'vhs-audio-change'
- });
- tech.trigger({
- type: 'usage',
- name: 'hls-audio-change'
- });
- };
-
- tech.audioTracks().addEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
- vhs.on('dispose', function () {
- tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
- }); // clear existing audio tracks and add the ones we just created
-
- tech.clearTracks('audio');
-
- for (var id in mediaTypes.AUDIO.tracks) {
- tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
- }
- };
- /**
- * Creates skeleton object used to store the loaders, tracks, and utility methods for each
- * media type
- *
- * @return {Object}
- * Object to store the loaders, tracks, and utility methods for each media type
- * @function createMediaTypes
- */
-
- var createMediaTypes = function createMediaTypes() {
- var mediaTypes = {};
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
- mediaTypes[type] = {
- groups: {},
- tracks: {},
- activePlaylistLoader: null,
- activeGroup: noop,
- activeTrack: noop,
- getActiveGroup: noop,
- onGroupChanged: noop,
- onTrackChanged: noop,
- lastTrack_: null,
- logger_: logger("MediaGroups[" + type + "]")
- };
- });
- return mediaTypes;
- };
-
- var ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
- var Vhs$1; // SegmentLoader stats that need to have each loader's
- // values summed to calculate the final value
-
- var loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
-
- var sumLoaderStat = function sumLoaderStat(stat) {
- return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
- };
-
- var shouldSwitchToMedia = function shouldSwitchToMedia(_ref) {
- var currentPlaylist = _ref.currentPlaylist,
- nextPlaylist = _ref.nextPlaylist,
- forwardBuffer = _ref.forwardBuffer,
- bufferLowWaterLine = _ref.bufferLowWaterLine,
- bufferHighWaterLine = _ref.bufferHighWaterLine,
- duration = _ref.duration,
- experimentalBufferBasedABR = _ref.experimentalBufferBasedABR,
- log = _ref.log;
-
- // we have no other playlist to switch to
- if (!nextPlaylist) {
- videojs__default['default'].log.warn('We received no playlist to switch to. Please check your stream.');
- return false;
- }
-
- var sharedLogLine = "allowing switch " + (currentPlaylist && currentPlaylist.id || 'null') + " -> " + nextPlaylist.id; // If the playlist is live, then we want to not take low water line into account.
- // This is because in LIVE, the player plays 3 segments from the end of the
- // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
- // in those segments, a viewer will never experience a rendition upswitch.
-
- if (!currentPlaylist || !currentPlaylist.endList) {
- log(sharedLogLine + " as current playlist " + (!currentPlaylist ? 'is not set' : 'is live'));
- return true;
- } // no need to switch playlist is the same
-
-
- if (nextPlaylist.id === currentPlaylist.id) {
- return false;
- }
-
- var maxBufferLowWaterLine = experimentalBufferBasedABR ? Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE; // For the same reason as LIVE, we ignore the low water line when the VOD
- // duration is below the max potential low water line
-
- if (duration < maxBufferLowWaterLine) {
- log(sharedLogLine + " as duration < max low water line (" + duration + " < " + maxBufferLowWaterLine + ")");
- return true;
- }
-
- var nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
- var currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
- // we can switch down
-
- if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
- var logLine = sharedLogLine + " as next bandwidth < current bandwidth (" + nextBandwidth + " < " + currBandwidth + ")";
-
- if (experimentalBufferBasedABR) {
- logLine += " and forwardBuffer < bufferHighWaterLine (" + forwardBuffer + " < " + bufferHighWaterLine + ")";
- }
-
- log(logLine);
- return true;
- } // and if our buffer is higher than the low water line,
- // we can switch up
-
-
- if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
- var _logLine = sharedLogLine + " as forwardBuffer >= bufferLowWaterLine (" + forwardBuffer + " >= " + bufferLowWaterLine + ")";
-
- if (experimentalBufferBasedABR) {
- _logLine += " and next bandwidth > current bandwidth (" + nextBandwidth + " > " + currBandwidth + ")";
- }
-
- log(_logLine);
- return true;
- }
-
- log("not " + sharedLogLine + " as no switching criteria met");
- return false;
- };
- /**
- * the master playlist controller controller all interactons
- * between playlists and segmentloaders. At this time this mainly
- * involves a master playlist and a series of audio playlists
- * if they are available
- *
- * @class MasterPlaylistController
- * @extends videojs.EventTarget
- */
-
-
- var MasterPlaylistController = /*#__PURE__*/function (_videojs$EventTarget) {
- inheritsLoose(MasterPlaylistController, _videojs$EventTarget);
-
- function MasterPlaylistController(options) {
- var _this;
-
- _this = _videojs$EventTarget.call(this) || this;
- var src = options.src,
- handleManifestRedirects = options.handleManifestRedirects,
- withCredentials = options.withCredentials,
- tech = options.tech,
- bandwidth = options.bandwidth,
- externVhs = options.externVhs,
- useCueTags = options.useCueTags,
- blacklistDuration = options.blacklistDuration,
- enableLowInitialPlaylist = options.enableLowInitialPlaylist,
- sourceType = options.sourceType,
- cacheEncryptionKeys = options.cacheEncryptionKeys,
- experimentalBufferBasedABR = options.experimentalBufferBasedABR;
-
- if (!src) {
- throw new Error('A non-empty playlist URL or JSON manifest string is required');
- }
-
- var maxPlaylistRetries = options.maxPlaylistRetries;
-
- if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
- maxPlaylistRetries = Infinity;
- }
-
- Vhs$1 = externVhs;
- _this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
- _this.withCredentials = withCredentials;
- _this.tech_ = tech;
- _this.vhs_ = tech.vhs;
- _this.sourceType_ = sourceType;
- _this.useCueTags_ = useCueTags;
- _this.blacklistDuration = blacklistDuration;
- _this.maxPlaylistRetries = maxPlaylistRetries;
- _this.enableLowInitialPlaylist = enableLowInitialPlaylist;
-
- if (_this.useCueTags_) {
- _this.cueTagsTrack_ = _this.tech_.addTextTrack('metadata', 'ad-cues');
- _this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
- }
-
- _this.requestOptions_ = {
- withCredentials: withCredentials,
- handleManifestRedirects: handleManifestRedirects,
- maxPlaylistRetries: maxPlaylistRetries,
- timeout: null
- };
-
- _this.on('error', _this.pauseLoading);
-
- _this.mediaTypes_ = createMediaTypes();
- _this.mediaSource = new window__default['default'].MediaSource();
- _this.handleDurationChange_ = _this.handleDurationChange_.bind(assertThisInitialized(_this));
- _this.handleSourceOpen_ = _this.handleSourceOpen_.bind(assertThisInitialized(_this));
- _this.handleSourceEnded_ = _this.handleSourceEnded_.bind(assertThisInitialized(_this));
-
- _this.mediaSource.addEventListener('durationchange', _this.handleDurationChange_); // load the media source into the player
-
-
- _this.mediaSource.addEventListener('sourceopen', _this.handleSourceOpen_);
-
- _this.mediaSource.addEventListener('sourceended', _this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
- // everything, and the MediaSource should not be detached without a proper disposal
-
-
- _this.seekable_ = videojs__default['default'].createTimeRanges();
- _this.hasPlayed_ = false;
- _this.syncController_ = new SyncController(options);
- _this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'segment-metadata'
- }, false).track;
- _this.decrypter_ = new Decrypter();
- _this.sourceUpdater_ = new SourceUpdater(_this.mediaSource);
- _this.inbandTextTracks_ = {};
- _this.timelineChangeController_ = new TimelineChangeController();
- var segmentLoaderSettings = {
- vhs: _this.vhs_,
- parse708captions: options.parse708captions,
- mediaSource: _this.mediaSource,
- currentTime: _this.tech_.currentTime.bind(_this.tech_),
- seekable: function seekable() {
- return _this.seekable();
- },
- seeking: function seeking() {
- return _this.tech_.seeking();
- },
- duration: function duration() {
- return _this.duration();
- },
- hasPlayed: function hasPlayed() {
- return _this.hasPlayed_;
- },
- goalBufferLength: function goalBufferLength() {
- return _this.goalBufferLength();
- },
- bandwidth: bandwidth,
- syncController: _this.syncController_,
- decrypter: _this.decrypter_,
- sourceType: _this.sourceType_,
- inbandTextTracks: _this.inbandTextTracks_,
- cacheEncryptionKeys: cacheEncryptionKeys,
- sourceUpdater: _this.sourceUpdater_,
- timelineChangeController: _this.timelineChangeController_
- }; // The source type check not only determines whether a special DASH playlist loader
- // should be used, but also covers the case where the provided src is a vhs-json
- // manifest object (instead of a URL). In the case of vhs-json, the default
- // PlaylistLoader should be used.
-
- _this.masterPlaylistLoader_ = _this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, _this.vhs_, _this.requestOptions_) : new PlaylistLoader(src, _this.vhs_, _this.requestOptions_);
-
- _this.setupMasterPlaylistLoaderListeners_(); // setup segment loaders
- // combined audio/video or just video when alternate audio track is selected
-
-
- _this.mainSegmentLoader_ = new SegmentLoader(videojs__default['default'].mergeOptions(segmentLoaderSettings, {
- segmentMetadataTrack: _this.segmentMetadataTrack_,
- loaderType: 'main'
- }), options); // alternate audio track
-
- _this.audioSegmentLoader_ = new SegmentLoader(videojs__default['default'].mergeOptions(segmentLoaderSettings, {
- loaderType: 'audio'
- }), options);
- _this.subtitleSegmentLoader_ = new VTTSegmentLoader(videojs__default['default'].mergeOptions(segmentLoaderSettings, {
- loaderType: 'vtt',
- featuresNativeTextTracks: _this.tech_.featuresNativeTextTracks
- }), options);
-
- _this.setupSegmentLoaderListeners_();
-
- if (_this.experimentalBufferBasedABR) {
- _this.masterPlaylistLoader_.one('loadedplaylist', function () {
- return _this.startABRTimer_();
- });
-
- _this.tech_.on('pause', function () {
- return _this.stopABRTimer_();
- });
-
- _this.tech_.on('play', function () {
- return _this.startABRTimer_();
- });
- } // Create SegmentLoader stat-getters
- // mediaRequests_
- // mediaRequestsAborted_
- // mediaRequestsTimedout_
- // mediaRequestsErrored_
- // mediaTransferDuration_
- // mediaBytesTransferred_
- // mediaAppends_
-
-
- loaderStats.forEach(function (stat) {
- _this[stat + '_'] = sumLoaderStat.bind(assertThisInitialized(_this), stat);
- });
- _this.logger_ = logger('MPC');
- _this.triggeredFmp4Usage = false;
-
- if (_this.tech_.preload() === 'none') {
- _this.loadOnPlay_ = function () {
- _this.loadOnPlay_ = null;
-
- _this.masterPlaylistLoader_.load();
- };
-
- _this.tech_.one('play', _this.loadOnPlay_);
- } else {
- _this.masterPlaylistLoader_.load();
- }
-
- _this.timeToLoadedData__ = -1;
- _this.mainAppendsToLoadedData__ = -1;
- _this.audioAppendsToLoadedData__ = -1;
- var event = _this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
-
- _this.tech_.one(event, function () {
- var timeToLoadedDataStart = Date.now();
-
- _this.tech_.one('loadeddata', function () {
- _this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
- _this.mainAppendsToLoadedData__ = _this.mainSegmentLoader_.mediaAppends;
- _this.audioAppendsToLoadedData__ = _this.audioSegmentLoader_.mediaAppends;
- });
- });
-
- return _this;
- }
-
- var _proto = MasterPlaylistController.prototype;
-
- _proto.mainAppendsToLoadedData_ = function mainAppendsToLoadedData_() {
- return this.mainAppendsToLoadedData__;
- };
-
- _proto.audioAppendsToLoadedData_ = function audioAppendsToLoadedData_() {
- return this.audioAppendsToLoadedData__;
- };
-
- _proto.appendsToLoadedData_ = function appendsToLoadedData_() {
- var main = this.mainAppendsToLoadedData_();
- var audio = this.audioAppendsToLoadedData_();
-
- if (main === -1 || audio === -1) {
- return -1;
- }
-
- return main + audio;
- };
-
- _proto.timeToLoadedData_ = function timeToLoadedData_() {
- return this.timeToLoadedData__;
- }
- /**
- * Run selectPlaylist and switch to the new playlist if we should
- *
- * @private
- *
- */
- ;
-
- _proto.checkABR_ = function checkABR_() {
- var nextPlaylist = this.selectPlaylist();
-
- if (this.shouldSwitchToMedia_(nextPlaylist)) {
- this.switchMedia_(nextPlaylist, 'abr');
- }
- };
-
- _proto.switchMedia_ = function switchMedia_(playlist, cause, delay) {
- var oldMedia = this.media();
- var oldId = oldMedia && (oldMedia.id || oldMedia.uri);
- var newId = playlist.id || playlist.uri;
-
- if (oldId && oldId !== newId) {
- this.logger_("switch media " + oldId + " -> " + newId + " from " + cause);
- this.tech_.trigger({
- type: 'usage',
- name: "vhs-rendition-change-" + cause
- });
- }
-
- this.masterPlaylistLoader_.media(playlist, delay);
- }
- /**
- * Start a timer that periodically calls checkABR_
- *
- * @private
- */
- ;
-
- _proto.startABRTimer_ = function startABRTimer_() {
- var _this2 = this;
-
- this.stopABRTimer_();
- this.abrTimer_ = window__default['default'].setInterval(function () {
- return _this2.checkABR_();
- }, 250);
- }
- /**
- * Stop the timer that periodically calls checkABR_
- *
- * @private
- */
- ;
-
- _proto.stopABRTimer_ = function stopABRTimer_() {
- // if we're scrubbing, we don't need to pause.
- // This getter will be added to Video.js in version 7.11.
- if (this.tech_.scrubbing && this.tech_.scrubbing()) {
- return;
- }
-
- window__default['default'].clearInterval(this.abrTimer_);
- this.abrTimer_ = null;
- }
- /**
- * Get a list of playlists for the currently selected audio playlist
- *
- * @return {Array} the array of audio playlists
- */
- ;
-
- _proto.getAudioTrackPlaylists_ = function getAudioTrackPlaylists_() {
- var master = this.master(); // if we don't have any audio groups then we can only
- // assume that the audio tracks are contained in masters
- // playlist array, use that or an empty array.
-
- if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
- return master && master.playlists || [];
- }
-
- var AUDIO = master.mediaGroups.AUDIO;
- var groupKeys = Object.keys(AUDIO);
- var track; // get the current active track
-
- if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
- track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from master if mediaTypes_ isn't setup yet
- } else {
- // default group is `main` or just the first group.
- var defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
-
- for (var label in defaultGroup) {
- if (defaultGroup[label].default) {
- track = {
- label: label
- };
- break;
- }
- }
- } // no active track no playlists.
-
-
- if (!track) {
- return [];
- }
-
- var playlists = []; // get all of the playlists that are possible for the
- // active track.
-
- for (var group in AUDIO) {
- if (AUDIO[group][track.label]) {
- var properties = AUDIO[group][track.label];
-
- if (properties.playlists) {
- playlists.push.apply(playlists, properties.playlists);
- } else {
- playlists.push(properties);
- }
- }
- }
-
- return playlists;
- }
- /**
- * Register event handlers on the master playlist loader. A helper
- * function for construction time.
- *
- * @private
- */
- ;
-
- _proto.setupMasterPlaylistLoaderListeners_ = function setupMasterPlaylistLoaderListeners_() {
- var _this3 = this;
-
- this.masterPlaylistLoader_.on('loadedmetadata', function () {
- var media = _this3.masterPlaylistLoader_.media();
-
- var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
- // timeout the request.
-
- if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
- _this3.requestOptions_.timeout = 0;
- } else {
- _this3.requestOptions_.timeout = requestTimeout;
- } // if this isn't a live video and preload permits, start
- // downloading segments
-
-
- if (media.endList && _this3.tech_.preload() !== 'none') {
- _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
-
- _this3.mainSegmentLoader_.load();
- }
-
- setupMediaGroups({
- sourceType: _this3.sourceType_,
- segmentLoaders: {
- AUDIO: _this3.audioSegmentLoader_,
- SUBTITLES: _this3.subtitleSegmentLoader_,
- main: _this3.mainSegmentLoader_
- },
- tech: _this3.tech_,
- requestOptions: _this3.requestOptions_,
- masterPlaylistLoader: _this3.masterPlaylistLoader_,
- vhs: _this3.vhs_,
- master: _this3.master(),
- mediaTypes: _this3.mediaTypes_,
- blacklistCurrentPlaylist: _this3.blacklistCurrentPlaylist.bind(_this3)
- });
-
- _this3.triggerPresenceUsage_(_this3.master(), media);
-
- _this3.setupFirstPlay();
-
- if (!_this3.mediaTypes_.AUDIO.activePlaylistLoader || _this3.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
- _this3.trigger('selectedinitialmedia');
- } else {
- // We must wait for the active audio playlist loader to
- // finish setting up before triggering this event so the
- // representations API and EME setup is correct
- _this3.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', function () {
- _this3.trigger('selectedinitialmedia');
- });
- }
- });
- this.masterPlaylistLoader_.on('loadedplaylist', function () {
- if (_this3.loadOnPlay_) {
- _this3.tech_.off('play', _this3.loadOnPlay_);
- }
-
- var updatedPlaylist = _this3.masterPlaylistLoader_.media();
-
- if (!updatedPlaylist) {
- // exclude any variants that are not supported by the browser before selecting
- // an initial media as the playlist selectors do not consider browser support
- _this3.excludeUnsupportedVariants_();
-
- var selectedMedia;
-
- if (_this3.enableLowInitialPlaylist) {
- selectedMedia = _this3.selectInitialPlaylist();
- }
-
- if (!selectedMedia) {
- selectedMedia = _this3.selectPlaylist();
- }
-
- if (!selectedMedia || !_this3.shouldSwitchToMedia_(selectedMedia)) {
- return;
- }
-
- _this3.initialMedia_ = selectedMedia;
-
- _this3.switchMedia_(_this3.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
- // fire again since the playlist will be requested. In the case of vhs-json
- // (where the manifest object is provided as the source), when the media
- // playlist's `segments` list is already available, a media playlist won't be
- // requested, and loadedplaylist won't fire again, so the playlist handler must be
- // called on its own here.
-
-
- var haveJsonSource = _this3.sourceType_ === 'vhs-json' && _this3.initialMedia_.segments;
-
- if (!haveJsonSource) {
- return;
- }
-
- updatedPlaylist = _this3.initialMedia_;
- }
-
- _this3.handleUpdatedMediaPlaylist(updatedPlaylist);
- });
- this.masterPlaylistLoader_.on('error', function () {
- _this3.blacklistCurrentPlaylist(_this3.masterPlaylistLoader_.error);
- });
- this.masterPlaylistLoader_.on('mediachanging', function () {
- _this3.mainSegmentLoader_.abort();
-
- _this3.mainSegmentLoader_.pause();
- });
- this.masterPlaylistLoader_.on('mediachange', function () {
- var media = _this3.masterPlaylistLoader_.media();
-
- var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
- // timeout the request.
-
- if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
- _this3.requestOptions_.timeout = 0;
- } else {
- _this3.requestOptions_.timeout = requestTimeout;
- } // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `loadedplaylist`
-
-
- _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
-
- _this3.mainSegmentLoader_.load();
-
- _this3.tech_.trigger({
- type: 'mediachange',
- bubbles: true
- });
- });
- this.masterPlaylistLoader_.on('playlistunchanged', function () {
- var updatedPlaylist = _this3.masterPlaylistLoader_.media(); // ignore unchanged playlists that have already been
- // excluded for not-changing. We likely just have a really slowly updating
- // playlist.
-
-
- if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
- return;
- }
-
- var playlistOutdated = _this3.stuckAtPlaylistEnd_(updatedPlaylist);
-
- if (playlistOutdated) {
- // Playlist has stopped updating and we're stuck at its end. Try to
- // blacklist it and switch to another playlist in the hope that that
- // one is updating (and give the player a chance to re-adjust to the
- // safe live point).
- _this3.blacklistCurrentPlaylist({
- message: 'Playlist no longer updating.',
- reason: 'playlist-unchanged'
- }); // useful for monitoring QoS
-
-
- _this3.tech_.trigger('playliststuck');
- }
- });
- this.masterPlaylistLoader_.on('renditiondisabled', function () {
- _this3.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-disabled'
- });
-
- _this3.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-disabled'
- });
- });
- this.masterPlaylistLoader_.on('renditionenabled', function () {
- _this3.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-enabled'
- });
-
- _this3.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-enabled'
- });
- });
- }
- /**
- * Given an updated media playlist (whether it was loaded for the first time, or
- * refreshed for live playlists), update any relevant properties and state to reflect
- * changes in the media that should be accounted for (e.g., cues and duration).
- *
- * @param {Object} updatedPlaylist the updated media playlist object
- *
- * @private
- */
- ;
-
- _proto.handleUpdatedMediaPlaylist = function handleUpdatedMediaPlaylist(updatedPlaylist) {
- if (this.useCueTags_) {
- this.updateAdCues_(updatedPlaylist);
- } // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `mediachange`
-
-
- this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
- this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
- // as it is possible that it was temporarily stopped while waiting for
- // a playlist (e.g., in case the playlist errored and we re-requested it).
-
- if (!this.tech_.paused()) {
- this.mainSegmentLoader_.load();
-
- if (this.audioSegmentLoader_) {
- this.audioSegmentLoader_.load();
- }
- }
- }
- /**
- * A helper function for triggerring presence usage events once per source
- *
- * @private
- */
- ;
-
- _proto.triggerPresenceUsage_ = function triggerPresenceUsage_(master, media) {
- var mediaGroups = master.mediaGroups || {};
- var defaultDemuxed = true;
- var audioGroupKeys = Object.keys(mediaGroups.AUDIO);
-
- for (var mediaGroup in mediaGroups.AUDIO) {
- for (var label in mediaGroups.AUDIO[mediaGroup]) {
- var properties = mediaGroups.AUDIO[mediaGroup][label];
-
- if (!properties.uri) {
- defaultDemuxed = false;
- }
- }
- }
-
- if (defaultDemuxed) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-demuxed'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-demuxed'
- });
- }
-
- if (Object.keys(mediaGroups.SUBTITLES).length) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-webvtt'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-webvtt'
- });
- }
-
- if (Vhs$1.Playlist.isAes(media)) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-aes'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-aes'
- });
- }
-
- if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-alternate-audio'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-alternate-audio'
- });
- }
-
- if (this.useCueTags_) {
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-playlist-cue-tags'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-playlist-cue-tags'
- });
- }
- };
-
- _proto.shouldSwitchToMedia_ = function shouldSwitchToMedia_(nextPlaylist) {
- var currentPlaylist = this.masterPlaylistLoader_.media();
- var buffered = this.tech_.buffered();
- var forwardBuffer = buffered.length ? buffered.end(buffered.length - 1) - this.tech_.currentTime() : 0;
- var bufferLowWaterLine = this.bufferLowWaterLine();
- var bufferHighWaterLine = this.bufferHighWaterLine();
- return shouldSwitchToMedia({
- currentPlaylist: currentPlaylist,
- nextPlaylist: nextPlaylist,
- forwardBuffer: forwardBuffer,
- bufferLowWaterLine: bufferLowWaterLine,
- bufferHighWaterLine: bufferHighWaterLine,
- duration: this.duration(),
- experimentalBufferBasedABR: this.experimentalBufferBasedABR,
- log: this.logger_
- });
- }
- /**
- * Register event handlers on the segment loaders. A helper function
- * for construction time.
- *
- * @private
- */
- ;
-
- _proto.setupSegmentLoaderListeners_ = function setupSegmentLoaderListeners_() {
- var _this4 = this;
-
- if (!this.experimentalBufferBasedABR) {
- this.mainSegmentLoader_.on('bandwidthupdate', function () {
- var nextPlaylist = _this4.selectPlaylist();
-
- if (_this4.shouldSwitchToMedia_(nextPlaylist)) {
- _this4.switchMedia_(nextPlaylist, 'bandwidthupdate');
- }
-
- _this4.tech_.trigger('bandwidthupdate');
- });
- this.mainSegmentLoader_.on('progress', function () {
- _this4.trigger('progress');
- });
- }
-
- this.mainSegmentLoader_.on('error', function () {
- _this4.blacklistCurrentPlaylist(_this4.mainSegmentLoader_.error());
- });
- this.mainSegmentLoader_.on('appenderror', function () {
- _this4.error = _this4.mainSegmentLoader_.error_;
-
- _this4.trigger('error');
- });
- this.mainSegmentLoader_.on('syncinfoupdate', function () {
- _this4.onSyncInfoUpdate_();
- });
- this.mainSegmentLoader_.on('timestampoffset', function () {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-timestamp-offset'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-timestamp-offset'
- });
- });
- this.audioSegmentLoader_.on('syncinfoupdate', function () {
- _this4.onSyncInfoUpdate_();
- });
- this.audioSegmentLoader_.on('appenderror', function () {
- _this4.error = _this4.audioSegmentLoader_.error_;
-
- _this4.trigger('error');
- });
- this.mainSegmentLoader_.on('ended', function () {
- _this4.logger_('main segment loader ended');
-
- _this4.onEndOfStream();
- });
- this.mainSegmentLoader_.on('earlyabort', function (event) {
- // never try to early abort with the new ABR algorithm
- if (_this4.experimentalBufferBasedABR) {
- return;
- }
-
- _this4.delegateLoaders_('all', ['abort']);
-
- _this4.blacklistCurrentPlaylist({
- message: 'Aborted early because there isn\'t enough bandwidth to complete the ' + 'request without rebuffering.'
- }, ABORT_EARLY_BLACKLIST_SECONDS);
- });
-
- var updateCodecs = function updateCodecs() {
- if (!_this4.sourceUpdater_.hasCreatedSourceBuffers()) {
- return _this4.tryToCreateSourceBuffers_();
- }
-
- var codecs = _this4.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
-
-
- if (!codecs) {
- return;
- }
-
- _this4.sourceUpdater_.addOrChangeSourceBuffers(codecs);
- };
-
- this.mainSegmentLoader_.on('trackinfo', updateCodecs);
- this.audioSegmentLoader_.on('trackinfo', updateCodecs);
- this.mainSegmentLoader_.on('fmp4', function () {
- if (!_this4.triggeredFmp4Usage) {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-fmp4'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-fmp4'
- });
-
- _this4.triggeredFmp4Usage = true;
- }
- });
- this.audioSegmentLoader_.on('fmp4', function () {
- if (!_this4.triggeredFmp4Usage) {
- _this4.tech_.trigger({
- type: 'usage',
- name: 'vhs-fmp4'
- });
-
- _this4.tech_.trigger({
- type: 'usage',
- name: 'hls-fmp4'
- });
-
- _this4.triggeredFmp4Usage = true;
- }
- });
- this.audioSegmentLoader_.on('ended', function () {
- _this4.logger_('audioSegmentLoader ended');
-
- _this4.onEndOfStream();
- });
- };
-
- _proto.mediaSecondsLoaded_ = function mediaSecondsLoaded_() {
- return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
- }
- /**
- * Call load on our SegmentLoaders
- */
- ;
-
- _proto.load = function load() {
- this.mainSegmentLoader_.load();
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.load();
- }
-
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.load();
- }
- }
- /**
- * Re-tune playback quality level for the current player
- * conditions without performing destructive actions, like
- * removing already buffered content
- *
- * @private
- * @deprecated
- */
- ;
-
- _proto.smoothQualityChange_ = function smoothQualityChange_(media) {
- if (media === void 0) {
- media = this.selectPlaylist();
- }
-
- this.fastQualityChange_(media);
- }
- /**
- * Re-tune playback quality level for the current player
- * conditions. This method will perform destructive actions like removing
- * already buffered content in order to readjust the currently active
- * playlist quickly. This is good for manual quality changes
- *
- * @private
- */
- ;
-
- _proto.fastQualityChange_ = function fastQualityChange_(media) {
- var _this5 = this;
-
- if (media === void 0) {
- media = this.selectPlaylist();
- }
-
- if (media === this.masterPlaylistLoader_.media()) {
- this.logger_('skipping fastQualityChange because new media is same as old');
- return;
- }
-
- this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
- // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
- // ahead is roughly the minimum that will accomplish this across a variety of content
- // in IE and Edge, but seeking in place is sufficient on all other browsers)
- // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
- // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
-
- this.mainSegmentLoader_.resetEverything(function () {
- // Since this is not a typical seek, we avoid the seekTo method which can cause segments
- // from the previously enabled rendition to load before the new playlist has finished loading
- if (videojs__default['default'].browser.IE_VERSION || videojs__default['default'].browser.IS_EDGE) {
- _this5.tech_.setCurrentTime(_this5.tech_.currentTime() + 0.04);
- } else {
- _this5.tech_.setCurrentTime(_this5.tech_.currentTime());
- }
- }); // don't need to reset audio as it is reset when media changes
- }
- /**
- * Begin playback.
- */
- ;
-
- _proto.play = function play() {
- if (this.setupFirstPlay()) {
- return;
- }
-
- if (this.tech_.ended()) {
- this.tech_.setCurrentTime(0);
- }
-
- if (this.hasPlayed_) {
- this.load();
- }
-
- var seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
- // seek forward to the live point
-
- if (this.tech_.duration() === Infinity) {
- if (this.tech_.currentTime() < seekable.start(0)) {
- return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
- }
- }
- }
- /**
- * Seek to the latest media position if this is a live video and the
- * player and video are loaded and initialized.
- */
- ;
-
- _proto.setupFirstPlay = function setupFirstPlay() {
- var _this6 = this;
-
- var media = this.masterPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
- // If 1) there is no active media
- // 2) the player is paused
- // 3) the first play has already been setup
- // then exit early
-
- if (!media || this.tech_.paused() || this.hasPlayed_) {
- return false;
- } // when the video is a live stream
-
-
- if (!media.endList) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- // without a seekable range, the player cannot seek to begin buffering at the live
- // point
- return false;
- }
-
- if (videojs__default['default'].browser.IE_VERSION && this.tech_.readyState() === 0) {
- // IE11 throws an InvalidStateError if you try to set currentTime while the
- // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
- this.tech_.one('loadedmetadata', function () {
- _this6.trigger('firstplay');
-
- _this6.tech_.setCurrentTime(seekable.end(0));
-
- _this6.hasPlayed_ = true;
- });
- return false;
- } // trigger firstplay to inform the source handler to ignore the next seek event
-
-
- this.trigger('firstplay'); // seek to the live point
-
- this.tech_.setCurrentTime(seekable.end(0));
- }
-
- this.hasPlayed_ = true; // we can begin loading now that everything is ready
-
- this.load();
- return true;
- }
- /**
- * handle the sourceopen event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleSourceOpen_ = function handleSourceOpen_() {
- // Only attempt to create the source buffer if none already exist.
- // handleSourceOpen is also called when we are "re-opening" a source buffer
- // after `endOfStream` has been called (in response to a seek for instance)
- this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
- // code in video.js but is required because play() must be invoked
- // *after* the media source has opened.
-
- if (this.tech_.autoplay()) {
- var playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
- // on browsers which return a promise
-
- if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
- playPromise.then(null, function (e) {});
- }
- }
-
- this.trigger('sourceopen');
- }
- /**
- * handle the sourceended event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleSourceEnded_ = function handleSourceEnded_() {
- if (!this.inbandTextTracks_.metadataTrack_) {
- return;
- }
-
- var cues = this.inbandTextTracks_.metadataTrack_.cues;
-
- if (!cues || !cues.length) {
- return;
- }
-
- var duration = this.duration();
- cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
- }
- /**
- * handle the durationchange event on the MediaSource
- *
- * @private
- */
- ;
-
- _proto.handleDurationChange_ = function handleDurationChange_() {
- this.tech_.trigger('durationchange');
- }
- /**
- * Calls endOfStream on the media source when all active stream types have called
- * endOfStream
- *
- * @param {string} streamType
- * Stream type of the segment loader that called endOfStream
- * @private
- */
- ;
-
- _proto.onEndOfStream = function onEndOfStream() {
- var isEndOfStream = this.mainSegmentLoader_.ended_;
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- // if the audio playlist loader exists, then alternate audio is active
- if (!this.mainSegmentLoader_.currentMediaInfo_ || this.mainSegmentLoader_.currentMediaInfo_.hasVideo) {
- // if we do not know if the main segment loader contains video yet or if we
- // definitively know the main segment loader contains video, then we need to wait
- // for both main and audio segment loaders to call endOfStream
- isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
- } else {
- // otherwise just rely on the audio loader
- isEndOfStream = this.audioSegmentLoader_.ended_;
- }
- }
-
- if (!isEndOfStream) {
- return;
- }
-
- this.stopABRTimer_();
- this.sourceUpdater_.endOfStream();
- }
- /**
- * Check if a playlist has stopped being updated
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist has stopped being updated or not
- */
- ;
-
- _proto.stuckAtPlaylistEnd_ = function stuckAtPlaylistEnd_(playlist) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- // playlist doesn't have enough information to determine whether we are stuck
- return false;
- }
-
- var expired = this.syncController_.getExpiredTime(playlist, this.duration());
-
- if (expired === null) {
- return false;
- } // does not use the safe live end to calculate playlist end, since we
- // don't want to say we are stuck while there is still content
-
-
- var absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
-
- if (!buffered.length) {
- // return true if the playhead reached the absolute end of the playlist
- return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
- }
-
- var bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
- // end of playlist
-
- return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
- }
- /**
- * Blacklists a playlist when an error occurs for a set amount of time
- * making it unavailable for selection by the rendition selection algorithm
- * and then forces a new playlist (rendition) selection.
- *
- * @param {Object=} error an optional error that may include the playlist
- * to blacklist
- * @param {number=} blacklistDuration an optional number of seconds to blacklist the
- * playlist
- */
- ;
-
- _proto.blacklistCurrentPlaylist = function blacklistCurrentPlaylist(error, blacklistDuration) {
- if (error === void 0) {
- error = {};
- }
-
- // If the `error` was generated by the playlist loader, it will contain
- // the playlist we were trying to load (but failed) and that should be
- // blacklisted instead of the currently selected playlist which is likely
- // out-of-date in this scenario
- var currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
- blacklistDuration = blacklistDuration || error.blacklistDuration || this.blacklistDuration; // If there is no current playlist, then an error occurred while we were
- // trying to load the master OR while we were disposing of the tech
-
- if (!currentPlaylist) {
- this.error = error;
-
- if (this.mediaSource.readyState !== 'open') {
- this.trigger('error');
- } else {
- this.sourceUpdater_.endOfStream('network');
- }
-
- return;
- }
-
- currentPlaylist.playlistErrors_++;
- var playlists = this.masterPlaylistLoader_.master.playlists;
- var enabledPlaylists = playlists.filter(isEnabled);
- var isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === currentPlaylist; // Don't blacklist the only playlist unless it was blacklisted
- // forever
-
- if (playlists.length === 1 && blacklistDuration !== Infinity) {
- videojs__default['default'].log.warn("Problem encountered with playlist " + currentPlaylist.id + ". " + 'Trying again since it is the only playlist.');
- this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
-
- return this.masterPlaylistLoader_.load(isFinalRendition);
- }
-
- if (isFinalRendition) {
- // Since we're on the final non-blacklisted playlist, and we're about to blacklist
- // it, instead of erring the player or retrying this playlist, clear out the current
- // blacklist. This allows other playlists to be attempted in case any have been
- // fixed.
- var reincluded = false;
- playlists.forEach(function (playlist) {
- // skip current playlist which is about to be blacklisted
- if (playlist === currentPlaylist) {
- return;
- }
-
- var excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
-
- if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
- reincluded = true;
- delete playlist.excludeUntil;
- }
- });
-
- if (reincluded) {
- videojs__default['default'].log.warn('Removing other playlists from the exclusion list because the last ' + 'rendition is about to be excluded.'); // Technically we are retrying a playlist, in that we are simply retrying a previous
- // playlist. This is needed for users relying on the retryplaylist event to catch a
- // case where the player might be stuck and looping through "dead" playlists.
-
- this.tech_.trigger('retryplaylist');
- }
- } // Blacklist this playlist
-
-
- var excludeUntil;
-
- if (currentPlaylist.playlistErrors_ > this.maxPlaylistRetries) {
- excludeUntil = Infinity;
- } else {
- excludeUntil = Date.now() + blacklistDuration * 1000;
- }
-
- currentPlaylist.excludeUntil = excludeUntil;
-
- if (error.reason) {
- currentPlaylist.lastExcludeReason_ = error.reason;
- }
-
- this.tech_.trigger('blacklistplaylist');
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-rendition-blacklisted'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-rendition-blacklisted'
- }); // TODO: should we select a new playlist if this blacklist wasn't for the currentPlaylist?
- // Would be something like media().id !=== currentPlaylist.id and we would need something
- // like `pendingMedia` in playlist loaders to check against that too. This will prevent us
- // from loading a new playlist on any blacklist.
- // Select a new playlist
-
- var nextPlaylist = this.selectPlaylist();
-
- if (!nextPlaylist) {
- this.error = 'Playback cannot continue. No available working or supported playlists.';
- this.trigger('error');
- return;
- }
-
- var logFn = error.internal ? this.logger_ : videojs__default['default'].log.warn;
- var errorMessage = error.message ? ' ' + error.message : '';
- logFn((error.internal ? 'Internal problem' : 'Problem') + " encountered with playlist " + currentPlaylist.id + "." + (errorMessage + " Switching to playlist " + nextPlaylist.id + ".")); // if audio group changed reset audio loaders
-
- if (nextPlaylist.attributes.AUDIO !== currentPlaylist.attributes.AUDIO) {
- this.delegateLoaders_('audio', ['abort', 'pause']);
- } // if subtitle group changed reset subtitle loaders
-
-
- if (nextPlaylist.attributes.SUBTITLES !== currentPlaylist.attributes.SUBTITLES) {
- this.delegateLoaders_('subtitle', ['abort', 'pause']);
- }
-
- this.delegateLoaders_('main', ['abort', 'pause']);
- var delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
- var shouldDelay = typeof nextPlaylist.lastRequest === 'number' && Date.now() - nextPlaylist.lastRequest <= delayDuration; // delay if it's a final rendition or if the last refresh is sooner than half targetDuration
-
- return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
- }
- /**
- * Pause all segment/playlist loaders
- */
- ;
-
- _proto.pauseLoading = function pauseLoading() {
- this.delegateLoaders_('all', ['abort', 'pause']);
- this.stopABRTimer_();
- }
- /**
- * Call a set of functions in order on playlist loaders, segment loaders,
- * or both types of loaders.
- *
- * @param {string} filter
- * Filter loaders that should call fnNames using a string. Can be:
- * * all - run on all loaders
- * * audio - run on all audio loaders
- * * subtitle - run on all subtitle loaders
- * * main - run on the main/master loaders
- *
- * @param {Array|string} fnNames
- * A string or array of function names to call.
- */
- ;
-
- _proto.delegateLoaders_ = function delegateLoaders_(filter, fnNames) {
- var _this7 = this;
-
- var loaders = [];
- var dontFilterPlaylist = filter === 'all';
-
- if (dontFilterPlaylist || filter === 'main') {
- loaders.push(this.masterPlaylistLoader_);
- }
-
- var mediaTypes = [];
-
- if (dontFilterPlaylist || filter === 'audio') {
- mediaTypes.push('AUDIO');
- }
-
- if (dontFilterPlaylist || filter === 'subtitle') {
- mediaTypes.push('CLOSED-CAPTIONS');
- mediaTypes.push('SUBTITLES');
- }
-
- mediaTypes.forEach(function (mediaType) {
- var loader = _this7.mediaTypes_[mediaType] && _this7.mediaTypes_[mediaType].activePlaylistLoader;
-
- if (loader) {
- loaders.push(loader);
- }
- });
- ['main', 'audio', 'subtitle'].forEach(function (name) {
- var loader = _this7[name + "SegmentLoader_"];
-
- if (loader && (filter === name || filter === 'all')) {
- loaders.push(loader);
- }
- });
- loaders.forEach(function (loader) {
- return fnNames.forEach(function (fnName) {
- if (typeof loader[fnName] === 'function') {
- loader[fnName]();
- }
- });
- });
- }
- /**
- * set the current time on all segment loaders
- *
- * @param {TimeRange} currentTime the current time to set
- * @return {TimeRange} the current time
- */
- ;
-
- _proto.setCurrentTime = function setCurrentTime(currentTime) {
- var buffered = findRange(this.tech_.buffered(), currentTime);
-
- if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
- // return immediately if the metadata is not ready yet
- return 0;
- } // it's clearly an edge-case but don't thrown an error if asked to
- // seek within an empty playlist
-
-
- if (!this.masterPlaylistLoader_.media().segments) {
- return 0;
- } // if the seek location is already buffered, continue buffering as usual
-
-
- if (buffered && buffered.length) {
- return currentTime;
- } // cancel outstanding requests so we begin buffering at the new
- // location
-
-
- this.mainSegmentLoader_.resetEverything();
- this.mainSegmentLoader_.abort();
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.resetEverything();
- this.audioSegmentLoader_.abort();
- }
-
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.resetEverything();
- this.subtitleSegmentLoader_.abort();
- } // start segment loader loading in case they are paused
-
-
- this.load();
- }
- /**
- * get the current duration
- *
- * @return {TimeRange} the duration
- */
- ;
-
- _proto.duration = function duration() {
- if (!this.masterPlaylistLoader_) {
- return 0;
- }
-
- var media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- // no playlists loaded yet, so can't determine a duration
- return 0;
- } // Don't rely on the media source for duration in the case of a live playlist since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, just return Infinity.
-
-
- if (!media.endList) {
- return Infinity;
- } // Since this is a VOD video, it is safe to rely on the media source's duration (if
- // available). If it's not available, fall back to a playlist-calculated estimate.
-
-
- if (this.mediaSource) {
- return this.mediaSource.duration;
- }
-
- return Vhs$1.Playlist.duration(media);
- }
- /**
- * check the seekable range
- *
- * @return {TimeRange} the seekable range
- */
- ;
-
- _proto.seekable = function seekable() {
- return this.seekable_;
- };
-
- _proto.onSyncInfoUpdate_ = function onSyncInfoUpdate_() {
- var audioSeekable;
-
- if (!this.masterPlaylistLoader_) {
- return;
- }
-
- var media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- return;
- }
-
- var expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- // not enough information to update seekable
- return;
- }
-
- var master = this.masterPlaylistLoader_.master;
- var mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
-
- if (mainSeekable.length === 0) {
- return;
- }
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
- expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- return;
- }
-
- audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
-
- if (audioSeekable.length === 0) {
- return;
- }
- }
-
- var oldEnd;
- var oldStart;
-
- if (this.seekable_ && this.seekable_.length) {
- oldEnd = this.seekable_.end(0);
- oldStart = this.seekable_.start(0);
- }
-
- if (!audioSeekable) {
- // seekable has been calculated based on buffering video data so it
- // can be returned directly
- this.seekable_ = mainSeekable;
- } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
- // seekables are pretty far off, rely on main
- this.seekable_ = mainSeekable;
- } else {
- this.seekable_ = videojs__default['default'].createTimeRanges([[audioSeekable.start(0) > mainSeekable.start(0) ? audioSeekable.start(0) : mainSeekable.start(0), audioSeekable.end(0) < mainSeekable.end(0) ? audioSeekable.end(0) : mainSeekable.end(0)]]);
- } // seekable is the same as last time
-
-
- if (this.seekable_ && this.seekable_.length) {
- if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
- return;
- }
- }
-
- this.logger_("seekable updated [" + printableRange(this.seekable_) + "]");
- this.tech_.trigger('seekablechanged');
- }
- /**
- * Update the player duration
- */
- ;
-
- _proto.updateDuration = function updateDuration(isLive) {
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- this.updateDuration_ = null;
- }
-
- if (this.mediaSource.readyState !== 'open') {
- this.updateDuration_ = this.updateDuration.bind(this, isLive);
- this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
- return;
- }
-
- if (isLive) {
- var seekable = this.seekable();
-
- if (!seekable.length) {
- return;
- } // Even in the case of a live playlist, the native MediaSource's duration should not
- // be set to Infinity (even though this would be expected for a live playlist), since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, the duration should be greater than or
- // equal to the last possible seekable value.
- // MediaSource duration starts as NaN
- // It is possible (and probable) that this case will never be reached for many
- // sources, since the MediaSource reports duration as the highest value without
- // accounting for timestamp offset. For example, if the timestamp offset is -100 and
- // we buffered times 0 to 100 with real times of 100 to 200, even though current
- // time will be between 0 and 100, the native media source may report the duration
- // as 200. However, since we report duration separate from the media source (as
- // Infinity), and as long as the native media source duration value is greater than
- // our reported seekable range, seeks will work as expected. The large number as
- // duration for live is actually a strategy used by some players to work around the
- // issue of live seekable ranges cited above.
-
-
- if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
- this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
- }
-
- return;
- }
-
- var buffered = this.tech_.buffered();
- var duration = Vhs$1.Playlist.duration(this.masterPlaylistLoader_.media());
-
- if (buffered.length > 0) {
- duration = Math.max(duration, buffered.end(buffered.length - 1));
- }
-
- if (this.mediaSource.duration !== duration) {
- this.sourceUpdater_.setDuration(duration);
- }
- }
- /**
- * dispose of the MasterPlaylistController and everything
- * that it controls
- */
- ;
-
- _proto.dispose = function dispose() {
- var _this8 = this;
-
- this.trigger('dispose');
- this.decrypter_.terminate();
- this.masterPlaylistLoader_.dispose();
- this.mainSegmentLoader_.dispose();
-
- if (this.loadOnPlay_) {
- this.tech_.off('play', this.loadOnPlay_);
- }
-
- ['AUDIO', 'SUBTITLES'].forEach(function (type) {
- var groups = _this8.mediaTypes_[type].groups;
-
- for (var id in groups) {
- groups[id].forEach(function (group) {
- if (group.playlistLoader) {
- group.playlistLoader.dispose();
- }
- });
- }
- });
- this.audioSegmentLoader_.dispose();
- this.subtitleSegmentLoader_.dispose();
- this.sourceUpdater_.dispose();
- this.timelineChangeController_.dispose();
- this.stopABRTimer_();
-
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- }
-
- this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
-
- this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
- this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
- this.off();
- }
- /**
- * return the master playlist object if we have one
- *
- * @return {Object} the master playlist object that we parsed
- */
- ;
-
- _proto.master = function master() {
- return this.masterPlaylistLoader_.master;
- }
- /**
- * return the currently selected playlist
- *
- * @return {Object} the currently selected playlist object that we parsed
- */
- ;
-
- _proto.media = function media() {
- // playlist loader will not return media if it has not been fully loaded
- return this.masterPlaylistLoader_.media() || this.initialMedia_;
- };
-
- _proto.areMediaTypesKnown_ = function areMediaTypesKnown_() {
- var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader; // one or both loaders has not loaded sufficently to get codecs
-
- if (!this.mainSegmentLoader_.currentMediaInfo_ || usingAudioLoader && !this.audioSegmentLoader_.currentMediaInfo_) {
- return false;
- }
-
- return true;
- };
-
- _proto.getCodecsOrExclude_ = function getCodecsOrExclude_() {
- var _this9 = this;
-
- var media = {
- main: this.mainSegmentLoader_.currentMediaInfo_ || {},
- audio: this.audioSegmentLoader_.currentMediaInfo_ || {}
- }; // set "main" media equal to video
-
- media.video = media.main;
- var playlistCodecs = codecsForPlaylist(this.master(), this.media());
- var codecs = {};
- var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
-
- if (media.main.hasVideo) {
- codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
- }
-
- if (media.main.isMuxed) {
- codecs.video += "," + (playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC);
- }
-
- if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
- codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
-
- media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
- } // no codecs, no playback.
-
-
- if (!codecs.audio && !codecs.video) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: 'Could not determine codecs for playlist.',
- blacklistDuration: Infinity
- });
- return;
- } // fmp4 relies on browser support, while ts relies on muxer support
-
-
- var supportFunction = function supportFunction(isFmp4, codec) {
- return isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
- };
-
- var unsupportedCodecs = {};
- var unsupportedAudio;
- ['video', 'audio'].forEach(function (type) {
- if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
- var supporter = media[type].isFmp4 ? 'browser' : 'muxer';
- unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
- unsupportedCodecs[supporter].push(codecs[type]);
-
- if (type === 'audio') {
- unsupportedAudio = supporter;
- }
- }
- });
-
- if (usingAudioLoader && unsupportedAudio && this.media().attributes.AUDIO) {
- var audioGroup = this.media().attributes.AUDIO;
- this.master().playlists.forEach(function (variant) {
- var variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
-
- if (variantAudioGroup === audioGroup && variant !== _this9.media()) {
- variant.excludeUntil = Infinity;
- }
- });
- this.logger_("excluding audio group " + audioGroup + " as " + unsupportedAudio + " does not support codec(s): \"" + codecs.audio + "\"");
- } // if we have any unsupported codecs blacklist this playlist.
-
-
- if (Object.keys(unsupportedCodecs).length) {
- var message = Object.keys(unsupportedCodecs).reduce(function (acc, supporter) {
- if (acc) {
- acc += ', ';
- }
-
- acc += supporter + " does not support codec(s): \"" + unsupportedCodecs[supporter].join(',') + "\"";
- return acc;
- }, '') + '.';
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- internal: true,
- message: message,
- blacklistDuration: Infinity
- });
- return;
- } // check if codec switching is happening
-
-
- if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
- var switchMessages = [];
- ['video', 'audio'].forEach(function (type) {
- var newCodec = (parseCodecs(_this9.sourceUpdater_.codecs[type] || '')[0] || {}).type;
- var oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
-
- if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
- switchMessages.push("\"" + _this9.sourceUpdater_.codecs[type] + "\" -> \"" + codecs[type] + "\"");
- }
- });
-
- if (switchMessages.length) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: "Codec switching not supported: " + switchMessages.join(', ') + ".",
- blacklistDuration: Infinity,
- internal: true
- });
- return;
- }
- } // TODO: when using the muxer shouldn't we just return
- // the codecs that the muxer outputs?
-
-
- return codecs;
- }
- /**
- * Create source buffers and exlude any incompatible renditions.
- *
- * @private
- */
- ;
-
- _proto.tryToCreateSourceBuffers_ = function tryToCreateSourceBuffers_() {
- // media source is not ready yet or sourceBuffers are already
- // created.
- if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
- return;
- }
-
- if (!this.areMediaTypesKnown_()) {
- return;
- }
-
- var codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
-
- if (!codecs) {
- return;
- }
-
- this.sourceUpdater_.createSourceBuffers(codecs);
- var codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
- this.excludeIncompatibleVariants_(codecString);
- }
- /**
- * Excludes playlists with codecs that are unsupported by the muxer and browser.
- */
- ;
-
- _proto.excludeUnsupportedVariants_ = function excludeUnsupportedVariants_() {
- var _this10 = this;
-
- var playlists = this.master().playlists;
- var ids = []; // TODO: why don't we have a property to loop through all
- // playlist? Why did we ever mix indexes and keys?
-
- Object.keys(playlists).forEach(function (key) {
- var variant = playlists[key]; // check if we already processed this playlist.
-
- if (ids.indexOf(variant.id) !== -1) {
- return;
- }
-
- ids.push(variant.id);
- var codecs = codecsForPlaylist(_this10.master, variant);
- var unsupported = [];
-
- if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
- unsupported.push("audio codec " + codecs.audio);
- }
-
- if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
- unsupported.push("video codec " + codecs.video);
- }
-
- if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
- unsupported.push("text codec " + codecs.text);
- }
-
- if (unsupported.length) {
- variant.excludeUntil = Infinity;
-
- _this10.logger_("excluding " + variant.id + " for unsupported: " + unsupported.join(', '));
- }
- });
- }
- /**
- * Blacklist playlists that are known to be codec or
- * stream-incompatible with the SourceBuffer configuration. For
- * instance, Media Source Extensions would cause the video element to
- * stall waiting for video data if you switched from a variant with
- * video and audio to an audio-only one.
- *
- * @param {Object} media a media playlist compatible with the current
- * set of SourceBuffers. Variants in the current master playlist that
- * do not appear to have compatible codec or stream configurations
- * will be excluded from the default playlist selection algorithm
- * indefinitely.
- * @private
- */
- ;
-
- _proto.excludeIncompatibleVariants_ = function excludeIncompatibleVariants_(codecString) {
- var _this11 = this;
-
- var ids = [];
- var playlists = this.master().playlists;
- var codecs = unwrapCodecList(parseCodecs(codecString));
- var codecCount_ = codecCount(codecs);
- var videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
- var audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
- Object.keys(playlists).forEach(function (key) {
- var variant = playlists[key]; // check if we already processed this playlist.
- // or it if it is already excluded forever.
-
- if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
- return;
- }
-
- ids.push(variant.id);
- var blacklistReasons = []; // get codecs from the playlist for this variant
-
- var variantCodecs = codecsForPlaylist(_this11.masterPlaylistLoader_.master, variant);
- var variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
- // variant is incompatible. Wait for mux.js to probe
-
- if (!variantCodecs.audio && !variantCodecs.video) {
- return;
- } // TODO: we can support this by removing the
- // old media source and creating a new one, but it will take some work.
- // The number of streams cannot change
-
-
- if (variantCodecCount !== codecCount_) {
- blacklistReasons.push("codec count \"" + variantCodecCount + "\" !== \"" + codecCount_ + "\"");
- } // only exclude playlists by codec change, if codecs cannot switch
- // during playback.
-
-
- if (!_this11.sourceUpdater_.canChangeType()) {
- var variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
- var variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
-
- if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
- blacklistReasons.push("video codec \"" + variantVideoDetails.type + "\" !== \"" + videoDetails.type + "\"");
- } // the audio codec cannot change
-
-
- if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
- blacklistReasons.push("audio codec \"" + variantAudioDetails.type + "\" !== \"" + audioDetails.type + "\"");
- }
- }
-
- if (blacklistReasons.length) {
- variant.excludeUntil = Infinity;
-
- _this11.logger_("blacklisting " + variant.id + ": " + blacklistReasons.join(' && '));
- }
- });
- };
-
- _proto.updateAdCues_ = function updateAdCues_(media) {
- var offset = 0;
- var seekable = this.seekable();
-
- if (seekable.length) {
- offset = seekable.start(0);
- }
-
- updateAdCues(media, this.cueTagsTrack_, offset);
- }
- /**
- * Calculates the desired forward buffer length based on current time
- *
- * @return {number} Desired forward buffer length in seconds
- */
- ;
-
- _proto.goalBufferLength = function goalBufferLength() {
- var currentTime = this.tech_.currentTime();
- var initial = Config.GOAL_BUFFER_LENGTH;
- var rate = Config.GOAL_BUFFER_LENGTH_RATE;
- var max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
- return Math.min(initial + currentTime * rate, max);
- }
- /**
- * Calculates the desired buffer low water line based on current time
- *
- * @return {number} Desired buffer low water line in seconds
- */
- ;
-
- _proto.bufferLowWaterLine = function bufferLowWaterLine() {
- var currentTime = this.tech_.currentTime();
- var initial = Config.BUFFER_LOW_WATER_LINE;
- var rate = Config.BUFFER_LOW_WATER_LINE_RATE;
- var max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
- var newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
- return Math.min(initial + currentTime * rate, this.experimentalBufferBasedABR ? newMax : max);
- };
-
- _proto.bufferHighWaterLine = function bufferHighWaterLine() {
- return Config.BUFFER_HIGH_WATER_LINE;
- };
-
- return MasterPlaylistController;
- }(videojs__default['default'].EventTarget);
-
- /**
- * Returns a function that acts as the Enable/disable playlist function.
- *
- * @param {PlaylistLoader} loader - The master playlist loader
- * @param {string} playlistID - id of the playlist
- * @param {Function} changePlaylistFn - A function to be called after a
- * playlist's enabled-state has been changed. Will NOT be called if a
- * playlist's enabled-state is unchanged
- * @param {boolean=} enable - Value to set the playlist enabled-state to
- * or if undefined returns the current enabled-state for the playlist
- * @return {Function} Function for setting/getting enabled
- */
-
- var enableFunction = function enableFunction(loader, playlistID, changePlaylistFn) {
- return function (enable) {
- var playlist = loader.master.playlists[playlistID];
- var incompatible = isIncompatible(playlist);
- var currentlyEnabled = isEnabled(playlist);
-
- if (typeof enable === 'undefined') {
- return currentlyEnabled;
- }
-
- if (enable) {
- delete playlist.disabled;
- } else {
- playlist.disabled = true;
- }
-
- if (enable !== currentlyEnabled && !incompatible) {
- // Ensure the outside world knows about our changes
- changePlaylistFn();
-
- if (enable) {
- loader.trigger('renditionenabled');
- } else {
- loader.trigger('renditiondisabled');
- }
- }
-
- return enable;
- };
- };
- /**
- * The representation object encapsulates the publicly visible information
- * in a media playlist along with a setter/getter-type function (enabled)
- * for changing the enabled-state of a particular playlist entry
- *
- * @class Representation
- */
-
-
- var Representation = function Representation(vhsHandler, playlist, id) {
- var mpc = vhsHandler.masterPlaylistController_,
- smoothQualityChange = vhsHandler.options_.smoothQualityChange; // Get a reference to a bound version of the quality change function
-
- var changeType = smoothQualityChange ? 'smooth' : 'fast';
- var qualityChangeFunction = mpc[changeType + "QualityChange_"].bind(mpc); // some playlist attributes are optional
-
- if (playlist.attributes) {
- var resolution = playlist.attributes.RESOLUTION;
- this.width = resolution && resolution.width;
- this.height = resolution && resolution.height;
- this.bandwidth = playlist.attributes.BANDWIDTH;
- }
-
- this.codecs = codecsForPlaylist(mpc.master(), playlist);
- this.playlist = playlist; // The id is simply the ordinality of the media playlist
- // within the master playlist
-
- this.id = id; // Partially-apply the enableFunction to create a playlist-
- // specific variant
-
- this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
- };
- /**
- * A mixin function that adds the `representations` api to an instance
- * of the VhsHandler class
- *
- * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
- * representation API into
- */
-
-
- var renditionSelectionMixin = function renditionSelectionMixin(vhsHandler) {
- // Add a single API-specific function to the VhsHandler instance
- vhsHandler.representations = function () {
- var master = vhsHandler.masterPlaylistController_.master();
- var playlists = isAudioOnly(master) ? vhsHandler.masterPlaylistController_.getAudioTrackPlaylists_() : master.playlists;
-
- if (!playlists) {
- return [];
- }
-
- return playlists.filter(function (media) {
- return !isIncompatible(media);
- }).map(function (e, i) {
- return new Representation(vhsHandler, e, e.id);
- });
- };
- };
-
- /**
- * @file playback-watcher.js
- *
- * Playback starts, and now my watch begins. It shall not end until my death. I shall
- * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
- * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
- * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
- * my life and honor to the Playback Watch, for this Player and all the Players to come.
- */
-
- var timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
- /**
- * Returns whether or not the current time should be considered close to buffered content,
- * taking into consideration whether there's enough buffered content for proper playback.
- *
- * @param {Object} options
- * Options object
- * @param {TimeRange} options.buffered
- * Current buffer
- * @param {number} options.targetDuration
- * The active playlist's target duration
- * @param {number} options.currentTime
- * The current time of the player
- * @return {boolean}
- * Whether the current time should be considered close to the buffer
- */
-
- var closeToBufferedContent = function closeToBufferedContent(_ref) {
- var buffered = _ref.buffered,
- targetDuration = _ref.targetDuration,
- currentTime = _ref.currentTime;
-
- if (!buffered.length) {
- return false;
- } // At least two to three segments worth of content should be buffered before there's a
- // full enough buffer to consider taking any actions.
-
-
- if (buffered.end(0) - buffered.start(0) < targetDuration * 2) {
- return false;
- } // It's possible that, on seek, a remove hasn't completed and the buffered range is
- // somewhere past the current time. In that event, don't consider the buffered content
- // close.
-
-
- if (currentTime > buffered.start(0)) {
- return false;
- } // Since target duration generally represents the max (or close to max) duration of a
- // segment, if the buffer is within a segment of the current time, the gap probably
- // won't be closed, and current time should be considered close to buffered content.
-
-
- return buffered.start(0) - currentTime < targetDuration;
- };
- /**
- * @class PlaybackWatcher
- */
-
- var PlaybackWatcher = /*#__PURE__*/function () {
- /**
- * Represents an PlaybackWatcher object.
- *
- * @class
- * @param {Object} options an object that includes the tech and settings
- */
- function PlaybackWatcher(options) {
- var _this = this;
-
- this.masterPlaylistController_ = options.masterPlaylistController;
- this.tech_ = options.tech;
- this.seekable = options.seekable;
- this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
- this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
- this.media = options.media;
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = null;
- this.timer_ = null;
- this.checkCurrentTimeTimeout_ = null;
- this.logger_ = logger('PlaybackWatcher');
- this.logger_('initialize');
-
- var playHandler = function playHandler() {
- return _this.monitorCurrentTime_();
- };
-
- var canPlayHandler = function canPlayHandler() {
- return _this.monitorCurrentTime_();
- };
-
- var waitingHandler = function waitingHandler() {
- return _this.techWaiting_();
- };
-
- var cancelTimerHandler = function cancelTimerHandler() {
- return _this.cancelTimer_();
- };
-
- var fixesBadSeeksHandler = function fixesBadSeeksHandler() {
- return _this.fixesBadSeeks_();
- };
-
- var mpc = this.masterPlaylistController_;
- var loaderTypes = ['main', 'subtitle', 'audio'];
- var loaderChecks = {};
- loaderTypes.forEach(function (type) {
- loaderChecks[type] = {
- reset: function reset() {
- return _this.resetSegmentDownloads_(type);
- },
- updateend: function updateend() {
- return _this.checkSegmentDownloads_(type);
- }
- };
- mpc[type + "SegmentLoader_"].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
- // isn't changing we want to reset. We cannot assume that the new rendition
- // will also be stalled, until after new appends.
-
- mpc[type + "SegmentLoader_"].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
- // This prevents one segment playlists (single vtt or single segment content)
- // from being detected as stalling. As the buffer will not change in those cases, since
- // the buffer is the entire video duration.
-
- _this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
- });
- this.tech_.on('seekablechanged', fixesBadSeeksHandler);
- this.tech_.on('waiting', waitingHandler);
- this.tech_.on(timerCancelEvents, cancelTimerHandler);
- this.tech_.on('canplay', canPlayHandler);
- /*
- An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
- is surfaced in one of two ways:
- 1) The `waiting` event is fired before the player has buffered content, making it impossible
- to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
- we can check if playback is stalled due to a gap, and skip the gap if necessary.
- 2) A source with a gap at the beginning of the stream is loaded programatically while the player
- is in a playing state. To catch this case, it's important that our one-time play listener is setup
- even if the player is in a playing state
- */
-
- this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
-
- this.dispose = function () {
- _this.logger_('dispose');
-
- _this.tech_.off('seekablechanged', fixesBadSeeksHandler);
-
- _this.tech_.off('waiting', waitingHandler);
-
- _this.tech_.off(timerCancelEvents, cancelTimerHandler);
-
- _this.tech_.off('canplay', canPlayHandler);
-
- _this.tech_.off('play', playHandler);
-
- loaderTypes.forEach(function (type) {
- mpc[type + "SegmentLoader_"].off('appendsdone', loaderChecks[type].updateend);
- mpc[type + "SegmentLoader_"].off('playlistupdate', loaderChecks[type].reset);
-
- _this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
- });
-
- if (_this.checkCurrentTimeTimeout_) {
- window__default['default'].clearTimeout(_this.checkCurrentTimeTimeout_);
- }
-
- _this.cancelTimer_();
- };
- }
- /**
- * Periodically check current time to see if playback stopped
- *
- * @private
- */
-
-
- var _proto = PlaybackWatcher.prototype;
-
- _proto.monitorCurrentTime_ = function monitorCurrentTime_() {
- this.checkCurrentTime_();
-
- if (this.checkCurrentTimeTimeout_) {
- window__default['default'].clearTimeout(this.checkCurrentTimeTimeout_);
- } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
-
-
- this.checkCurrentTimeTimeout_ = window__default['default'].setTimeout(this.monitorCurrentTime_.bind(this), 250);
- }
- /**
- * Reset stalled download stats for a specific type of loader
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#playlistupdate
- * @listens Tech#seeking
- * @listens Tech#seeked
- */
- ;
-
- _proto.resetSegmentDownloads_ = function resetSegmentDownloads_(type) {
- var loader = this.masterPlaylistController_[type + "SegmentLoader_"];
-
- if (this[type + "StalledDownloads_"] > 0) {
- this.logger_("resetting possible stalled download count for " + type + " loader");
- }
-
- this[type + "StalledDownloads_"] = 0;
- this[type + "Buffered_"] = loader.buffered_();
- }
- /**
- * Checks on every segment `appendsdone` to see
- * if segment appends are making progress. If they are not
- * and we are still downloading bytes. We blacklist the playlist.
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#appendsdone
- */
- ;
-
- _proto.checkSegmentDownloads_ = function checkSegmentDownloads_(type) {
- var mpc = this.masterPlaylistController_;
- var loader = mpc[type + "SegmentLoader_"];
- var buffered = loader.buffered_();
- var isBufferedDifferent = isRangeDifferent(this[type + "Buffered_"], buffered);
- this[type + "Buffered_"] = buffered; // if another watcher is going to fix the issue or
- // the buffered value for this loader changed
- // appends are working
-
- if (isBufferedDifferent) {
- this.resetSegmentDownloads_(type);
- return;
- }
-
- this[type + "StalledDownloads_"]++;
- this.logger_("found #" + this[type + "StalledDownloads_"] + " " + type + " appends that did not increase buffer (possible stalled download)", {
- playlistId: loader.playlist_ && loader.playlist_.id,
- buffered: timeRangesToArray(buffered)
- }); // after 10 possibly stalled appends with no reset, exclude
-
- if (this[type + "StalledDownloads_"] < 10) {
- return;
- }
-
- this.logger_(type + " loader stalled download exclusion");
- this.resetSegmentDownloads_(type);
- this.tech_.trigger({
- type: 'usage',
- name: "vhs-" + type + "-download-exclusion"
- });
-
- if (type === 'subtitle') {
- return;
- } // TODO: should we exclude audio tracks rather than main tracks
- // when type is audio?
-
-
- mpc.blacklistCurrentPlaylist({
- message: "Excessive " + type + " segment downloading detected."
- }, Infinity);
- }
- /**
- * The purpose of this function is to emulate the "waiting" event on
- * browsers that do not emit it when they are waiting for more
- * data to continue playback
- *
- * @private
- */
- ;
-
- _proto.checkCurrentTime_ = function checkCurrentTime_() {
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = this.tech_.currentTime();
- return;
- }
-
- if (this.tech_.paused() || this.tech_.seeking()) {
- return;
- }
-
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
-
- if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
- // If current time is at the end of the final buffered region, then any playback
- // stall is most likely caused by buffering in a low bandwidth environment. The tech
- // should fire a `waiting` event in this scenario, but due to browser and tech
- // inconsistencies. Calling `techWaiting_` here allows us to simulate
- // responding to a native `waiting` event when the tech fails to emit one.
- return this.techWaiting_();
- }
-
- if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- this.waiting_();
- } else if (currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- } else {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = currentTime;
- }
- }
- /**
- * Cancels any pending timers and resets the 'timeupdate' mechanism
- * designed to detect that we are stalled
- *
- * @private
- */
- ;
-
- _proto.cancelTimer_ = function cancelTimer_() {
- this.consecutiveUpdates = 0;
-
- if (this.timer_) {
- this.logger_('cancelTimer_');
- clearTimeout(this.timer_);
- }
-
- this.timer_ = null;
- }
- /**
- * Fixes situations where there's a bad seek
- *
- * @return {boolean} whether an action was taken to fix the seek
- * @private
- */
- ;
-
- _proto.fixesBadSeeks_ = function fixesBadSeeks_() {
- var seeking = this.tech_.seeking();
-
- if (!seeking) {
- return false;
- }
-
- var seekable = this.seekable();
- var currentTime = this.tech_.currentTime();
- var isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
- var seekTo;
-
- if (isAfterSeekableRange) {
- var seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
-
- seekTo = seekableEnd;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- var seekableStart = seekable.start(0); // sync to the beginning of the live window
- // provide a buffer of .1 seconds to handle rounding/imprecise numbers
-
- seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
- // happen in live with a 3 segment playlist), then don't use a time delta
- seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
- }
-
- if (typeof seekTo !== 'undefined') {
- this.logger_("Trying to seek outside of seekable at time " + currentTime + " with " + ("seekable range " + printableRange(seekable) + ". Seeking to ") + (seekTo + "."));
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- var buffered = this.tech_.buffered();
-
- if (closeToBufferedContent({
- buffered: buffered,
- targetDuration: this.media().targetDuration,
- currentTime: currentTime
- })) {
- seekTo = buffered.start(0) + SAFE_TIME_DELTA;
- this.logger_("Buffered region starts (" + buffered.start(0) + ") " + (" just beyond seek point (" + currentTime + "). Seeking to " + seekTo + "."));
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- return false;
- }
- /**
- * Handler for situations when we determine the player is waiting.
- *
- * @private
- */
- ;
-
- _proto.waiting_ = function waiting_() {
- if (this.techWaiting_()) {
- return;
- } // All tech waiting checks failed. Use last resort correction
-
-
- var currentTime = this.tech_.currentTime();
- var buffered = this.tech_.buffered();
- var currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
- // region with no indication that anything is amiss (seen in Firefox). Seeking to
- // currentTime is usually enough to kickstart the player. This checks that the player
- // is currently within a buffered region before attempting a corrective seek.
- // Chrome does not appear to continue `timeupdate` events after a `waiting` event
- // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
- // make sure there is ~3 seconds of forward buffer before taking any corrective action
- // to avoid triggering an `unknownwaiting` event when the network is slow.
-
- if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime);
- this.logger_("Stopped at " + currentTime + " while inside a buffered region " + ("[" + currentRange.start(0) + " -> " + currentRange.end(0) + "]. Attempting to resume ") + 'playback by seeking to the current time.'); // unknown waiting corrections may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-unknown-waiting'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-unknown-waiting'
- });
- return;
- }
- }
- /**
- * Handler for situations when the tech fires a `waiting` event
- *
- * @return {boolean}
- * True if an action (or none) was needed to correct the waiting. False if no
- * checks passed
- * @private
- */
- ;
-
- _proto.techWaiting_ = function techWaiting_() {
- var seekable = this.seekable();
- var currentTime = this.tech_.currentTime();
-
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- // Tech is seeking or bad seek fixed, no action needed
- return true;
- }
-
- if (this.tech_.seeking() || this.timer_ !== null) {
- // Tech is seeking or already waiting on another action, no action needed
- return true;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- var livePoint = seekable.end(seekable.length - 1);
- this.logger_("Fell out of live window at time " + currentTime + ". Seeking to " + ("live point (seekable end) " + livePoint));
- this.cancelTimer_();
- this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-live-resync'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-live-resync'
- });
- return true;
- }
-
- var sourceUpdater = this.tech_.vhs.masterPlaylistController_.sourceUpdater_;
- var buffered = this.tech_.buffered();
- var videoUnderflow = this.videoUnderflow_({
- audioBuffered: sourceUpdater.audioBuffered(),
- videoBuffered: sourceUpdater.videoBuffered(),
- currentTime: currentTime
- });
-
- if (videoUnderflow) {
- // Even though the video underflowed and was stuck in a gap, the audio overplayed
- // the gap, leading currentTime into a buffered range. Seeking to currentTime
- // allows the video to catch up to the audio position without losing any audio
- // (only suffering ~3 seconds of frozen video and a pause in audio playback).
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
-
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-video-underflow'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-video-underflow'
- });
- return true;
- }
-
- var nextRange = findNextRange(buffered, currentTime); // check for gap
-
- if (nextRange.length > 0) {
- var difference = nextRange.start(0) - currentTime;
- this.logger_("Stopped at " + currentTime + ", setting timer for " + difference + ", seeking " + ("to " + nextRange.start(0)));
- this.cancelTimer_();
- this.timer_ = setTimeout(this.skipTheGap_.bind(this), difference * 1000, currentTime);
- return true;
- } // All checks failed. Returning false to indicate failure to correct waiting
-
-
- return false;
- };
-
- _proto.afterSeekableWindow_ = function afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow) {
- if (allowSeeksWithinUnsafeLiveWindow === void 0) {
- allowSeeksWithinUnsafeLiveWindow = false;
- }
-
- if (!seekable.length) {
- // we can't make a solid case if there's no seekable, default to false
- return false;
- }
-
- var allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
- var isLive = !playlist.endList;
-
- if (isLive && allowSeeksWithinUnsafeLiveWindow) {
- allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
- }
-
- if (currentTime > allowedEnd) {
- return true;
- }
-
- return false;
- };
-
- _proto.beforeSeekableWindow_ = function beforeSeekableWindow_(seekable, currentTime) {
- if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
- seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
- return true;
- }
-
- return false;
- };
-
- _proto.videoUnderflow_ = function videoUnderflow_(_ref2) {
- var videoBuffered = _ref2.videoBuffered,
- audioBuffered = _ref2.audioBuffered,
- currentTime = _ref2.currentTime;
-
- // audio only content will not have video underflow :)
- if (!videoBuffered) {
- return;
- }
-
- var gap; // find a gap in demuxed content.
-
- if (videoBuffered.length && audioBuffered.length) {
- // in Chrome audio will continue to play for ~3s when we run out of video
- // so we have to check that the video buffer did have some buffer in the
- // past.
- var lastVideoRange = findRange(videoBuffered, currentTime - 3);
- var videoRange = findRange(videoBuffered, currentTime);
- var audioRange = findRange(audioBuffered, currentTime);
-
- if (audioRange.length && !videoRange.length && lastVideoRange.length) {
- gap = {
- start: lastVideoRange.end(0),
- end: audioRange.end(0)
- };
- } // find a gap in muxed content.
-
- } else {
- var nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
- // stuck in a gap due to video underflow.
-
- if (!nextRange.length) {
- gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
- }
- }
-
- if (gap) {
- this.logger_("Encountered a gap in video from " + gap.start + " to " + gap.end + ". " + ("Seeking to current time " + currentTime));
- return true;
- }
-
- return false;
- }
- /**
- * Timer callback. If playback still has not proceeded, then we seek
- * to the start of the next buffered region.
- *
- * @private
- */
- ;
-
- _proto.skipTheGap_ = function skipTheGap_(scheduledCurrentTime) {
- var buffered = this.tech_.buffered();
- var currentTime = this.tech_.currentTime();
- var nextRange = findNextRange(buffered, currentTime);
- this.cancelTimer_();
-
- if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
- return;
- }
-
- this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
-
- this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-gap-skip'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-gap-skip'
- });
- };
-
- _proto.gapFromVideoUnderflow_ = function gapFromVideoUnderflow_(buffered, currentTime) {
- // At least in Chrome, if there is a gap in the video buffer, the audio will continue
- // playing for ~3 seconds after the video gap starts. This is done to account for
- // video buffer underflow/underrun (note that this is not done when there is audio
- // buffer underflow/underrun -- in that case the video will stop as soon as it
- // encounters the gap, as audio stalls are more noticeable/jarring to a user than
- // video stalls). The player's time will reflect the playthrough of audio, so the
- // time will appear as if we are in a buffered region, even if we are stuck in a
- // "gap."
- //
- // Example:
- // video buffer: 0 => 10.1, 10.2 => 20
- // audio buffer: 0 => 20
- // overall buffer: 0 => 10.1, 10.2 => 20
- // current time: 13
- //
- // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
- // however, the audio continued playing until it reached ~3 seconds past the gap
- // (13 seconds), at which point it stops as well. Since current time is past the
- // gap, findNextRange will return no ranges.
- //
- // To check for this issue, we see if there is a gap that starts somewhere within
- // a 3 second range (3 seconds +/- 1 second) back from our current time.
- var gaps = findGaps(buffered);
-
- for (var i = 0; i < gaps.length; i++) {
- var start = gaps.start(i);
- var end = gaps.end(i); // gap is starts no more than 4 seconds back
-
- if (currentTime - start < 4 && currentTime - start > 2) {
- return {
- start: start,
- end: end
- };
- }
- }
-
- return null;
- };
-
- return PlaybackWatcher;
- }();
-
- var defaultOptions = {
- errorInterval: 30,
- getSource: function getSource(next) {
- var tech = this.tech({
- IWillNotUseThisInPlugins: true
- });
- var sourceObj = tech.currentSource_ || this.currentSource();
- return next(sourceObj);
- }
- };
- /**
- * Main entry point for the plugin
- *
- * @param {Player} player a reference to a videojs Player instance
- * @param {Object} [options] an object with plugin options
- * @private
- */
-
- var initPlugin = function initPlugin(player, options) {
- var lastCalled = 0;
- var seekTo = 0;
- var localOptions = videojs__default['default'].mergeOptions(defaultOptions, options);
- player.ready(function () {
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload-initialized'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload-initialized'
- });
- });
- /**
- * Player modifications to perform that must wait until `loadedmetadata`
- * has been triggered
- *
- * @private
- */
-
- var loadedMetadataHandler = function loadedMetadataHandler() {
- if (seekTo) {
- player.currentTime(seekTo);
- }
- };
- /**
- * Set the source on the player element, play, and seek if necessary
- *
- * @param {Object} sourceObj An object specifying the source url and mime-type to play
- * @private
- */
-
-
- var setSource = function setSource(sourceObj) {
- if (sourceObj === null || sourceObj === undefined) {
- return;
- }
-
- seekTo = player.duration() !== Infinity && player.currentTime() || 0;
- player.one('loadedmetadata', loadedMetadataHandler);
- player.src(sourceObj);
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload'
- });
- player.play();
- };
- /**
- * Attempt to get a source from either the built-in getSource function
- * or a custom function provided via the options
- *
- * @private
- */
-
-
- var errorHandler = function errorHandler() {
- // Do not attempt to reload the source if a source-reload occurred before
- // 'errorInterval' time has elapsed since the last source-reload
- if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
- player.trigger({
- type: 'usage',
- name: 'vhs-error-reload-canceled'
- });
- player.trigger({
- type: 'usage',
- name: 'hls-error-reload-canceled'
- });
- return;
- }
-
- if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
- videojs__default['default'].log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
- return;
- }
-
- lastCalled = Date.now();
- return localOptions.getSource.call(player, setSource);
- };
- /**
- * Unbind any event handlers that were bound by the plugin
- *
- * @private
- */
-
-
- var cleanupEvents = function cleanupEvents() {
- player.off('loadedmetadata', loadedMetadataHandler);
- player.off('error', errorHandler);
- player.off('dispose', cleanupEvents);
- };
- /**
- * Cleanup before re-initializing the plugin
- *
- * @param {Object} [newOptions] an object with plugin options
- * @private
- */
-
-
- var reinitPlugin = function reinitPlugin(newOptions) {
- cleanupEvents();
- initPlugin(player, newOptions);
- };
-
- player.on('error', errorHandler);
- player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
- // initializing the plugin
-
- player.reloadSourceOnError = reinitPlugin;
- };
- /**
- * Reload the source when an error is detected as long as there
- * wasn't an error previously within the last 30 seconds
- *
- * @param {Object} [options] an object with plugin options
- */
-
-
- var reloadSourceOnError = function reloadSourceOnError(options) {
- initPlugin(this, options);
- };
-
- var version$4 = "2.9.1";
-
- var version$3 = "5.11.1";
-
- var version$2 = "0.17.0";
-
- var version$1 = "4.7.0";
-
- var version = "3.1.2";
-
- var Vhs = {
- PlaylistLoader: PlaylistLoader,
- Playlist: Playlist,
- utils: utils,
- STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
- INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
- lastBandwidthSelector: lastBandwidthSelector,
- movingAverageBandwidthSelector: movingAverageBandwidthSelector,
- comparePlaylistBandwidth: comparePlaylistBandwidth,
- comparePlaylistResolution: comparePlaylistResolution,
- xhr: xhrFactory()
- }; // Define getter/setters for config properties
-
- Object.keys(Config).forEach(function (prop) {
- Object.defineProperty(Vhs, prop, {
- get: function get() {
- videojs__default['default'].log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
- return Config[prop];
- },
- set: function set(value) {
- videojs__default['default'].log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
-
- if (typeof value !== 'number' || value < 0) {
- videojs__default['default'].log.warn("value of Vhs." + prop + " must be greater than or equal to 0");
- return;
- }
-
- Config[prop] = value;
- }
- });
- });
- var LOCAL_STORAGE_KEY = 'videojs-vhs';
- /**
- * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
- * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
- * @function handleVhsMediaChange
- */
-
- var handleVhsMediaChange = function handleVhsMediaChange(qualityLevels, playlistLoader) {
- var newPlaylist = playlistLoader.media();
- var selectedIndex = -1;
-
- for (var i = 0; i < qualityLevels.length; i++) {
- if (qualityLevels[i].id === newPlaylist.id) {
- selectedIndex = i;
- break;
- }
- }
-
- qualityLevels.selectedIndex_ = selectedIndex;
- qualityLevels.trigger({
- selectedIndex: selectedIndex,
- type: 'change'
- });
- };
- /**
- * Adds quality levels to list once playlist metadata is available
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
- * @param {Object} vhs Vhs object to listen to for media events.
- * @function handleVhsLoadedMetadata
- */
-
-
- var handleVhsLoadedMetadata = function handleVhsLoadedMetadata(qualityLevels, vhs) {
- vhs.representations().forEach(function (rep) {
- qualityLevels.addQualityLevel(rep);
- });
- handleVhsMediaChange(qualityLevels, vhs.playlists);
- }; // HLS is a source handler, not a tech. Make sure attempts to use it
- // as one do not cause exceptions.
-
-
- Vhs.canPlaySource = function () {
- return videojs__default['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
- };
-
- var emeKeySystems = function emeKeySystems(keySystemOptions, mainPlaylist, audioPlaylist) {
- if (!keySystemOptions) {
- return keySystemOptions;
- }
-
- var codecs = {};
-
- if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
- codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
- }
-
- if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
- codecs.audio = audioPlaylist.attributes.CODECS;
- }
-
- var videoContentType = getMimeForCodec(codecs.video);
- var audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
-
- var keySystemContentTypes = {};
-
- for (var keySystem in keySystemOptions) {
- keySystemContentTypes[keySystem] = {};
-
- if (audioContentType) {
- keySystemContentTypes[keySystem].audioContentType = audioContentType;
- }
-
- if (videoContentType) {
- keySystemContentTypes[keySystem].videoContentType = videoContentType;
- } // Default to using the video playlist's PSSH even though they may be different, as
- // videojs-contrib-eme will only accept one in the options.
- //
- // This shouldn't be an issue for most cases as early intialization will handle all
- // unique PSSH values, and if they aren't, then encrypted events should have the
- // specific information needed for the unique license.
-
-
- if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
- keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
- } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
- // so we need to prevent overwriting the URL entirely
-
-
- if (typeof keySystemOptions[keySystem] === 'string') {
- keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
- }
- }
-
- return videojs__default['default'].mergeOptions(keySystemOptions, keySystemContentTypes);
- };
- /**
- * @typedef {Object} KeySystems
- *
- * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
- * Note: not all options are listed here.
- *
- * @property {Uint8Array} [pssh]
- * Protection System Specific Header
- */
-
- /**
- * Goes through all the playlists and collects an array of KeySystems options objects
- * containing each playlist's keySystems and their pssh values, if available.
- *
- * @param {Object[]} playlists
- * The playlists to look through
- * @param {string[]} keySystems
- * The keySystems to collect pssh values for
- *
- * @return {KeySystems[]}
- * An array of KeySystems objects containing available key systems and their
- * pssh values
- */
-
-
- var getAllPsshKeySystemsOptions = function getAllPsshKeySystemsOptions(playlists, keySystems) {
- return playlists.reduce(function (keySystemsArr, playlist) {
- if (!playlist.contentProtection) {
- return keySystemsArr;
- }
-
- var keySystemsOptions = keySystems.reduce(function (keySystemsObj, keySystem) {
- var keySystemOptions = playlist.contentProtection[keySystem];
-
- if (keySystemOptions && keySystemOptions.pssh) {
- keySystemsObj[keySystem] = {
- pssh: keySystemOptions.pssh
- };
- }
-
- return keySystemsObj;
- }, {});
-
- if (Object.keys(keySystemsOptions).length) {
- keySystemsArr.push(keySystemsOptions);
- }
-
- return keySystemsArr;
- }, []);
- };
- /**
- * Returns a promise that waits for the
- * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
- *
- * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
- * browsers.
- *
- * As per the above ticket, this is particularly important for Chrome, where, if
- * unencrypted content is appended before encrypted content and the key session has not
- * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
- * during playback.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- * @param {Object[]} mainPlaylists
- * The playlists found on the master playlist object
- *
- * @return {Object}
- * Promise that resolves when the key session has been created
- */
-
-
- var waitForKeySessionCreation = function waitForKeySessionCreation(_ref) {
- var player = _ref.player,
- sourceKeySystems = _ref.sourceKeySystems,
- audioMedia = _ref.audioMedia,
- mainPlaylists = _ref.mainPlaylists;
-
- if (!player.eme.initializeMediaKeys) {
- return Promise.resolve();
- } // TODO should all audio PSSH values be initialized for DRM?
- //
- // All unique video rendition pssh values are initialized for DRM, but here only
- // the initial audio playlist license is initialized. In theory, an encrypted
- // event should be fired if the user switches to an alternative audio playlist
- // where a license is required, but this case hasn't yet been tested. In addition, there
- // may be many alternate audio playlists unlikely to be used (e.g., multiple different
- // languages).
-
-
- var playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
- var keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
- var initializationFinishedPromises = [];
- var keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
- // only place where it should not be deduped is for ms-prefixed APIs, but the early
- // return for IE11 above, and the existence of modern EME APIs in addition to
- // ms-prefixed APIs on Edge should prevent this from being a concern.
- // initializeMediaKeys also won't use the webkit-prefixed APIs.
-
- keySystemsOptionsArr.forEach(function (keySystemsOptions) {
- keySessionCreatedPromises.push(new Promise(function (resolve, reject) {
- player.tech_.one('keysessioncreated', resolve);
- }));
- initializationFinishedPromises.push(new Promise(function (resolve, reject) {
- player.eme.initializeMediaKeys({
- keySystems: keySystemsOptions
- }, function (err) {
- if (err) {
- reject(err);
- return;
- }
-
- resolve();
- });
- }));
- }); // The reasons Promise.race is chosen over Promise.any:
- //
- // * Promise.any is only available in Safari 14+.
- // * None of these promises are expected to reject. If they do reject, it might be
- // better here for the race to surface the rejection, rather than mask it by using
- // Promise.any.
-
- return Promise.race([// If a session was previously created, these will all finish resolving without
- // creating a new session, otherwise it will take until the end of all license
- // requests, which is why the key session check is used (to make setup much faster).
- Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
- Promise.race(keySessionCreatedPromises)]);
- };
- /**
- * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
- * there are keySystems on the source, sets up source options to prepare the source for
- * eme.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} media
- * The active media playlist
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- *
- * @return {boolean}
- * Whether or not options were configured and EME is available
- */
-
- var setupEmeOptions = function setupEmeOptions(_ref2) {
- var player = _ref2.player,
- sourceKeySystems = _ref2.sourceKeySystems,
- media = _ref2.media,
- audioMedia = _ref2.audioMedia;
- var sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
-
- if (!sourceOptions) {
- return false;
- }
-
- player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
- // do nothing.
-
- if (sourceOptions && !player.eme) {
- videojs__default['default'].log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
- return false;
- }
-
- return true;
- };
-
- var getVhsLocalStorage = function getVhsLocalStorage() {
- if (!window__default['default'].localStorage) {
- return null;
- }
-
- var storedObject = window__default['default'].localStorage.getItem(LOCAL_STORAGE_KEY);
-
- if (!storedObject) {
- return null;
- }
-
- try {
- return JSON.parse(storedObject);
- } catch (e) {
- // someone may have tampered with the value
- return null;
- }
- };
-
- var updateVhsLocalStorage = function updateVhsLocalStorage(options) {
- if (!window__default['default'].localStorage) {
- return false;
- }
-
- var objectToStore = getVhsLocalStorage();
- objectToStore = objectToStore ? videojs__default['default'].mergeOptions(objectToStore, options) : options;
-
- try {
- window__default['default'].localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
- } catch (e) {
- // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
- // storage is set to 0).
- // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
- // No need to perform any operation.
- return false;
- }
-
- return objectToStore;
- };
- /**
- * Parses VHS-supported media types from data URIs. See
- * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
- * for information on data URIs.
- *
- * @param {string} dataUri
- * The data URI
- *
- * @return {string|Object}
- * The parsed object/string, or the original string if no supported media type
- * was found
- */
-
-
- var expandDataUri = function expandDataUri(dataUri) {
- if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
- return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
- } // no known case for this data URI, return the string as-is
-
-
- return dataUri;
- };
- /**
- * Whether the browser has built-in HLS support.
- */
-
-
- Vhs.supportsNativeHls = function () {
- if (!document__default['default'] || !document__default['default'].createElement) {
- return false;
- }
-
- var video = document__default['default'].createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
-
- if (!videojs__default['default'].getTech('Html5').isSupported()) {
- return false;
- } // HLS manifests can go by many mime-types
-
-
- var canPlay = [// Apple santioned
- 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
- 'audio/mpegurl', // Very common
- 'audio/x-mpegurl', // Very common
- 'application/x-mpegurl', // Included for completeness
- 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
- return canPlay.some(function (canItPlay) {
- return /maybe|probably/i.test(video.canPlayType(canItPlay));
- });
- }();
-
- Vhs.supportsNativeDash = function () {
- if (!document__default['default'] || !document__default['default'].createElement || !videojs__default['default'].getTech('Html5').isSupported()) {
- return false;
- }
-
- return /maybe|probably/i.test(document__default['default'].createElement('video').canPlayType('application/dash+xml'));
- }();
-
- Vhs.supportsTypeNatively = function (type) {
- if (type === 'hls') {
- return Vhs.supportsNativeHls;
- }
-
- if (type === 'dash') {
- return Vhs.supportsNativeDash;
- }
-
- return false;
- };
- /**
- * HLS is a source handler, not a tech. Make sure attempts to use it
- * as one do not cause exceptions.
- */
-
-
- Vhs.isSupported = function () {
- return videojs__default['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
- };
-
- var Component = videojs__default['default'].getComponent('Component');
- /**
- * The Vhs Handler object, where we orchestrate all of the parts
- * of HLS to interact with video.js
- *
- * @class VhsHandler
- * @extends videojs.Component
- * @param {Object} source the soruce object
- * @param {Tech} tech the parent tech object
- * @param {Object} options optional and required options
- */
-
- var VhsHandler = /*#__PURE__*/function (_Component) {
- inheritsLoose(VhsHandler, _Component);
-
- function VhsHandler(source, tech, options) {
- var _this;
-
- _this = _Component.call(this, tech, videojs__default['default'].mergeOptions(options.hls, options.vhs)) || this;
-
- if (options.hls && Object.keys(options.hls).length) {
- videojs__default['default'].log.warn('Using hls options is deprecated. Use vhs instead.');
- } // if a tech level `initialBandwidth` option was passed
- // use that over the VHS level `bandwidth` option
-
-
- if (typeof options.initialBandwidth === 'number') {
- _this.options_.bandwidth = options.initialBandwidth;
- }
-
- _this.logger_ = logger('VhsHandler'); // tech.player() is deprecated but setup a reference to HLS for
- // backwards-compatibility
-
- if (tech.options_ && tech.options_.playerId) {
- var _player = videojs__default['default'](tech.options_.playerId);
-
- if (!_player.hasOwnProperty('hls')) {
- Object.defineProperty(_player, 'hls', {
- get: function get() {
- videojs__default['default'].log.warn('player.hls is deprecated. Use player.tech().vhs instead.');
- tech.trigger({
- type: 'usage',
- name: 'hls-player-access'
- });
- return assertThisInitialized(_this);
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('vhs')) {
- Object.defineProperty(_player, 'vhs', {
- get: function get() {
- videojs__default['default'].log.warn('player.vhs is deprecated. Use player.tech().vhs instead.');
- tech.trigger({
- type: 'usage',
- name: 'vhs-player-access'
- });
- return assertThisInitialized(_this);
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('dash')) {
- Object.defineProperty(_player, 'dash', {
- get: function get() {
- videojs__default['default'].log.warn('player.dash is deprecated. Use player.tech().vhs instead.');
- return assertThisInitialized(_this);
- },
- configurable: true
- });
- }
-
- _this.player_ = _player;
- }
-
- _this.tech_ = tech;
- _this.source_ = source;
- _this.stats = {};
- _this.ignoreNextSeekingEvent_ = false;
-
- _this.setOptions_();
-
- if (_this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
- tech.overrideNativeAudioTracks(true);
- tech.overrideNativeVideoTracks(true);
- } else if (_this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
- // overriding native HLS only works if audio tracks have been emulated
- // error early if we're misconfigured
- throw new Error('Overriding native HLS requires emulated tracks. ' + 'See https://git.io/vMpjB');
- } // listen for fullscreenchange events for this player so that we
- // can adjust our quality selection quickly
-
-
- _this.on(document__default['default'], ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
- var fullscreenElement = document__default['default'].fullscreenElement || document__default['default'].webkitFullscreenElement || document__default['default'].mozFullScreenElement || document__default['default'].msFullscreenElement;
-
- if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
- _this.masterPlaylistController_.fastQualityChange_();
- } else {
- // When leaving fullscreen, since the in page pixel dimensions should be smaller
- // than full screen, see if there should be a rendition switch down to preserve
- // bandwidth.
- _this.masterPlaylistController_.checkABR_();
- }
- });
-
- _this.on(_this.tech_, 'seeking', function () {
- if (this.ignoreNextSeekingEvent_) {
- this.ignoreNextSeekingEvent_ = false;
- return;
- }
-
- this.setCurrentTime(this.tech_.currentTime());
- });
-
- _this.on(_this.tech_, 'error', function () {
- // verify that the error was real and we are loaded
- // enough to have mpc loaded.
- if (this.tech_.error() && this.masterPlaylistController_) {
- this.masterPlaylistController_.pauseLoading();
- }
- });
-
- _this.on(_this.tech_, 'play', _this.play);
-
- return _this;
- }
-
- var _proto = VhsHandler.prototype;
-
- _proto.setOptions_ = function setOptions_() {
- var _this2 = this;
-
- // defaults
- this.options_.withCredentials = this.options_.withCredentials || false;
- this.options_.handleManifestRedirects = this.options_.handleManifestRedirects === false ? false : true;
- this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
- this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
- this.options_.smoothQualityChange = this.options_.smoothQualityChange || false;
- this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
- this.options_.customTagParsers = this.options_.customTagParsers || [];
- this.options_.customTagMappers = this.options_.customTagMappers || [];
- this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
-
- if (typeof this.options_.blacklistDuration !== 'number') {
- this.options_.blacklistDuration = 5 * 60;
- }
-
- if (typeof this.options_.bandwidth !== 'number') {
- if (this.options_.useBandwidthFromLocalStorage) {
- var storedObject = getVhsLocalStorage();
-
- if (storedObject && storedObject.bandwidth) {
- this.options_.bandwidth = storedObject.bandwidth;
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-bandwidth-from-local-storage'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-bandwidth-from-local-storage'
- });
- }
-
- if (storedObject && storedObject.throughput) {
- this.options_.throughput = storedObject.throughput;
- this.tech_.trigger({
- type: 'usage',
- name: 'vhs-throughput-from-local-storage'
- });
- this.tech_.trigger({
- type: 'usage',
- name: 'hls-throughput-from-local-storage'
- });
- }
- }
- } // if bandwidth was not set by options or pulled from local storage, start playlist
- // selection at a reasonable bandwidth
-
-
- if (typeof this.options_.bandwidth !== 'number') {
- this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
- } // If the bandwidth number is unchanged from the initial setting
- // then this takes precedence over the enableLowInitialPlaylist option
-
-
- this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
-
- ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'smoothQualityChange', 'customTagParsers', 'customTagMappers', 'handleManifestRedirects', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'experimentalBufferBasedABR', 'liveRangeSafeTimeDelta', 'experimentalLLHLS'].forEach(function (option) {
- if (typeof _this2.source_[option] !== 'undefined') {
- _this2.options_[option] = _this2.source_[option];
- }
- });
- this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
- this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
- }
- /**
- * called when player.src gets called, handle a new source
- *
- * @param {Object} src the source object to handle
- */
- ;
-
- _proto.src = function src(_src, type) {
- var _this3 = this;
-
- // do nothing if the src is falsey
- if (!_src) {
- return;
- }
-
- this.setOptions_(); // add master playlist controller options
-
- this.options_.src = expandDataUri(this.source_.src);
- this.options_.tech = this.tech_;
- this.options_.externVhs = Vhs;
- this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
-
- this.options_.seekTo = function (time) {
- _this3.tech_.setCurrentTime(time);
- };
-
- if (this.options_.smoothQualityChange) {
- videojs__default['default'].log.warn('smoothQualityChange is deprecated and will be removed in the next major version');
- }
-
- this.masterPlaylistController_ = new MasterPlaylistController(this.options_);
- var playbackWatcherOptions = videojs__default['default'].mergeOptions({
- liveRangeSafeTimeDelta: SAFE_TIME_DELTA
- }, this.options_, {
- seekable: function seekable() {
- return _this3.seekable();
- },
- media: function media() {
- return _this3.masterPlaylistController_.media();
- },
- masterPlaylistController: this.masterPlaylistController_
- });
- this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
- this.masterPlaylistController_.on('error', function () {
- var player = videojs__default['default'].players[_this3.tech_.options_.playerId];
- var error = _this3.masterPlaylistController_.error;
-
- if (typeof error === 'object' && !error.code) {
- error.code = 3;
- } else if (typeof error === 'string') {
- error = {
- message: error,
- code: 3
- };
- }
-
- player.error(error);
- });
- var defaultSelector = this.options_.experimentalBufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
- // compatibility with < v2
-
- this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
- this.masterPlaylistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
-
- this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
- this.mediaSource = this.masterPlaylistController_.mediaSource; // Proxy assignment of some properties to the master playlist
- // controller. Using a custom property for backwards compatibility
- // with < v2
-
- Object.defineProperties(this, {
- selectPlaylist: {
- get: function get() {
- return this.masterPlaylistController_.selectPlaylist;
- },
- set: function set(selectPlaylist) {
- this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
- }
- },
- throughput: {
- get: function get() {
- return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
- },
- set: function set(throughput) {
- this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
- // for the cumulative average
-
- this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
- }
- },
- bandwidth: {
- get: function get() {
- return this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
- },
- set: function set(bandwidth) {
- this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
- // `count` is set to zero that current value of `rate` isn't included
- // in the cumulative average
-
- this.masterPlaylistController_.mainSegmentLoader_.throughput = {
- rate: 0,
- count: 0
- };
- }
- },
-
- /**
- * `systemBandwidth` is a combination of two serial processes bit-rates. The first
- * is the network bitrate provided by `bandwidth` and the second is the bitrate of
- * the entire process after that - decryption, transmuxing, and appending - provided
- * by `throughput`.
- *
- * Since the two process are serial, the overall system bandwidth is given by:
- * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
- */
- systemBandwidth: {
- get: function get() {
- var invBandwidth = 1 / (this.bandwidth || 1);
- var invThroughput;
-
- if (this.throughput > 0) {
- invThroughput = 1 / this.throughput;
- } else {
- invThroughput = 0;
- }
-
- var systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
- return systemBitrate;
- },
- set: function set() {
- videojs__default['default'].log.error('The "systemBandwidth" property is read-only');
- }
- }
- });
-
- if (this.options_.bandwidth) {
- this.bandwidth = this.options_.bandwidth;
- }
-
- if (this.options_.throughput) {
- this.throughput = this.options_.throughput;
- }
-
- Object.defineProperties(this.stats, {
- bandwidth: {
- get: function get() {
- return _this3.bandwidth || 0;
- },
- enumerable: true
- },
- mediaRequests: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequests_() || 0;
- },
- enumerable: true
- },
- mediaRequestsAborted: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsAborted_() || 0;
- },
- enumerable: true
- },
- mediaRequestsTimedout: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsTimedout_() || 0;
- },
- enumerable: true
- },
- mediaRequestsErrored: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaRequestsErrored_() || 0;
- },
- enumerable: true
- },
- mediaTransferDuration: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaTransferDuration_() || 0;
- },
- enumerable: true
- },
- mediaBytesTransferred: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaBytesTransferred_() || 0;
- },
- enumerable: true
- },
- mediaSecondsLoaded: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaSecondsLoaded_() || 0;
- },
- enumerable: true
- },
- mediaAppends: {
- get: function get() {
- return _this3.masterPlaylistController_.mediaAppends_() || 0;
- },
- enumerable: true
- },
- mainAppendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.mainAppendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- audioAppendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.audioAppendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- appendsToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.appendsToLoadedData_() || 0;
- },
- enumerable: true
- },
- timeToLoadedData: {
- get: function get() {
- return _this3.masterPlaylistController_.timeToLoadedData_() || 0;
- },
- enumerable: true
- },
- buffered: {
- get: function get() {
- return timeRangesToArray(_this3.tech_.buffered());
- },
- enumerable: true
- },
- currentTime: {
- get: function get() {
- return _this3.tech_.currentTime();
- },
- enumerable: true
- },
- currentSource: {
- get: function get() {
- return _this3.tech_.currentSource_;
- },
- enumerable: true
- },
- currentTech: {
- get: function get() {
- return _this3.tech_.name_;
- },
- enumerable: true
- },
- duration: {
- get: function get() {
- return _this3.tech_.duration();
- },
- enumerable: true
- },
- master: {
- get: function get() {
- return _this3.playlists.master;
- },
- enumerable: true
- },
- playerDimensions: {
- get: function get() {
- return _this3.tech_.currentDimensions();
- },
- enumerable: true
- },
- seekable: {
- get: function get() {
- return timeRangesToArray(_this3.tech_.seekable());
- },
- enumerable: true
- },
- timestamp: {
- get: function get() {
- return Date.now();
- },
- enumerable: true
- },
- videoPlaybackQuality: {
- get: function get() {
- return _this3.tech_.getVideoPlaybackQuality();
- },
- enumerable: true
- }
- });
- this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
- this.tech_.on('bandwidthupdate', function () {
- if (_this3.options_.useBandwidthFromLocalStorage) {
- updateVhsLocalStorage({
- bandwidth: _this3.bandwidth,
- throughput: Math.round(_this3.throughput)
- });
- }
- });
- this.masterPlaylistController_.on('selectedinitialmedia', function () {
- // Add the manual rendition mix-in to VhsHandler
- renditionSelectionMixin(_this3);
- });
- this.masterPlaylistController_.sourceUpdater_.on('createdsourcebuffers', function () {
- _this3.setupEme_();
- }); // the bandwidth of the primary segment loader is our best
- // estimate of overall bandwidth
-
- this.on(this.masterPlaylistController_, 'progress', function () {
- this.tech_.trigger('progress');
- }); // In the live case, we need to ignore the very first `seeking` event since
- // that will be the result of the seek-to-live behavior
-
- this.on(this.masterPlaylistController_, 'firstplay', function () {
- this.ignoreNextSeekingEvent_ = true;
- });
- this.setupQualityLevels_(); // do nothing if the tech has been disposed already
- // this can occur if someone sets the src in player.ready(), for instance
-
- if (!this.tech_.el()) {
- return;
- }
-
- this.mediaSourceUrl_ = window__default['default'].URL.createObjectURL(this.masterPlaylistController_.mediaSource);
- this.tech_.src(this.mediaSourceUrl_);
- }
- /**
- * If necessary and EME is available, sets up EME options and waits for key session
- * creation.
- *
- * This function also updates the source updater so taht it can be used, as for some
- * browsers, EME must be configured before content is appended (if appending unencrypted
- * content before encrypted content).
- */
- ;
-
- _proto.setupEme_ = function setupEme_() {
- var _this4 = this;
-
- var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
- var didSetupEmeOptions = setupEmeOptions({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- media: this.playlists.media(),
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
- }); // In IE11 this is too early to initialize media keys, and IE11 does not support
- // promises.
-
- if (videojs__default['default'].browser.IE_VERSION === 11 || !didSetupEmeOptions) {
- // If EME options were not set up, we've done all we could to initialize EME.
- this.masterPlaylistController_.sourceUpdater_.initializedEme();
- return;
- }
-
- this.logger_('waiting for EME key session creation');
- waitForKeySessionCreation({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
- mainPlaylists: this.playlists.master.playlists
- }).then(function () {
- _this4.logger_('created EME key session');
-
- _this4.masterPlaylistController_.sourceUpdater_.initializedEme();
- }).catch(function (err) {
- _this4.logger_('error while creating EME key session', err);
-
- _this4.player_.error({
- message: 'Failed to initialize media keys for EME',
- code: 3
- });
- });
- }
- /**
- * Initializes the quality levels and sets listeners to update them.
- *
- * @method setupQualityLevels_
- * @private
- */
- ;
-
- _proto.setupQualityLevels_ = function setupQualityLevels_() {
- var _this5 = this;
-
- var player = videojs__default['default'].players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
- // or qualityLevels_ listeners have already been setup, do nothing.
-
- if (!player || !player.qualityLevels || this.qualityLevels_) {
- return;
- }
-
- this.qualityLevels_ = player.qualityLevels();
- this.masterPlaylistController_.on('selectedinitialmedia', function () {
- handleVhsLoadedMetadata(_this5.qualityLevels_, _this5);
- });
- this.playlists.on('mediachange', function () {
- handleVhsMediaChange(_this5.qualityLevels_, _this5.playlists);
- });
- }
- /**
- * return the version
- */
- ;
-
- VhsHandler.version = function version$5() {
- return {
- '@videojs/http-streaming': version$4,
- 'mux.js': version$3,
- 'mpd-parser': version$2,
- 'm3u8-parser': version$1,
- 'aes-decrypter': version
- };
- }
- /**
- * return the version
- */
- ;
-
- _proto.version = function version() {
- return this.constructor.version();
- };
-
- _proto.canChangeType = function canChangeType() {
- return SourceUpdater.canChangeType();
- }
- /**
- * Begin playing the video.
- */
- ;
-
- _proto.play = function play() {
- this.masterPlaylistController_.play();
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.setCurrentTime = function setCurrentTime(currentTime) {
- this.masterPlaylistController_.setCurrentTime(currentTime);
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.duration = function duration() {
- return this.masterPlaylistController_.duration();
- }
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- ;
-
- _proto.seekable = function seekable() {
- return this.masterPlaylistController_.seekable();
- }
- /**
- * Abort all outstanding work and cleanup.
- */
- ;
-
- _proto.dispose = function dispose() {
- if (this.playbackWatcher_) {
- this.playbackWatcher_.dispose();
- }
-
- if (this.masterPlaylistController_) {
- this.masterPlaylistController_.dispose();
- }
-
- if (this.qualityLevels_) {
- this.qualityLevels_.dispose();
- }
-
- if (this.player_) {
- delete this.player_.vhs;
- delete this.player_.dash;
- delete this.player_.hls;
- }
-
- if (this.tech_ && this.tech_.vhs) {
- delete this.tech_.vhs;
- } // don't check this.tech_.hls as it will log a deprecated warning
-
-
- if (this.tech_) {
- delete this.tech_.hls;
- }
-
- if (this.mediaSourceUrl_ && window__default['default'].URL.revokeObjectURL) {
- window__default['default'].URL.revokeObjectURL(this.mediaSourceUrl_);
- this.mediaSourceUrl_ = null;
- }
-
- _Component.prototype.dispose.call(this);
- };
-
- _proto.convertToProgramTime = function convertToProgramTime(time, callback) {
- return getProgramTime({
- playlist: this.masterPlaylistController_.media(),
- time: time,
- callback: callback
- });
- } // the player must be playing before calling this
- ;
-
- _proto.seekToProgramTime = function seekToProgramTime$1(programTime, callback, pauseAfterSeek, retryCount) {
- if (pauseAfterSeek === void 0) {
- pauseAfterSeek = true;
- }
-
- if (retryCount === void 0) {
- retryCount = 2;
- }
-
- return seekToProgramTime({
- programTime: programTime,
- playlist: this.masterPlaylistController_.media(),
- retryCount: retryCount,
- pauseAfterSeek: pauseAfterSeek,
- seekTo: this.options_.seekTo,
- tech: this.options_.tech,
- callback: callback
- });
- };
-
- return VhsHandler;
- }(Component);
- /**
- * The Source Handler object, which informs video.js what additional
- * MIME types are supported and sets up playback. It is registered
- * automatically to the appropriate tech based on the capabilities of
- * the browser it is running in. It is not necessary to use or modify
- * this object in normal usage.
- */
-
-
- var VhsSourceHandler = {
- name: 'videojs-http-streaming',
- VERSION: version$4,
- canHandleSource: function canHandleSource(srcObj, options) {
- if (options === void 0) {
- options = {};
- }
-
- var localOptions = videojs__default['default'].mergeOptions(videojs__default['default'].options, options);
- return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
- },
- handleSource: function handleSource(source, tech, options) {
- if (options === void 0) {
- options = {};
- }
-
- var localOptions = videojs__default['default'].mergeOptions(videojs__default['default'].options, options);
- tech.vhs = new VhsHandler(source, tech, localOptions);
-
- if (!videojs__default['default'].hasOwnProperty('hls')) {
- Object.defineProperty(tech, 'hls', {
- get: function get() {
- videojs__default['default'].log.warn('player.tech().hls is deprecated. Use player.tech().vhs instead.');
- return tech.vhs;
- },
- configurable: true
- });
- }
-
- tech.vhs.xhr = xhrFactory();
- tech.vhs.src(source.src, source.type);
- return tech.vhs;
- },
- canPlayType: function canPlayType(type, options) {
- if (options === void 0) {
- options = {};
- }
-
- var _videojs$mergeOptions = videojs__default['default'].mergeOptions(videojs__default['default'].options, options),
- _videojs$mergeOptions2 = _videojs$mergeOptions.vhs.overrideNative,
- overrideNative = _videojs$mergeOptions2 === void 0 ? !videojs__default['default'].browser.IS_ANY_SAFARI : _videojs$mergeOptions2;
-
- var supportedType = simpleTypeFromSourceType(type);
- var canUseMsePlayback = supportedType && (!Vhs.supportsTypeNatively(supportedType) || overrideNative);
- return canUseMsePlayback ? 'maybe' : '';
- }
- };
- /**
- * Check to see if the native MediaSource object exists and supports
- * an MP4 container with both H.264 video and AAC-LC audio.
- *
- * @return {boolean} if native media sources are supported
- */
-
- var supportsNativeMediaSources = function supportsNativeMediaSources() {
- return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
- }; // register source handlers with the appropriate techs
-
-
- if (supportsNativeMediaSources()) {
- videojs__default['default'].getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
- }
-
- videojs__default['default'].VhsHandler = VhsHandler;
- Object.defineProperty(videojs__default['default'], 'HlsHandler', {
- get: function get() {
- videojs__default['default'].log.warn('videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.');
- return VhsHandler;
- },
- configurable: true
- });
- videojs__default['default'].VhsSourceHandler = VhsSourceHandler;
- Object.defineProperty(videojs__default['default'], 'HlsSourceHandler', {
- get: function get() {
- videojs__default['default'].log.warn('videojs.HlsSourceHandler is deprecated. ' + 'Use videojs.VhsSourceHandler instead.');
- return VhsSourceHandler;
- },
- configurable: true
- });
- videojs__default['default'].Vhs = Vhs;
- Object.defineProperty(videojs__default['default'], 'Hls', {
- get: function get() {
- videojs__default['default'].log.warn('videojs.Hls is deprecated. Use videojs.Vhs instead.');
- return Vhs;
- },
- configurable: true
- });
-
- if (!videojs__default['default'].use) {
- videojs__default['default'].registerComponent('Hls', Vhs);
- videojs__default['default'].registerComponent('Vhs', Vhs);
- }
-
- videojs__default['default'].options.vhs = videojs__default['default'].options.vhs || {};
- videojs__default['default'].options.hls = videojs__default['default'].options.hls || {};
-
- if (videojs__default['default'].registerPlugin) {
- videojs__default['default'].registerPlugin('reloadSourceOnError', reloadSourceOnError);
- } else {
- videojs__default['default'].plugin('reloadSourceOnError', reloadSourceOnError);
- }
-
- exports.LOCAL_STORAGE_KEY = LOCAL_STORAGE_KEY;
- exports.Vhs = Vhs;
- exports.VhsHandler = VhsHandler;
- exports.VhsSourceHandler = VhsSourceHandler;
- exports.emeKeySystems = emeKeySystems;
- exports.expandDataUri = expandDataUri;
- exports.getAllPsshKeySystemsOptions = getAllPsshKeySystemsOptions;
- exports.setupEmeOptions = setupEmeOptions;
- exports.simpleTypeFromSourceType = simpleTypeFromSourceType;
- exports.waitForKeySessionCreation = waitForKeySessionCreation;
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
-})));
diff --git a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.min.js b/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.min.js
deleted file mode 100644
index 777e384..0000000
--- a/node_modules/@videojs/http-streaming/dist/videojs-http-streaming.min.js
+++ /dev/null
@@ -1,6 +0,0 @@
-/*! @name @videojs/http-streaming @version 2.9.1 @license Apache-2.0 */
-!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("global/document"),require("global/window"),require("video.js"),require("xmldom")):"function"==typeof define&&define.amd?define(["exports","global/document","global/window","video.js","xmldom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).httpStreaming={},e.document,e.window,e.videojs,e.window)}(this,(function(e,t,i,n,r){"use strict";function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=a(t),o=a(i),u=a(n);function d(e,t,i){return e(i={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&i.path)}},i.exports),i.exports}var l=d((function(e){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e},e.exports.default=e.exports,e.exports.__esModule=!0})),c=d((function(e){function t(i,n){return e.exports=t=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},e.exports.default=e.exports,e.exports.__esModule=!0,t(i,n)}e.exports=t,e.exports.default=e.exports,e.exports.__esModule=!0})),h=d((function(e){e.exports=function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,c(e,t)},e.exports.default=e.exports,e.exports.__esModule=!0})),f=d((function(e,t){var i,n,r,a,s;i=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/,n=/^([^\/?#]*)(.*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var r=s.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=s.normalizePath(r.path),s.buildURLFromParts(r)}var a=s.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):t;var o=s.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var u=n.exec(o.path);o.netLoc=u[1],o.path=u[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var l=o.path,c=l.substring(0,l.lastIndexOf("/")+1)+a.path;d.path=s.normalizePath(c)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=i.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(d)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(a,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=s})),p="http://example.com",m=function(e,t){if(/^[a-z]+:/i.test(t))return t;/^data:/.test(e)&&(e=o.default.location&&o.default.location.href||"");var i="function"==typeof o.default.URL,n=/^\/\//.test(e),r=!o.default.location&&!/\/\//i.test(e);if(i?e=new o.default.URL(e,o.default.location||p):/\/\//i.test(e)||(e=f.buildAbsoluteURL(o.default.location&&o.default.location.href||"",e)),i){var a=new URL(t,e);return r?a.href.slice(p.length):n?a.href.slice(a.protocol.length):a.href}return f.buildAbsoluteURL(e,t)},g=m,y=function(e,t,i){return e&&i&&i.responseURL&&t!==i.responseURL?i.responseURL:t},_=function(e){return u.default.log.debug?u.default.log.debug.bind(u.default,"VHS:",e+" >"):function(){}},v=d((function(e){function t(){return e.exports=t=Object.assign||function(e){for(var t=1;t-1},t.trigger=function(e){var t=this.listeners[e];if(t)if(2===arguments.length)for(var i=t.length,n=0;n-1;t=this.buffer.indexOf("\n"))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)},t}(T),I=String.fromCharCode(9),E=function(e){var t=/([0-9.]*)?@?([0-9.]*)?/.exec(e||""),i={};return t[1]&&(i.length=parseInt(t[1],10)),t[2]&&(i.offset=parseInt(t[2],10)),i},w=function(e){for(var t,i=e.split(new RegExp('(?:^|,)((?:[^=]*)=(?:"[^"]*"|[^,]*))')),n={},r=i.length;r--;)""!==i[r]&&((t=/([^=]*)=(.*)/.exec(i[r]).slice(1))[0]=t[0].replace(/^\s+|\s+$/g,""),t[1]=t[1].replace(/^\s+|\s+$/g,""),t[1]=t[1].replace(/^['"](.*)['"]$/g,"$1"),n[t[0]]=t[1]);return n},A=function(e){function t(){var t;return(t=e.call(this)||this).customParsers=[],t.tagMappers=[],t}h(t,e);var i=t.prototype;return i.push=function(e){var t,i,n=this;0!==(e=e.trim()).length&&("#"===e[0]?this.tagMappers.reduce((function(t,i){var n=i(e);return n===e?t:t.concat([n])}),[e]).forEach((function(e){for(var r=0;r0&&(s.duration=e.duration),0===e.duration&&(s.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=a},key:function(){if(e.attributes)if("NONE"!==e.attributes.METHOD)if(e.attributes.URI){if("com.apple.streamingkeydelivery"===e.attributes.KEYFORMAT)return this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:e.attributes});if("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"===e.attributes.KEYFORMAT)return-1===["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(e.attributes.METHOD)?void this.trigger("warn",{message:"invalid key method provided for Widevine"}):("SAMPLE-AES-CENC"===e.attributes.METHOD&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),"data:text/plain;base64,"!==e.attributes.URI.substring(0,23)?void this.trigger("warn",{message:"invalid key URI provided for Widevine"}):e.attributes.KEYID&&"0x"===e.attributes.KEYID.substring(0,2)?(this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:e.attributes.KEYFORMAT,keyId:e.attributes.KEYID.substring(2)},pssh:b(e.attributes.URI.split(",")[1])})):void this.trigger("warn",{message:"invalid key ID provided for Widevine"}));e.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),n={method:e.attributes.METHOD||"AES-128",uri:e.attributes.URI},void 0!==e.attributes.IV&&(n.iv=e.attributes.IV)}else this.trigger("warn",{message:"ignoring key declaration without URI"});else n=null;else this.trigger("warn",{message:"ignoring key declaration without attribute list"})},"media-sequence":function(){isFinite(e.number)?this.manifest.mediaSequence=e.number:this.trigger("warn",{message:"ignoring invalid media sequence: "+e.number})},"discontinuity-sequence":function(){isFinite(e.number)?(this.manifest.discontinuitySequence=e.number,c=e.number):this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+e.number})},"playlist-type":function(){/VOD|EVENT/.test(e.playlistType)?this.manifest.playlistType=e.playlistType:this.trigger("warn",{message:"ignoring unknown playlist type: "+e.playlist})},map:function(){i={},e.uri&&(i.uri=e.uri),e.byterange&&(i.byterange=e.byterange),n&&(i.key=n)},"stream-inf":function(){this.manifest.playlists=a,this.manifest.mediaGroups=this.manifest.mediaGroups||d,e.attributes?(s.attributes||(s.attributes={}),v(s.attributes,e.attributes)):this.trigger("warn",{message:"ignoring empty stream-inf attributes"})},media:function(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||d,e.attributes&&e.attributes.TYPE&&e.attributes["GROUP-ID"]&&e.attributes.NAME){var i=this.manifest.mediaGroups[e.attributes.TYPE];i[e.attributes["GROUP-ID"]]=i[e.attributes["GROUP-ID"]]||{},t=i[e.attributes["GROUP-ID"]],(l={default:/yes/i.test(e.attributes.DEFAULT)}).default?l.autoselect=!0:l.autoselect=/yes/i.test(e.attributes.AUTOSELECT),e.attributes.LANGUAGE&&(l.language=e.attributes.LANGUAGE),e.attributes.URI&&(l.uri=e.attributes.URI),e.attributes["INSTREAM-ID"]&&(l.instreamId=e.attributes["INSTREAM-ID"]),e.attributes.CHARACTERISTICS&&(l.characteristics=e.attributes.CHARACTERISTICS),e.attributes.FORCED&&(l.forced=/yes/i.test(e.attributes.FORCED)),t[e.attributes.NAME]=l}else this.trigger("warn",{message:"ignoring incomplete or missing media group"})},discontinuity:function(){c+=1,s.discontinuity=!0,this.manifest.discontinuityStarts.push(a.length)},"program-date-time":function(){void 0===this.manifest.dateTimeString&&(this.manifest.dateTimeString=e.dateTimeString,this.manifest.dateTimeObject=e.dateTimeObject),s.dateTimeString=e.dateTimeString,s.dateTimeObject=e.dateTimeObject},targetduration:function(){!isFinite(e.duration)||e.duration<0?this.trigger("warn",{message:"ignoring invalid target duration: "+e.duration}):(this.manifest.targetDuration=e.duration,P.call(this,this.manifest))},start:function(){e.attributes&&!isNaN(e.attributes["TIME-OFFSET"])?this.manifest.start={timeOffset:e.attributes["TIME-OFFSET"],precise:e.attributes.PRECISE}:this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"})},"cue-out":function(){s.cueOut=e.data},"cue-out-cont":function(){s.cueOutCont=e.data},"cue-in":function(){s.cueIn=e.data},skip:function(){this.manifest.skip=L(e.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",e.attributes,["SKIPPED-SEGMENTS"])},part:function(){var t=this;o=!0;var i=this.manifest.segments.length,n=L(e.attributes);s.parts=s.parts||[],s.parts.push(n),n.byterange&&(n.byterange.hasOwnProperty("offset")||(n.byterange.offset=f),f=n.byterange.offset+n.byterange.length);var r=s.parts.length-1;this.warnOnMissingAttributes_("#EXT-X-PART #"+r+" for segment #"+i,e.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((function(e,i){e.hasOwnProperty("lastPart")||t.trigger("warn",{message:"#EXT-X-RENDITION-REPORT #"+i+" lacks required attribute(s): LAST-PART"})}))},"server-control":function(){var t=this.manifest.serverControl=L(e.attributes);t.hasOwnProperty("canBlockReload")||(t.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),P.call(this,this.manifest),t.canSkipDateranges&&!t.hasOwnProperty("canSkipUntil")&&this.trigger("warn",{message:"#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"})},"preload-hint":function(){var t=this.manifest.segments.length,i=L(e.attributes),n=i.type&&"PART"===i.type;s.preloadHints=s.preloadHints||[],s.preloadHints.push(i),i.byterange&&(i.byterange.hasOwnProperty("offset")||(i.byterange.offset=n?f:0,n&&(f=i.byterange.offset+i.byterange.length)));var r=s.preloadHints.length-1;if(this.warnOnMissingAttributes_("#EXT-X-PRELOAD-HINT #"+r+" for segment #"+t,e.attributes,["TYPE","URI"]),i.type)for(var a=0;a=t}))},V=function(e,t){return W(e,(function(e){return e-q>=t}))},j=function(e){var t=[];if(!e||!e.length)return"";for(var i=0;i "+e.end(i));return t.join(", ")},X=function(e){for(var t=[],i=0;i0;return i&&t.serverControl&&t.serverControl.partHoldBack?t.serverControl.partHoldBack:i&&t.partTargetDuration?3*t.partTargetDuration:t.serverControl&&t.serverControl.holdBack?t.serverControl.holdBack:t.targetDuration?3*t.targetDuration:0},Z=function(e,t,i){if(void 0===t&&(t=e.mediaSequence+e.segments.length),tr){var s=[r,n];n=s[0],r=s[1]}if(n<0){for(var o=n;oDate.now()},re=function(e){return e.excludeUntil&&e.excludeUntil===1/0},ae=function(e){var t=ne(e);return!e.disabled&&!t},se=function(e,t){return t.attributes&&t.attributes[e]},oe=function(e,t){if(1===e.playlists.length)return!0;var i=t.attributes.BANDWIDTH||Number.MAX_VALUE;return 0===e.playlists.filter((function(e){return!!ae(e)&&(e.attributes.BANDWIDTH||0)0)for(var c=u-1;c>=0;c--){var h=o[c];if((s+=h.duration)+q>0)return{partIndex:h.partIndex,segmentIndex:h.segmentIndex,startTime:a-te({defaultDuration:t.targetDuration,durationList:o,startIndex:u,endIndex:c})}}return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:i}}if(u<0){for(var f=u;f<0;f++)if((s-=t.targetDuration)<0)return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:i};u=0}for(var p=u;p-1&&s!==a.length-1&&i.push("_HLS_part="+s),(s>-1||a.length)&&r--}i.unshift("_HLS_msn="+r)}return t.serverControl&&t.serverControl.canSkipUntil&&i.unshift("_HLS_skip="+(t.serverControl.canSkipDateranges?"v2":"YES")),i.forEach((function(t,i){e+=(0===i?"?":"&")+t})),e}(i,t)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:i,withCredentials:this.withCredentials},(function(t,i){if(e.request)return t?e.playlistRequestError(e.request,e.media(),"HAVE_METADATA"):void e.haveMetadata({playlistString:e.request.responseText,url:e.media().uri,id:e.media().id})}))}},i.playlistRequestError=function(e,t,i){var n=t.uri,r=t.id;this.request=null,i&&(this.state=i),this.error={playlist:this.master.playlists[r],status:e.status,message:"HLS playlist request error at URL: "+n+".",responseText:e.responseText,code:e.status>=500?4:2},this.trigger("error")},i.parseManifest_=function(e){var t=this,i=e.url;return function(e){var t=e.onwarn,i=e.oninfo,n=e.manifestString,r=e.customTagParsers,a=void 0===r?[]:r,s=e.customTagMappers,o=void 0===s?[]:s,u=e.experimentalLLHLS,d=new k;t&&d.on("warn",t),i&&d.on("info",i),a.forEach((function(e){return d.addParser(e)})),o.forEach((function(e){return d.addTagMapper(e)})),d.push(n),d.end();var l=d.manifest;if(u||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach((function(e){l.hasOwnProperty(e)&&delete l[e]})),l.segments&&l.segments.forEach((function(e){["parts","preloadHints"].forEach((function(t){e.hasOwnProperty(t)&&delete e[t]}))}))),!l.targetDuration){var c=10;l.segments&&l.segments.length&&(c=l.segments.reduce((function(e,t){return Math.max(e,t.duration)}),0)),t&&t("manifest has no targetDuration defaulting to "+c),l.targetDuration=c}var h=K(l);if(h.length&&!l.partTargetDuration){var f=h.reduce((function(e,t){return Math.max(e,t.duration)}),0);t&&(t("manifest has no partTargetDuration defaulting to "+f),he.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),l.partTargetDuration=f}return l}({onwarn:function(e){var n=e.message;return t.logger_("m3u8-parser warn for "+i+": "+n)},oninfo:function(e){var n=e.message;return t.logger_("m3u8-parser info for "+i+": "+n)},manifestString:e.manifestString,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,experimentalLLHLS:this.experimentalLLHLS})},i.haveMetadata=function(e){var t=this,i=e.playlistString,n=e.playlistObject,r=e.url,a=e.id;this.request=null,this.state="HAVE_METADATA";var s=n||this.parseManifest_({url:r,manifestString:i});s.lastRequest=Date.now(),me({playlist:s,uri:r,id:a});var u=Ie(this.master,s);this.targetDuration=s.partTargetDuration||s.targetDuration,u?(this.master=u,this.media_=this.master.playlists[a]):this.trigger("playlistunchanged"),this.media().endList||(o.default.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=o.default.setTimeout((function(){t.trigger("mediaupdatetimeout")}),Ee(this.media(),!!u))),this.trigger("loadedplaylist")},i.dispose=function(){this.trigger("dispose"),this.stopRequest(),o.default.clearTimeout(this.mediaUpdateTimeout),o.default.clearTimeout(this.finalRenditionTimeout),this.off()},i.stopRequest=function(){if(this.request){var e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}},i.media=function(e,t){var i=this;if(!e)return this.media_;if("HAVE_NOTHING"===this.state)throw new Error("Cannot switch media playlist from "+this.state);if("string"==typeof e){if(!this.master.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.master.playlists[e]}if(o.default.clearTimeout(this.finalRenditionTimeout),t){var n=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=o.default.setTimeout(this.media.bind(this,e,!1),n)}else{var r=this.state,a=!this.media_||e.id!==this.media_.id,s=this.master.playlists[e.id];if(s&&s.endList||e.endList&&e.segments.length)return this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=e,void(a&&(this.trigger("mediachanging"),"HAVE_MASTER"===r?this.trigger("loadedmetadata"):this.trigger("mediachange")));if(a){if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials},(function(t,n){if(i.request){if(e.lastRequest=Date.now(),e.resolvedUri=y(i.handleManifestRedirects,e.resolvedUri,n),t)return i.playlistRequestError(i.request,e,r);i.haveMetadata({playlistString:n.responseText,url:e.uri,id:e.id}),"HAVE_MASTER"===r?i.trigger("loadedmetadata"):i.trigger("mediachange")}}))}}},i.pause=function(){this.stopRequest(),o.default.clearTimeout(this.mediaUpdateTimeout),"HAVE_NOTHING"===this.state&&(this.started=!1),"SWITCHING_MEDIA"===this.state?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MASTER":"HAVE_CURRENT_METADATA"===this.state&&(this.state="HAVE_METADATA")},i.load=function(e){var t=this;o.default.clearTimeout(this.mediaUpdateTimeout);var i=this.media();if(e){var n=i?(i.partTargetDuration||i.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=o.default.setTimeout((function(){return t.load()}),n)}else this.started?i&&!i.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist"):this.start()},i.start=function(){var e=this;if(this.started=!0,"object"==typeof this.src)return this.src.uri||(this.src.uri=o.default.location.href),this.src.resolvedUri=this.src.uri,void setTimeout((function(){e.setupInitialPlaylist(e.src)}),0);this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials},(function(t,i){if(e.request){if(e.request=null,t)return e.error={status:i.status,message:"HLS playlist request error at URL: "+e.src+".",responseText:i.responseText,code:2},"HAVE_NOTHING"===e.state&&(e.started=!1),e.trigger("error");e.src=y(e.handleManifestRedirects,e.src,i);var n=e.parseManifest_({manifestString:i.responseText,url:e.src});e.setupInitialPlaylist(n)}}))},i.srcUri=function(){return"string"==typeof this.src?this.src:this.src.uri},i.setupInitialPlaylist=function(e){if(this.state="HAVE_MASTER",e.playlists)return this.master=e,ge(this.master,this.srcUri()),e.playlists.forEach((function(e){e.segments=be(e),e.segments.forEach((function(t){Te(t,e.resolvedUri)}))})),this.trigger("loadedplaylist"),void(this.request||this.media(this.master.playlists[0]));var t=this.srcUri()||o.default.location.href;this.master=function(e,t){var i=fe(0,t),n={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:o.default.location.href,resolvedUri:o.default.location.href,playlists:[{uri:t,id:i,resolvedUri:t,attributes:{}}]};return n.playlists[i]=n.playlists[0],n.playlists[t]=n.playlists[0],n}(0,t),this.haveMetadata({playlistObject:e,url:t,id:this.master.playlists[0].id}),this.trigger("loadedmetadata")},t}(_e),Ae=u.default.xhr,Le=u.default.mergeOptions,Pe=function(e,t,i,n){var r="arraybuffer"===e.responseType?e.response:e.responseText;!t&&r&&(e.responseTime=Date.now(),e.roundTripTime=e.responseTime-e.requestTime,e.bytesReceived=r.byteLength||r.length,e.bandwidth||(e.bandwidth=Math.floor(e.bytesReceived/e.roundTripTime*8*1e3))),i.headers&&(e.responseHeaders=i.headers),t&&"ETIMEDOUT"===t.code&&(e.timedout=!0),t||e.aborted||200===i.statusCode||206===i.statusCode||0===i.statusCode||(t=new Error("XHR Failed with a response of: "+(e&&(r||e.responseText)))),n(t,e)},ke=function(){var e=function e(t,i){t=Le({timeout:45e3},t);var n=e.beforeRequest||u.default.Vhs.xhr.beforeRequest;if(n&&"function"==typeof n){var r=n(t);r&&(t=r)}var a=(!0===u.default.Vhs.xhr.original?Ae:u.default.Vhs.xhr)(t,(function(e,t){return Pe(a,e,t,i)})),s=a.abort;return a.abort=function(){return a.aborted=!0,s.apply(a,arguments)},a.uri=t.uri,a.requestTime=Date.now(),a};return e.original=!0,e},Oe=function(e){var t,i,n={};return e.byterange&&(n.Range=(i=(t=e.byterange).offset+t.length-1,"bytes="+t.offset+"-"+i)),n},xe=/^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i,De=/^application\/dash\+xml/i,Ce=function(e){return xe.test(e)?"hls":De.test(e)?"dash":"application/vnd.videojs.vhs+json"===e?"vhs-json":null},Ue=function(e,t){return e.start(t)+"-"+e.end(t)},Re=function(e,t){var i=e.toString(16);return"00".substring(0,2-i.length)+i+(t%2?" ":"")},Me=function(e){return e>=32&&e<126?String.fromCharCode(e):"."},Be=function(e){var t={};return Object.keys(e).forEach((function(i){var n=e[i];ArrayBuffer.isView(n)?t[i]={bytes:n.buffer,byteOffset:n.byteOffset,byteLength:n.byteLength}:t[i]=n})),t},Ne=function(e){var t=e.byterange||{length:1/0,offset:0};return[t.length,t.offset,e.resolvedUri].join(",")},Fe=function(e){return e.resolvedUri},qe=function(e){for(var t=Array.prototype.slice.call(e),i=16,n="",r=0;rnew Date(o.getTime()+1e3*u)?null:(i>o&&(n=s),{segment:n,estimatedStart:n.videoTimingInfo?n.videoTimingInfo.transmuxedPresentationStart:ce.duration(t,t.mediaSequence+t.segments.indexOf(n)),type:n.videoTimingInfo?"accurate":"estimate"})}(i,n);if(!c)return l({message:i+" was not found in the stream"});var h=c.segment,f=function(e,t){var i,n;try{i=new Date(e),n=new Date(t)}catch(e){}var r=i.getTime();return(n.getTime()-r)/1e3}(h.dateTimeObject,i);if("estimate"===c.type)return 0===a?l({message:i+" is not buffered yet. Try again"}):(s(c.estimatedStart+f),void d.one("seeked",(function(){e({programTime:i,playlist:n,retryCount:a-1,seekTo:s,pauseAfterSeek:u,tech:d,callback:l})})));var p=h.start+f;d.one("seeked",(function(){return l(null,d.currentTime())})),u&&d.pause(),s(p)},Ge=function(e){return!!e&&"object"==typeof e},Ve=function e(){for(var t=arguments.length,i=new Array(t),n=0;nm&&(m=T);var b=void 0;if(v<0){var S=g+1;b=S===t.length?"dynamic"===n&&a>0&&o.indexOf("$Number$")>0?ot(e,m,_):(u*l-m)/_:(t[S].t-m)/_}else b=v+1;for(var I=h+p.length+b,E=h+p.length;E=r?a:""+new Array(r-a.length+1).join("0")+a)}}(t))},ct=function(e,t){var i={RepresentationID:e.id,Bandwidth:e.bandwidth||0},n=e.initialization,r=void 0===n?{sourceURL:"",range:""}:n,a=ze({baseUrl:e.baseUrl,source:lt(r.sourceURL,i),range:r.range});return function(e,t){return e.duration||t?e.duration?Ke(e):ut(e,t):[{number:e.startNumber||1,duration:e.sourceDuration,time:0,timeline:e.periodIndex}]}(e,t).map((function(t){i.Number=t.number,i.Time=t.time;var n=lt(e.media||"",i),r={uri:n,timeline:t.timeline,duration:t.duration,resolvedUri:m(e.baseUrl||"",n),map:a,number:t.number};return e.presentationTimeOffset&&(r.presentationTimeOffset=e.presentationTimeOffset),r}))},ht=function(e,t){var i=e.duration,n=e.segmentUrls,r=void 0===n?[]:n;if(!i&&!t||i&&t)throw new Error("SEGMENT_TIME_UNSPECIFIED");var a,s=r.map((function(t){return function(e,t){var i=e.baseUrl,n=e.initialization,r=void 0===n?{}:n,a=ze({baseUrl:i,source:r.sourceURL,range:r.range}),s=ze({baseUrl:i,source:t.media,range:t.mediaRange});return s.map=a,s}(e,t)}));return i&&(a=Ke(e)),t&&(a=ut(e,t)),a.map((function(e,t){if(s[t]){var i=s[t];return i.timeline=e.timeline,i.duration=e.duration,i.number=e.number,i}})).filter((function(e){return e}))},ft=function(e){var t,i,n=e.attributes,r=e.segmentInfo;r.template?(i=ct,t=Ve(n,r.template),r.template.presentationTimeOffset&&(t.presentationTimeOffset=r.template.presentationTimeOffset/r.template.timescale)):r.base?(i=$e,t=Ve(n,r.base)):r.list&&(i=ht,t=Ve(n,r.list));var a={attributes:n};if(!i)return a;var s=i(t,r.timeline);if(t.duration){var o=t,u=o.duration,d=o.timescale,l=void 0===d?1:d;t.duration=u/l}else s.length?t.duration=s.reduce((function(e,t){return Math.max(e,Math.ceil(t.duration))}),0):t.duration=0;return a.attributes=t,a.segments=s,r.base&&t.indexRange&&(a.sidx=s[0],a.segments=[]),a},pt=function(e,t){return Xe(e.childNodes).filter((function(e){return e.tagName===t}))},mt=function(e){return e.textContent.trim()},gt=function(e){var t=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(e);if(!t)return 0;var i=t.slice(1),n=i[0],r=i[1],a=i[2],s=i[3],o=i[4],u=i[5];return 31536e3*parseFloat(n||0)+2592e3*parseFloat(r||0)+86400*parseFloat(a||0)+3600*parseFloat(s||0)+60*parseFloat(o||0)+parseFloat(u||0)},yt={mediaPresentationDuration:function(e){return gt(e)},availabilityStartTime:function(e){return/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(t=e)&&(t+="Z"),Date.parse(t)/1e3;var t},minimumUpdatePeriod:function(e){return gt(e)},suggestedPresentationDelay:function(e){return gt(e)},type:function(e){return e},timeShiftBufferDepth:function(e){return gt(e)},start:function(e){return gt(e)},width:function(e){return parseInt(e,10)},height:function(e){return parseInt(e,10)},bandwidth:function(e){return parseInt(e,10)},startNumber:function(e){return parseInt(e,10)},timescale:function(e){return parseInt(e,10)},presentationTimeOffset:function(e){return parseInt(e,10)},duration:function(e){var t=parseInt(e,10);return isNaN(t)?gt(e):t},d:function(e){return parseInt(e,10)},t:function(e){return parseInt(e,10)},r:function(e){return parseInt(e,10)},DEFAULT:function(e){return e}},_t=function(e){return e&&e.attributes?Xe(e.attributes).reduce((function(e,t){var i=yt[t.name]||yt.DEFAULT;return e[t.name]=i(t.value),e}),{}):{}},vt={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":"com.adobe.primetime"},Tt=function(e,t){return t.length?je(e.map((function(e){return t.map((function(t){return m(e,mt(t))}))}))):e},bt=function(e){var t=pt(e,"SegmentTemplate")[0],i=pt(e,"SegmentList")[0],n=i&&pt(i,"SegmentURL").map((function(e){return Ve({tag:"SegmentURL"},_t(e))})),r=pt(e,"SegmentBase")[0],a=i||t,s=a&&pt(a,"SegmentTimeline")[0],o=i||r||t,u=o&&pt(o,"Initialization")[0],d=t&&_t(t);d&&u?d.initialization=u&&_t(u):d&&d.initialization&&(d.initialization={sourceURL:d.initialization});var l={template:d,timeline:s&&pt(s,"S").map((function(e){return _t(e)})),list:i&&Ve(_t(i),{segmentUrls:n,initialization:_t(u)}),base:r&&Ve(_t(r),{initialization:_t(u)})};return Object.keys(l).forEach((function(e){l[e]||delete l[e]})),l},St=function(e,t){return function(i,n){var r=Tt(t,pt(i,"BaseURL")),a=_t(i),s=parseInt(a.id,10),u=o.default.isNaN(s)?n:s,d=Ve(e,{periodIndex:u}),l=pt(i,"AdaptationSet"),c=bt(i);return je(l.map(function(e,t,i){return function(n){var r,a=_t(n),s=Tt(t,pt(n,"BaseURL")),o=pt(n,"Role")[0],u={role:_t(o)},d=Ve(e,a,u),l=pt(n,"Accessibility")[0],c="urn:scte:dash:cc:cea-608:2015"===(r=_t(l)).schemeIdUri?r.value.split(";").map((function(e){var t,i;if(i=e,/^CC\d=/.test(e)){var n=e.split("=");t=n[0],i=n[1]}else/^CC\d$/.test(e)&&(t=e);return{channel:t,language:i}})):"urn:scte:dash:cc:cea-708:2015"===r.schemeIdUri?r.value.split(";").map((function(e){var t={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(e)){var i=e.split("="),n=i[0],r=i[1],a=void 0===r?"":r;t.channel=n,t.language=e,a.split(",").forEach((function(e){var i=e.split(":"),n=i[0],r=i[1];"lang"===n?t.language=r:"er"===n?t.easyReader=Number(r):"war"===n?t.aspectRatio=Number(r):"3D"===n&&(t["3D"]=Number(r))}))}else t.language=e;return t.channel&&(t.channel="SERVICE"+t.channel),t})):void 0;c&&(d=Ve(d,{captionServices:c}));var h=pt(n,"Label")[0];if(h&&h.childNodes.length){var f=h.childNodes[0].nodeValue.trim();d=Ve(d,{label:f})}var p=pt(n,"ContentProtection").reduce((function(e,t){var i=_t(t),n=vt[i.schemeIdUri];if(n){e[n]={attributes:i};var r=pt(t,"cenc:pssh")[0];if(r){var a=mt(r),s=a&&b(a);e[n].pssh=s}}return e}),{});Object.keys(p).length&&(d=Ve(d,{contentProtection:p}));var m=bt(n),g=pt(n,"Representation"),y=Ve(i,m);return je(g.map(function(e,t,i){return function(n){var r=pt(n,"BaseURL"),a=Tt(t,r),s=Ve(e,_t(n)),o=bt(n);return a.map((function(e){return{segmentInfo:Ve(i,o),attributes:Ve(s,{baseUrl:e})}}))}}(d,s,y)))}}(d,r,c)))}},It=function(e){if(""===e)throw new Error("DASH_EMPTY_MANIFEST");var t,i,n=new r.DOMParser;try{i=(t=n.parseFromString(e,"application/xml"))&&"MPD"===t.documentElement.tagName?t.documentElement:null}catch(e){}if(!i||i&&i.getElementsByTagName("parsererror").length>0)throw new Error("DASH_INVALID_XML");return i},Et=function(e,t){void 0===t&&(t={});var i=function(e,t){void 0===t&&(t={});var i=t,n=i.manifestUri,r=void 0===n?"":n,a=i.NOW,s=void 0===a?Date.now():a,o=i.clientOffset,u=void 0===o?0:o,d=pt(e,"Period");if(!d.length)throw new Error("INVALID_NUMBER_OF_PERIOD");var l=pt(e,"Location"),c=_t(e),h=Tt([r],pt(e,"BaseURL"));return c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=s,c.clientOffset=u,l.length&&(c.locations=l.map(mt)),{locations:c.locations,representationInfo:je(d.map(St(c,h)))}}(It(e),t);return function(e,t,i){var n;if(void 0===i&&(i={}),!e.length)return{};var r=e[0].attributes,a=r.sourceDuration,s=r.type,o=void 0===s?"static":s,u=r.suggestedPresentationDelay,d=r.minimumUpdatePeriod,l=et(e.filter(rt)).map(nt),c=et(e.filter(at)),h=e.filter(st),f=e.map((function(e){return e.attributes.captionServices})).filter(Boolean),p={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:(n={AUDIO:{},VIDEO:{}},n["CLOSED-CAPTIONS"]={},n.SUBTITLES={},n),uri:"",duration:a,playlists:it(l,i)};d>=0&&(p.minimumUpdatePeriod=1e3*d),t&&(p.locations=t),"dynamic"===o&&(p.suggestedPresentationDelay=u);var m=0===p.playlists.length;return c.length&&(p.mediaGroups.AUDIO.audio=function(e,t,i){var n;void 0===t&&(t={}),void 0===i&&(i=!1);var r=e.reduce((function(e,r){var a=r.attributes.role&&r.attributes.role.value||"",s=r.attributes.lang||"",o=r.attributes.label||"main";if(s&&!r.attributes.label){var u=a?" ("+a+")":"";o=""+r.attributes.lang+u}e[o]||(e[o]={language:s,autoselect:!0,default:"main"===a,playlists:[],uri:""});var d=tt(function(e,t){var i,n=e.attributes,r=e.segments,a=e.sidx,s={attributes:(i={NAME:n.id,BANDWIDTH:n.bandwidth,CODECS:n.codecs},i["PROGRAM-ID"]=1,i),uri:"",endList:"static"===(n.type||"static"),timeline:n.periodIndex,resolvedUri:"",targetDuration:n.duration,segments:r,mediaSequence:r.length?r[0].number:1};return n.contentProtection&&(s.contentProtection=n.contentProtection),a&&(s.sidx=a),t&&(s.attributes.AUDIO="audio",s.attributes.SUBTITLES="subs"),s}(r,i),t);return e[o].playlists.push(d),void 0===n&&"main"===a&&((n=r).default=!0),e}),{});return n||(r[Object.keys(r)[0]].default=!0),r}(c,i,m)),h.length&&(p.mediaGroups.SUBTITLES.subs=function(e,t){return void 0===t&&(t={}),e.reduce((function(e,i){var n=i.attributes.lang||"text";return e[n]||(e[n]={language:n,default:!1,autoselect:!1,playlists:[],uri:""}),e[n].playlists.push(tt(function(e){var t,i=e.attributes,n=e.segments;void 0===n&&(n=[{uri:i.baseUrl,timeline:i.periodIndex,resolvedUri:i.baseUrl||"",duration:i.sourceDuration,number:0}],i.duration=i.sourceDuration);var r=((t={NAME:i.id,BANDWIDTH:i.bandwidth})["PROGRAM-ID"]=1,t);return i.codecs&&(r.CODECS=i.codecs),{attributes:r,uri:"",endList:"static"===(i.type||"static"),timeline:i.periodIndex,resolvedUri:i.baseUrl||"",targetDuration:i.duration,segments:n,mediaSequence:n.length?n[0].number:1}}(i),t)),e}),{})}(h,i)),f.length&&(p.mediaGroups["CLOSED-CAPTIONS"].cc=f.reduce((function(e,t){return t?(t.forEach((function(t){var i=t.channel,n=t.language;e[n]={autoselect:!1,default:!1,instreamId:i,language:n},t.hasOwnProperty("aspectRatio")&&(e[n].aspectRatio=t.aspectRatio),t.hasOwnProperty("easyReader")&&(e[n].easyReader=t.easyReader),t.hasOwnProperty("3D")&&(e[n]["3D"]=t["3D"])})),e):e}),{})),p}(i.representationInfo.map(ft),i.locations,t.sidxMapping)},wt=Math.pow(2,32),At=function(e){return e instanceof Uint8Array?e:(Array.isArray(e)||(t=e,ArrayBuffer.isView(t))||e instanceof ArrayBuffer||(e="number"!=typeof e||"number"==typeof e&&e!=e?0:[e]),new Uint8Array(e&&e.buffer||e,e&&e.byteOffset||0,e&&e.byteLength||0));var t},Lt=o.default.BigInt||Number,Pt=[Lt("0x1"),Lt("0x100"),Lt("0x10000"),Lt("0x1000000"),Lt("0x100000000"),Lt("0x10000000000"),Lt("0x1000000000000"),Lt("0x100000000000000"),Lt("0x10000000000000000")],kt=function(e,t){var i=void 0===t?{}:t,n=i.signed,r=void 0!==n&&n,a=i.le,s=void 0!==a&&a;e=At(e);var o=s?"reduce":"reduceRight",u=(e[o]?e[o]:Array.prototype[o]).call(e,(function(t,i,n){var r=s?n:Math.abs(n+1-e.length);return t+Lt(i)*Pt[r]}),Lt(0));if(r){var d=Pt[e.length]/Lt(2)-Lt(1);(u=Lt(u))>d&&(u-=d,u-=d,u-=Lt(2))}return Number(u)},Ot=function(e,t){if("string"!=typeof e&&e&&"function"==typeof e.toString&&(e=e.toString()),"string"!=typeof e)return new Uint8Array;t||(e=unescape(encodeURIComponent(e)));for(var i=new Uint8Array(e.length),n=0;n=t.length&&u.call(t,(function(t,i){return t===(o[i]?o[i]&e[a+i]:e[a+i])}))},Dt=At([73,68,51]),Ct=function e(t,i){return void 0===i&&(i=0),(t=At(t)).length-i<10||!xt(t,Dt,{offset:i})?i:(i+=function(e,t){void 0===t&&(t=0);var i=(e=At(e))[t+5],n=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9];return(16&i)>>4?n+20:n+10}(t,i),e(t,i))},Ut=function(e){return"string"==typeof e?Ot(e):e},Rt=function e(t,i,n){void 0===n&&(n=!1),i=function(e){return Array.isArray(e)?e.map((function(e){return Ut(e)})):[Ut(e)]}(i),t=At(t);var r=[];if(!i.length)return r;for(var a=0;a>>0,o=t.subarray(a+4,a+8);if(0===s)break;var u=a+s;if(u>t.length){if(n)break;u=t.length}var d=t.subarray(a+8,u);xt(o,i[0])&&(1===i.length?r.push(d):r.push.apply(r,e(d,i.slice(1),n))),a=u}return r},Mt={EBML:At([26,69,223,163]),DocType:At([66,130]),Segment:At([24,83,128,103]),SegmentInfo:At([21,73,169,102]),Tracks:At([22,84,174,107]),Track:At([174]),TrackNumber:At([215]),DefaultDuration:At([35,227,131]),TrackEntry:At([174]),TrackType:At([131]),FlagDefault:At([136]),CodecID:At([134]),CodecPrivate:At([99,162]),VideoTrack:At([224]),AudioTrack:At([225]),Cluster:At([31,67,182,117]),Timestamp:At([231]),TimestampScale:At([42,215,177]),BlockGroup:At([160]),BlockDuration:At([155]),Block:At([161]),SimpleBlock:At([163])},Bt=[128,64,32,16,8,4,2,1],Nt=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=!1);var r=function(e){for(var t=1,i=0;i=i.length)return i.length;var r=Nt(i,n,!1);if(xt(t.bytes,r.bytes))return n;var a=Nt(i,n+r.length);return e(t,i,n+a.length+a.value+r.length)},Ht=function e(t,i){i=function(e){return Array.isArray(e)?e.map((function(e){return Ft(e)})):[Ft(e)]}(i),t=At(t);var n=[];if(!i.length)return n;for(var r=0;rt.length?t.length:o+s.value,d=t.subarray(o,u);xt(i[0],a.bytes)&&(1===i.length?n.push(d):n=n.concat(e(d,i.slice(1)))),r+=a.length+s.length+d.length}return n},Wt=At([0,0,0,1]),Gt=At([0,0,1]),Vt=At([0,0,3]),jt=function(e){for(var t=[],i=1;i>1&63),-1!==i.indexOf(u)&&(r=a+o),a+=o+("h264"===t?1:2)}else a++}return e.subarray(0,0)},zt={webm:At([119,101,98,109]),matroska:At([109,97,116,114,111,115,107,97]),flac:At([102,76,97,67]),ogg:At([79,103,103,83]),ac3:At([11,119]),riff:At([82,73,70,70]),avi:At([65,86,73]),wav:At([87,65,86,69]),"3gp":At([102,116,121,112,51,103]),mp4:At([102,116,121,112]),fmp4:At([115,116,121,112]),mov:At([102,116,121,112,113,116])},Qt={aac:function(e){var t=Ct(e);return xt(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=Ct(e);return xt(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=Ht(e,[Mt.EBML,Mt.DocType])[0];return xt(t,zt.webm)},mkv:function(e){var t=Ht(e,[Mt.EBML,Mt.DocType])[0];return xt(t,zt.matroska)},mp4:function(e){return!Qt["3gp"](e)&&!Qt.mov(e)&&(xt(e,zt.mp4,{offset:4})||xt(e,zt.fmp4,{offset:4}))},mov:function(e){return xt(e,zt.mov,{offset:4})},"3gp":function(e){return xt(e,zt["3gp"],{offset:4})},ac3:function(e){var t=Ct(e);return xt(e,zt.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return 71===e[0];for(var t=0;t+1880;n+=12,r--)i.references.push({referenceType:(128&e[n])>>>7,referencedSize:2147483647&t.getUint32(n),subsegmentDuration:t.getUint32(n+4),startsWithSap:!!(128&e[n+8]),sapType:(112&e[n+8])>>>4,sapDeltaTime:268435455&t.getUint32(n+8)});return i}(At(s.response).subarray(8))}catch(e){return void n.requestErrored_(e,s,t)}return u[r]={sidxInfo:e.sidx,sidx:o},Je(e,o,e.sidx.resolvedUri),i(!0)}};this.request=function(e,t,i){var n,r=[],a=!1,s=function(e,t,n,r){return t.abort(),a=!0,i(e,t,n,r)},o=function(e,t){if(!a){if(e)return s(e,t,"",r);var i=t.responseText.substring(r&&r.byteLength||0,t.responseText.length);if(r=function(){for(var e=arguments.length,t=new Array(e),i=0;i=l+d)return s(t,{response:o.subarray(d,d+l),status:i.status,uri:i.uri});n.request=n.vhs_.xhr({uri:a,responseType:"arraybuffer",headers:Oe({byterange:e.sidx.byterange})},s)}))}else this.mediaRequest_=o.default.setTimeout((function(){return i(!1)}),0)},i.dispose=function(){this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},o.default.clearTimeout(this.minimumUpdatePeriodTimeout_),o.default.clearTimeout(this.mediaRequest_),o.default.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.masterPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.masterPlaylistLoader_.createMupOnMedia_),this.masterPlaylistLoader_.createMupOnMedia_=null),this.off()},i.hasPendingRequest=function(){return this.request||this.mediaRequest_},i.stopRequest=function(){if(this.request){var e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}},i.media=function(e){var t=this;if(!e)return this.media_;if("HAVE_NOTHING"===this.state)throw new Error("Cannot switch media playlist from "+this.state);var i=this.state;if("string"==typeof e){if(!this.masterPlaylistLoader_.master.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.masterPlaylistLoader_.master.playlists[e]}var n=!this.media_||e.id!==this.media_.id;if(n&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList)return this.state="HAVE_METADATA",this.media_=e,void(n&&(this.trigger("mediachanging"),this.trigger("mediachange")));n&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,i,(function(n){t.haveMetadata({startingState:i,playlist:e})})))},i.haveMetadata=function(e){var t=e.startingState,i=e.playlist;this.state="HAVE_METADATA",this.loadedPlaylists_[i.id]=i,this.mediaRequest_=null,this.refreshMedia_(i.id),"HAVE_MASTER"===t?this.trigger("loadedmetadata"):this.trigger("mediachange")},i.pause=function(){this.masterPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.masterPlaylistLoader_.createMupOnMedia_),this.masterPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),o.default.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMaster_&&(o.default.clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_),this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_=null),"HAVE_NOTHING"===this.state&&(this.started=!1)},i.load=function(e){var t=this;o.default.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;var i=this.media();if(e){var n=i?i.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=o.default.setTimeout((function(){return t.load()}),n)}else this.started?i&&!i.endList?(this.isMaster_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist"):this.start()},i.start=function(){var e=this;this.started=!0,this.isMaster_?this.requestMaster_((function(t,i){e.haveMaster_(),e.hasPendingRequest()||e.media_||e.media(e.masterPlaylistLoader_.master.playlists[0])})):this.mediaRequest_=o.default.setTimeout((function(){return e.haveMaster_()}),0)},i.requestMaster_=function(e){var t=this;this.request=this.vhs_.xhr({uri:this.masterPlaylistLoader_.srcUrl,withCredentials:this.withCredentials},(function(i,n){if(!t.requestErrored_(i,n)){var r=n.responseText!==t.masterPlaylistLoader_.masterXml_;return t.masterPlaylistLoader_.masterXml_=n.responseText,n.responseHeaders&&n.responseHeaders.date?t.masterLoaded_=Date.parse(n.responseHeaders.date):t.masterLoaded_=Date.now(),t.masterPlaylistLoader_.srcUrl=y(t.handleManifestRedirects,t.masterPlaylistLoader_.srcUrl,n),r?(t.handleMaster_(),void t.syncClientServerClock_((function(){return e(n,r)}))):e(n,r)}"HAVE_NOTHING"===t.state&&(t.started=!1)}))},i.syncClientServerClock_=function(e){var t,i=this,n=(t=this.masterPlaylistLoader_.masterXml_,function(e){var t=pt(e,"UTCTiming")[0];if(!t)return null;var i=_t(t);switch(i.schemeIdUri){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":i.method="HEAD";break;case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":i.method="GET";break;case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":i.method="DIRECT",i.value=Date.parse(i.value);break;case"urn:mpeg:dash:utc:http-ntp:2014":case"urn:mpeg:dash:utc:ntp:2014":case"urn:mpeg:dash:utc:sntp:2014":default:throw new Error("UNSUPPORTED_UTC_TIMING_SCHEME")}return i}(It(t)));return null===n?(this.masterPlaylistLoader_.clientOffset_=this.masterLoaded_-Date.now(),e()):"DIRECT"===n.method?(this.masterPlaylistLoader_.clientOffset_=n.value-Date.now(),e()):void(this.request=this.vhs_.xhr({uri:g(this.masterPlaylistLoader_.srcUrl,n.value),method:n.method,withCredentials:this.withCredentials},(function(t,r){if(i.request){if(t)return i.masterPlaylistLoader_.clientOffset_=i.masterLoaded_-Date.now(),e();var a;a="HEAD"===n.method?r.responseHeaders&&r.responseHeaders.date?Date.parse(r.responseHeaders.date):i.masterLoaded_:Date.parse(r.responseText),i.masterPlaylistLoader_.clientOffset_=a-Date.now(),e()}})))},i.haveMaster_=function(){this.state="HAVE_MASTER",this.isMaster_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)},i.handleMaster_=function(){this.mediaRequest_=null;var e,t,i,n=(e={masterXml:this.masterPlaylistLoader_.masterXml_,srcUrl:this.masterPlaylistLoader_.srcUrl,clientOffset:this.masterPlaylistLoader_.clientOffset_,sidxMapping:this.masterPlaylistLoader_.sidxMapping_},i=Et(e.masterXml,{manifestUri:t=e.srcUrl,clientOffset:e.clientOffset,sidxMapping:e.sidxMapping}),ge(i,t),i),r=this.masterPlaylistLoader_.master;r&&(n=function(e,t,i){for(var n=!0,r=ei(e,{duration:t.duration,minimumUpdatePeriod:t.minimumUpdatePeriod}),a=0;a-1)},this.trigger=function(t){var i,n,r,a;if(i=e[t])if(2===arguments.length)for(r=i.length,n=0;n>>1,e.samplingfrequencyindex<<7|e.channelcount<<3,6,1,2]))},m=function(e){return t(S.hdlr,P[e])},p=function(e){var i=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,e.duration>>>24&255,e.duration>>>16&255,e.duration>>>8&255,255&e.duration,85,196,0,0]);return e.samplerate&&(i[12]=e.samplerate>>>24&255,i[13]=e.samplerate>>>16&255,i[14]=e.samplerate>>>8&255,i[15]=255&e.samplerate),t(S.mdhd,i)},f=function(e){return t(S.mdia,p(e),m(e.type),s(e))},a=function(e){return t(S.mfhd,new Uint8Array([0,0,0,0,(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e]))},s=function(e){return t(S.minf,"video"===e.type?t(S.vmhd,k):t(S.smhd,O),i(),y(e))},o=function(e,i){for(var n=[],r=i.length;r--;)n[r]=v(i[r]);return t.apply(null,[S.moof,a(e)].concat(n))},u=function(e){for(var i=e.length,n=[];i--;)n[i]=c(e[i]);return t.apply(null,[S.moov,l(4294967295)].concat(n).concat(d(e)))},d=function(e){for(var i=e.length,n=[];i--;)n[i]=T(e[i]);return t.apply(null,[S.mvex].concat(n))},l=function(e){var i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t(S.mvhd,i)},g=function(e){var i,n,r=e.samples||[],a=new Uint8Array(4+r.length);for(n=0;n>>8),s.push(255&r[i].byteLength),s=s.concat(Array.prototype.slice.call(r[i]));for(i=0;i>>8),o.push(255&a[i].byteLength),o=o.concat(Array.prototype.slice.call(a[i]));if(n=[S.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,(65280&e.width)>>8,255&e.width,(65280&e.height)>>8,255&e.height,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),t(S.avcC,new Uint8Array([1,e.profileIdc,e.profileCompatibility,e.levelIdc,255].concat([r.length],s,[a.length],o))),t(S.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],e.sarRatio){var u=e.sarRatio[0],d=e.sarRatio[1];n.push(t(S.pasp,new Uint8Array([(4278190080&u)>>24,(16711680&u)>>16,(65280&u)>>8,255&u,(4278190080&d)>>24,(16711680&d)>>16,(65280&d)>>8,255&d])))}return t.apply(null,n)},B=function(e){return t(S.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(65280&e.channelcount)>>8,255&e.channelcount,(65280&e.samplesize)>>8,255&e.samplesize,0,0,0,0,(65280&e.samplerate)>>8,255&e.samplerate,0,0]),n(e))},h=function(e){var i=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(4278190080&e.id)>>24,(16711680&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,0,(4278190080&e.duration)>>24,(16711680&e.duration)>>16,(65280&e.duration)>>8,255&e.duration,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(65280&e.width)>>8,255&e.width,0,0,(65280&e.height)>>8,255&e.height,0,0]);return t(S.tkhd,i)},v=function(e){var i,n,r,a,s,o;return i=t(S.tfhd,new Uint8Array([0,0,0,58,(4278190080&e.id)>>24,(16711680&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),s=Math.floor(e.baseMediaDecodeTime/(W+1)),o=Math.floor(e.baseMediaDecodeTime%(W+1)),n=t(S.tfdt,new Uint8Array([1,0,0,0,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o>>>24&255,o>>>16&255,o>>>8&255,255&o])),"audio"===e.type?(r=b(e,92),t(S.traf,i,n,r)):(a=g(e),r=b(e,a.length+92),t(S.traf,i,n,r,a))},c=function(e){return e.duration=e.duration||4294967295,t(S.trak,h(e),f(e))},T=function(e){var i=new Uint8Array([0,0,0,0,(4278190080&e.id)>>24,(16711680&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return"video"!==e.type&&(i[i.length-1]=0),t(S.trex,i)},q=function(e,t){var i=0,n=0,r=0,a=0;return e.length&&(void 0!==e[0].duration&&(i=1),void 0!==e[0].size&&(n=2),void 0!==e[0].flags&&(r=4),void 0!==e[0].compositionTimeOffset&&(a=8)),[0,0,i|n|r|a,1,(4278190080&e.length)>>>24,(16711680&e.length)>>>16,(65280&e.length)>>>8,255&e.length,(4278190080&t)>>>24,(16711680&t)>>>16,(65280&t)>>>8,255&t]},F=function(e,i){var n,r,a,s,o,u;for(i+=20+16*(s=e.samples||[]).length,a=q(s,i),(r=new Uint8Array(a.length+16*s.length)).set(a),n=a.length,u=0;u>>24,r[n++]=(16711680&o.duration)>>>16,r[n++]=(65280&o.duration)>>>8,r[n++]=255&o.duration,r[n++]=(4278190080&o.size)>>>24,r[n++]=(16711680&o.size)>>>16,r[n++]=(65280&o.size)>>>8,r[n++]=255&o.size,r[n++]=o.flags.isLeading<<2|o.flags.dependsOn,r[n++]=o.flags.isDependedOn<<6|o.flags.hasRedundancy<<4|o.flags.paddingValue<<1|o.flags.isNonSyncSample,r[n++]=61440&o.flags.degradationPriority,r[n++]=15&o.flags.degradationPriority,r[n++]=(4278190080&o.compositionTimeOffset)>>>24,r[n++]=(16711680&o.compositionTimeOffset)>>>16,r[n++]=(65280&o.compositionTimeOffset)>>>8,r[n++]=255&o.compositionTimeOffset;return t(S.trun,r)},N=function(e,i){var n,r,a,s,o,u;for(i+=20+8*(s=e.samples||[]).length,a=q(s,i),(n=new Uint8Array(a.length+8*s.length)).set(a),r=a.length,u=0;u>>24,n[r++]=(16711680&o.duration)>>>16,n[r++]=(65280&o.duration)>>>8,n[r++]=255&o.duration,n[r++]=(4278190080&o.size)>>>24,n[r++]=(16711680&o.size)>>>16,n[r++]=(65280&o.size)>>>8,n[r++]=255&o.size;return t(S.trun,n)},b=function(e,t){return"audio"===e.type?N(e,t):F(e,t)},r=function(){return t(S.ftyp,I,E,I,w)};var G,V,j,X,z,Q,Y,K,$=function(e){return t(S.mdat,e)},J=o,Z=function(e,t){var i={size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}};return i.dataOffset=t,i.compositionTimeOffset=e.pts-e.dts,i.duration=e.duration,i.size=4*e.length,i.size+=e.byteLength,e.keyFrame&&(i.flags.dependsOn=2,i.flags.isNonSyncSample=0),i},ee=[33,16,5,32,164,27],te=[33,65,108,84,1,2,4,8,168,2,4,8,17,191,252],ie=function(e){for(var t=[];e--;)t.push(0);return t},ne=9e4;Q=function(e,t){return V(z(e,t))},Y=function(e,t){return j(X(e),t)},K=function(e,t,i){return X(i?e:e-t)};var re=ne,ae=V=function(e){return e*ne},se=(j=function(e,t){return e*t},X=function(e){return e/ne}),oe=(z=function(e,t){return e/t},Q),ue=Y,de=K,le=function(e,t,i,n){var r,a,s,o,u,d=0,l=0,c=0;if(t.length&&(r=oe(e.baseMediaDecodeTime,e.samplerate),a=Math.ceil(re/(e.samplerate/1024)),i&&n&&(d=r-Math.max(i,n),c=(l=Math.floor(d/a))*a),!(l<1||c>45e3))){for((s=function(){if(!G){var e={96e3:[ee,[227,64],ie(154),[56]],88200:[ee,[231],ie(170),[56]],64e3:[ee,[248,192],ie(240),[56]],48e3:[ee,[255,192],ie(268),[55,148,128],ie(54),[112]],44100:[ee,[255,192],ie(268),[55,163,128],ie(84),[112]],32e3:[ee,[255,192],ie(268),[55,234],ie(226),[112]],24e3:[ee,[255,192],ie(268),[55,255,128],ie(268),[111,112],ie(126),[224]],16e3:[ee,[255,192],ie(268),[55,255,128],ie(268),[111,255],ie(269),[223,108],ie(195),[1,192]],12e3:[te,ie(268),[3,127,248],ie(268),[6,255,240],ie(268),[13,255,224],ie(268),[27,253,128],ie(259),[56]],11025:[te,ie(268),[3,127,248],ie(268),[6,255,240],ie(268),[13,255,224],ie(268),[27,255,192],ie(268),[55,175,128],ie(108),[112]],8e3:[te,ie(268),[3,121,16],ie(47),[7]]};t=e,G=Object.keys(t).reduce((function(e,i){return e[i]=new Uint8Array(t[i].reduce((function(e,t){return e.concat(t)}),[])),e}),{})}var t;return G}()[e.samplerate])||(s=t[0].data),o=0;o=this.virtualRowCount&&"function"==typeof this.beforeRowOverflow&&this.beforeRowOverflow(e),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},ye.prototype.isEmpty=function(){return 0===this.rows.length||1===this.rows.length&&""===this.rows[0]},ye.prototype.addText=function(e){this.rows[this.rowIdx]+=e},ye.prototype.backspace=function(){if(!this.isEmpty()){var e=this.rows[this.rowIdx];this.rows[this.rowIdx]=e.substr(0,e.length-1)}};var _e=function(e){this.serviceNum=e,this.text="",this.currentWindow=new ye(-1),this.windows=[]};_e.prototype.init=function(e,t){this.startPts=e;for(var i=0;i<8;i++)this.windows[i]=new ye(i),"function"==typeof t&&(this.windows[i].beforeRowOverflow=t)},_e.prototype.setCurrentWindow=function(e){this.currentWindow=this.windows[e]};var ve=function e(){e.prototype.init.call(this);var t=this;this.current708Packet=null,this.services={},this.push=function(e){3===e.type?(t.new708Packet(),t.add708Bytes(e)):(null===t.current708Packet&&t.new708Packet(),t.add708Bytes(e))}};ve.prototype=new H,ve.prototype.new708Packet=function(){null!==this.current708Packet&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},ve.prototype.add708Bytes=function(e){var t=e.ccData,i=t>>>8,n=255&t;this.current708Packet.ptsVals.push(e.pts),this.current708Packet.data.push(i),this.current708Packet.data.push(n)},ve.prototype.push708Packet=function(){var e=this.current708Packet,t=e.data,i=null,n=null,r=0,a=t[r++];for(e.seq=a>>6,e.sizeCode=63&a;r>5)&&n>0&&(i=a=t[r++]),this.pushServiceBlock(i,r,n),n>0&&(r+=n-1)},ve.prototype.pushServiceBlock=function(e,t,i){var n,r=t,a=this.current708Packet.data,s=this.services[e];for(s||(s=this.initService(e,r));r>5,a.rowLock=(16&n)>>4,a.columnLock=(8&n)>>3,a.priority=7&n,n=i[++e],a.relativePositioning=(128&n)>>7,a.anchorVertical=127&n,n=i[++e],a.anchorHorizontal=n,n=i[++e],a.anchorPoint=(240&n)>>4,a.rowCount=15&n,n=i[++e],a.columnCount=63&n,n=i[++e],a.windowStyle=(56&n)>>3,a.penStyle=7&n,a.virtualRowCount=a.rowCount+1,e},ve.prototype.setWindowAttributes=function(e,t){var i=this.current708Packet.data,n=i[e],r=t.currentWindow.winAttr;return n=i[++e],r.fillOpacity=(192&n)>>6,r.fillRed=(48&n)>>4,r.fillGreen=(12&n)>>2,r.fillBlue=3&n,n=i[++e],r.borderType=(192&n)>>6,r.borderRed=(48&n)>>4,r.borderGreen=(12&n)>>2,r.borderBlue=3&n,n=i[++e],r.borderType+=(128&n)>>5,r.wordWrap=(64&n)>>6,r.printDirection=(48&n)>>4,r.scrollDirection=(12&n)>>2,r.justify=3&n,n=i[++e],r.effectSpeed=(240&n)>>4,r.effectDirection=(12&n)>>2,r.displayEffect=3&n,e},ve.prototype.flushDisplayed=function(e,t){for(var i=[],n=0;n<8;n++)t.windows[n].visible&&!t.windows[n].isEmpty()&&i.push(t.windows[n].getText());t.endPts=e,t.text=i.join("\n\n"),this.pushCaption(t),t.startPts=e},ve.prototype.pushCaption=function(e){""!==e.text&&(this.trigger("data",{startPts:e.startPts,endPts:e.endPts,text:e.text,stream:"cc708_"+e.serviceNum}),e.text="",e.startPts=e.endPts)},ve.prototype.displayWindows=function(e,t){var i=this.current708Packet.data[++e],n=this.getPts(e);this.flushDisplayed(n,t);for(var r=0;r<8;r++)i&1<>4,r.offset=(12&n)>>2,r.penSize=3&n,n=i[++e],r.italics=(128&n)>>7,r.underline=(64&n)>>6,r.edgeType=(56&n)>>3,r.fontStyle=7&n,e},ve.prototype.setPenColor=function(e,t){var i=this.current708Packet.data,n=i[e],r=t.currentWindow.penColor;return n=i[++e],r.fgOpacity=(192&n)>>6,r.fgRed=(48&n)>>4,r.fgGreen=(12&n)>>2,r.fgBlue=3&n,n=i[++e],r.bgOpacity=(192&n)>>6,r.bgRed=(48&n)>>4,r.bgGreen=(12&n)>>2,r.bgBlue=3&n,n=i[++e],r.edgeRed=(48&n)>>4,r.edgeGreen=(12&n)>>2,r.edgeBlue=3&n,e},ve.prototype.setPenLocation=function(e,t){var i=this.current708Packet.data,n=i[e],r=t.currentWindow.penLoc;return t.currentWindow.pendingNewLine=!0,n=i[++e],r.row=15&n,n=i[++e],r.column=63&n,e},ve.prototype.reset=function(e,t){var i=this.getPts(e);return this.flushDisplayed(i,t),this.initService(t.serviceNum,e)};var Te={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},be=function(e){return null===e?"":(e=Te[e]||e,String.fromCharCode(e))},Se=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],Ie=function(){for(var e=[],t=15;t--;)e.push("");return e},Ee=function e(t,i){e.prototype.init.call(this),this.field_=t||0,this.dataChannel_=i||0,this.name_="CC"+(1+(this.field_<<1|this.dataChannel_)),this.setConstants(),this.reset(),this.push=function(e){var t,i,n,r,a;if((t=32639&e.ccData)!==this.lastControlCode_){if(4096==(61440&t)?this.lastControlCode_=t:t!==this.PADDING_&&(this.lastControlCode_=null),n=t>>>8,r=255&t,t!==this.PADDING_)if(t===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(t===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(e.pts),this.flushDisplayed(e.pts),i=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=i,this.startPts_=e.pts;else if(t===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(e.pts);else if(t===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(e.pts);else if(t===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(e.pts);else if(t===this.CARRIAGE_RETURN_)this.clearFormatting(e.pts),this.flushDisplayed(e.pts),this.shiftRowsUp_(),this.startPts_=e.pts;else if(t===this.BACKSPACE_)"popOn"===this.mode_?this.nonDisplayed_[this.row_]=this.nonDisplayed_[this.row_].slice(0,-1):this.displayed_[this.row_]=this.displayed_[this.row_].slice(0,-1);else if(t===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(e.pts),this.displayed_=Ie();else if(t===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=Ie();else if(t===this.RESUME_DIRECT_CAPTIONING_)"paintOn"!==this.mode_&&(this.flushDisplayed(e.pts),this.displayed_=Ie()),this.mode_="paintOn",this.startPts_=e.pts;else if(this.isSpecialCharacter(n,r))a=be((n=(3&n)<<8)|r),this[this.mode_](e.pts,a),this.column_++;else if(this.isExtCharacter(n,r))"popOn"===this.mode_?this.nonDisplayed_[this.row_]=this.nonDisplayed_[this.row_].slice(0,-1):this.displayed_[this.row_]=this.displayed_[this.row_].slice(0,-1),a=be((n=(3&n)<<8)|r),this[this.mode_](e.pts,a),this.column_++;else if(this.isMidRowCode(n,r))this.clearFormatting(e.pts),this[this.mode_](e.pts," "),this.column_++,14==(14&r)&&this.addFormatting(e.pts,["i"]),1==(1&r)&&this.addFormatting(e.pts,["u"]);else if(this.isOffsetControlCode(n,r))this.column_+=3&r;else if(this.isPAC(n,r)){var s=Se.indexOf(7968&t);"rollUp"===this.mode_&&(s-this.rollUpRows_+1<0&&(s=this.rollUpRows_-1),this.setRollUp(e.pts,s)),s!==this.row_&&(this.clearFormatting(e.pts),this.row_=s),1&r&&-1===this.formatting_.indexOf("u")&&this.addFormatting(e.pts,["u"]),16==(16&t)&&(this.column_=4*((14&t)>>1)),this.isColorPAC(r)&&14==(14&r)&&this.addFormatting(e.pts,["i"])}else this.isNormalChar(n)&&(0===r&&(r=null),a=be(n),a+=be(r),this[this.mode_](e.pts,a),this.column_+=a.length)}else this.lastControlCode_=null}};Ee.prototype=new H,Ee.prototype.flushDisplayed=function(e){var t=this.displayed_.map((function(e){try{return e.trim()}catch(e){return console.error("Skipping malformed caption."),""}})).join("\n").replace(/^\n+|\n+$/g,"");t.length&&this.trigger("data",{startPts:this.startPts_,endPts:e,text:t,stream:this.name_})},Ee.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=Ie(),this.nonDisplayed_=Ie(),this.lastControlCode_=null,this.column_=0,this.row_=14,this.rollUpRows_=2,this.formatting_=[]},Ee.prototype.setConstants=function(){0===this.dataChannel_?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):1===this.dataChannel_&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=32|this.CONTROL_,this.END_OF_CAPTION_=47|this.CONTROL_,this.ROLL_UP_2_ROWS_=37|this.CONTROL_,this.ROLL_UP_3_ROWS_=38|this.CONTROL_,this.ROLL_UP_4_ROWS_=39|this.CONTROL_,this.CARRIAGE_RETURN_=45|this.CONTROL_,this.RESUME_DIRECT_CAPTIONING_=41|this.CONTROL_,this.BACKSPACE_=33|this.CONTROL_,this.ERASE_DISPLAYED_MEMORY_=44|this.CONTROL_,this.ERASE_NON_DISPLAYED_MEMORY_=46|this.CONTROL_},Ee.prototype.isSpecialCharacter=function(e,t){return e===this.EXT_&&t>=48&&t<=63},Ee.prototype.isExtCharacter=function(e,t){return(e===this.EXT_+1||e===this.EXT_+2)&&t>=32&&t<=63},Ee.prototype.isMidRowCode=function(e,t){return e===this.EXT_&&t>=32&&t<=47},Ee.prototype.isOffsetControlCode=function(e,t){return e===this.OFFSET_&&t>=33&&t<=35},Ee.prototype.isPAC=function(e,t){return e>=this.BASE_&&e=64&&t<=127},Ee.prototype.isColorPAC=function(e){return e>=64&&e<=79||e>=96&&e<=127},Ee.prototype.isNormalChar=function(e){return e>=32&&e<=127},Ee.prototype.setRollUp=function(e,t){if("rollUp"!==this.mode_&&(this.row_=14,this.mode_="rollUp",this.flushDisplayed(e),this.nonDisplayed_=Ie(),this.displayed_=Ie()),void 0!==t&&t!==this.row_)for(var i=0;i"}),"");this[this.mode_](e,i)},Ee.prototype.clearFormatting=function(e){if(this.formatting_.length){var t=this.formatting_.reverse().reduce((function(e,t){return e+""+t+">"}),"");this.formatting_=[],this[this.mode_](e,t)}},Ee.prototype.popOn=function(e,t){var i=this.nonDisplayed_[this.row_];i+=t,this.nonDisplayed_[this.row_]=i},Ee.prototype.rollUp=function(e,t){var i=this.displayed_[this.row_];i+=t,this.displayed_[this.row_]=i},Ee.prototype.shiftRowsUp_=function(){var e;for(e=0;et&&(i=-1);Math.abs(t-e)>4294967296;)e+=8589934592*i;return e},ke=function e(t){var i,n;e.prototype.init.call(this),this.type_=t||Le,this.push=function(e){this.type_!==Le&&e.type!==this.type_||(void 0===n&&(n=e.dts),e.dts=Pe(e.dts,n),e.pts=Pe(e.pts,n),i=e.dts,this.trigger("data",e))},this.flush=function(){n=i,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){n=void 0,i=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};ke.prototype=new H;var Oe,xe=ke,De=Pe,Ce=function(e,t,i){var n,r="";for(n=t;n>>2;c*=4,c+=3&l[7],u.timeStamp=c,void 0===t.pts&&void 0===t.dts&&(t.pts=u.timeStamp,t.dts=u.timeStamp),this.trigger("timestamp",u)}t.frames.push(u),s+=10,s+=o}while(s>>4>1&&(n+=t[n]+1),0===i.pid)i.type="pat",e(t.subarray(n),i),this.trigger("data",i);else if(i.pid===this.pmtPid)for(i.type="pmt",e(t.subarray(n),i),this.trigger("data",i);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else void 0===this.programMapTable?this.packetsWaitingForPmt.push([t,n,i]):this.processPes_(t,n,i)},this.processPes_=function(e,t,i){i.pid===this.programMapTable.video?i.streamType=Ae.H264_STREAM_TYPE:i.pid===this.programMapTable.audio?i.streamType=Ae.ADTS_STREAM_TYPE:i.streamType=this.programMapTable["timed-metadata"][i.pid],i.type="pes",i.data=e.subarray(t),this.trigger("data",i)}}).prototype=new H,Ne.STREAM_TYPES={h264:27,adts:15},(Fe=function(){var e,t=this,i={data:[],size:0},n={data:[],size:0},r={data:[],size:0},a=function(e,i,n){var r,a,s=new Uint8Array(e.size),o={type:i},u=0,d=0;if(e.data.length&&!(e.size<9)){for(o.trackId=e.data[0].pid,u=0;u>>3,c.pts*=4,c.pts+=(6&l[13])>>>1,c.dts=c.pts,64&h&&(c.dts=(14&l[14])<<27|(255&l[15])<<20|(254&l[16])<<12|(255&l[17])<<5|(254&l[18])>>>3,c.dts*=4,c.dts+=(6&l[18])>>>1)),c.data=l.subarray(9+l[8])),r="video"===i||o.packetLength<=e.size,(n||r)&&(e.size=0,e.data.length=0),r&&t.trigger("data",o)}};Fe.prototype.init.call(this),this.push=function(s){({pat:function(){},pes:function(){var e,t;switch(s.streamType){case Ae.H264_STREAM_TYPE:e=i,t="video";break;case Ae.ADTS_STREAM_TYPE:e=n,t="audio";break;case Ae.METADATA_STREAM_TYPE:e=r,t="timed-metadata";break;default:return}s.payloadUnitStartIndicator&&a(e,t,!0),e.data.push(s),e.size+=s.data.byteLength},pmt:function(){var i={type:"metadata",tracks:[]};null!==(e=s.programMapTable).video&&i.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.video,codec:"avc",type:"video"}),null!==e.audio&&i.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.audio,codec:"adts",type:"audio"}),t.trigger("data",i)}})[s.type]()},this.reset=function(){i.size=0,i.data.length=0,n.size=0,n.data.length=0,this.trigger("reset")},this.flushStreams_=function(){a(i,"video"),a(n,"audio"),a(r,"timed-metadata")},this.flush=function(){this.flushStreams_(),this.trigger("done")}}).prototype=new H;var Ge={PAT_PID:0,MP2T_PACKET_LENGTH:We,TransportPacketStream:Be,TransportParseStream:Ne,ElementaryStream:Fe,TimestampRolloverStream:He,CaptionStream:we.CaptionStream,Cea608Stream:we.Cea608Stream,Cea708Stream:we.Cea708Stream,MetadataStream:qe};for(var Ve in Ae)Ae.hasOwnProperty(Ve)&&(Ge[Ve]=Ae[Ve]);var je,Xe=Ge,ze=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];(je=function(e){var t,i=0;je.prototype.init.call(this),this.push=function(n){var r,a,s,o,u,d,l=0;if(e||(i=0),"audio"===n.type)for(t?(o=t,(t=new Uint8Array(o.byteLength+n.data.byteLength)).set(o),t.set(n.data,o.byteLength)):t=n.data;l+5>5,d=9e4*(u=1024*(1+(3&t[l+6])))/ze[(60&t[l+2])>>>2],s=l+r,t.byteLength>>6&3),channelcount:(1&t[l+2])<<2|(192&t[l+3])>>>6,samplerate:ze[(60&t[l+2])>>>2],samplingfrequencyindex:(60&t[l+2])>>>2,samplesize:16,data:t.subarray(l+7+a,s)}),i++,t.byteLength===s)return void(t=void 0);t=t.subarray(s)}else l++},this.flush=function(){i=0,this.trigger("done")},this.reset=function(){t=void 0,this.trigger("reset")},this.endTimeline=function(){t=void 0,this.trigger("endedtimeline")}}).prototype=new H;var Qe,Ye,Ke,$e=je,Je=function(e){var t=e.byteLength,i=0,n=0;this.length=function(){return 8*t},this.bitsAvailable=function(){return 8*t+n},this.loadWord=function(){var r=e.byteLength-t,a=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");a.set(e.subarray(r,r+s)),i=new DataView(a.buffer).getUint32(0),n=8*s,t-=s},this.skipBits=function(e){var r;n>e?(i<<=e,n-=e):(e-=n,e-=8*(r=Math.floor(e/8)),t-=r,this.loadWord(),i<<=e,n-=e)},this.readBits=function(e){var r=Math.min(n,e),a=i>>>32-r;return(n-=r)>0?i<<=r:t>0&&this.loadWord(),(r=e-r)>0?a<>>e))return i<<=e,n-=e,e;return this.loadWord(),e+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var e=this.skipLeadingZeros();return this.readBits(e+1)-1},this.readExpGolomb=function(){var e=this.readUnsignedExpGolomb();return 1&e?1+e>>>1:-1*(e>>>1)},this.readBoolean=function(){return 1===this.readBits(1)},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};(Ye=function(){var e,t,i=0;Ye.prototype.init.call(this),this.push=function(n){var r;t?((r=new Uint8Array(t.byteLength+n.data.byteLength)).set(t),r.set(n.data,t.byteLength),t=r):t=n.data;for(var a=t.byteLength;i3&&this.trigger("data",t.subarray(i+3)),t=null,i=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}}).prototype=new H,Ke={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},(Qe=function(){var e,t,i,n,r,a,s,o=new Ye;Qe.prototype.init.call(this),e=this,this.push=function(e){"video"===e.type&&(t=e.trackId,i=e.pts,n=e.dts,o.push(e))},o.on("data",(function(s){var o={trackId:t,pts:i,dts:n,data:s};switch(31&s[0]){case 5:o.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:o.nalUnitType="sei_rbsp",o.escapedRBSP=r(s.subarray(1));break;case 7:o.nalUnitType="seq_parameter_set_rbsp",o.escapedRBSP=r(s.subarray(1)),o.config=a(o.escapedRBSP);break;case 8:o.nalUnitType="pic_parameter_set_rbsp";break;case 9:o.nalUnitType="access_unit_delimiter_rbsp"}e.trigger("data",o)})),o.on("done",(function(){e.trigger("done")})),o.on("partialdone",(function(){e.trigger("partialdone")})),o.on("reset",(function(){e.trigger("reset")})),o.on("endedtimeline",(function(){e.trigger("endedtimeline")})),this.flush=function(){o.flush()},this.partialFlush=function(){o.partialFlush()},this.reset=function(){o.reset()},this.endTimeline=function(){o.endTimeline()},s=function(e,t){var i,n=8,r=8;for(i=0;i=0?i:0,(16&e[t+5])>>4?i+20:i+10},nt=function e(t,i){return t.length-i<10||t[i]!=="I".charCodeAt(0)||t[i+1]!=="D".charCodeAt(0)||t[i+2]!=="3".charCodeAt(0)?i:e(t,i+=it(t,i))},rt=function(e){return e[0]<<21|e[1]<<14|e[2]<<7|e[3]},at={isLikelyAacData:function(e){var t=nt(e,0);return e.length>=t+2&&255==(255&e[t])&&240==(240&e[t+1])&&16==(22&e[t+1])},parseId3TagSize:it,parseAdtsSize:function(e,t){var i=(224&e[t+5])>>5,n=e[t+4]<<3;return 6144&e[t+3]|n|i},parseType:function(e,t){return e[t]==="I".charCodeAt(0)&&e[t+1]==="D".charCodeAt(0)&&e[t+2]==="3".charCodeAt(0)?"timed-metadata":!0&e[t]&&240==(240&e[t+1])?"audio":null},parseSampleRate:function(e){for(var t=0;t+5>>2];t++}return null},parseAacTimestamp:function(e){var t,i,n;t=10,64&e[5]&&(t+=4,t+=rt(e.subarray(10,14)));do{if((i=rt(e.subarray(t+4,t+8)))<1)return null;if("PRIV"===String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3])){n=e.subarray(t+10,t+i+10);for(var r=0;r>>2;return(s*=4)+(3&a[7])}break}}t+=10,t+=i}while(t=3;)if(e[u]!=="I".charCodeAt(0)||e[u+1]!=="D".charCodeAt(0)||e[u+2]!=="3".charCodeAt(0))if(255!=(255&e[u])||240!=(240&e[u+1]))u++;else{if(e.length-u<7)break;if(u+(o=at.parseAdtsSize(e,u))>e.length)break;a={type:"audio",data:e.subarray(u,u+o),pts:t,dts:t},this.trigger("data",a),u+=o}else{if(e.length-u<10)break;if(u+(o=at.parseId3TagSize(e,u))>e.length)break;r={type:"timed-metadata",data:e.subarray(u,u+o)},this.trigger("data",r),u+=o}n=e.length-u,e=n>0?e.subarray(u):new Uint8Array},this.reset=function(){e=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){e=new Uint8Array,this.trigger("endedtimeline")}}).prototype=new H;var st,ot,ut,dt,lt=Ze,ct=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],ht=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],ft=et.H264Stream,pt=at.isLikelyAacData,mt=function(e,t){var i;if(e.length!==t.length)return!1;for(i=0;i=i?e:(t.minSegmentDts=1/0,e.filter((function(e){return e.dts>=i&&(t.minSegmentDts=Math.min(t.minSegmentDts,e.dts),t.minSegmentPts=t.minSegmentDts,!0)})))}(i,e,r),e.baseMediaDecodeTime=he(e,t.keepOriginalTimestamps),f=le(e,o,a,s),e.samples=function(e){var t,i,n=[];for(t=0;t1&&(t=e.shift(),e.byteLength-=t.byteLength,e.nalCount-=t.nalCount,e[0][0].dts=t.dts,e[0][0].pts=t.pts,e[0][0].duration+=t.duration),e}(n)),s.length){var f;if(!(f=t.alignGopsAtEnd?this.alignGopsAtEnd_(n):this.alignGopsAtStart_(n)))return this.gopCache_.unshift({gop:n.pop(),pps:e.pps,sps:e.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),a=[],this.resetStream_(),void this.trigger("done","VideoSegmentStream");ce(e),n=f}fe(e,n),e.samples=function(e,t){var i,n,r,a,s,o=t||0,u=[];for(i=0;i=-1e4&&i<=45e3&&(!n||o>i)&&(n=a,o=i));return n?n.gop:null},this.alignGopsAtStart_=function(e){var t,i,n,r,a,o,u,d;for(a=e.byteLength,o=e.nalCount,u=e.duration,t=i=0;tn.pts?t++:(i++,a-=r.byteLength,o-=r.nalCount,u-=r.duration);return 0===i?e:i===e.length?null:((d=e.slice(i)).byteLength=a,d.duration=u,d.nalCount=o,d.pts=d[0].pts,d.dts=d[0].dts,d)},this.alignGopsAtEnd_=function(e){var t,i,n,r,a,o,u;for(t=s.length-1,i=e.length-1,a=null,o=!1;t>=0&&i>=0;){if(n=s[t],r=e[i],n.pts===r.pts){o=!0;break}n.pts>r.pts?t--:(t===s.length-1&&(a=i),i--)}if(!o&&null===a)return null;if(0===(u=o?i:a))return e;var d=e.slice(u),l=d.reduce((function(e,t){return e.byteLength+=t.byteLength,e.duration+=t.duration,e.nalCount+=t.nalCount,e}),{byteLength:0,duration:0,nalCount:0});return d.byteLength=l.byteLength,d.duration=l.duration,d.nalCount=l.nalCount,d.pts=d[0].pts,d.dts=d[0].dts,d},this.alignGopsWith=function(e){s=e}}).prototype=new H,(dt=function(e,t){this.numberOfTracks=0,this.metadataStream=t,void 0!==(e=e||{}).remux?this.remuxTracks=!!e.remux:this.remuxTracks=!0,"boolean"==typeof e.keepOriginalTimestamps?this.keepOriginalTimestamps=e.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,dt.prototype.init.call(this),this.push=function(e){return e.text?this.pendingCaptions.push(e):e.frames?this.pendingMetadata.push(e):(this.pendingTracks.push(e.track),this.pendingBytes+=e.boxes.byteLength,"video"===e.track.type&&(this.videoTrack=e.track,this.pendingBoxes.push(e.boxes)),void("audio"===e.track.type&&(this.audioTrack=e.track,this.pendingBoxes.unshift(e.boxes))))}}).prototype=new H,dt.prototype.flush=function(e){var t,i,n,a,s,o,d,l,c=0,h={captions:[],captionStreams:{},metadata:[],info:{}},f=0;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0))}if(this.videoTrack?(f=this.videoTrack.timelineStartInfo.pts,ht.forEach((function(e){h.info[e]=this.videoTrack[e]}),this)):this.audioTrack&&(f=this.audioTrack.timelineStartInfo.pts,ct.forEach((function(e){h.info[e]=this.audioTrack[e]}),this)),this.videoTrack||this.audioTrack){for(1===this.pendingTracks.length?h.type=this.pendingTracks[0].type:h.type="combined",this.emittedTracks+=this.pendingTracks.length,s=this.pendingTracks,o=void 0,d=void 0,l=void 0,d=r(),l=u(s),(o=new Uint8Array(d.byteLength+l.byteLength)).set(d),o.set(l,d.byteLength),n=o,h.initSegment=new Uint8Array(n.byteLength),h.initSegment.set(n),h.data=new Uint8Array(this.pendingBytes),a=0;a=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},dt.prototype.setRemux=function(e){this.remuxTracks=e},(ut=function(e){var t,i,n=this,r=!0;ut.prototype.init.call(this),e=e||{},this.baseMediaDecodeTime=e.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var r={};this.transmuxPipeline_=r,r.type="aac",r.metadataStream=new Xe.MetadataStream,r.aacStream=new lt,r.audioTimestampRolloverStream=new Xe.TimestampRolloverStream("audio"),r.timedMetadataTimestampRolloverStream=new Xe.TimestampRolloverStream("timed-metadata"),r.adtsStream=new $e,r.coalesceStream=new dt(e,r.metadataStream),r.headOfPipeline=r.aacStream,r.aacStream.pipe(r.audioTimestampRolloverStream).pipe(r.adtsStream),r.aacStream.pipe(r.timedMetadataTimestampRolloverStream).pipe(r.metadataStream).pipe(r.coalesceStream),r.metadataStream.on("timestamp",(function(e){r.aacStream.setTimestamp(e.timeStamp)})),r.aacStream.on("data",(function(a){"timed-metadata"!==a.type&&"audio"!==a.type||r.audioSegmentStream||(i=i||{timelineStartInfo:{baseMediaDecodeTime:n.baseMediaDecodeTime},codec:"adts",type:"audio"},r.coalesceStream.numberOfTracks++,r.audioSegmentStream=new ot(i,e),r.audioSegmentStream.on("timingInfo",n.trigger.bind(n,"audioTimingInfo")),r.adtsStream.pipe(r.audioSegmentStream).pipe(r.coalesceStream),n.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t}))})),r.coalesceStream.on("data",this.trigger.bind(this,"data")),r.coalesceStream.on("done",this.trigger.bind(this,"done"))},this.setupTsPipeline=function(){var r={};this.transmuxPipeline_=r,r.type="ts",r.metadataStream=new Xe.MetadataStream,r.packetStream=new Xe.TransportPacketStream,r.parseStream=new Xe.TransportParseStream,r.elementaryStream=new Xe.ElementaryStream,r.timestampRolloverStream=new Xe.TimestampRolloverStream,r.adtsStream=new $e,r.h264Stream=new ft,r.captionStream=new Xe.CaptionStream(e),r.coalesceStream=new dt(e,r.metadataStream),r.headOfPipeline=r.packetStream,r.packetStream.pipe(r.parseStream).pipe(r.elementaryStream).pipe(r.timestampRolloverStream),r.timestampRolloverStream.pipe(r.h264Stream),r.timestampRolloverStream.pipe(r.adtsStream),r.timestampRolloverStream.pipe(r.metadataStream).pipe(r.coalesceStream),r.h264Stream.pipe(r.captionStream).pipe(r.coalesceStream),r.elementaryStream.on("data",(function(a){var s;if("metadata"===a.type){for(s=a.tracks.length;s--;)t||"video"!==a.tracks[s].type?i||"audio"!==a.tracks[s].type||((i=a.tracks[s]).timelineStartInfo.baseMediaDecodeTime=n.baseMediaDecodeTime):(t=a.tracks[s]).timelineStartInfo.baseMediaDecodeTime=n.baseMediaDecodeTime;t&&!r.videoSegmentStream&&(r.coalesceStream.numberOfTracks++,r.videoSegmentStream=new st(t,e),r.videoSegmentStream.on("timelineStartInfo",(function(t){i&&!e.keepOriginalTimestamps&&(i.timelineStartInfo=t,r.audioSegmentStream.setEarliestDts(t.dts-n.baseMediaDecodeTime))})),r.videoSegmentStream.on("processedGopsInfo",n.trigger.bind(n,"gopInfo")),r.videoSegmentStream.on("segmentTimingInfo",n.trigger.bind(n,"videoSegmentTimingInfo")),r.videoSegmentStream.on("baseMediaDecodeTime",(function(e){i&&r.audioSegmentStream.setVideoBaseMediaDecodeTime(e)})),r.videoSegmentStream.on("timingInfo",n.trigger.bind(n,"videoTimingInfo")),r.h264Stream.pipe(r.videoSegmentStream).pipe(r.coalesceStream)),i&&!r.audioSegmentStream&&(r.coalesceStream.numberOfTracks++,r.audioSegmentStream=new ot(i,e),r.audioSegmentStream.on("timingInfo",n.trigger.bind(n,"audioTimingInfo")),r.audioSegmentStream.on("segmentTimingInfo",n.trigger.bind(n,"audioSegmentTimingInfo")),r.adtsStream.pipe(r.audioSegmentStream).pipe(r.coalesceStream)),n.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t})}})),r.coalesceStream.on("data",this.trigger.bind(this,"data")),r.coalesceStream.on("id3Frame",(function(e){e.dispatchType=r.metadataStream.dispatchType,n.trigger("id3Frame",e)})),r.coalesceStream.on("caption",this.trigger.bind(this,"caption")),r.coalesceStream.on("done",this.trigger.bind(this,"done"))},this.setBaseMediaDecodeTime=function(n){var r=this.transmuxPipeline_;e.keepOriginalTimestamps||(this.baseMediaDecodeTime=n),i&&(i.timelineStartInfo.dts=void 0,i.timelineStartInfo.pts=void 0,ce(i),r.audioTimestampRolloverStream&&r.audioTimestampRolloverStream.discontinuity()),t&&(r.videoSegmentStream&&(r.videoSegmentStream.gopCache_=[]),t.timelineStartInfo.dts=void 0,t.timelineStartInfo.pts=void 0,ce(t),r.captionStream.reset()),r.timestampRolloverStream&&r.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(e){i&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(e)},this.setRemux=function(t){var i=this.transmuxPipeline_;e.remux=t,i&&i.coalesceStream&&i.coalesceStream.setRemux(t)},this.alignGopsWith=function(e){t&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(e)},this.push=function(e){if(r){var t=pt(e);t&&"aac"!==this.transmuxPipeline_.type?this.setupAacPipeline():t||"ts"===this.transmuxPipeline_.type||this.setupTsPipeline(),r=!1}this.transmuxPipeline_.headOfPipeline.push(e)},this.flush=function(){r=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}}).prototype=new H;var yt,_t={Transmuxer:ut,VideoSegmentStream:st,AudioSegmentStream:ot,AUDIO_PROPERTIES:ct,VIDEO_PROPERTIES:ht,generateSegmentTimingInfo:gt},vt=function(e){return e>>>0},Tt=function(e){var t="";return t+=String.fromCharCode(e[0]),t+=String.fromCharCode(e[1]),(t+=String.fromCharCode(e[2]))+String.fromCharCode(e[3])},bt=vt,St=function e(t,i){var n,r,a,s,o,u=[];if(!i.length)return null;for(n=0;n1?n+r:t.byteLength,a===i[0]&&(1===i.length?u.push(t.subarray(n+8,s)):(o=e(t.subarray(n+8,s),i.slice(1))).length&&(u=u.concat(o))),n=s;return u},It=vt,Et=function(e){return{isLeading:(12&e[0])>>>2,dependsOn:3&e[0],isDependedOn:(192&e[1])>>>6,hasRedundancy:(48&e[1])>>>4,paddingValue:(14&e[1])>>>1,isNonSyncSample:1&e[1],degradationPriority:e[2]<<8|e[3]}},wt=function(e){for(var t,i,n=e.byteLength,r=[],a=1;a0?function(e){var t={version:e[0],flags:new Uint8Array(e.subarray(1,4)),baseMediaDecodeTime:It(e[4]<<24|e[5]<<16|e[6]<<8|e[7])};return 1===t.version&&(t.baseMediaDecodeTime*=Math.pow(2,32),t.baseMediaDecodeTime+=It(e[8]<<24|e[9]<<16|e[10]<<8|e[11])),t}(T[0]).baseMediaDecodeTime:0,S=St(g,["trun"]);t===v&&S.length>0&&(i=function(e,t,i){var n,r,a,s,o=new DataView(e.buffer,e.byteOffset,e.byteLength),u=[];for(r=0;r+40;){var u=t.shift();this.parse(u,a,s)}return null!==(o=function(e,t,i){return null===t?null:{seiNals:Pt(e,t)[t],timescale:i}}(e,i,n))&&o.seiNals?(this.pushNals(o.seiNals),this.flushStream(),r):null},this.pushNals=function(t){if(!this.isInitialized()||!t||0===t.length)return null;t.forEach((function(t){e.push(t)}))},this.flushStream=function(){if(!this.isInitialized())return null;a?e.partialFlush():e.flush()},this.clearParsedCaptions=function(){r.captions=[],r.captionStreams={}},this.resetCaptionStream=function(){if(!this.isInitialized())return null;e.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){t=[],i=null,n=null,r?this.clearParsedCaptions():r={captions:[],captionStreams:{}},this.resetCaptionStream()},this.reset()},Ot=vt,xt=function(e){return("00"+e.toString(16)).slice(-2)},Dt=function(e,t){var i,n,r;return i=St(t,["moof","traf"]),n=[].concat.apply([],i.map((function(t){return St(t,["tfhd"]).map((function(i){var n,r,a;return n=Ot(i[4]<<24|i[5]<<16|i[6]<<8|i[7]),r=e[n]||9e4,(a="number"!=typeof(a=St(t,["tfdt"]).map((function(e){var t,i;return t=e[0],i=Ot(e[4]<<24|e[5]<<16|e[6]<<8|e[7]),1===t&&(i*=Math.pow(2,32),i+=Ot(e[8]<<24|e[9]<<16|e[10]<<8|e[11])),i}))[0])||isNaN(a)?1/0:a)/r}))}))),r=Math.min.apply(null,n),isFinite(r)?r:0},Ct=function(e){var t=St(e,["moov","trak"]),i=[];return t.forEach((function(e){var t,n,r={},a=St(e,["tkhd"])[0];a&&(n=(t=new DataView(a.buffer,a.byteOffset,a.byteLength)).getUint8(0),r.id=0===n?t.getUint32(12):t.getUint32(20));var s=St(e,["mdia","hdlr"])[0];if(s){var o=Tt(s.subarray(8,12));r.type="vide"===o?"video":"soun"===o?"audio":o}var u=St(e,["mdia","minf","stbl","stsd"])[0];if(u){var d=u.subarray(8);r.codec=Tt(d.subarray(4,8));var l,c=St(d,[r.codec])[0];c&&(/^[a-z]vc[1-9]$/i.test(r.codec)?(l=c.subarray(78),"avcC"===Tt(l.subarray(4,8))&&l.length>11?(r.codec+=".",r.codec+=xt(l[9]),r.codec+=xt(l[10]),r.codec+=xt(l[11])):r.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(r.codec)?(l=c.subarray(28),"esds"===Tt(l.subarray(4,8))&&l.length>20&&0!==l[19]?(r.codec+="."+xt(l[19]),r.codec+="."+xt(l[20]>>>2&63).replace(/^0/,"")):r.codec="mp4a.40.2"):r.codec=r.codec.toLowerCase())}var h=St(e,["mdia","mdhd"])[0];h&&(r.timescale=yt(h)),i.push(r)})),i},Ut=(yt=function(e){var t=0===e[0]?12:20;return Ot(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])},function(e){var t=31&e[1];return(t<<=8)|e[2]}),Rt=function(e){return!!(64&e[1])},Mt=function(e){var t=0;return(48&e[3])>>>4>1&&(t+=e[4]+1),t},Bt=function(e){switch(e){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},Nt={parseType:function(e,t){var i=Ut(e);return 0===i?"pat":i===t?"pmt":t?"pes":null},parsePat:function(e){var t=Rt(e),i=4+Mt(e);return t&&(i+=e[i]+1),(31&e[i+10])<<8|e[i+11]},parsePmt:function(e){var t={},i=Rt(e),n=4+Mt(e);if(i&&(n+=e[n]+1),1&e[n+5]){var r;r=3+((15&e[n+1])<<8|e[n+2])-4;for(var a=12+((15&e[n+10])<<8|e[n+11]);a=e.byteLength)return null;var i,n=null;return 192&(i=e[t+7])&&((n={}).pts=(14&e[t+9])<<27|(255&e[t+10])<<20|(254&e[t+11])<<12|(255&e[t+12])<<5|(254&e[t+13])>>>3,n.pts*=4,n.pts+=(6&e[t+13])>>>1,n.dts=n.pts,64&i&&(n.dts=(14&e[t+14])<<27|(255&e[t+15])<<20|(254&e[t+16])<<12|(255&e[t+17])<<5|(254&e[t+18])>>>3,n.dts*=4,n.dts+=(6&e[t+18])>>>1)),n},videoPacketContainsKeyFrame:function(e){for(var t=4+Mt(e),i=e.subarray(t),n=0,r=0,a=!1;r3&&"slice_layer_without_partitioning_rbsp_idr"===Bt(31&i[r+3])&&(a=!0),a}},Ft=De,qt={};qt.ts=Nt,qt.aac=at;var Ht=re,Wt=188,Gt=71,Vt=function(e,t,i){for(var n,r,a,s,o=0,u=Wt,d=!1;u<=e.byteLength;)if(e[o]!==Gt||e[u]!==Gt&&u!==e.byteLength)o++,u++;else{switch(n=e.subarray(o,u),qt.ts.parseType(n,t.pid)){case"pes":r=qt.ts.parsePesType(n,t.table),a=qt.ts.parsePayloadUnitStartIndicator(n),"audio"===r&&a&&(s=qt.ts.parsePesTime(n))&&(s.type="audio",i.audio.push(s),d=!0)}if(d)break;o+=Wt,u+=Wt}for(o=(u=e.byteLength)-Wt,d=!1;o>=0;)if(e[o]!==Gt||e[u]!==Gt&&u!==e.byteLength)o--,u--;else{switch(n=e.subarray(o,u),qt.ts.parseType(n,t.pid)){case"pes":r=qt.ts.parsePesType(n,t.table),a=qt.ts.parsePayloadUnitStartIndicator(n),"audio"===r&&a&&(s=qt.ts.parsePesTime(n))&&(s.type="audio",i.audio.push(s),d=!0)}if(d)break;o-=Wt,u-=Wt}},jt=function(e,t,i){for(var n,r,a,s,o,u,d,l=0,c=Wt,h=!1,f={data:[],size:0};c=0;)if(e[l]!==Gt||e[c]!==Gt)l--,c--;else{switch(n=e.subarray(l,c),qt.ts.parseType(n,t.pid)){case"pes":r=qt.ts.parsePesType(n,t.table),a=qt.ts.parsePayloadUnitStartIndicator(n),"video"===r&&a&&(s=qt.ts.parsePesTime(n))&&(s.type="video",i.video.push(s),h=!0)}if(h)break;l-=Wt,c-=Wt}},Xt=function(e,t){var i;return(i=qt.aac.isLikelyAacData(e)?function(e){for(var t,i=!1,n=0,r=null,a=null,s=0,o=0;e.length-o>=3;){switch(qt.aac.parseType(e,o)){case"timed-metadata":if(e.length-o<10){i=!0;break}if((s=qt.aac.parseId3TagSize(e,o))>e.length){i=!0;break}null===a&&(t=e.subarray(o,o+s),a=qt.aac.parseAacTimestamp(t)),o+=s;break;case"audio":if(e.length-o<7){i=!0;break}if((s=qt.aac.parseAdtsSize(e,o))>e.length){i=!0;break}null===r&&(t=e.subarray(o,o+s),r=qt.aac.parseSampleRate(t)),n++,o+=s;break;default:o++}if(i)return null}if(null===r||null===a)return null;var u=Ht/r;return{audio:[{type:"audio",dts:a,pts:a},{type:"audio",dts:a+1024*n*u,pts:a+1024*n*u}]}}(e):function(e){var t={pid:null,table:null},i={};for(var n in function(e,t){for(var i,n=0,r=Wt;r0}(f)){t.isFmp4=!0;var p=t.map.tracks,m={isFmp4:!0,hasVideo:!!p.video,hasAudio:!!p.audio};p.audio&&p.audio.codec&&"enca"!==p.audio.codec&&(m.audioCodec=p.audio.codec),p.video&&p.video.codec&&"encv"!==p.video.codec&&(m.videoCodec=p.video.codec),p.video&&p.audio&&(m.isMuxed=!0),n(t,m);var g=function(e){c(t,{data:f,type:m.hasAudio&&!m.isMuxed?"audio":"video"}),e&&e.length&&u(t,e),h(null,t,{})};pi({action:"probeMp4StartTime",timescales:t.map.timescales,data:f,transmuxer:t.transmuxer,callback:function(e){var n=e.data,a=e.startTime;i=n.buffer,t.bytes=f=n,m.hasAudio&&!m.isMuxed&&r(t,"audio","start",a),m.hasVideo&&r(t,"video","start",a),p.video&&n.byteLength&&t.transmuxer?pi({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:t.transmuxer,data:f,timescales:t.map.timescales,trackIds:[p.video.id],callback:function(e){i=e.data.buffer,t.bytes=f=e.data,g(e.captions)}}):g()}})}else if(t.transmuxer){if(void 0===t.container&&(t.container=$t(f)),"ts"!==t.container&&"aac"!==t.container)return n(t,{hasAudio:!1,hasVideo:!1}),void h(null,t,{});bi({segment:t,bytes:i,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:a,audioSegmentTimingInfoFn:s,id3Fn:o,captionsFn:u,isEndOfTimeline:d,endedTimelineFn:l,dataFn:c,doneFn:h})}else h(null,t,{})},Ii=function(e,t){var i,n=e.id,r=e.key,a=e.encryptedBytes,s=e.decryptionWorker;s.addEventListener("message",(function e(i){if(i.data.source===n){s.removeEventListener("message",e);var r=i.data.decrypted;t(new Uint8Array(r.bytes,r.byteOffset,r.byteLength))}})),i=r.bytes.slice?r.bytes.slice():new Uint32Array(Array.prototype.slice.call(r.bytes)),s.postMessage(Be({source:n,encrypted:a,key:i,iv:r.iv}),[a.buffer,i.buffer])},Ei=function(e){var t=e.xhr,i=e.xhrOptions,n=e.decryptionWorker,r=e.segment,a=e.abortFn,s=e.progressFn,o=e.trackInfoFn,d=e.timingInfoFn,l=e.videoSegmentTimingInfoFn,c=e.audioSegmentTimingInfoFn,h=e.id3Fn,f=e.captionsFn,p=e.isEndOfTimeline,m=e.endedTimelineFn,g=e.dataFn,y=e.doneFn,_=[],v=function(e){var t=e.activeXhrs,i=e.decryptionWorker,n=e.trackInfoFn,r=e.timingInfoFn,a=e.videoSegmentTimingInfoFn,s=e.audioSegmentTimingInfoFn,o=e.id3Fn,u=e.captionsFn,d=e.isEndOfTimeline,l=e.endedTimelineFn,c=e.dataFn,h=e.doneFn,f=0,p=!1;return function(e,m){if(!p){if(e)return p=!0,yi(t),h(e,m);if((f+=1)===t.length){var g=function(){if(m.encryptedBytes)return function(e){var t=e.decryptionWorker,i=e.segment,n=e.trackInfoFn,r=e.timingInfoFn,a=e.videoSegmentTimingInfoFn,s=e.audioSegmentTimingInfoFn,o=e.id3Fn,u=e.captionsFn,d=e.isEndOfTimeline,l=e.endedTimelineFn,c=e.dataFn,h=e.doneFn;Ii({id:i.requestId,key:i.key,encryptedBytes:i.encryptedBytes,decryptionWorker:t},(function(e){i.bytes=e,Si({segment:i,bytes:i.bytes,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:a,audioSegmentTimingInfoFn:s,id3Fn:o,captionsFn:u,isEndOfTimeline:d,endedTimelineFn:l,dataFn:c,doneFn:h})}))}({decryptionWorker:i,segment:m,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:a,audioSegmentTimingInfoFn:s,id3Fn:o,captionsFn:u,isEndOfTimeline:d,endedTimelineFn:l,dataFn:c,doneFn:h});Si({segment:m,bytes:m.bytes,trackInfoFn:n,timingInfoFn:r,videoSegmentTimingInfoFn:a,audioSegmentTimingInfoFn:s,id3Fn:o,captionsFn:u,isEndOfTimeline:d,endedTimelineFn:l,dataFn:c,doneFn:h})};if(m.endOfAllRequests=Date.now(),m.map&&m.map.encryptedBytes&&!m.map.bytes)return Ii({decryptionWorker:i,id:m.requestId+"-init",encryptedBytes:m.map.encryptedBytes,key:m.map.key},(function(e){m.map.bytes=e,Ti(m,(function(e){if(e)return yi(t),h(e,m);g()}))}));g()}}}}({activeXhrs:_,decryptionWorker:n,trackInfoFn:o,timingInfoFn:d,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:c,id3Fn:h,captionsFn:f,isEndOfTimeline:p,endedTimelineFn:m,dataFn:g,doneFn:y});if(r.key&&!r.key.bytes){var T=[r.key];r.map&&!r.map.bytes&&r.map.key&&r.map.key.resolvedUri===r.key.resolvedUri&&T.push(r.map.key);var b=t(u.default.mergeOptions(i,{uri:r.key.resolvedUri,responseType:"arraybuffer"}),vi(r,T,v));_.push(b)}if(r.map&&!r.map.bytes){if(r.map.key&&(!r.key||r.key.resolvedUri!==r.map.key.resolvedUri)){var S=t(u.default.mergeOptions(i,{uri:r.map.key.resolvedUri,responseType:"arraybuffer"}),vi(r,[r.map.key],v));_.push(S)}var I=t(u.default.mergeOptions(i,{uri:r.map.resolvedUri,responseType:"arraybuffer",headers:Oe(r.map)}),function(e){var t=e.segment,i=e.finishProcessingFn;return function(e,n){var r=_i(e,n);if(r)return i(r,t);var a=new Uint8Array(n.response);if(t.map.key)return t.map.encryptedBytes=a,i(null,t);t.map.bytes=a,Ti(t,(function(e){if(e)return e.xhr=n,e.status=n.status,i(e,t);i(null,t)}))}}({segment:r,finishProcessingFn:v}));_.push(I)}var E=u.default.mergeOptions(i,{uri:r.part&&r.part.resolvedUri||r.resolvedUri,responseType:"arraybuffer",headers:Oe(r)}),w=t(E,function(e){var t=e.segment,i=e.finishProcessingFn,n=e.responseType;return function(e,r){var a=_i(e,r);if(a)return i(a,t);var s="arraybuffer"!==n&&r.responseText?function(e){for(var t=new Uint8Array(new ArrayBuffer(e.length)),i=0;i1)return wi("multiple "+e+" codecs found as attributes: "+t[e].join(", ")+". Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs."),void(t[e]=null);t[e]=t[e][0]})),t},Pi=function(e){var t=0;return e.audio&&t++,e.video&&t++,t},ki=function(e,t){var i=t.attributes||{},n=Li(function(e){var t=e.attributes||{};if(t.CODECS)return U(t.CODECS)}(t)||[]);if(Ai(e,t)&&!n.audio&&!function(e,t){if(!Ai(e,t))return!0;var i=t.attributes||{},n=e.mediaGroups.AUDIO[i.AUDIO];for(var r in n)if(!n[r].uri&&!n[r].playlists)return!0;return!1}(e,t)){var r=Li(function(e,t){if(!e.mediaGroups.AUDIO||!t)return null;var i=e.mediaGroups.AUDIO[t];if(!i)return null;for(var n in i){var r=i[n];if(r.default&&r.playlists)return U(r.playlists[0].attributes.CODECS)}return null}(e,i.AUDIO)||[]);r.audio&&(n.audio=r.audio)}return n},Oi=_("PlaylistSelector"),xi=function(e){if(e&&e.playlist){var t=e.playlist;return JSON.stringify({id:t.id,bandwidth:e.bandwidth,width:e.width,height:e.height,codecs:t.attributes&&t.attributes.CODECS||""})}},Di=function(e,t){if(!e)return"";var i=o.default.getComputedStyle(e);return i?i[t]:""},Ci=function(e,t){var i=e.slice();e.sort((function(e,n){var r=t(e,n);return 0===r?i.indexOf(e)-i.indexOf(n):r}))},Ui=function(e,t){var i,n;return e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||o.default.Number.MAX_VALUE,t.attributes.BANDWIDTH&&(n=t.attributes.BANDWIDTH),i-(n||o.default.Number.MAX_VALUE)},Ri=function(e,t,i,n,r,a){if(e){var s={bandwidth:t,width:i,height:n,limitRenditionByPlayerDimensions:r},u=e.playlists;ce.isAudioOnly(e)&&(u=a.getAudioTrackPlaylists_(),s.audioOnly=!0);var d=u.map((function(e){var t=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width,i=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height;return{bandwidth:e.attributes&&e.attributes.BANDWIDTH||o.default.Number.MAX_VALUE,width:t,height:i,playlist:e}}));Ci(d,(function(e,t){return e.bandwidth-t.bandwidth}));var l=(d=d.filter((function(e){return!ce.isIncompatible(e.playlist)}))).filter((function(e){return ce.isEnabled(e.playlist)}));l.length||(l=d.filter((function(e){return!ce.isDisabled(e.playlist)})));var c=l.filter((function(e){return e.bandwidth*ri.BANDWIDTH_VARIANCEi||e.height>n}))).filter((function(e){return e.width===_[0].width&&e.height===_[0].height})),h=v[v.length-1],T=v.filter((function(e){return e.bandwidth===h.bandwidth}))[0]);var S=T||b||f||l[0]||d[0];if(S&&S.playlist){var I="sortedPlaylistReps";return T?I="resolutionPlusOneRep":b?I="resolutionBestRep":f?I="bandwidthBestRep":l[0]&&(I="enabledPlaylistReps"),Oi("choosing "+xi(S)+" using "+I+" with options",s),S.playlist}return Oi("could not choose a playlist with options",s),null}},Mi=function(){var e=this.useDevicePixelRatio&&o.default.devicePixelRatio||1;return Ri(this.playlists.master,this.systemBandwidth,parseInt(Di(this.tech_.el(),"width"),10)*e,parseInt(Di(this.tech_.el(),"height"),10)*e,this.limitRenditionByPlayerDimensions,this.masterPlaylistController_)},Bi=function(e,t,i){var n,r;if(i&&i.cues)for(n=i.cues.length;n--;)(r=i.cues[n]).startTime>=e&&r.endTime<=t&&i.removeCue(r)},Ni=9e4,Fi=Ni,qi=(function(e){return e*Ni},function(e,t){return e*t},function(e){return e/Ni},function(e,t){return e/t},function(e){return"number"==typeof e&&isFinite(e)}),Hi=1/60,Wi=function(e){var t=e.startOfSegment,i=e.duration,n=e.segment,r=e.part,a=e.playlist,s=a.mediaSequence,o=a.id,u=a.segments,d=void 0===u?[]:u,l=e.mediaIndex,c=e.partIndex,h=e.timeline,f=d.length-1,p="mediaIndex/partIndex increment";e.getMediaInfoForTime?p="getMediaInfoForTime ("+e.getMediaInfoForTime+")":e.isSyncRequest&&(p="getSyncSegmentCandidate (isSyncRequest)");var m="number"==typeof c,g=e.segment.uri?"segment":"pre-segment",y=m?$({preloadSegment:n})-1:0;return g+" ["+(s+l)+"/"+(s+f)+"]"+(m?" part ["+c+"/"+y+"]":"")+" segment start/end ["+n.start+" => "+n.end+"]"+(m?" part start/end ["+r.start+" => "+r.end+"]":"")+" startOfSegment ["+t+"] duration ["+i+"] timeline ["+h+"] selected by ["+p+"] playlist ["+o+"]"},Gi=function(e){return e+"TimingInfo"},Vi=function(e){var t=e.timelineChangeController,i=e.currentTimeline,n=e.segmentTimeline,r=e.loaderType,a=e.audioDisabled;if(i===n)return!1;if("audio"===r){var s=t.lastTimelineChange({type:"main"});return!s||s.to!==n}if("main"===r&&a){var o=t.pendingTimelineChange({type:"audio"});return!o||o.to!==n}return!1},ji=function(e){var t=e.segmentDuration,i=e.maxDuration;return!!t&&Math.round(t)>i+q},Xi=function(e){function t(t,i){var n;if(n=e.call(this)||this,!t)throw new TypeError("Initialization settings are required");if("function"!=typeof t.currentTime)throw new TypeError("No currentTime getter specified");if(!t.mediaSource)throw new TypeError("No MediaSource specified");return n.bandwidth=t.bandwidth,n.throughput={rate:0,count:0},n.roundTrip=NaN,n.resetStats_(),n.mediaIndex=null,n.partIndex=null,n.hasPlayed_=t.hasPlayed,n.currentTime_=t.currentTime,n.seekable_=t.seekable,n.seeking_=t.seeking,n.duration_=t.duration,n.mediaSource_=t.mediaSource,n.vhs_=t.vhs,n.loaderType_=t.loaderType,n.currentMediaInfo_=void 0,n.startingMediaInfo_=void 0,n.segmentMetadataTrack_=t.segmentMetadataTrack,n.goalBufferLength_=t.goalBufferLength,n.sourceType_=t.sourceType,n.sourceUpdater_=t.sourceUpdater,n.inbandTextTracks_=t.inbandTextTracks,n.state_="INIT",n.timelineChangeController_=t.timelineChangeController,n.shouldSaveSegmentTimingInfo_=!0,n.parse708captions_=t.parse708captions,n.checkBufferTimeout_=null,n.error_=void 0,n.currentTimeline_=-1,n.pendingSegment_=null,n.xhrOptions_=null,n.pendingSegments_=[],n.audioDisabled_=!1,n.isPendingTimestampOffset_=!1,n.gopBuffer_=[],n.timeMapping_=0,n.safeAppend_=u.default.browser.IE_VERSION>=11,n.appendInitSegment_={audio:!0,video:!0},n.playlistOfLastInitSegment_={audio:null,video:null},n.callQueue_=[],n.loadQueue_=[],n.metadataQueue_={id3:[],caption:[]},n.waitingOnRemove_=!1,n.quotaExceededErrorRetryTimeout_=null,n.activeInitSegmentId_=null,n.initSegments_={},n.cacheEncryptionKeys_=t.cacheEncryptionKeys,n.keyCache_={},n.decrypter_=t.decrypter,n.syncController_=t.syncController,n.syncPoint_={segmentIndex:0,time:0},n.transmuxer_=n.createTransmuxer_(),n.triggerSyncInfoUpdate_=function(){return n.trigger("syncinfoupdate")},n.syncController_.on("syncinfoupdate",n.triggerSyncInfoUpdate_),n.mediaSource_.addEventListener("sourceopen",(function(){n.isEndOfStream_()||(n.ended_=!1)})),n.fetchAtBuffer_=!1,n.logger_=_("SegmentLoader["+n.loaderType_+"]"),Object.defineProperty(l(n),"state",{get:function(){return this.state_},set:function(e){e!==this.state_&&(this.logger_(this.state_+" -> "+e),this.state_=e,this.trigger("statechange"))}}),n.sourceUpdater_.on("ready",(function(){n.hasEnoughInfoToAppend_()&&n.processCallQueue_()})),"main"===n.loaderType_&&n.timelineChangeController_.on("pendingtimelinechange",(function(){n.hasEnoughInfoToAppend_()&&n.processCallQueue_()})),"audio"===n.loaderType_&&n.timelineChangeController_.on("timelinechange",(function(){n.hasEnoughInfoToLoad_()&&n.processLoadQueue_(),n.hasEnoughInfoToAppend_()&&n.processCallQueue_()})),n}h(t,e);var i=t.prototype;return i.createTransmuxer_=function(){return function(e){var t=new di;t.currentTransmux=null,t.transmuxQueue=[];var i=t.terminate;return t.terminate=function(){return t.currentTransmux=null,t.transmuxQueue.length=0,i.call(t)},t.postMessage({action:"init",options:e}),t}({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_})},i.resetStats_=function(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0},i.dispose=function(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&o.default.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()},i.setAudio=function(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())},i.abort=function(){"WAITING"===this.state?(this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()):this.pendingSegment_&&(this.pendingSegment_=null)},i.abort_=function(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,o.default.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null},i.checkForAbort_=function(e){return"APPENDING"!==this.state||this.pendingSegment_?!this.pendingSegment_||this.pendingSegment_.requestId!==e:(this.state="READY",!0)},i.error=function(e){return void 0!==e&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_},i.endOfStream=function(){this.ended_=!0,this.transmuxer_&&fi(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")},i.buffered_=function(){if(!this.sourceUpdater_||!this.startingMediaInfo_)return u.default.createTimeRanges();if("main"===this.loaderType_){var e=this.startingMediaInfo_,t=e.hasAudio,i=e.hasVideo,n=e.isMuxed;if(i&&t&&!this.audioDisabled_&&!n)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()},i.initSegmentForMap=function(e,t){if(void 0===t&&(t=!1),!e)return null;var i=Ne(e),n=this.initSegments_[i];return t&&!n&&e.bytes&&(this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),n||e},i.segmentKey=function(e,t){if(void 0===t&&(t=!1),!e)return null;var i=Fe(e),n=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!n&&e.bytes&&(this.keyCache_[i]=n={resolvedUri:e.resolvedUri,bytes:e.bytes});var r={resolvedUri:(n||e).resolvedUri};return n&&(r.bytes=n.bytes),r},i.couldBeginLoading_=function(){return this.playlist_&&!this.paused()},i.load=function(){if(this.monitorBuffer_(),this.playlist_)return"INIT"===this.state&&this.couldBeginLoading_()?this.init_():void(!this.couldBeginLoading_()||"READY"!==this.state&&"INIT"!==this.state||(this.state="READY"))},i.init_=function(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()},i.playlist=function(e,t){if(void 0===t&&(t={}),e){var i=this.playlist_,n=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,"INIT"===this.state&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},"main"===this.loaderType_&&this.syncController_.setDateTimeMappingForStart(e));var r=null;if(i&&(i.id?r=i.id:i.uri&&(r=i.uri)),this.logger_("playlist update ["+r+" => "+(e.id||e.uri)+"]"),this.trigger("syncinfoupdate"),"INIT"===this.state&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri)return null!==this.mediaIndex&&this.resyncLoader(),this.currentMediaInfo_=void 0,void this.trigger("playlistupdate");var a=e.mediaSequence-i.mediaSequence;if(this.logger_("live window shift ["+a+"]"),null!==this.mediaIndex)if(this.mediaIndex-=a,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{var s=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!s.parts||!s.parts.length||!s.parts[this.partIndex])){var o=this.mediaIndex;this.logger_("currently processing part (index "+this.partIndex+") no longer exists."),this.resetLoader(),this.mediaIndex=o}}n&&(n.mediaIndex-=a,n.mediaIndex<0?(n.mediaIndex=null,n.partIndex=null):(n.mediaIndex>=0&&(n.segment=e.segments[n.mediaIndex]),n.partIndex>=0&&n.segment.parts&&(n.part=n.segment.parts[n.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}},i.pause=function(){this.checkBufferTimeout_&&(o.default.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)},i.paused=function(){return null===this.checkBufferTimeout_},i.resetEverything=function(e){this.ended_=!1,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"})},i.resetLoader=function(){this.fetchAtBuffer_=!1,this.resyncLoader()},i.resyncLoader=function(){this.transmuxer_&&fi(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})},i.remove=function(e,t,i,n){if(void 0===i&&(i=function(){}),void 0===n&&(n=!1),t===1/0&&(t=this.duration_()),t<=e)this.logger_("skipping remove because end ${end} is <= start ${start}");else if(this.sourceUpdater_&&this.startingMediaInfo_){var r=1,a=function(){0==--r&&i()};for(var s in!n&&this.audioDisabled_||(r++,this.sourceUpdater_.removeAudio(e,t,a)),(n||"main"===this.loaderType_)&&(this.gopBuffer_=function(e,t,i,n){for(var r=Math.ceil((t-n)*Fi),a=Math.ceil((i-n)*Fi),s=e.slice(),o=e.length;o--&&!(e[o].pts<=a););if(-1===o)return s;for(var u=o+1;u--&&!(e[u].pts<=r););return u=Math.max(u,0),s.splice(u,o-u+1),s}(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,a)),this.inbandTextTracks_)Bi(e,t,this.inbandTextTracks_[s]);Bi(e,t,this.segmentMetadataTrack_),a()}else this.logger_("skipping remove because no source updater or starting media info")},i.monitorBuffer_=function(){this.checkBufferTimeout_&&o.default.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=o.default.setTimeout(this.monitorBufferTick_.bind(this),1)},i.monitorBufferTick_=function(){"READY"===this.state&&this.fillBuffer_(),this.checkBufferTimeout_&&o.default.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=o.default.setTimeout(this.monitorBufferTick_.bind(this),500)},i.fillBuffer_=function(){if(!this.sourceUpdater_.updating()){var e=this.chooseNextRequest_();e&&("number"==typeof e.timestampOffset&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e))}},i.isEndOfStream_=function(e,t,i){if(void 0===e&&(e=this.mediaIndex),void 0===t&&(t=this.playlist_),void 0===i&&(i=this.partIndex),!t||!this.mediaSource_)return!1;var n="number"==typeof e&&t.segments[e],r=e+1===t.segments.length,a=!n||!n.parts||i+1===n.parts.length;return t.endList&&"open"===this.mediaSource_.readyState&&r&&a},i.chooseNextRequest_=function(){var e=z(this.buffered_())||0,t=Math.max(0,e-this.currentTime_()),i=!this.hasPlayed_()&&t>=1,n=t>=this.goalBufferLength_(),r=this.playlist_.segments;if(!r.length||i||n)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_());var a={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:Boolean(!this.syncPoint_)};if(a.isSyncRequest)a.mediaIndex=function(e,t,i){t=t||[];for(var n=[],r=0,a=0;ai))return a}return 0===n.length?0:n[n.length-1]}(this.currentTimeline_,r,e);else if(null!==this.mediaIndex){var s=r[this.mediaIndex],o="number"==typeof this.partIndex?this.partIndex:-1;a.startOfSegment=s.end?s.end:e,s.parts&&s.parts[o+1]?(a.mediaIndex=this.mediaIndex,a.partIndex=o+1):a.mediaIndex=this.mediaIndex+1}else{var u=ce.getMediaInfoForTime({playlist:this.playlist_,currentTime:this.fetchAtBuffer_?e:this.currentTime_(),startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time}),d=u.segmentIndex,l=u.startTime,c=u.partIndex;a.getMediaInfoForTime=this.fetchAtBuffer_?"bufferedEnd":"currentTime",a.mediaIndex=d,a.startOfSegment=l,a.partIndex=c}var h=r[a.mediaIndex],f=h&&"number"==typeof a.partIndex&&h.parts&&h.parts[a.partIndex];if(!h||"number"==typeof a.partIndex&&!f)return null;"number"!=typeof a.partIndex&&h.parts&&(a.partIndex=0);var p=this.mediaSource_&&"ended"===this.mediaSource_.readyState;return a.mediaIndex>=r.length-1&&p&&!this.seeking_()?null:this.generateSegmentInfo_(a)},i.generateSegmentInfo_=function(e){var t=e.playlist,i=e.mediaIndex,n=e.startOfSegment,r=e.isSyncRequest,a=e.partIndex,s=e.forceTimestampOffset,o=e.getMediaInfoForTime,u=t.segments[i],d="number"==typeof a&&u.parts[a],l={requestId:"segment-loader-"+Math.random(),uri:d&&d.resolvedUri||u.resolvedUri,mediaIndex:i,partIndex:d?a:null,isSyncRequest:r,startOfSegment:n,playlist:t,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:u.timeline,duration:d&&d.duration||u.duration,segment:u,part:d,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:o},c=void 0!==s?s:this.isPendingTimestampOffset_;l.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:u.timeline,currentTimeline:this.currentTimeline_,startOfSegment:n,buffered:this.buffered_(),overrideCheck:c});var h=z(this.sourceUpdater_.audioBuffered());return"number"==typeof h&&(l.audioAppendStart=h-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(l.gopsToAlignWith=function(e,t,i){if(null==t||!e.length)return[];var n,r=Math.ceil((t-i+3)*Fi);for(n=0;nr);n++);return e.slice(n)}(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),l},i.timestampOffsetForSegment_=function(e){return i=(t=e).segmentTimeline,n=t.currentTimeline,r=t.startOfSegment,a=t.buffered,t.overrideCheck||i!==n?i "+s+" for "+e),function(e,t,i){if(!e[i]){t.trigger({type:"usage",name:"vhs-608"}),t.trigger({type:"usage",name:"hls-608"});var n=i;/^cc708_/.test(i)&&(n="SERVICE"+i.split("_")[1]);var r=t.textTracks().getTrackById(n);if(r)e[i]=r;else{var a=i,s=i,o=!1,u=(t.options_.vhs&&t.options_.vhs.captionServices||{})[n];u&&(a=u.label,s=u.language,o=u.default),e[i]=t.addRemoteTextTrack({kind:"captions",id:n,default:o,label:a,language:s},!1).track}}}(d,i.vhs_.tech_,e),Bi(a,s,d[e]),function(e){var t=e.inbandTextTracks,i=e.captionArray,n=e.timestampOffset;if(i){var r=o.default.WebKitDataCue||o.default.VTTCue;i.forEach((function(e){var i=e.stream;t[i].addCue(new r(e.startTime+n,e.endTime+n,e.text))}))}}({captionArray:u,inbandTextTracks:d,timestampOffset:n})})),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}else this.metadataQueue_.caption.push(this.handleCaptions_.bind(this,e,t));else this.logger_("SegmentLoader received no captions from a caption event")},i.handleId3_=function(e,t,i){if(this.earlyAbortWhenNeeded_(e.stats),!this.checkForAbort_(e.requestId))if(this.pendingSegment_.hasAppendedData_){var n=null===this.sourceUpdater_.videoTimestampOffset()?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();!function(e,t,i){e.metadataTrack_||(e.metadataTrack_=i.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,e.metadataTrack_.inBandMetadataTrackDispatchType=t)}(this.inbandTextTracks_,i,this.vhs_.tech_),function(e){var t=e.inbandTextTracks,i=e.metadataArray,n=e.timestampOffset,r=e.videoDuration;if(i){var a=o.default.WebKitDataCue||o.default.VTTCue,s=t.metadataTrack_;if(s&&(i.forEach((function(e){var t=e.cueTime+n;!("number"!=typeof t||o.default.isNaN(t)||t<0)&&t<1/0&&e.frames.forEach((function(e){var i=new a(t,t,e.value||e.url||e.data||"");i.frame=e,i.value=e,function(e){Object.defineProperties(e.frame,{id:{get:function(){return u.default.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),e.value.key}},value:{get:function(){return u.default.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),e.value.data}},privateData:{get:function(){return u.default.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),e.value.data}}})}(i),s.addCue(i)}))})),s.cues&&s.cues.length)){for(var d=s.cues,l=[],c=0;c1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+X(s).join(", ")),u.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+X(u).join(", "));var d=s.length?s.start(0):0,l=s.length?s.end(s.length-1):0,c=u.length?u.start(0):0,h=u.length?u.end(u.length-1):0;if(l-d<=1&&h-c<=1)return this.logger_("On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: "+a.byteLength+", audio buffer: "+X(s).join(", ")+", video buffer: "+X(u).join(", ")+", "),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),void this.trigger("error");this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:n,type:r,bytes:a}));var f=this.currentTime_()-1;this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to "+f),this.remove(0,f,(function(){i.logger_("On QUOTA_EXCEEDED_ERR, retrying append in 1s"),i.waitingOnRemove_=!1,i.quotaExceededErrorRetryTimeout_=o.default.setTimeout((function(){i.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),i.quotaExceededErrorRetryTimeout_=null,i.processCallQueue_()}),1e3)}),!0)},i.handleAppendError_=function(e,t){var i=e.segmentInfo,n=e.type,r=e.bytes;t&&(22!==t.code?(this.logger_("Received non QUOTA_EXCEEDED_ERR on append",t),this.error(n+" append of "+r.length+"b failed for segment #"+i.mediaIndex+" in playlist "+i.playlist.id),this.trigger("appenderror")):this.handleQuotaExceededError_({segmentInfo:i,type:n,bytes:r}))},i.appendToSourceBuffer_=function(e){var t,i,n,r=e.segmentInfo,a=e.type,s=e.initSegment,o=e.data,u=e.bytes;if(!u){var d=[o],l=o.byteLength;s&&(d.unshift(s),l+=s.byteLength),n=0,(t={bytes:l,segments:d}).bytes&&(i=new Uint8Array(t.bytes),t.segments.forEach((function(e){i.set(e,n),n+=e.byteLength}))),u=i}this.sourceUpdater_.appendBuffer({segmentInfo:r,type:a,bytes:u},this.handleAppendError_.bind(this,{segmentInfo:r,type:a,bytes:u}))},i.handleSegmentTimingInfo_=function(e,t,i){if(this.pendingSegment_&&t===this.pendingSegment_.requestId){var n=this.pendingSegment_.segment,r=e+"TimingInfo";n[r]||(n[r]={}),n[r].transmuxerPrependedSeconds=i.prependedContentDuration||0,n[r].transmuxedPresentationStart=i.start.presentation,n[r].transmuxedDecodeStart=i.start.decode,n[r].transmuxedPresentationEnd=i.end.presentation,n[r].transmuxedDecodeEnd=i.end.decode,n[r].baseMediaDecodeTime=i.baseMediaDecodeTime}},i.appendData_=function(e,t){var i=t.type,n=t.data;if(n&&n.byteLength&&("audio"!==i||!this.audioDisabled_)){var r=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:r,data:n})}},i.loadSegment_=function(e){var t=this;this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),"number"==typeof e.timestampOffset&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.hasEnoughInfoToLoad_()?this.updateTransmuxerAndRequestSegment_(e):this.loadQueue_.push((function(){var i=v({},e,{forceTimestampOffset:!0});v(e,t.generateSegmentInfo_(i)),t.isPendingTimestampOffset_=!1,t.updateTransmuxerAndRequestSegment_(e)}))},i.updateTransmuxerAndRequestSegment_=function(e){var t=this;this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));var i=this.createSimplifiedSegmentObj_(e),n=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),r=null!==this.mediaIndex,a=e.timeline!==this.currentTimeline_&&e.timeline>0,s=n||r&&a;this.logger_("Requesting "+Wi(e)),i.map&&!i.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=Ei({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:i,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:s,endedTimelineFn:function(){t.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this)})},i.trimBackBuffer_=function(e){var t=function(e,t,i){var n=t-ri.BACK_BUFFER_LENGTH;e.length&&(n=Math.max(n,e.start(0)));var r=t-i;return Math.min(r,n)}(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)},i.createSimplifiedSegmentObj_=function(e){var t=e.segment,i=e.part,n={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part},r=e.playlist.segments[e.mediaIndex-1];if(r&&r.timeline===t.timeline&&(r.videoTimingInfo?n.baseStartTime=r.videoTimingInfo.transmuxedDecodeEnd:r.audioTimingInfo&&(n.baseStartTime=r.audioTimingInfo.transmuxedDecodeEnd)),t.key){var a=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);n.key=this.segmentKey(t.key),n.key.iv=a}return t.map&&(n.map=this.initSegmentForMap(t.map)),n},i.saveTransferStats_=function(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)},i.saveBandwidthRelatedStats_=function(e,t){this.pendingSegment_.byteLength=t.bytesReceived,e=n);r++);return e.slice(0,r).concat(t)}(this.gopBuffer_,i.gopInfo,this.safeAppend_)),this.state="APPENDING",this.trigger("appending"),this.waitForAppendsToComplete_(n)}},i.setTimeMapping_=function(e){var t=this.syncController_.mappingForTimeline(e);null!==t&&(this.timeMapping_=t)},i.updateMediaSecondsLoaded_=function(e){"number"==typeof e.start&&"number"==typeof e.end?this.mediaSecondsLoaded+=e.end-e.start:this.mediaSecondsLoaded+=e.duration},i.shouldUpdateTransmuxerTimestampOffset_=function(e){return null!==e&&("main"===this.loaderType_&&e!==this.sourceUpdater_.videoTimestampOffset()||!this.audioDisabled_&&e!==this.sourceUpdater_.audioTimestampOffset())},i.trueSegmentStart_=function(e){var t=e.currentStart,i=e.playlist,n=e.mediaIndex,r=e.firstVideoFrameTimeForData,a=e.currentVideoTimestampOffset,s=e.useVideoTimingInfo,o=e.videoTimingInfo,u=e.audioTimingInfo;if(void 0!==t)return t;if(!s)return u.start;var d=i.segments[n-1];return 0!==n&&d&&void 0!==d.start&&d.end===r+a?o.start:r},i.waitForAppendsToComplete_=function(e){if(!this.currentMediaInfo_)return this.error({message:"No starting media returned, likely due to an unsupported media format.",blacklistDuration:1/0}),void this.trigger("error");var t=this.currentMediaInfo_,i=t.hasAudio,n=t.hasVideo,r=t.isMuxed,a="main"===this.loaderType_&&n,s=!this.audioDisabled_&&i&&!r;if(e.waitingOnAppends=0,!e.hasAppendedData_)return e.timingInfo||"number"!=typeof e.timestampOffset||(this.isPendingTimestampOffset_=!0),e.timingInfo={start:0},e.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(e),this.processMetadataQueue_()),void this.checkAppendsDone_(e);a&&e.waitingOnAppends++,s&&e.waitingOnAppends++,a&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),s&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,e))},i.checkAppendsDone_=function(e){this.checkForAbort_(e.requestId)||(e.waitingOnAppends--,0===e.waitingOnAppends&&this.handleAppendsDone_())},i.checkForIllegalMediaSwitch=function(e){var t=function(e,t,i){return"main"===e&&t&&i?i.hasAudio||i.hasVideo?t.hasVideo&&!i.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!t.hasVideo&&i.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null:"Neither audio nor video found in segment.":null}(this.loaderType_,this.currentMediaInfo_,e);return!!t&&(this.error({message:t,blacklistDuration:1/0}),this.trigger("error"),!0)},i.updateSourceBufferTimestampOffset_=function(e){if(null!==e.timestampOffset&&"number"==typeof e.timingInfo.start&&!e.changedTimestampOffset&&"main"===this.loaderType_){var t=!1;e.timestampOffset-=e.timingInfo.start,e.changedTimestampOffset=!0,e.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(e.timestampOffset),t=!0),e.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(e.timestampOffset),t=!0),t&&this.trigger("timestampoffset")}},i.updateTimingInfoEnd_=function(e){e.timingInfo=e.timingInfo||{};var t="main"===this.loaderType_&&this.currentMediaInfo_.hasVideo&&e.videoTimingInfo?e.videoTimingInfo:e.audioTimingInfo;t&&(e.timingInfo.end="number"==typeof t.end?t.end:t.start+e.duration)},i.handleAppendsDone_=function(){if(this.pendingSegment_&&this.trigger("appendsdone"),!this.pendingSegment_)return this.state="READY",void(this.paused()||this.monitorBuffer_());var e=this.pendingSegment_;this.updateTimingInfoEnd_(e),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:"main"===this.loaderType_});var t=function(e,t){if("hls"!==t)return null;var i,n,r,a,s=(i=e.audioTimingInfo,n=e.videoTimingInfo,r=i&&"number"==typeof i.start&&"number"==typeof i.end?i.end-i.start:0,a=n&&"number"==typeof n.start&&"number"==typeof n.end?n.end-n.start:0,Math.max(r,a));if(!s)return null;var o=e.playlist.targetDuration,u=ji({segmentDuration:s,maxDuration:2*o}),d=ji({segmentDuration:s,maxDuration:o}),l="Segment with index "+e.mediaIndex+" from playlist "+e.playlist.id+" has a duration of "+s+" when the reported duration is "+e.duration+" and the target duration is "+o+". For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1";return u||d?{severity:u?"warn":"info",message:l}:null}(e,this.sourceType_);if(t&&("warn"===t.severity?u.default.log.warn(t.message):this.logger_(t.message)),this.recordThroughput_(e),this.pendingSegment_=null,this.state="READY",!e.isSyncRequest||(this.trigger("syncinfoupdate"),e.hasAppendedData_)){this.logger_("Appended "+Wi(e)),this.addSegmentMetadataCue_(e),this.fetchAtBuffer_=!0,this.currentTimeline_!==e.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline}),"main"!==this.loaderType_||this.audioDisabled_||this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:e.timeline})),this.currentTimeline_=e.timeline,this.trigger("syncinfoupdate");var i=e.segment;i.end&&this.currentTime_()-i.end>3*e.playlist.targetDuration?this.resetEverything():(null!==this.mediaIndex&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger("appended"),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_())}else this.logger_("Throwing away un-appended sync request "+Wi(e))},i.recordThroughput_=function(e){if(e.duration=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e},i.stopForError=function(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")},i.segmentRequestFinished_=function(e,t,i){var n=this;if(this.subtitlesTrack_){if(this.saveTransferStats_(t.stats),!this.pendingSegment_)return this.state="READY",void(this.mediaRequestsAborted+=1);if(e)return e.code===mi&&this.handleTimeout_(),e.code===gi?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,void this.stopForError(e);var r=this.pendingSegment_;this.saveBandwidthRelatedStats_(r.duration,t.stats),this.state="APPENDING",this.trigger("appending");var a=r.segment;if(a.map&&(a.map.bytes=t.map.bytes),r.bytes=t.bytes,"function"!=typeof o.default.WebVTT&&this.subtitlesTrack_&&this.subtitlesTrack_.tech_){var s,u=function(){n.subtitlesTrack_.tech_.off("vttjsloaded",s),n.stopForError({message:"Error loading vtt.js"})};return s=function(){n.subtitlesTrack_.tech_.off("vttjserror",u),n.segmentRequestFinished_(e,t,i)},this.state="WAITING_ON_VTTJS",this.subtitlesTrack_.tech_.one("vttjsloaded",s),void this.subtitlesTrack_.tech_.one("vttjserror",u)}a.requested=!0;try{this.parseVTTCues_(r)}catch(e){return void this.stopForError({message:e.message})}if(this.updateTimeMapping_(r,this.syncController_.timelines[r.timeline],this.playlist_),r.cues.length?r.timingInfo={start:r.cues[0].startTime,end:r.cues[r.cues.length-1].endTime}:r.timingInfo={start:r.startOfSegment,end:r.startOfSegment+r.duration},r.isSyncRequest)return this.trigger("syncinfoupdate"),this.pendingSegment_=null,void(this.state="READY");r.byteLength=r.bytes.byteLength,this.mediaSecondsLoaded+=a.duration,r.cues.forEach((function(e){n.subtitlesTrack_.addCue(n.featuresNativeTextTracks_?new o.default.VTTCue(e.startTime,e.endTime,e.text):e)})),function(e){var t=e.cues;if(t)for(var i=0;i1&&n.push(t[a]);n.length&&n.forEach((function(t){return e.removeCue(t)}))}}(this.subtitlesTrack_),this.handleAppendsDone_()}else this.state="READY"},i.handleData_=function(){},i.updateTimingInfoEnd_=function(){},i.parseVTTCues_=function(e){var t,i=!1;"function"==typeof o.default.TextDecoder?t=new o.default.TextDecoder("utf8"):(t=o.default.WebVTT.StringDecoder(),i=!0);var n=new o.default.WebVTT.Parser(o.default,o.default.vttjs,t);if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=function(t){e.timestampmap=t},n.onparsingerror=function(e){u.default.log.warn("Error encountered when parsing cues: "+e.message)},e.segment.map){var r=e.segment.map.bytes;i&&(r=fn(r)),n.parse(r)}var a=e.bytes;i&&(a=fn(a)),n.parse(a),n.flush()},i.updateTimeMapping_=function(e,t,i){var n=e.segment;if(t)if(e.cues.length){var r=e.timestampmap,a=r.MPEGTS/Fi-r.LOCAL+t.mapping;if(e.cues.forEach((function(e){e.startTime+=a,e.endTime+=a})),!i.syncInfo){var s=e.cues[0].startTime,o=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(s,o-n.duration)}}}else n.empty=!0},t}(Xi),gn=function(e,t){for(var i=e.cues,n=0;n=r.adStartTime&&t<=r.adEndTime)return r}return null},yn=[{name:"VOD",run:function(e,t,i,n,r){return i!==1/0?{time:0,segmentIndex:0,partIndex:null}:null}},{name:"ProgramDateTime",run:function(e,t,i,n,r){if(!Object.keys(e.timelineToDatetimeMappings).length)return null;var a=null,s=null,o=Y(t);r=r||0;for(var u=0;u=h)&&(s=h,a={time:c,segmentIndex:d.segmentIndex,partIndex:d.partIndex})}}return a}},{name:"Discontinuity",run:function(e,t,i,n,r){var a=null;if(r=r||0,t.discontinuityStarts&&t.discontinuityStarts.length)for(var s=null,o=0;o=c)&&(s=c,a={time:l.time,segmentIndex:u,partIndex:null})}}return a}},{name:"Playlist",run:function(e,t,i,n,r){return t.syncInfo?{time:t.syncInfo.time,segmentIndex:t.syncInfo.mediaSequence-t.mediaSequence,partIndex:null}:null}}],_n=function(e){function t(t){var i;return(i=e.call(this)||this).timelines=[],i.discontinuities=[],i.timelineToDatetimeMappings={},i.logger_=_("SyncController"),i}h(t,e);var i=t.prototype;return i.getSyncPoint=function(e,t,i,n){var r=this.runStrategies_(e,t,i,n);return r.length?this.selectSyncPoint_(r,{key:"time",value:n}):null},i.getExpiredTime=function(e,t){if(!e||!e.segments)return null;var i=this.runStrategies_(e,t,e.discontinuitySequence,0);if(!i.length)return null;var n=this.selectSyncPoint_(i,{key:"segmentIndex",value:0});return n.segmentIndex>0&&(n.time*=-1),Math.abs(n.time+te({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))},i.runStrategies_=function(e,t,i,n){for(var r=[],a=0;a=0;i--){var n=e.segments[i];if(n&&void 0!==n.start){t.syncInfo={mediaSequence:e.mediaSequence+i,time:n.start},this.logger_("playlist refresh sync: [time:"+t.syncInfo.time+", mediaSequence: "+t.syncInfo.mediaSequence+"]"),this.trigger("syncinfoupdate");break}}},i.setDateTimeMappingForStart=function(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){var t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}},i.saveSegmentTimingInfo=function(e){var t=e.segmentInfo,i=e.shouldSaveTimelineMapping,n=this.calculateSegmentTimeMapping_(t,t.timingInfo,i),r=t.segment;n&&(this.saveDiscontinuitySyncInfo_(t),t.playlist.syncInfo||(t.playlist.syncInfo={mediaSequence:t.playlist.mediaSequence+t.mediaIndex,time:r.start}));var a=r.dateTimeObject;r.discontinuity&&i&&a&&(this.timelineToDatetimeMappings[r.timeline]=-a.getTime()/1e3)},i.timestampOffsetForTimeline=function(e){return void 0===this.timelines[e]?null:this.timelines[e].time},i.mappingForTimeline=function(e){return void 0===this.timelines[e]?null:this.timelines[e].mapping},i.calculateSegmentTimeMapping_=function(e,t,i){var n,r,a=e.segment,s=e.part,o=this.timelines[e.timeline];if("number"==typeof e.timestampOffset)o={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=o,this.trigger("timestampoffset"),this.logger_("time mapping for timeline "+e.timeline+": [time: "+o.time+"] [mapping: "+o.mapping+"]")),n=e.startOfSegment,r=t.end+o.mapping;else{if(!o)return!1;n=t.start+o.mapping,r=t.end+o.mapping}return s&&(s.start=n,s.end=r),(!a.start||no){var u;u=s<0?i.start-te({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):i.end+te({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[a]={time:u,accuracy:o}}}},i.dispose=function(){this.trigger("dispose"),this.off()},t}(u.default.EventTarget),vn=function(e){function t(){var t;return(t=e.call(this)||this).pendingTimelineChanges_={},t.lastTimelineChanges_={},t}h(t,e);var i=t.prototype;return i.clearPendingTimelineChange=function(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")},i.pendingTimelineChange=function(e){var t=e.type,i=e.from,n=e.to;return"number"==typeof i&&"number"==typeof n&&(this.pendingTimelineChanges_[t]={type:t,from:i,to:n},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[t]},i.lastTimelineChange=function(e){var t=e.type,i=e.from,n=e.to;return"number"==typeof i&&"number"==typeof n&&(this.lastTimelineChanges_[t]={type:t,from:i,to:n},delete this.pendingTimelineChanges_[t],this.trigger("timelinechange")),this.lastTimelineChanges_[t]},i.dispose=function(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()},t}(u.default.EventTarget),Tn=si(oi(ui((function(){function e(e,t,i){return e(i={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&i.path)}},i.exports),i.exports}var t=e((function(e){function t(e,t){for(var i=0;i-1},t.trigger=function(e){var t=this.listeners[e];if(t)if(2===arguments.length)for(var i=t.length,n=0;n>7))^e]=e;for(t=i=0;!c[t];t^=n||1,i=p[i]||1)for(a=(a=i^i<<1^i<<2^i<<3^i<<4)>>8^255&a^99,c[t]=a,h[a]=t,o=16843009*f[r=f[n=f[t]]]^65537*r^257*n^16843008*t,s=257*f[a]^16843008*a,e=0;e<4;e++)d[e][t]=s=s<<24^s>>>8,l[e][a]=o=o<<24^o>>>8;for(e=0;e<5;e++)d[e]=d[e].slice(0),l[e]=l[e].slice(0);return u}()),this._tables=[[a[0][0].slice(),a[0][1].slice(),a[0][2].slice(),a[0][3].slice(),a[0][4].slice()],[a[1][0].slice(),a[1][1].slice(),a[1][2].slice(),a[1][3].slice(),a[1][4].slice()]];var r=this._tables[0][4],s=this._tables[1],o=e.length,u=1;if(4!==o&&6!==o&&8!==o)throw new Error("Invalid aes key size");var d=e.slice(0),l=[];for(this._key=[d,l],t=o;t<4*o+28;t++)n=d[t-1],(t%o==0||8===o&&t%o==4)&&(n=r[n>>>24]<<24^r[n>>16&255]<<16^r[n>>8&255]<<8^r[255&n],t%o==0&&(n=n<<8^n>>>24^u<<24,u=u<<1^283*(u>>7))),d[t]=d[t-o]^n;for(i=0;t;i++,t--)n=d[3&i?t:t-4],l[i]=t<=4||i<4?n:s[0][r[n>>>24]]^s[1][r[n>>16&255]]^s[2][r[n>>8&255]]^s[3][r[255&n]]}return e.prototype.decrypt=function(e,t,i,n,r,a){var s,o,u,d,l=this._key[1],c=e^l[0],h=n^l[1],f=i^l[2],p=t^l[3],m=l.length/4-2,g=4,y=this._tables[1],_=y[0],v=y[1],T=y[2],b=y[3],S=y[4];for(d=0;d>>24]^v[h>>16&255]^T[f>>8&255]^b[255&p]^l[g],o=_[h>>>24]^v[f>>16&255]^T[p>>8&255]^b[255&c]^l[g+1],u=_[f>>>24]^v[p>>16&255]^T[c>>8&255]^b[255&h]^l[g+2],p=_[p>>>24]^v[c>>16&255]^T[h>>8&255]^b[255&f]^l[g+3],g+=4,c=s,h=o,f=u;for(d=0;d<4;d++)r[(3&-d)+a]=S[c>>>24]<<24^S[h>>16&255]<<16^S[f>>8&255]<<8^S[255&p]^l[g++],s=c,c=h,h=f,f=p,p=s},e}(),o=function(e){function t(){var t;return(t=e.call(this,r)||this).jobs=[],t.delay=1,t.timeout_=null,t}n(t,e);var i=t.prototype;return i.processJob_=function(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null},i.push=function(e){this.jobs.push(e),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))},t}(r),u=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},d=function(){function e(t,i,n,r){var a=e.STEP,s=new Int32Array(t.buffer),d=new Uint8Array(t.byteLength),l=0;for(this.asyncStream_=new o,this.asyncStream_.push(this.decryptChunk_(s.subarray(l,l+a),i,n,d)),l=a;l>2),m=new s(Array.prototype.slice.call(t)),g=new Uint8Array(e.byteLength),y=new Int32Array(g.buffer);for(n=i[0],r=i[1],a=i[2],o=i[3],f=0;f=0&&(t="main-desc"),t},Sn=function(e,t){e.abort(),e.pause(),t&&t.activePlaylistLoader&&(t.activePlaylistLoader.pause(),t.activePlaylistLoader=null)},In=function(e,t){t.activePlaylistLoader=e,e.load()},En={AUDIO:function(e,t){return function(){var i=t.segmentLoaders[e],n=t.mediaTypes[e],r=t.blacklistCurrentPlaylist;Sn(i,n);var a=n.activeTrack(),s=n.activeGroup(),o=(s.filter((function(e){return e.default}))[0]||s[0]).id,d=n.tracks[o];if(a!==d){for(var l in u.default.log.warn("Problem encountered loading the alternate audio track.Switching back to default."),n.tracks)n.tracks[l].enabled=n.tracks[l]===d;n.onTrackChanged()}else r({message:"Problem encountered loading the default audio track."})}},SUBTITLES:function(e,t){return function(){var i=t.segmentLoaders[e],n=t.mediaTypes[e];u.default.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track."),Sn(i,n);var r=n.activeTrack();r&&(r.mode="disabled"),n.onTrackChanged()}}},wn={AUDIO:function(e,t,i){if(t){var n=i.tech,r=i.requestOptions,a=i.segmentLoaders[e];t.on("loadedmetadata",(function(){var e=t.media();a.playlist(e,r),(!n.paused()||e.endList&&"none"!==n.preload())&&a.load()})),t.on("loadedplaylist",(function(){a.playlist(t.media(),r),n.paused()||a.load()})),t.on("error",En[e](e,i))}},SUBTITLES:function(e,t,i){var n=i.tech,r=i.requestOptions,a=i.segmentLoaders[e],s=i.mediaTypes[e];t.on("loadedmetadata",(function(){var e=t.media();a.playlist(e,r),a.track(s.activeTrack()),(!n.paused()||e.endList&&"none"!==n.preload())&&a.load()})),t.on("loadedplaylist",(function(){a.playlist(t.media(),r),n.paused()||a.load()})),t.on("error",En[e](e,i))}},An={AUDIO:function(e,t){var i=t.vhs,n=t.sourceType,r=t.segmentLoaders[e],a=t.requestOptions,s=t.master.mediaGroups,o=t.mediaTypes[e],d=o.groups,l=o.tracks,c=o.logger_,h=t.masterPlaylistLoader,f=le(h.master);for(var p in s[e]&&0!==Object.keys(s[e]).length||(s[e]={main:{default:{default:!0}}}),s[e])for(var m in d[p]||(d[p]=[]),s[e][p]){var g=s[e][p][m],y=void 0;if(f?(c("AUDIO group '"+p+"' label '"+m+"' is a master playlist"),g.isMasterPlaylist=!0,y=null):y="vhs-json"===n&&g.playlists?new we(g.playlists[0],i,a):g.resolvedUri?new we(g.resolvedUri,i,a):g.playlists&&"dash"===n?new ni(g.playlists[0],i,a,h):null,g=u.default.mergeOptions({id:m,playlistLoader:y},g),wn[e](e,g.playlistLoader,t),d[p].push(g),void 0===l[m]){var _=new u.default.AudioTrack({id:m,kind:bn(g),enabled:!1,language:g.language,default:g.default,label:m});l[m]=_}}r.on("error",En[e](e,t))},SUBTITLES:function(e,t){var i=t.tech,n=t.vhs,r=t.sourceType,a=t.segmentLoaders[e],s=t.requestOptions,o=t.master.mediaGroups,d=t.mediaTypes[e],l=d.groups,c=d.tracks,h=t.masterPlaylistLoader;for(var f in o[e])for(var p in l[f]||(l[f]=[]),o[e][f])if(!o[e][f][p].forced){var m=o[e][f][p],g=void 0;if("hls"===r)g=new we(m.resolvedUri,n,s);else if("dash"===r){if(!m.playlists.filter((function(e){return e.excludeUntil!==1/0})).length)return;g=new ni(m.playlists[0],n,s,h)}else"vhs-json"===r&&(g=new we(m.playlists?m.playlists[0]:m.resolvedUri,n,s));if(m=u.default.mergeOptions({id:p,playlistLoader:g},m),wn[e](e,m.playlistLoader,t),l[f].push(m),void 0===c[p]){var y=i.addRemoteTextTrack({id:p,kind:"subtitles",default:m.default&&m.autoselect,language:m.language,label:p},!1).track;c[p]=y}}a.on("error",En[e](e,t))},"CLOSED-CAPTIONS":function(e,t){var i=t.tech,n=t.master.mediaGroups,r=t.mediaTypes[e],a=r.groups,s=r.tracks;for(var o in n[e])for(var d in a[o]||(a[o]=[]),n[e][o]){var l=n[e][o][d];if(/^(?:CC|SERVICE)/.test(l.instreamId)){var c=i.options_.vhs&&i.options_.vhs.captionServices||{},h={label:d,language:l.language,instreamId:l.instreamId,default:l.default&&l.autoselect};if(c[h.instreamId]&&(h=u.default.mergeOptions(h,c[h.instreamId])),void 0===h.default&&delete h.default,a[o].push(u.default.mergeOptions({id:d},l)),void 0===s[d]){var f=i.addRemoteTextTrack({id:h.instreamId,kind:"captions",default:h.default,language:h.language,label:h.label},!1).track;s[d]=f}}}}},Ln=function e(t,i){for(var n=0;n "+a+" from "+t),this.tech_.trigger({type:"usage",name:"vhs-rendition-change-"+t})),this.masterPlaylistLoader_.media(e,i)},i.startABRTimer_=function(){var e=this;this.stopABRTimer_(),this.abrTimer_=o.default.setInterval((function(){return e.checkABR_()}),250)},i.stopABRTimer_=function(){this.tech_.scrubbing&&this.tech_.scrubbing()||(o.default.clearInterval(this.abrTimer_),this.abrTimer_=null)},i.getAudioTrackPlaylists_=function(){var e=this.master();if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return e&&e.playlists||[];var t,i=e.mediaGroups.AUDIO,n=Object.keys(i);if(Object.keys(this.mediaTypes_.AUDIO.groups).length)t=this.mediaTypes_.AUDIO.activeTrack();else{var r=i.main||n.length&&i[n[0]];for(var a in r)if(r[a].default){t={label:a};break}}if(!t)return[];var s=[];for(var o in i)if(i[o][t.label]){var u=i[o][t.label];u.playlists?s.push.apply(s,u.playlists):s.push(u)}return s},i.setupMasterPlaylistLoaderListeners_=function(){var e=this;this.masterPlaylistLoader_.on("loadedmetadata",(function(){var t=e.masterPlaylistLoader_.media(),i=1.5*t.targetDuration*1e3;oe(e.masterPlaylistLoader_.master,e.masterPlaylistLoader_.media())?e.requestOptions_.timeout=0:e.requestOptions_.timeout=i,t.endList&&"none"!==e.tech_.preload()&&(e.mainSegmentLoader_.playlist(t,e.requestOptions_),e.mainSegmentLoader_.load()),function(e){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((function(t){An[t](t,e)}));var t=e.mediaTypes,i=e.masterPlaylistLoader,n=e.tech,r=e.vhs,a=e.segmentLoaders,s=a.AUDIO,o=a.main;["AUDIO","SUBTITLES"].forEach((function(i){t[i].activeGroup=function(e,t){return function(i){var n=t.masterPlaylistLoader,r=t.mediaTypes[e].groups,a=n.media();if(!a)return null;var s=null;a.attributes[e]&&(s=r[a.attributes[e]]);var o=Object.keys(r);if(!s)if("AUDIO"===e&&o.length>1&&le(t.master))for(var u=0;u1&&(this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.tech_.trigger({type:"usage",name:"hls-alternate-audio"})),this.useCueTags_&&(this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"}),this.tech_.trigger({type:"usage",name:"hls-playlist-cue-tags"}))},i.shouldSwitchToMedia_=function(e){var t=this.masterPlaylistLoader_.media(),i=this.tech_.buffered();return function(e){var t=e.currentPlaylist,i=e.nextPlaylist,n=e.forwardBuffer,r=e.bufferLowWaterLine,a=e.bufferHighWaterLine,s=e.duration,o=e.experimentalBufferBasedABR,d=e.log;if(!i)return u.default.log.warn("We received no playlist to switch to. Please check your stream."),!1;var l="allowing switch "+(t&&t.id||"null")+" -> "+i.id;if(!t||!t.endList)return d(l+" as current playlist "+(t?"is live":"is not set")),!0;if(i.id===t.id)return!1;var c=o?ri.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:ri.MAX_BUFFER_LOW_WATER_LINE;if(sf)&&n>=r){var m=l+" as forwardBuffer >= bufferLowWaterLine ("+n+" >= "+r+")";return o&&(m+=" and next bandwidth > current bandwidth ("+h+" > "+f+")"),d(m),!0}return d("not "+l+" as no switching criteria met"),!1}({currentPlaylist:t,nextPlaylist:e,forwardBuffer:i.length?i.end(i.length-1)-this.tech_.currentTime():0,bufferLowWaterLine:this.bufferLowWaterLine(),bufferHighWaterLine:this.bufferHighWaterLine(),duration:this.duration(),experimentalBufferBasedABR:this.experimentalBufferBasedABR,log:this.logger_})},i.setupSegmentLoaderListeners_=function(){var e=this;this.experimentalBufferBasedABR||(this.mainSegmentLoader_.on("bandwidthupdate",(function(){var t=e.selectPlaylist();e.shouldSwitchToMedia_(t)&&e.switchMedia_(t,"bandwidthupdate"),e.tech_.trigger("bandwidthupdate")})),this.mainSegmentLoader_.on("progress",(function(){e.trigger("progress")}))),this.mainSegmentLoader_.on("error",(function(){e.blacklistCurrentPlaylist(e.mainSegmentLoader_.error())})),this.mainSegmentLoader_.on("appenderror",(function(){e.error=e.mainSegmentLoader_.error_,e.trigger("error")})),this.mainSegmentLoader_.on("syncinfoupdate",(function(){e.onSyncInfoUpdate_()})),this.mainSegmentLoader_.on("timestampoffset",(function(){e.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"}),e.tech_.trigger({type:"usage",name:"hls-timestamp-offset"})})),this.audioSegmentLoader_.on("syncinfoupdate",(function(){e.onSyncInfoUpdate_()})),this.audioSegmentLoader_.on("appenderror",(function(){e.error=e.audioSegmentLoader_.error_,e.trigger("error")})),this.mainSegmentLoader_.on("ended",(function(){e.logger_("main segment loader ended"),e.onEndOfStream()})),this.mainSegmentLoader_.on("earlyabort",(function(t){e.experimentalBufferBasedABR||(e.delegateLoaders_("all",["abort"]),e.blacklistCurrentPlaylist({message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},120))}));var t=function(){if(!e.sourceUpdater_.hasCreatedSourceBuffers())return e.tryToCreateSourceBuffers_();var t=e.getCodecsOrExclude_();t&&e.sourceUpdater_.addOrChangeSourceBuffers(t)};this.mainSegmentLoader_.on("trackinfo",t),this.audioSegmentLoader_.on("trackinfo",t),this.mainSegmentLoader_.on("fmp4",(function(){e.triggeredFmp4Usage||(e.tech_.trigger({type:"usage",name:"vhs-fmp4"}),e.tech_.trigger({type:"usage",name:"hls-fmp4"}),e.triggeredFmp4Usage=!0)})),this.audioSegmentLoader_.on("fmp4",(function(){e.triggeredFmp4Usage||(e.tech_.trigger({type:"usage",name:"vhs-fmp4"}),e.tech_.trigger({type:"usage",name:"hls-fmp4"}),e.triggeredFmp4Usage=!0)})),this.audioSegmentLoader_.on("ended",(function(){e.logger_("audioSegmentLoader ended"),e.onEndOfStream()}))},i.mediaSecondsLoaded_=function(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)},i.load=function(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()},i.smoothQualityChange_=function(e){void 0===e&&(e=this.selectPlaylist()),this.fastQualityChange_(e)},i.fastQualityChange_=function(e){var t=this;void 0===e&&(e=this.selectPlaylist()),e!==this.masterPlaylistLoader_.media()?(this.switchMedia_(e,"fast-quality"),this.mainSegmentLoader_.resetEverything((function(){u.default.browser.IE_VERSION||u.default.browser.IS_EDGE?t.tech_.setCurrentTime(t.tech_.currentTime()+.04):t.tech_.setCurrentTime(t.tech_.currentTime())}))):this.logger_("skipping fastQualityChange because new media is same as old")},i.play=function(){if(!this.setupFirstPlay()){this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();var e=this.tech_.seekable();return this.tech_.duration()===1/0&&this.tech_.currentTime()this.maxPlaylistRetries?1/0:Date.now()+1e3*t,i.excludeUntil=n,e.reason&&(i.lastExcludeReason_=e.reason),this.tech_.trigger("blacklistplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-blacklisted"}),this.tech_.trigger({type:"usage",name:"hls-rendition-blacklisted"});var d=this.selectPlaylist();if(!d)return this.error="Playback cannot continue. No available working or supported playlists.",void this.trigger("error");var l=e.internal?this.logger_:u.default.log.warn,c=e.message?" "+e.message:"";l((e.internal?"Internal problem":"Problem")+" encountered with playlist "+i.id+"."+c+" Switching to playlist "+d.id+"."),d.attributes.AUDIO!==i.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),d.attributes.SUBTITLES!==i.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);var h=d.targetDuration/2*1e3||5e3,f="number"==typeof d.lastRequest&&Date.now()-d.lastRequest<=h;return this.switchMedia_(d,"exclude",s||f)},i.pauseLoading=function(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()},i.delegateLoaders_=function(e,t){var i=this,n=[],r="all"===e;(r||"main"===e)&&n.push(this.masterPlaylistLoader_);var a=[];(r||"audio"===e)&&a.push("AUDIO"),(r||"subtitle"===e)&&(a.push("CLOSED-CAPTIONS"),a.push("SUBTITLES")),a.forEach((function(e){var t=i.mediaTypes_[e]&&i.mediaTypes_[e].activePlaylistLoader;t&&n.push(t)})),["main","audio","subtitle"].forEach((function(t){var r=i[t+"SegmentLoader_"];!r||e!==t&&"all"!==e||n.push(r)})),n.forEach((function(e){return t.forEach((function(t){"function"==typeof e[t]&&e[t]()}))}))},i.setCurrentTime=function(e){var t=G(this.tech_.buffered(),e);return this.masterPlaylistLoader_&&this.masterPlaylistLoader_.media()&&this.masterPlaylistLoader_.media().segments?t&&t.length?e:(this.mainSegmentLoader_.resetEverything(),this.mainSegmentLoader_.abort(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.resetEverything(),this.audioSegmentLoader_.abort()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.resetEverything(),this.subtitleSegmentLoader_.abort()),void this.load()):0},i.duration=function(){if(!this.masterPlaylistLoader_)return 0;var e=this.masterPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:Qi.Playlist.duration(e):1/0:0},i.seekable=function(){return this.seekable_},i.onSyncInfoUpdate_=function(){var e;if(this.masterPlaylistLoader_){var t=this.masterPlaylistLoader_.media();if(t){var i=this.syncController_.getExpiredTime(t,this.duration());if(null!==i){var n=this.masterPlaylistLoader_.master,r=Qi.Playlist.seekable(t,i,Qi.Playlist.liveEdgeDelay(n,t));if(0!==r.length){if(this.mediaTypes_.AUDIO.activePlaylistLoader){if(t=this.mediaTypes_.AUDIO.activePlaylistLoader.media(),null===(i=this.syncController_.getExpiredTime(t,this.duration())))return;if(0===(e=Qi.Playlist.seekable(t,i,Qi.Playlist.liveEdgeDelay(n,t))).length)return}var a,s;this.seekable_&&this.seekable_.length&&(a=this.seekable_.end(0),s=this.seekable_.start(0)),e?e.start(0)>r.end(0)||r.start(0)>e.end(0)?this.seekable_=r:this.seekable_=u.default.createTimeRanges([[e.start(0)>r.start(0)?e.start(0):r.start(0),e.end(0)0&&(n=Math.max(n,i.end(i.length-1))),this.mediaSource.duration!==n&&this.sourceUpdater_.setDuration(n)}},i.dispose=function(){var e=this;this.trigger("dispose"),this.decrypter_.terminate(),this.masterPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach((function(t){var i=e.mediaTypes_[t].groups;for(var n in i)i[n].forEach((function(e){e.playlistLoader&&e.playlistLoader.dispose()}))})),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()},i.master=function(){return this.masterPlaylistLoader_.master},i.media=function(){return this.masterPlaylistLoader_.media()||this.initialMedia_},i.areMediaTypesKnown_=function(){var e=!!this.mediaTypes_.AUDIO.activePlaylistLoader;return!(!this.mainSegmentLoader_.currentMediaInfo_||e&&!this.audioSegmentLoader_.currentMediaInfo_)},i.getCodecsOrExclude_=function(){var e=this,t={main:this.mainSegmentLoader_.currentMediaInfo_||{},audio:this.audioSegmentLoader_.currentMediaInfo_||{}};t.video=t.main;var i=ki(this.master(),this.media()),n={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(t.main.hasVideo&&(n.video=i.video||t.main.videoCodec||"avc1.4d400d"),t.main.isMuxed&&(n.video+=","+(i.audio||t.main.audioCodec||F)),(t.main.hasAudio&&!t.main.isMuxed||t.audio.hasAudio||r)&&(n.audio=i.audio||t.main.audioCodec||t.audio.audioCodec||F,t.audio.isFmp4=t.main.hasAudio&&!t.main.isMuxed?t.main.isFmp4:t.audio.isFmp4),n.audio||n.video){var a,s={};if(["video","audio"].forEach((function(e){if(n.hasOwnProperty(e)&&(r=t[e].isFmp4,o=n[e],!(r?B(o):N(o)))){var i=t[e].isFmp4?"browser":"muxer";s[i]=s[i]||[],s[i].push(n[e]),"audio"===e&&(a=i)}var r,o})),r&&a&&this.media().attributes.AUDIO){var o=this.media().attributes.AUDIO;this.master().playlists.forEach((function(t){(t.attributes&&t.attributes.AUDIO)===o&&t!==e.media()&&(t.excludeUntil=1/0)})),this.logger_("excluding audio group "+o+" as "+a+' does not support codec(s): "'+n.audio+'"')}if(!Object.keys(s).length){if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){var u=[];if(["video","audio"].forEach((function(t){var i=(U(e.sourceUpdater_.codecs[t]||"")[0]||{}).type,r=(U(n[t]||"")[0]||{}).type;i&&r&&i.toLowerCase()!==r.toLowerCase()&&u.push('"'+e.sourceUpdater_.codecs[t]+'" -> "'+n[t]+'"')})),u.length)return void this.blacklistCurrentPlaylist({playlist:this.media(),message:"Codec switching not supported: "+u.join(", ")+".",blacklistDuration:1/0,internal:!0})}return n}var d=Object.keys(s).reduce((function(e,t){return e&&(e+=", "),e+(t+' does not support codec(s): "')+s[t].join(",")+'"'}),"")+".";this.blacklistCurrentPlaylist({playlist:this.media(),internal:!0,message:d,blacklistDuration:1/0})}else this.blacklistCurrentPlaylist({playlist:this.media(),message:"Could not determine codecs for playlist.",blacklistDuration:1/0})},i.tryToCreateSourceBuffers_=function(){if("open"===this.mediaSource.readyState&&!this.sourceUpdater_.hasCreatedSourceBuffers()&&this.areMediaTypesKnown_()){var e=this.getCodecsOrExclude_();if(e){this.sourceUpdater_.createSourceBuffers(e);var t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}}},i.excludeUnsupportedVariants_=function(){var e=this,t=this.master().playlists,i=[];Object.keys(t).forEach((function(n){var r=t[n];if(-1===i.indexOf(r.id)){i.push(r.id);var a=ki(e.master,r),s=[];!a.audio||N(a.audio)||B(a.audio)||s.push("audio codec "+a.audio),!a.video||N(a.video)||B(a.video)||s.push("video codec "+a.video),a.text&&"stpp.ttml.im1t"===a.text&&s.push("text codec "+a.text),s.length&&(r.excludeUntil=1/0,e.logger_("excluding "+r.id+" for unsupported: "+s.join(", ")))}}))},i.excludeIncompatibleVariants_=function(e){var t=this,i=[],n=this.master().playlists,r=Li(U(e)),a=Pi(r),s=r.video&&U(r.video)[0]||null,o=r.audio&&U(r.audio)[0]||null;Object.keys(n).forEach((function(e){var r=n[e];if(-1===i.indexOf(r.id)&&r.excludeUntil!==1/0){i.push(r.id);var u=[],d=ki(t.masterPlaylistLoader_.master,r),l=Pi(d);if(d.audio||d.video){if(l!==a&&u.push('codec count "'+l+'" !== "'+a+'"'),!t.sourceUpdater_.canChangeType()){var c=d.video&&U(d.video)[0]||null,h=d.audio&&U(d.audio)[0]||null;c&&s&&c.type.toLowerCase()!==s.type.toLowerCase()&&u.push('video codec "'+c.type+'" !== "'+s.type+'"'),h&&o&&h.type.toLowerCase()!==o.type.toLowerCase()&&u.push('audio codec "'+h.type+'" !== "'+o.type+'"')}u.length&&(r.excludeUntil=1/0,t.logger_("blacklisting "+r.id+": "+u.join(" && ")))}}}))},i.updateAdCues_=function(e){var t=0,i=this.seekable();i.length&&(t=i.start(0)),function(e,t,i){if(void 0===i&&(i=0),e.segments)for(var n,r=i,a=0;a0&&this.logger_("resetting possible stalled download count for "+e+" loader"),this[e+"StalledDownloads_"]=0,this[e+"Buffered_"]=t.buffered_()},t.checkSegmentDownloads_=function(e){var t=this.masterPlaylistController_,i=t[e+"SegmentLoader_"],n=i.buffered_(),r=function(e,t){if(e===t)return!1;if(!e&&t||!t&&e)return!0;if(e.length!==t.length)return!0;for(var i=0;i=t.end(t.length-1)))return this.techWaiting_();this.consecutiveUpdates>=5&&e===this.lastRecordedTime?(this.consecutiveUpdates++,this.waiting_()):e===this.lastRecordedTime?this.consecutiveUpdates++:(this.consecutiveUpdates=0,this.lastRecordedTime=e)}},t.cancelTimer_=function(){this.consecutiveUpdates=0,this.timer_&&(this.logger_("cancelTimer_"),clearTimeout(this.timer_)),this.timer_=null},t.fixesBadSeeks_=function(){if(!this.tech_.seeking())return!1;var e,t=this.seekable(),i=this.tech_.currentTime();if(this.afterSeekableWindow_(t,i,this.media(),this.allowSeeksWithinUnsafeLiveWindow)&&(e=t.end(t.length-1)),this.beforeSeekableWindow_(t,i)){var n=t.start(0);e=n+(n===t.end(0)?0:H)}if(void 0!==e)return this.logger_("Trying to seek outside of seekable at time "+i+" with seekable range "+j(t)+". Seeking to "+e+"."),this.tech_.setCurrentTime(e),!0;var r=this.tech_.buffered();return!!function(e){var t=e.buffered,i=e.targetDuration,n=e.currentTime;return!(!t.length||t.end(0)-t.start(0)<2*i||n>t.start(0)||!(t.start(0)-n "+i.end(0)+"]. Attempting to resume playback by seeking to the current time."),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"}),void this.tech_.trigger({type:"usage",name:"hls-unknown-waiting"})):void 0}},t.techWaiting_=function(){var e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking()&&this.fixesBadSeeks_())return!0;if(this.tech_.seeking()||null!==this.timer_)return!0;if(this.beforeSeekableWindow_(e,t)){var i=e.end(e.length-1);return this.logger_("Fell out of live window at time "+t+". Seeking to live point (seekable end) "+i),this.cancelTimer_(),this.tech_.setCurrentTime(i),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),this.tech_.trigger({type:"usage",name:"hls-live-resync"}),!0}var n=this.tech_.vhs.masterPlaylistController_.sourceUpdater_,r=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:n.audioBuffered(),videoBuffered:n.videoBuffered(),currentTime:t}))return this.cancelTimer_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),this.tech_.trigger({type:"usage",name:"hls-video-underflow"}),!0;var a=V(r,t);if(a.length>0){var s=a.start(0)-t;return this.logger_("Stopped at "+t+", setting timer for "+s+", seeking to "+a.start(0)),this.cancelTimer_(),this.timer_=setTimeout(this.skipTheGap_.bind(this),1e3*s,t),!0}return!1},t.afterSeekableWindow_=function(e,t,i,n){if(void 0===n&&(n=!1),!e.length)return!1;var r=e.end(e.length-1)+H;return!i.endList&&n&&(r=e.end(e.length-1)+3*i.targetDuration),t>r},t.beforeSeekableWindow_=function(e,t){return!!(e.length&&e.start(0)>0&&t2)return{start:r,end:a}}return null},e}(),Rn={errorInterval:30,getSource:function(e){return e(this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource())}},Mn=function e(t,i){var n=0,r=0,a=u.default.mergeOptions(Rn,i);t.ready((function(){t.trigger({type:"usage",name:"vhs-error-reload-initialized"}),t.trigger({type:"usage",name:"hls-error-reload-initialized"})}));var s=function(){r&&t.currentTime(r)},o=function(e){null!=e&&(r=t.duration()!==1/0&&t.currentTime()||0,t.one("loadedmetadata",s),t.src(e),t.trigger({type:"usage",name:"vhs-error-reload"}),t.trigger({type:"usage",name:"hls-error-reload"}),t.play())},d=function(){return Date.now()-n<1e3*a.errorInterval?(t.trigger({type:"usage",name:"vhs-error-reload-canceled"}),void t.trigger({type:"usage",name:"hls-error-reload-canceled"})):a.getSource&&"function"==typeof a.getSource?(n=Date.now(),a.getSource.call(t,o)):void u.default.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!")},l=function e(){t.off("loadedmetadata",s),t.off("error",d),t.off("dispose",e)};t.on("error",d),t.on("dispose",l),t.reloadSourceOnError=function(i){l(),e(t,i)}},Bn=function(e){Mn(this,e)},Nn="2.9.1",Fn={PlaylistLoader:we,Playlist:ce,utils:He,STANDARD_PLAYLIST_SELECTOR:Mi,INITIAL_PLAYLIST_SELECTOR:function(){var e=this,t=this.playlists.master.playlists.filter(ce.isEnabled);return Ci(t,(function(e,t){return Ui(e,t)})),t.filter((function(t){return!!ki(e.playlists.master,t).video}))[0]||null},lastBandwidthSelector:Mi,movingAverageBandwidthSelector:function(e){var t=-1,i=-1;if(e<0||e>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){var n=this.useDevicePixelRatio&&o.default.devicePixelRatio||1;return t<0&&(t=this.systemBandwidth,i=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==i&&(t=e*this.systemBandwidth+(1-e)*t,i=this.systemBandwidth),Ri(this.playlists.master,t,parseInt(Di(this.tech_.el(),"width"),10)*n,parseInt(Di(this.tech_.el(),"height"),10)*n,this.limitRenditionByPlayerDimensions,this.masterPlaylistController_)}},comparePlaylistBandwidth:Ui,comparePlaylistResolution:function(e,t){var i,n;return e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||o.default.Number.MAX_VALUE,t.attributes.RESOLUTION&&t.attributes.RESOLUTION.width&&(n=t.attributes.RESOLUTION.width),i===(n=n||o.default.Number.MAX_VALUE)&&e.attributes.BANDWIDTH&&t.attributes.BANDWIDTH?e.attributes.BANDWIDTH-t.attributes.BANDWIDTH:i-n},xhr:ke()};Object.keys(ri).forEach((function(e){Object.defineProperty(Fn,e,{get:function(){return u.default.log.warn("using Vhs."+e+" is UNSAFE be sure you know what you are doing"),ri[e]},set:function(t){u.default.log.warn("using Vhs."+e+" is UNSAFE be sure you know what you are doing"),"number"!=typeof t||t<0?u.default.log.warn("value of Vhs."+e+" must be greater than or equal to 0"):ri[e]=t}})}));var qn="videojs-vhs",Hn=function(e,t){for(var i=t.media(),n=-1,r=0;r0?1/this.throughput:0,Math.floor(1/(t+e))},set:function(){u.default.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:function(){return i.bandwidth||0},enumerable:!0},mediaRequests:{get:function(){return i.masterPlaylistController_.mediaRequests_()||0},enumerable:!0},mediaRequestsAborted:{get:function(){return i.masterPlaylistController_.mediaRequestsAborted_()||0},enumerable:!0},mediaRequestsTimedout:{get:function(){return i.masterPlaylistController_.mediaRequestsTimedout_()||0},enumerable:!0},mediaRequestsErrored:{get:function(){return i.masterPlaylistController_.mediaRequestsErrored_()||0},enumerable:!0},mediaTransferDuration:{get:function(){return i.masterPlaylistController_.mediaTransferDuration_()||0},enumerable:!0},mediaBytesTransferred:{get:function(){return i.masterPlaylistController_.mediaBytesTransferred_()||0},enumerable:!0},mediaSecondsLoaded:{get:function(){return i.masterPlaylistController_.mediaSecondsLoaded_()||0},enumerable:!0},mediaAppends:{get:function(){return i.masterPlaylistController_.mediaAppends_()||0},enumerable:!0},mainAppendsToLoadedData:{get:function(){return i.masterPlaylistController_.mainAppendsToLoadedData_()||0},enumerable:!0},audioAppendsToLoadedData:{get:function(){return i.masterPlaylistController_.audioAppendsToLoadedData_()||0},enumerable:!0},appendsToLoadedData:{get:function(){return i.masterPlaylistController_.appendsToLoadedData_()||0},enumerable:!0},timeToLoadedData:{get:function(){return i.masterPlaylistController_.timeToLoadedData_()||0},enumerable:!0},buffered:{get:function(){return X(i.tech_.buffered())},enumerable:!0},currentTime:{get:function(){return i.tech_.currentTime()},enumerable:!0},currentSource:{get:function(){return i.tech_.currentSource_},enumerable:!0},currentTech:{get:function(){return i.tech_.name_},enumerable:!0},duration:{get:function(){return i.tech_.duration()},enumerable:!0},master:{get:function(){return i.playlists.master},enumerable:!0},playerDimensions:{get:function(){return i.tech_.currentDimensions()},enumerable:!0},seekable:{get:function(){return X(i.tech_.seekable())},enumerable:!0},timestamp:{get:function(){return Date.now()},enumerable:!0},videoPlaybackQuality:{get:function(){return i.tech_.getVideoPlaybackQuality()},enumerable:!0}}),this.tech_.one("canplay",this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_)),this.tech_.on("bandwidthupdate",(function(){i.options_.useBandwidthFromLocalStorage&&function(e){if(!o.default.localStorage)return!1;var t=Xn();t=t?u.default.mergeOptions(t,e):e;try{o.default.localStorage.setItem(qn,JSON.stringify(t))}catch(e){return!1}}({bandwidth:i.bandwidth,throughput:Math.round(i.throughput)})})),this.masterPlaylistController_.on("selectedinitialmedia",(function(){var e;(e=i).representations=function(){var t=e.masterPlaylistController_.master(),i=le(t)?e.masterPlaylistController_.getAudioTrackPlaylists_():t.playlists;return i?i.filter((function(e){return!re(e)})).map((function(t,i){return new Dn(e,t,t.id)})):[]}})),this.masterPlaylistController_.sourceUpdater_.on("createdsourcebuffers",(function(){i.setupEme_()})),this.on(this.masterPlaylistController_,"progress",(function(){this.tech_.trigger("progress")})),this.on(this.masterPlaylistController_,"firstplay",(function(){this.ignoreNextSeekingEvent_=!0})),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=o.default.URL.createObjectURL(this.masterPlaylistController_.mediaSource),this.tech_.src(this.mediaSourceUrl_))}},i.setupEme_=function(){var e=this,t=this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader,i=jn({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:t&&t.media()});11!==u.default.browser.IE_VERSION&&i?(this.logger_("waiting for EME key session creation"),Vn({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:t&&t.media(),mainPlaylists:this.playlists.master.playlists}).then((function(){e.logger_("created EME key session"),e.masterPlaylistController_.sourceUpdater_.initializedEme()})).catch((function(t){e.logger_("error while creating EME key session",t),e.player_.error({message:"Failed to initialize media keys for EME",code:3})}))):this.masterPlaylistController_.sourceUpdater_.initializedEme()},i.setupQualityLevels_=function(){var e=this,t=u.default.players[this.tech_.options_.playerId];t&&t.qualityLevels&&!this.qualityLevels_&&(this.qualityLevels_=t.qualityLevels(),this.masterPlaylistController_.on("selectedinitialmedia",(function(){var t,i;t=e.qualityLevels_,(i=e).representations().forEach((function(e){t.addQualityLevel(e)})),Hn(t,i.playlists)})),this.playlists.on("mediachange",(function(){Hn(e.qualityLevels_,e.playlists)})))},t.version=function(){return{"@videojs/http-streaming":Nn,"mux.js":"5.11.1","mpd-parser":"0.17.0","m3u8-parser":"4.7.0","aes-decrypter":"3.1.2"}},i.version=function(){return this.constructor.version()},i.canChangeType=function(){return hn.canChangeType()},i.play=function(){this.masterPlaylistController_.play()},i.setCurrentTime=function(e){this.masterPlaylistController_.setCurrentTime(e)},i.duration=function(){return this.masterPlaylistController_.duration()},i.seekable=function(){return this.masterPlaylistController_.seekable()},i.dispose=function(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.masterPlaylistController_&&this.masterPlaylistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.player_&&(delete this.player_.vhs,delete this.player_.dash,delete this.player_.hls),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.tech_&&delete this.tech_.hls,this.mediaSourceUrl_&&o.default.URL.revokeObjectURL&&(o.default.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),e.prototype.dispose.call(this)},i.convertToProgramTime=function(e,t){return function(e){var t=e.playlist,i=e.time,n=void 0===i?void 0:i,r=e.callback;if(!r)throw new Error("getProgramTime: callback must be provided");if(!t||void 0===n)return r({message:"getProgramTime: playlist and time must be provided"});var a=function(e,t){if(!t||!t.segments||0===t.segments.length)return null;for(var i,n=0,r=0;rn){if(e>n+.25*a.duration)return null;i=a}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:n-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}}(n,t);if(!a)return r({message:"valid programTime was not found"});if("estimate"===a.type)return r({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:a.estimatedStart});var s={mediaSeconds:n},o=function(e,t){if(!t.dateTimeObject)return null;var i=t.videoTimingInfo.transmuxerPrependedSeconds,n=e-(t.videoTimingInfo.transmuxedPresentationStart+i);return new Date(t.dateTimeObject.getTime()+1e3*n)}(n,a.segment);return o&&(s.programDateTime=o.toISOString()),r(null,s)}({playlist:this.masterPlaylistController_.media(),time:e,callback:t})},i.seekToProgramTime=function(e,t,i,n){return void 0===i&&(i=!0),void 0===n&&(n=2),We({programTime:e,playlist:this.masterPlaylistController_.media(),retryCount:n,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})},t}(u.default.getComponent("Component")),Yn={name:"videojs-http-streaming",VERSION:Nn,canHandleSource:function(e,t){void 0===t&&(t={});var i=u.default.mergeOptions(u.default.options,t);return Yn.canPlayType(e.type,i)},handleSource:function(e,t,i){void 0===i&&(i={});var n=u.default.mergeOptions(u.default.options,i);return t.vhs=new Qn(e,t,n),u.default.hasOwnProperty("hls")||Object.defineProperty(t,"hls",{get:function(){return u.default.log.warn("player.tech().hls is deprecated. Use player.tech().vhs instead."),t.vhs},configurable:!0}),t.vhs.xhr=ke(),t.vhs.src(e.src,e.type),t.vhs},canPlayType:function(e,t){void 0===t&&(t={});var i=u.default.mergeOptions(u.default.options,t).vhs.overrideNative,n=void 0===i?!u.default.browser.IS_ANY_SAFARI:i,r=Ce(e);return!r||Fn.supportsTypeNatively(r)&&!n?"":"maybe"}};B("avc1.4d400d,mp4a.40.2")&&u.default.getTech("Html5").registerSourceHandler(Yn,0),u.default.VhsHandler=Qn,Object.defineProperty(u.default,"HlsHandler",{get:function(){return u.default.log.warn("videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead."),Qn},configurable:!0}),u.default.VhsSourceHandler=Yn,Object.defineProperty(u.default,"HlsSourceHandler",{get:function(){return u.default.log.warn("videojs.HlsSourceHandler is deprecated. Use videojs.VhsSourceHandler instead."),Yn},configurable:!0}),u.default.Vhs=Fn,Object.defineProperty(u.default,"Hls",{get:function(){return u.default.log.warn("videojs.Hls is deprecated. Use videojs.Vhs instead."),Fn},configurable:!0}),u.default.use||(u.default.registerComponent("Hls",Fn),u.default.registerComponent("Vhs",Fn)),u.default.options.vhs=u.default.options.vhs||{},u.default.options.hls=u.default.options.hls||{},u.default.registerPlugin?u.default.registerPlugin("reloadSourceOnError",Bn):u.default.plugin("reloadSourceOnError",Bn),e.LOCAL_STORAGE_KEY=qn,e.Vhs=Fn,e.VhsHandler=Qn,e.VhsSourceHandler=Yn,e.emeKeySystems=Wn,e.expandDataUri=zn,e.getAllPsshKeySystemsOptions=Gn,e.setupEmeOptions=jn,e.simpleTypeFromSourceType=Ce,e.waitForKeySessionCreation=Vn,Object.defineProperty(e,"__esModule",{value:!0})}));
diff --git a/node_modules/@videojs/http-streaming/docs/README.md b/node_modules/@videojs/http-streaming/docs/README.md
deleted file mode 100644
index 9a5fc2b..0000000
--- a/node_modules/@videojs/http-streaming/docs/README.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# Overview
-This project supports both [HLS][hls] and [MPEG-DASH][dash] playback in the video.js player. This document is intended as a primer for anyone interested in contributing or just better understanding how bits from a server get turned into video on their display.
-
-## HTTP Live Streaming
-[HLS][apple-hls-intro] has two primary characteristics that distinguish it from other video formats:
-
-- Delivered over HTTP(S): it uses the standard application protocol of the web to deliver all its data
-- Segmented: longer videos are broken up into smaller chunks which can be downloaded independently and switched between at runtime
-
-A standard HLS stream consists of a *Master Playlist* which references one or more *Media Playlists*. Each Media Playlist contains one or more sequential video segments. All these components form a logical hierarchy that informs the player of the different quality levels of the video available and how to address the individual segments of video at each of those levels:
-
-
-
-HLS streams can be delivered in two different modes: a "static" mode for videos that can be played back from any point, often referred to as video-on-demand (VOD); or a "live" mode where later portions of the video become available as time goes by. In the static mode, the Master and Media playlists are fixed. The player is guaranteed that the set of video segments referenced by those playlists will not change over time.
-
-Live mode can work in one of two ways. For truly live events, the most common configuration is for each individual Media Playlist to only include the latest video segment and a small number of consecutive previous segments. In this mode, the player may be able to seek backwards a short time in the video but probably not all the way back to the beginning. In the other live configuration, new video segments can be appended to the Media Playlists but older segments are never removed. This configuration allows the player to seek back to the beginning of the stream at any time during the broadcast and transitions seamlessly to the static stream type when the event finishes.
-
-If you're interested in a more in-depth treatment of the HLS format, check out [Apple's documentation][apple-hls-intro] and the IETF [Draft Specification][hls-spec].
-
-## Dynamic Adaptive Streaming over HTTP
-Similar to HLS, [DASH][dash-wiki] content is segmented and is delivered over HTTP(s).
-
-A DASH stream consits of a *Media Presentation Description*(MPD) that describes segment metadata such as timing information, URLs, resolution and bitrate. Each segment can contain either ISO base media file format(e.g MP4) or MPEG-2 TS data. Typically, the MPD will describe the various *Representations* that map to collections of segments at different bitrates to allow bitrate selection. These Representations can be organized as a SegmentList, SegmentTemplate, SegmentBase, or SegmentTimeline.
-
-DASH streams can be delivered in both video-on-demand(VOD) and live streaming modes. In the VOD case, the MPD describes all the segments and representations available and the player can chose which representation to play based on it's capabilities.
-
-Live mode is accomplished using the ISOBMFF Live profile if the segments are in ISOBMFF. There are a few different ways to setup the MPD including but not limited to updating the MPD after an interval of time, using *Periods*, or using the *availabilityTimeOffset* field. A few examples of this are provided by the [DASH Reference Client][dash-if-reference-client]. The MPD will provide enough information for the player to playback the live stream and seek back as far as is specified in the MPD.
-
-If you're interested in a more in-depth description of MPEG-DASH, check out [MDN's tutorial on setting up DASH][mdn-dash-tut] or the [DASHIF Guidelines][dash-if-guide].
-
-# Further Documentation
-
-- [Architechture](arch.md)
-- [Glossary](glossary.md)
-- [Adaptive Bitrate Switching](bitrate-switching.md)
-- [Multiple Alternative Audio Tracks](multiple-alternative-audio-tracks.md)
-- [reloadSourceOnError](reload-source-on-error.md)
-
-# Helpful Tools
-- [FFmpeg](http://trac.ffmpeg.org/wiki/CompilationGuide)
-- [Thumbcoil](http://thumb.co.il/): web based video inspector
-
-[hls]: /docs/intro.md#http-live-streaming
-[dash]: /docs/intro.md#dynamic-adaptive-streaming-over-http
-[apple-hls-intro]: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/StreamingMediaGuide/Introduction/Introduction.html
-[hls-spec]: https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
-[dash-wiki]: https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
-[dash-if-reference-client]: https://reference.dashif.org/dash.js/
-[mdn-dash-tut]: https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Setting_up_adaptive_streaming_media_sources
-[dash-if-guide]: http://dashif.org/guidelines/
diff --git a/node_modules/@videojs/http-streaming/docs/arch.md b/node_modules/@videojs/http-streaming/docs/arch.md
deleted file mode 100644
index 994757f..0000000
--- a/node_modules/@videojs/http-streaming/docs/arch.md
+++ /dev/null
@@ -1,28 +0,0 @@
-## HLS Project Overview
-This project has three primary duties:
-
-1. Download and parse playlist files
-1. Implement the [HTMLVideoElement](https://html.spec.whatwg.org/multipage/embedded-content.html#the-video-element) interface
-1. Feed content bits to a SourceBuffer by downloading and transmuxing video segments
-
-### Playlist Management
-The [playlist loader](../src/playlist-loader.js) handles all of the details of requesting, parsing, updating, and switching playlists at runtime. It's operation is described by this state diagram:
-
-
-
-During VOD playback, the loader will move quickly to the HAVE_METADATA state and then stay there unless a quality switch request sends it to SWITCHING_MEDIA while it fetches an alternate playlist. The loader enters the HAVE_CURRENT_METADATA when a live stream is detected and it's time to refresh the current media playlist to find out about new video segments.
-
-### HLS Tech
-Currently, the HLS project integrates with [video.js](http://www.videojs.com/) as a [tech](https://github.com/videojs/video.js/blob/master/docs/guides/tech.md). That means it's responsible for providing an interface that closely mirrors the `` element. You can see that implementation in [videojs-http-streaming.js](../src/videojs-http-streaming.js), the primary entry point of the project.
-
-### Transmuxing
-Most browsers don't have support for the file type that HLS video segments are stored in. To get HLS playing back on those browsers, contrib-hls strings together a number of technologies:
-
-1. The [Netstream](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html) in [video.js SWF](https://github.com/videojs/video-js-swf) has a special mode of operation that allows binary video data packaged as an [FLV](http://en.wikipedia.org/wiki/Flash_Video) to be provided directly
-1. [videojs-contrib-media-sources](https://github.com/videojs/videojs-contrib-media-sources) provides an abstraction layer over the SWF that operates like a [Media Source](https://w3c.github.io/media-source/#mediasource)
-1. A pure javascript transmuxer that repackages HLS segments as FLVs
-
-Transmuxing is the process of transforming media stored in one container format into another container without modifying the underlying media data. If that last sentence doesn't make any sense to you, check out the [Introduction to Media](media.md) for more details.
-
-### Buffer Management
-Buffering in contrib-hls is driven by two functions in videojs-hls.js: fillBuffer() and drainBuffer(). During its operation, contrib-hls periodically calls fillBuffer() which determines when more video data is required and begins a segment download if so. Meanwhile, drainBuffer() is invoked periodically during playback to process incoming segments and append them onto the [SourceBuffer](http://w3c.github.io/media-source/#sourcebuffer). In conjunction with a goal buffer length, this producer-consumer relationship drives the buffering behavior of contrib-hls.
diff --git a/node_modules/@videojs/http-streaming/docs/bitrate-switching.md b/node_modules/@videojs/http-streaming/docs/bitrate-switching.md
deleted file mode 100644
index 64ae2a5..0000000
--- a/node_modules/@videojs/http-streaming/docs/bitrate-switching.md
+++ /dev/null
@@ -1,44 +0,0 @@
-# Adaptive Switching Behavior
-The HLS tech tries to ensure the highest-quality viewing experience
-possible, given the available bandwidth and encodings. This doesn't
-always mean using the highest-bitrate rendition available-- if the player
-is 300px by 150px, it would be a big waste of bandwidth to download a 4k
-stream. By default, the player attempts to load the highest-bitrate
-variant that is less than the most recently detected segment bandwidth,
-with one condition: if there are multiple variants with dimensions greater
-than the current player size, it will only switch up one size greater
-than the current player size.
-
-If you're the visual type, the whole process is illustrated
-below. Whenever a new segment is downloaded, we calculate the download
-bitrate based on the size of the segment and the time it took to
-download:
-
-
-
-First, we filter out all the renditions that have a higher bitrate
-than the new measurement:
-
-
-
-Then we get rid of any renditions that are bigger than the current
-player dimensions:
-
-
-
-We don't want to signficant quality drop just because your player is
-one pixel too small, so we add back in the next highest
-resolution. The highest bitrate rendition that remains is the one that
-gets used:
-
-
-
-If it turns out no rendition is acceptable based on the filtering
-described above, the first encoding listed in the master playlist will
-be used.
-
-If you'd like your player to use a different set of priorities, it's
-possible to completely replace the rendition selection logic. For
-instance, you could always choose the most appropriate rendition by
-resolution, even though this might mean more stalls during playback.
-See the documentation on `player.vhs.selectPlaylist` for more details.
diff --git a/node_modules/@videojs/http-streaming/docs/creating-content.md b/node_modules/@videojs/http-streaming/docs/creating-content.md
deleted file mode 100644
index ec1e16c..0000000
--- a/node_modules/@videojs/http-streaming/docs/creating-content.md
+++ /dev/null
@@ -1,218 +0,0 @@
-# Creating Content
-
-## Commands for creating tests streams
-
-### Streams with EXT-X-PROGRAM-DATE-TIME for testing seekToProgramTime and convertToProgramTime
-
-lavfi and testsrc are provided for creating a test stream in ffmpeg
--g 300 sets the GOP size to 300 (keyframe interval, at 30fps, one keyframe every 10 seconds)
--f hls sets the format to HLS (creates an m3u8 and TS segments)
--hls\_time 10 sets the goal segment size to 10 seconds
--hls\_list\_size 20 sets the number of segments in the m3u8 file to 20
--program\_date\_time an hls flag for setting #EXT-X-PROGRAM-DATE-TIME on each segment
-
-```
-ffmpeg \
- -f lavfi \
- -i testsrc=duration=200:size=1280x720:rate=30 \
- -g 300 \
- -f hls \
- -hls_time 10 \
- -hls_list_size 20 \
- -hls_flags program_date_time \
- stream.m3u8
-```
-
-## Commands used for segments in `test/segments` dir
-
-### video.ts
-
-Copy only the first two video frames, leave out audio.
-
-```
-$ ffmpeg -i index0.ts -vframes 2 -an -vcodec copy video.ts
-```
-
-### videoOneSecond.ts
-
-Blank video for 1 second, MMS-Small resolution, start at 0 PTS/DTS, 2 frames per second
-
-```
-$ ffmpeg -f lavfi -i color=c=black:s=128x96:r=2:d=1 -muxdelay 0 -c:v libx264 videoOneSecond.ts
-```
-
-### videoOneSecond1.ts through videoOneSecond4.ts
-
-Same as videoOneSecond.ts, but follows timing in sequence, with videoOneSecond.ts acting as the 0 index. Each segment starts at the second that its index indicates (e.g., videoOneSecond2.ts has a start time of 2 seconds).
-
-```
-$ ffmpeg -i videoOneSecond.ts -muxdelay 0 -output_ts_offset 1 -vcodec copy videoOneSecond1.ts
-$ ffmpeg -i videoOneSecond.ts -muxdelay 0 -output_ts_offset 2 -vcodec copy videoOneSecond2.ts
-$ ffmpeg -i videoOneSecond.ts -muxdelay 0 -output_ts_offset 3 -vcodec copy videoOneSecond3.ts
-$ ffmpeg -i videoOneSecond.ts -muxdelay 0 -output_ts_offset 4 -vcodec copy videoOneSecond4.ts
-```
-
-### audio.ts
-
-Copy only the first two audio frames, leave out video.
-
-```
-$ ffmpeg -i index0.ts -aframes 2 -vn -acodec copy audio.ts
-```
-
-### videoMinOffset.ts
-
-video.ts but with an offset of 0
-
-```
-$ ffmpeg -i video.ts -muxpreload 0 -muxdelay 0 -vcodec copy videoMinOffset.ts
-```
-
-### audioMinOffset.ts
-
-audio.ts but with an offset of 0. Note that muxed.ts is used because ffmpeg didn't like
-the use of audio.ts
-
-```
-$ ffmpeg -i muxed.ts -muxpreload 0 -muxdelay 0 -acodec copy -vn audioMinOffset.ts
-```
-
-### videoMaxOffset.ts
-
-This segment offsets content such that it ends at exactly the max timestamp before a rollover occurs. It uses the max timestamp of 2^33 (8589934592) minus the segment duration of 6006 (0.066733 seconds) in order to not rollover mid segment, and divides the value by 90,000 to convert it from media time to seconds.
-
-(2^33 - 6006) / 90,000 = 95443.6509556
-
-```
-$ ffmpeg -i videoMinOffset.ts -muxdelay 95443.6509556 -muxpreload 95443.6509556 -output_ts_offset 95443.6509556 -vcodec copy videoMaxOffset.ts
-```
-
-### audioMaxOffset.ts
-
-This segment offsets content such that it ends at exactly the max timestamp before a rollover occurs. It uses the max timestamp of 2^33 (8589934592) minus the segment duration of 11520 (0.128000 seconds) in order to not rollover mid segment, and divides the value by 90,000 to convert it from media time to seconds.
-
-(2^33 - 11520) / 90,000 = 95443.5896889
-
-```
-$ ffmpeg -i audioMinOffset.ts -muxdelay 95443.5896889 -muxpreload 95443.5896889 -output_ts_offset 95443.5896889 -acodec copy audioMaxOffset.ts
-```
-
-### videoLargeOffset.ts
-
-This segment offsets content by the rollover threshhold of 2^32 (4294967296) found in the rollover handling of mux.js, adds 1 to ensure there aren't any cases where there's an equal match, then divides the value by 90,000 to convert it from media time to seconds.
-
-(2^32 + 1) / 90,000 = 47721.8588556
-
-```
-$ ffmpeg -i videoMinOffset.ts -muxdelay 47721.8588556 -muxpreload 47721.8588556 -output_ts_offset 47721.8588556 -vcodec copy videoLargeOffset.ts
-```
-
-### audioLargeOffset.ts
-
-This segment offsets content by the rollover threshhold of 2^32 (4294967296) found in the rollover handling of mux.js, adds 1 to ensure there aren't any cases where there's an equal match, then divides the value by 90,000 to convert it from media time to seconds.
-
-(2^32 + 1) / 90,000 = 47721.8588556
-
-```
-$ ffmpeg -i audioMinOffset.ts -muxdelay 47721.8588556 -muxpreload 47721.8588556 -output_ts_offset 47721.8588556 -acodec copy audioLargeOffset.ts
-```
-
-### videoLargeOffset2.ts
-
-This takes videoLargeOffset.ts and adds the duration of videoLargeOffset.ts (6006 / 90,000 = 0.066733 seconds) to its offset so that this segment can act as the second in one continuous stream.
-
-47721.8588556 + 0.066733 = 47721.9255886
-
-```
-$ ffmpeg -i videoLargeOffset.ts -muxdelay 47721.9255886 -muxpreload 47721.9255886 -output_ts_offset 47721.9255886 -vcodec copy videoLargeOffset2.ts
-```
-
-### audioLargeOffset2.ts
-
-This takes audioLargeOffset.ts and adds the duration of audioLargeOffset.ts (11520 / 90,000 = 0.128 seconds) to its offset so that this segment can act as the second in one continuous stream.
-
-47721.8588556 + 0.128 = 47721.9868556
-
-```
-$ ffmpeg -i audioLargeOffset.ts -muxdelay 47721.9868556 -muxpreload 47721.9868556 -output_ts_offset 47721.9868556 -acodec copy audioLargeOffset2.ts
-```
-
-### caption.ts
-
-Copy the first two frames of video out of a ts segment that already includes CEA-608 captions.
-
-`ffmpeg -i index0.ts -vframes 2 -an -vcodec copy caption.ts`
-
-### id3.ts
-
-Copy only the first five frames of video, leave out audio.
-
-`ffmpeg -i index0.ts -vframes 5 -an -vcodec copy smaller.ts`
-
-Create an ID3 tag using [id3taggenerator][apple_streaming_tools]:
-
-`id3taggenerator -text "{\"id\":1, \"data\": \"id3\"}" -o tag.id3`
-
-Create a file `macro.txt` with the following:
-
-`0 id3 tag.id3`
-
-Run [mediafilesegmenter][apple_streaming_tools] with the small video segment and macro file, to produce a new segment with ID3 tags inserted at the specified times.
-
-`mediafilesegmenter -start-segments-with-iframe --target-duration=1 --meta-macro-file=macro.txt -s -A smaller.ts`
-
-### mp4Video.mp4
-
-Copy only the first two video frames, leave out audio.
-movflags:
-* frag\_keyframe: "Start a new fragment at each video keyframe."
-* empty\_moov: "Write an initial moov atom directly at the start of the file, without describing any samples in it."
-* omit\_tfhd\_offset: "Do not write any absolute base\_data\_offset in tfhd atoms. This avoids tying fragments to absolute byte positions in the file/streams." (see also: https://www.w3.org/TR/mse-byte-stream-format-isobmff/#movie-fragment-relative-addressing)
-
-```
-$ ffmpeg -i file.mp4 -movflags frag_keyframe+empty_moov+omit_tfhd_offset -vframes 2 -an -vcodec copy mp4Video.mp4
-```
-
-### mp4Audio.mp4
-
-Copy only the first two audio frames, leave out video.
-movflags:
-* frag\_keyframe: "Start a new fragment at each video keyframe."
-* empty\_moov: "Write an initial moov atom directly at the start of the file, without describing any samples in it."
-* omit\_tfhd\_offset: "Do not write any absolute base\_data\_offset in tfhd atoms. This avoids tying fragments to absolute byte positions in the file/streams." (see also: https://www.w3.org/TR/mse-byte-stream-format-isobmff/#movie-fragment-relative-addressing)
-
-```
-$ ffmpeg -i file.mp4 -movflags frag_keyframe+empty_moov+omit_tfhd_offset -aframes 2 -vn -acodec copy mp4Audio.mp4
-```
-
-### mp4VideoInit.mp4 and mp4AudioInit.mp4
-
-Using DASH as the format type (-f) will lead to two init segments, one for video and one for audio. Using HLS will lead to one joined.
-Renamed from .m4s to .mp4
-
-```
-$ ffmpeg -i input.mp4 -f dash out.mpd
-```
-
-### webmVideoInit.webm and webmVideo.webm
-
-```
-$ cat mp4VideoInit.mp4 mp4Video.mp4 > video.mp4
-$ ffmpeg -i video.mp4 -dash_segment_type webm -c:v libvpx-vp9 -f dash output.mpd
-$ mv init-stream0.webm webmVideoInit.webm
-$ mv chunk-stream0-00001.webm webmVideo.webm
-```
-
-## Other useful commands
-
-### Joined (audio and video) initialization segment (for HLS)
-
-Using DASH as the format type (-f) will lead to two init segments, one for video and one for audio. Using HLS will lead to one joined.
-Note that -hls\_fmp4\_init\_filename defaults to init.mp4, but is here for readability.
-Without specifying fmp4 for hls\_segment\_type, ffmpeg defaults to ts.
-
-```
-$ ffmpeg -i input.mp4 -f hls -hls_fmp4_init_filename init.mp4 -hls_segment_type fmp4 out.m3u8
-```
-
-[apple_streaming_tools]: https://developer.apple.com/documentation/http_live_streaming/about_apple_s_http_live_streaming_tools
diff --git a/node_modules/@videojs/http-streaming/docs/dash-playlist-loader.md b/node_modules/@videojs/http-streaming/docs/dash-playlist-loader.md
deleted file mode 100644
index 0ce46c0..0000000
--- a/node_modules/@videojs/http-streaming/docs/dash-playlist-loader.md
+++ /dev/null
@@ -1,87 +0,0 @@
-# DASH Playlist Loader
-
-## Purpose
-
-The [DashPlaylistLoader][dpl] (DPL) is responsible for requesting MPDs, parsing them and keeping track of the media "playlists" associated with the MPD. The [DPL] is used with a [SegmentLoader] to load fmp4 fragments from a DASH source.
-
-## Basic Responsibilities
-
-1. To request an MPD.
-2. To parse an MPD into a format [videojs-http-streaming][vhs] can understand.
-3. To refresh MPDs according to their minimumUpdatePeriod.
-4. To allow selection of a specific media stream.
-5. To sync the client clock with a server clock according to the UTCTiming node.
-6. To refresh a live MPD for changes.
-
-## Design
-
-The [DPL] is written to be as similar as possible to the [PlaylistLoader][pl]. This means that majority of the public API for these two classes are the same, and so are the states they go through and events that they trigger.
-
-### States
-
-
-
-- `HAVE_NOTHING` the state before the MPD is received and parsed.
-- `HAVE_MASTER` the state before a media stream is setup but the MPD has been parsed.
-- `HAVE_METADATA` the state after a media stream is setup.
-
-### API
-
-- `load()` this will either start or kick the loader during playback.
-- `start()` this will start the [DPL] and request the MPD.
-- `parseMasterXml()` this will parse the MPD manifest and return the result.
-- `media()` this will return the currently active media stream or set a new active media stream.
-
-### Events
-
-- `loadedplaylist` signals the setup of a master playlist, representing the DASH source as a whole, from the MPD; or a media playlist, representing a media stream.
-- `loadedmetadata` signals initial setup of a media stream.
-- `minimumUpdatePeriod` signals that a update period has ended and the MPD must be requested again.
-- `playlistunchanged` signals that no changes have been made to a MPD.
-- `mediaupdatetimeout` signals that a live MPD and media stream must be refreshed.
-- `mediachanging` signals that the currently active media stream is going to be changed.
-- `mediachange` signals that the new media stream has been updated.
-
-### Interaction with Other Modules
-
-
-
-### Special Features
-
-There are a few features of [DPL] that are different from [PL] due to fundamental differences between HLS and DASH standards.
-
-#### MinimumUpdatePeriod
-
-This is a time period specified in the MPD after which the MPD should be re-requested and parsed. There could be any number of changes to the MPD between these update periods.
-
-#### SyncClientServerClock
-
-There is a UTCTiming node in the MPD that allows the client clock to be synced with a clock on the server. This may affect the results of parsing the MPD.
-
-#### Requesting `sidx` Boxes
-
-To be filled out.
-
-### Previous Behavior
-
-Until version 1.9.0 of [VHS], we thought that [DPL] could skip the `HAVE_NOTHING` and `HAVE_MASTER` states, as no other XHR requests are needed once the MPD has been downloaded and parsed. However, this is incorrect as there are some Presentations that signal the use of a "Segment Index box" or `sidx`. This `sidx` references specific byte ranges in a file that could contain media or potentially other `sidx` boxes.
-
-A DASH MPD that describes a `sidx` is therefore similar to an HLS master manifest, in that the MPD contains references to something that must be requested and parsed first before references to media segments can be obtained. With this in mind, it was necessary to update the initialization and state transitions of [DPL] to allow further XHR requests to be made after the initial request for the MPD.
-
-### Current Behavior
-
-In [this PR](https://github.com/videojs/http-streaming/pull/386), the [DPL] was updated to go through the `HAVE_NOTHING` and `HAVE_MASTER` states before arriving at `HAVE_METADATA`. If the MPD does not contain `sidx` boxes, then this transition happens quickly after `load()` is called, spending little time in the `HAVE_MASTER` state.
-
-The initial media selection for `masterPlaylistLoader` is made in the `loadedplaylist` handler located in [MasterPlaylistController][mpc]. We now use `hasPendingRequest` to determine whether to automatically select a media playlist for the `masterPlaylistLoader` as a fallback in case one is not selected by [MPC]. The child [DPL]s are created with a media playlist passed in as an argument, so this fallback is not necessary for them. Instead, that media playlist is saved and auto-selected once we enter the `HAVE_MASTER` state.
-
-The `updateMaster` method will return `null` if no updates are found.
-
-The `selectinitialmedia` event is not triggered until an audioPlaylistLoader (which for DASH is always a child [DPL]) has a media playlist. This is signaled by triggering `loadedmetadata` on the respective [DPL]. This event is used to initialize the [Representations API][representations] and setup EME (see [contrib-eme]).
-
-[dpl]: ../src/dash-playlist-loader.js
-[sl]: ../src/segment-loader.js
-[vhs]: intro.md
-[pl]: ../src/playlist-loader.js
-[mpc]: ../src/master-playlist-controller.js
-[representations]: ../README.md#hlsrepresentations
-[contrib-eme]: https://github.com/videojs/videojs-contrib-eme
diff --git a/node_modules/@videojs/http-streaming/docs/glossary.md b/node_modules/@videojs/http-streaming/docs/glossary.md
deleted file mode 100644
index 370c772..0000000
--- a/node_modules/@videojs/http-streaming/docs/glossary.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# Glossary
-
-**Playlist**: This is a representation of an HLS or DASH manifest.
-
-**Media Playlist**: This is a manifest that represents a single rendition or media stream of the source.
-
-**Master Playlist Controller**: This acts as the main controller for the playback engine. It interacts with the SegmentLoaders, PlaylistLoaders, PlaybackWatcher, etc.
-
-**Playlist Loader**: This will request the source and load the master manifest. It is also instructed by the ABR algorithm to load a media playlist or wraps a media playlist if it is provided as the source. There are more details about the playlist loader [here](./arch.md).
-
-**DASH Playlist Loader**: This will do as the PlaylistLoader does, but for DASH sources. It also handles DASH specific functionaltiy, such as refreshing the MPD according to the minimumRefreshPeriod and synchronizing to a server clock.
-
-**Segment Loader**: This determines which segment should be loaded, requests it via the Media Segment Loader and passes the result to the Source Updater.
-
-**Media Segment Loader**: This requests a given segment, decrypts the segment if necessary, and returns it to the Segment Loader.
-
-**Source Updater**: This manages the browser's [SourceBuffers](https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer). It appends decrypted segment bytes provided by the Segment Loader to the corresponding Source Buffer.
-
-**ABR(Adaptive Bitrate) Algorithm**: This concept is described more in detail [here](https://en.wikipedia.org/wiki/Adaptive_bitrate_streaming). Our chosen ABR algorithm is referenced by [selectPlaylist](../README.md#hlsselectplaylist) and is described more [here](./bitrate-switching.md).
-
-**Playback Watcher**: This attemps to resolve common playback stalls caused by improper seeking, gaps in content and browser issues.
-
-**Sync Controller**: This will attempt to create a mapping between the segment index and a display time on the player.
diff --git a/node_modules/@videojs/http-streaming/docs/hlse.md b/node_modules/@videojs/http-streaming/docs/hlse.md
deleted file mode 100644
index f32f8a9..0000000
--- a/node_modules/@videojs/http-streaming/docs/hlse.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Encrypted HTTP Live Streaming
-The [HLS spec](http://tools.ietf.org/html/draft-pantos-http-live-streaming-13#section-6.2.3) requires segments to be encrypted with AES-128 in CBC mode with PKCS7 padding. You can encrypt data to that specification with a combination of [OpenSSL](https://www.openssl.org/) and the [pkcs7 utility](https://github.com/brightcove/pkcs7). From the command-line:
-
-```sh
-# encrypt the text "hello" into a file
-# since this is for testing, skip the key salting so the output is stable
-# using -nosalt outside of testing is a terrible idea!
-echo -n "hello" | pkcs7 | \
-openssl enc -aes-128-cbc -nopad -nosalt -K $KEY -iv $IV > hello.encrypted
-
-# xxd is a handy way of translating binary into a format easily consumed by
-# javascript
-xxd -i hello.encrypted
-```
-
-Later, you can decrypt it:
-
-```sh
-openssl enc -d -nopad -aes-128-cbc -K $KEY -iv $IV
-```
diff --git a/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-1.png b/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-1.png
deleted file mode 100644
index f999068..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-1.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-2.png b/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-2.png
deleted file mode 100644
index 973e156..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-2.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-3.png b/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-3.png
deleted file mode 100644
index fd1e2af..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-3.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-4.png b/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-4.png
deleted file mode 100644
index faf8587..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/bitrate-switching-4.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/containers.png b/node_modules/@videojs/http-streaming/docs/images/containers.png
deleted file mode 100644
index eb37279..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/containers.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/dash-playlist-loader-mpc-mg-sequence.plantuml.png b/node_modules/@videojs/http-streaming/docs/images/dash-playlist-loader-mpc-mg-sequence.plantuml.png
deleted file mode 100644
index 200fa74..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/dash-playlist-loader-mpc-mg-sequence.plantuml.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/dash-playlist-loader-states.nomnoml.svg b/node_modules/@videojs/http-streaming/docs/images/dash-playlist-loader-states.nomnoml.svg
deleted file mode 100644
index 08b203a..0000000
--- a/node_modules/@videojs/http-streaming/docs/images/dash-playlist-loader-states.nomnoml.svg
+++ /dev/null
@@ -1,12 +0,0 @@
-load()
-
-
-media()
-
-
-
-HAVE_NOTHING
-
-HAVE_MASTER
-
-HAVE_METADATA
\ No newline at end of file
diff --git a/node_modules/@videojs/http-streaming/docs/images/h264-nal.svg b/node_modules/@videojs/http-streaming/docs/images/h264-nal.svg
deleted file mode 100644
index d547df6..0000000
--- a/node_modules/@videojs/http-streaming/docs/images/h264-nal.svg
+++ /dev/null
@@ -1,125 +0,0 @@
-
-
-
-
-
-
-
-
-
- image/svg+xml
-
-
-
-
-
-
-
-
-
- Header
-
-
- Raw Bitstream Payload (RBSP)
-
-
-
- 1 byte
- H264 Network Abstraction Layer (NAL) Unit
-
-
diff --git a/node_modules/@videojs/http-streaming/docs/images/hls-format.png b/node_modules/@videojs/http-streaming/docs/images/hls-format.png
deleted file mode 100644
index 058baf8..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/hls-format.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/mp2t-packet-types.png b/node_modules/@videojs/http-streaming/docs/images/mp2t-packet-types.png
deleted file mode 100644
index 5c890b9..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/mp2t-packet-types.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/mp2t-structure.png b/node_modules/@videojs/http-streaming/docs/images/mp2t-structure.png
deleted file mode 100644
index ea3ada6..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/mp2t-structure.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/playlist-loader-mpc-mg-sequence.plantuml.png b/node_modules/@videojs/http-streaming/docs/images/playlist-loader-mpc-mg-sequence.plantuml.png
deleted file mode 100644
index a4c862f..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/playlist-loader-mpc-mg-sequence.plantuml.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/playlist-loader-states.nomnoml.svg b/node_modules/@videojs/http-streaming/docs/images/playlist-loader-states.nomnoml.svg
deleted file mode 100644
index f61f06d..0000000
--- a/node_modules/@videojs/http-streaming/docs/images/playlist-loader-states.nomnoml.svg
+++ /dev/null
@@ -1,26 +0,0 @@
-load()
-
-
-media()
-
-
-media()/ start()
-
-
-
-
-
-
-
-
-
-HAVE_NOTHING
-
-HAVE_MASTER
-
-SWITCHING_MEDIA
-
-HAVE_METADATA
-mediaupdatetimeout
-
-HAVE_CURRENT_METADATA
\ No newline at end of file
diff --git a/node_modules/@videojs/http-streaming/docs/images/segment-loader-states.png b/node_modules/@videojs/http-streaming/docs/images/segment-loader-states.png
deleted file mode 100644
index c330e16..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/segment-loader-states.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-1.graffle b/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-1.graffle
deleted file mode 100644
index cc0c86c..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-1.graffle and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-2.graffle b/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-2.graffle
deleted file mode 100644
index 6c38e51..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-2.graffle and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-3.graffle b/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-3.graffle
deleted file mode 100644
index f6e90fd..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-3.graffle and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-4.graffle b/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-4.graffle
deleted file mode 100644
index 2628ee1..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/sources/bitrate-switching-4.graffle and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/containers.graffle b/node_modules/@videojs/http-streaming/docs/images/sources/containers.graffle
deleted file mode 100644
index fac642c..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/sources/containers.graffle and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/dash-playlist-loader-mpc-mg-sequence.plantuml b/node_modules/@videojs/http-streaming/docs/images/sources/dash-playlist-loader-mpc-mg-sequence.plantuml
deleted file mode 100644
index 2151303..0000000
--- a/node_modules/@videojs/http-streaming/docs/images/sources/dash-playlist-loader-mpc-mg-sequence.plantuml
+++ /dev/null
@@ -1,119 +0,0 @@
-@startuml
-
-header DashPlaylistLoader sequences
-title DashPlaylistLoader sequences: Master Manifest with Alternate Audio
-
-Participant "MasterPlaylistController" as MPC #red
-Participant "MasterDashPlaylistLoader" as MPL #blue
-Participant "mainSegmentLoader" as SL #blue
-Participant "AudioDashPlaylistLoader" as APL #green
-Participant "audioSegmentLoader" as ASL #green
-Participant "external server" as ext #brown
-Participant "mpdParser" as parser #orange
-Participant "mediaGroups" as MG #purple
-Participant Tech #lightblue
-
-== Initialization ==
-
-MPC -> MPL : construct MasterPlaylistLoader
-MPC -> MPL: load()
-
-== Requesting Master Manifest ==
-
-MPL -> MPL : start()
-
-MPL -> ext: xhr request for master manifest
-ext -> MPL : response with master manifest
-
-MPL -> parser: parse manifest
-parser -> MPL: object representing manifest
-
-note over MPL #lightblue: trigger 'loadedplaylist'
-
-== Requesting Video Manifest ==
-
-note over MPL #lightblue: handling loadedplaylist
-MPL -> MPL: media(x)
-
-alt if no sidx
- note over MPL #lightgray: zero delay to fake network request
-else if sidx
- break
- MPL -> ext: request sidx
- end
-end
-
-note over MPL #lightblue: trigger 'loadedmetadata' on master loader [T1]
-
-note over MPL #lightblue: handling 'loadedmetadata'
-
-opt vod and preload !== 'none'
-
- MPL -> SL: playlist()
- MPL -> SL: load()
-
-end
-
-== Initializing Media Groups, Choosing Active Tracks ==
-
-MPL -> MG: setupMediaGroups()
-MG -> MG: initialize()
-
-== Initializing Alternate Audio Loader ==
-
-MG -> APL: create child playlist loader for alt audio
-
-MG -> MG: activeGroup and audio variant selected
-MG -> MG: enable activeTrack, onTrackChanged()
-MG -> ASL: reset audio segment loader
-
-== Requesting Alternate Audio Manifest ==
-
-MG -> MG: startLoaders()
-
-MG -> APL: load()
-APL -> APL: start()
-APL -> APL: zero delay to fake network request
-
-break finish pending tasks
- MG -> Tech: add audioTrack
- MPL -> MPC: setupSourceBuffers_()
- MPL -> MPC: setupFirstPlay()
-
- loop mainSegmentLoader.monitorBufferTick_()
- SL -> ext: requests media segments
- ext -> SL: response with media segment bytes
- end
-end
-
-APL -> APL: zero delay over
-APL -> APL: media(x)
-
-alt if no sidx
- note over APL #lightgray: zero delay to fake network request
-else if sidx
- break
- MPL -> ext: request sidx
- end
-end
-
-== Requesting Alternate Audio Segments ==
-
-note over APL #lightblue: trigger 'loadedplaylist'
-note over APL #lightblue: handling 'loadedplaylist'
-APL -> ASL: playlist()
-
-
-note over ASL #lightblue: trigger 'loadedmetadata' [T2]
-note over APL #lightblue: handling 'loadedmetadata'
-APL -> ASL: playlist()
-APL -> ASL: load()
-
-loop audioSegmentLoader.monitorBufferTick_()
-
- ASL -> ext: requests media segments
- ext -> ASL: response with media segment bytes
-
-end
-
-@enduml
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/dash-playlist-loader-states.nomnoml.txt b/node_modules/@videojs/http-streaming/docs/images/sources/dash-playlist-loader-states.nomnoml.txt
deleted file mode 100644
index 6d20aac..0000000
--- a/node_modules/@videojs/http-streaming/docs/images/sources/dash-playlist-loader-states.nomnoml.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-#title: DASH Playlist Loader States
-#arrowSize: 0.5
-#bendSize: 1
-#direction: down
-#gutter: 10
-#edgeMargin: 1
-#edges: rounded
-#fillArrows: false
-#font: Arial
-#fontSize: 10
-#leading: 1
-#lineWidth: 2
-#padding: 20
-#spacing: 50
-#stroke: #33322E
-#zoom: 1
-
-#.label: align=center visual=none italic
-
-[HAVE_NOTHING] load()-> [HAVE_MASTER]
-[HAVE_MASTER] media()-> [HAVE_METADATA]
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/hls-format.graffle b/node_modules/@videojs/http-streaming/docs/images/sources/hls-format.graffle
deleted file mode 100644
index d8c49c1..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/sources/hls-format.graffle and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/mp2t-packet-types.graffle b/node_modules/@videojs/http-streaming/docs/images/sources/mp2t-packet-types.graffle
deleted file mode 100644
index d0aeb47..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/sources/mp2t-packet-types.graffle and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/mp2t-structure.graffle b/node_modules/@videojs/http-streaming/docs/images/sources/mp2t-structure.graffle
deleted file mode 100644
index 53afb70..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/images/sources/mp2t-structure.graffle and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/new-playlist-loader-master-video-alt-audio-sequence.plantuml b/node_modules/@videojs/http-streaming/docs/images/sources/new-playlist-loader-master-video-alt-audio-sequence.plantuml
deleted file mode 100644
index c2af5f0..0000000
--- a/node_modules/@videojs/http-streaming/docs/images/sources/new-playlist-loader-master-video-alt-audio-sequence.plantuml
+++ /dev/null
@@ -1,246 +0,0 @@
-@startuml
-
-header PlaylistLoader sequences
-title PlaylistLoader sequences: Master Manifest and Alternate Audio
-
-Participant "MasterPlaylistController" as MPC #red
-Participant "MasterPlaylistLoader" as MPL #blue
-Participant "mainSegmentLoader" as SL #blue
-Participant "AudioPlaylistLoader" as APL #green
-Participant "audioSegmentLoader" as ASL #green
-Participant "external server" as ext #brown
-Participant "m3u8Parser" as parser #orange
-Participant "mediaGroups" as MG #purple
-Participant Tech #lightblue
-
-== Initialization ==
-
-group MasterPlaylistController.constructor()
-
- MPC -> MPL : setting up MasterPlaylistLoader
- note left #lightyellow
- sets up mediaupdatetimeout
- handler for live playlist staleness
- end note
- note over MPL #lightgray: state = 'HAVE_NOTHING'
-
- MPC -> MPL: load()
-
-end
-
-group MasterPlaylistLoader.load()
-
- MPL -> MPL : start()
- note left #lightyellow: not started yet
-
-== Requesting Master Manifest ==
-
- group start()
-
- note over MPL #lightgray: started = true
-
- MPL -> ext: xhr request for master manifest
- ext -> MPL : response with master manifest
-
- MPL -> parser: parse master manifest
- parser -> MPL: object representing manifest
- MPL -> MPL: set loader's master playlist
- note over MPL #lightgray: state = 'HAVE_MASTER'
- note over MPL #lightblue: trigger 'loadedplaylist' on master loader
-
-== Requesting Video Manifest ==
-
- group 'loadedplaylist' handler
-
- note over MPL #lightblue: handling loadedplaylist
- MPL -> MPL : media()
- note left #lightgray: select initial (video) playlist
- note over MPL #lightyellow: state = 'SWITCHING_MEDIA'
-
- group media()
-
- MPL -> ext : request child manifest
- ext -> MPL: child manifest returned
- MPL -> MPL: haveMetadata()
- note over MPL #lightyellow: state = 'HAVE_METADATA'
-
- group haveMetadata()
-
- MPL -> parser: parse child manifest
- parser -> MPL: object representing the child manifest
- note over MPL #lightyellow
- update master and media playlists
- end note
-
- opt live
- MPL -> MPL: setup mediaupdatetimeout
- end
-
- note over MPL #lightblue
- trigger 'loadedplaylist' on master loader.
- This does not end up requesting segments
- at this point.
- end note
-
- group MasterPlaylistLoader 'loadedplaylist' handler
-
- MPL -> MPL : setup durationchange handler
-
- end
-
- end
-
-== Requesting Video Segments ==
-
- note over MPL #lightblue: trigger 'loadedmetadata'
-
- group 'loadedmetadata' handler
-
- note over MPL #lightblue: handling 'loadedmetadata'
-
- opt vod and preload !== 'none'
-
- MPL -> SL: playlist()
- note over SL #lightyellow: updates playlist
-
- MPL -> SL: load()
- note right #lightgray
- This does nothing as mimeTypes
- have not been set yet.
- end note
-
- end
-
- MPL -> MG: setupMediaGroups()
-
-== Initializing Media Groups, Choosing Active Tracks ==
-
- group MediaGroups.setupMediaGroups()
-
- group initialize()
-
- MG -> APL: create child playlist loader for alt audio
- note over APL #lightyellow: state = 'HAVE_NOTHING'
-
- note left #lightgray
- setup 'loadedmetadata' and 'loadedplaylist' listeners
- on child alt audio playlist loader
- end note
-
- MG -> Tech: add audioTracks
-
- end
-
- MG -> MG: activeGroup and audio variant selected
- MG -> MG: enable activeTrack, onTrackChanged()
- note left #lightgray
- There is no activePlaylistLoader at this point,
- but there is an audio playlistLoader
- end note
-
- group onTrackChanged()
-
- MG -> SL: reset mainSegmentLoader
- note left #lightgray: Clears buffer, aborts all inflight requests
-
-== Requesting Alternate Audio Manifest ==
-
- MG -> MG: startLoaders()
-
- group startLoaders()
- note over MG #lightyellow
- activePlaylistLoader = AudioPlaylistLoader
- end note
-
- MG -> APL: load()
- end
-
- group AudioPlaylistLoader.load()
- APL -> APL: start()
-
- group alt start()
-
- note over APL #lightyellow: started = true
- APL -> ext: request alt audio media manifest
-
- break MasterPlaylistLoader 'loadedmetadata' handler
-
- MPL -> MPC: setupSourceBuffers()
- note left #lightgray
- This will set mimeType.
- Segments can be loaded from now on.
- end note
-
- MPL -> MPC: setupFirstPlay()
- note left #lightgray
- Immediate exit since the player
- is paused
- end note
-
- end
-
- ext -> APL: responds with child manifest
- APL -> parser: parse child manifest
- parser -> APL: object representing child manifest returned
- note over APL #lightyellow: state = 'HAVE_MASTER'
- note left #lightgray: Infer a master playlist
-
- APL -> APL: haveMetadata()
- note over APL #lightyellow: state = 'HAVE_METADATA'
-
- group haveMetadata()
-
- APL -> parser: parsing the child manifest again
- parser -> APL: returning object representing child manifest
- note over APL #lightyellow
- update master and media references
- end note
-
-== Requesting Alternate Audio Segments ==
-
- note over APL #lightblue: trigger 'loadedplaylist'
-
- group 'loadedplaylist' handler
-
- note over APL #lightblue: handling 'loadedplaylist'
- APL -> ASL: playlist()
- note over ASL #lightyellow: set playlist
-
- end
-
- end
-
- note over APL #lightblue: trigger 'loadedmetadata'
-
- group 'loadedmetadata' handler
-
- note over APL #lightblue: handling 'loadedmetadata'
-
- APL -> ASL: playlist()
- APL -> ASL: load()
-
- loop audioSegmentLoader.load()
-
- ASL -> ext: requests media segments
- ext -> ASL: response with media segment bytes
- end
-
- end
-
- end
-
- end
-
- end
-
- end
-
- end
-
- end
-
- end
-
-end
-
-@enduml
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/playlist-loader-mpc-mg-sequence.plantuml b/node_modules/@videojs/http-streaming/docs/images/sources/playlist-loader-mpc-mg-sequence.plantuml
deleted file mode 100644
index d7a631c..0000000
--- a/node_modules/@videojs/http-streaming/docs/images/sources/playlist-loader-mpc-mg-sequence.plantuml
+++ /dev/null
@@ -1,114 +0,0 @@
-@startuml
-
-header PlaylistLoader sequences
-title PlaylistLoader sequences: Master Manifest and Alternate Audio
-
-Participant "MasterPlaylistController" as MPC #red
-Participant "MasterPlaylistLoader" as MPL #blue
-Participant "mainSegmentLoader" as SL #blue
-Participant "AudioPlaylistLoader" as APL #green
-Participant "audioSegmentLoader" as ASL #green
-Participant "external server" as ext #brown
-Participant "m3u8Parser" as parser #orange
-Participant "mediaGroups" as MG #purple
-Participant Tech #lightblue
-
-== Initialization ==
-
-MPC -> MPL : construct MasterPlaylistLoader
-MPC -> MPL: load()
-
-MPL -> MPL : start()
-
-== Requesting Master Manifest ==
-
-MPL -> ext: xhr request for master manifest
-ext -> MPL : response with master manifest
-
-MPL -> parser: parse master manifest
-parser -> MPL: object representing manifest
-
-note over MPL #lightblue: trigger 'loadedplaylist'
-
-== Requesting Video Manifest ==
-
-note over MPL #lightblue: handling loadedplaylist
-MPL -> MPL : media()
-
-MPL -> ext : request child manifest
-ext -> MPL: child manifest returned
-
-MPL -> parser: parse child manifest
-parser -> MPL: object representing the child manifest
-
-note over MPL #lightblue: trigger 'loadedplaylist'
-note over MPL #lightblue: handleing 'loadedplaylist'
-
-MPL -> SL: playlist()
-MPL -> SL: load()
-
-== Requesting Video Segments ==
-
-note over MPL #lightblue: trigger 'loadedmetadata'
-note over MPL #lightblue: handling 'loadedmetadata'
-
-opt vod and preload !== 'none'
-
- MPL -> SL: playlist()
- MPL -> SL: load()
-
-end
-
-MPL -> MG: setupMediaGroups()
-
-== Initializing Media Groups, Choosing Active Tracks ==
-
-MG -> APL: create child playlist loader for alt audio
-
-MG -> MG: activeGroup and audio variant selected
-MG -> MG: enable activeTrack, onTrackChanged()
-MG -> SL: reset mainSegmentLoader
-
-== Requesting Alternate Audio Manifest ==
-
-MG -> MG: startLoaders()
-
-MG -> APL: load()
-APL -> APL: start()
-
-APL -> ext: request alt audio media manifest
-
-break finish pending tasks
- MG -> Tech: add audioTracks
- MPL -> MPC: setupSourceBuffers()
- MPL -> MPC: setupFirstPlay()
-
- loop on monitorBufferTick
- SL -> ext: requests media segments
- ext -> SL: response with media segment bytes
- end
-end
-
-ext -> APL: responds with child manifest
-
-APL -> parser: parse child manifest
-parser -> APL: object representing child manifest returned
-
-== Requesting Alternate Audio Segments ==
-
-note over APL #lightblue: trigger 'loadedplaylist'
-note over APL #lightblue: handling 'loadedplaylist'
-APL -> ASL: playlist()
-
-note over APL #lightblue: trigger 'loadedmetadata'
-note over APL #lightblue: handling 'loadedmetadata'
-APL -> ASL: playlist()
-APL -> ASL: load()
-
-loop audioSegmentLoader.load()
-
- ASL -> ext: requests media segments
- ext -> ASL: response with media segment bytes
-end
-
-@enduml
diff --git a/node_modules/@videojs/http-streaming/docs/images/sources/playlist-loader-states.nomnoml.txt b/node_modules/@videojs/http-streaming/docs/images/sources/playlist-loader-states.nomnoml.txt
deleted file mode 100644
index 846fa29..0000000
--- a/node_modules/@videojs/http-streaming/docs/images/sources/playlist-loader-states.nomnoml.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-#title: Playlist Loader States
-#arrowSize: 0.5
-#bendSize: 1
-#direction: down
-#gutter: 10
-#edgeMargin: 1
-#edges: rounded
-#fillArrows: false
-#font: Arial
-#fontSize: 10
-#leading: 1
-#lineWidth: 2
-#padding: 20
-#spacing: 50
-#stroke: #33322E
-#zoom: 1
-
-#.label: align=center visual=none italic
-
-[HAVE_NOTHING] load()-> [HAVE_MASTER]
-[HAVE_MASTER] media()-> [SWITCHING_MEDIA]
-[SWITCHING_MEDIA] media()/ start()-> [HAVE_METADATA]
-
-[HAVE_METADATA] <--> [ mediaupdatetimeout]
-[ mediaupdatetimeout] <--> [HAVE_CURRENT_METADATA]
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/current-flow.plantuml b/node_modules/@videojs/http-streaming/docs/lhls/current-flow.plantuml
deleted file mode 100644
index 334a132..0000000
--- a/node_modules/@videojs/http-streaming/docs/lhls/current-flow.plantuml
+++ /dev/null
@@ -1,13 +0,0 @@
-@startuml
-
-state "Download Segment" as DL
-state "Prepare for Append" as PfA
-
-[*] -> DL
-DL -> PfA
-PfA : transmux (if needed)
-PfA -> Append
-Append : MSE source buffer
-Append -> [*]
-
-@enduml
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/current-flow.plantuml.png b/node_modules/@videojs/http-streaming/docs/lhls/current-flow.plantuml.png
deleted file mode 100644
index 7641015..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/lhls/current-flow.plantuml.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/current-transmux-and-append-flow.plantuml b/node_modules/@videojs/http-streaming/docs/lhls/current-transmux-and-append-flow.plantuml
deleted file mode 100644
index ec49c97..0000000
--- a/node_modules/@videojs/http-streaming/docs/lhls/current-transmux-and-append-flow.plantuml
+++ /dev/null
@@ -1,57 +0,0 @@
-@startuml
-
-participant SegmentLoader order 1
-participant "media-segment-request" order 2
-participant "videojs-contrib-media-sources" order 3
-participant mux.js order 4
-participant "Native Source Buffer" order 5
-
-SegmentLoader -> "media-segment-request" : mediaSegmentRequest(...)
-
-group Request
- "media-segment-request" -> SegmentLoader : doneFn(...)
- note left
- At end of all requests
- (key/segment/init segment)
- end note
- SegmentLoader -> SegmentLoader : handleSegment(...)
- note left
- "Probe" (parse) segment for
- timing and track information
- end note
- SegmentLoader -> "videojs-contrib-media-sources" : append to "fake" source buffer
- note left
- Source buffer here is a
- wrapper around native buffers
- end note
- group Transmux
- "videojs-contrib-media-sources" -> mux.js : postMessage(...setAudioAppendStart...)
- note left
- Used for checking for overlap when
- prefixing audio with silence.
- end note
- "videojs-contrib-media-sources" -> mux.js : postMessage(...alignGopsWith...)
- note left
- Used for aligning gops when overlapping
- content (switching renditions) to fix
- some browser glitching.
- end note
-
- "videojs-contrib-media-sources" -> mux.js : postMessage(...push...)
- note left
- Pushes bytes into the transmuxer pipeline.
- end note
- "videojs-contrib-media-sources" -> mux.js : postMessage(...flush...)
- "mux.js" -> "videojs-contrib-media-sources" : postMessage(...data...)
- "videojs-contrib-media-sources" -> "Native Source Buffer" : append
- "Native Source Buffer" -> "videojs-contrib-media-sources" : //updateend//
- "videojs-contrib-media-sources" -> SegmentLoader : handleUpdateEnd(...)
- end
-end
-SegmentLoader -> SegmentLoader : handleUpdateEnd_()
-note left
- Saves segment timing info
- and starts next request.
-end note
-
-@enduml
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/current-transmux-and-append-flow.plantuml.png b/node_modules/@videojs/http-streaming/docs/lhls/current-transmux-and-append-flow.plantuml.png
deleted file mode 100644
index 08fa978..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/lhls/current-transmux-and-append-flow.plantuml.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/expected-flow.plantuml b/node_modules/@videojs/http-streaming/docs/lhls/expected-flow.plantuml
deleted file mode 100644
index 90bad7a..0000000
--- a/node_modules/@videojs/http-streaming/docs/lhls/expected-flow.plantuml
+++ /dev/null
@@ -1,29 +0,0 @@
-@startuml
-
-state "Request Segment" as RS
-state "Partial Response (1)" as PR1
-state "..." as DDD
-state "Partial Response (n)" as PRN
-state "Prepare for Append (1)" as PfA1
-state "Prepare for Append (n)" as PfAN
-state "Append (1)" as A1
-state "Append (n)" as AN
-
-[*] -> RS
-
-RS --> PR1
-PR1 --> DDD
-DDD --> PRN
-
-PR1 -> PfA1
-PfA1 : transmux (if needed)
-PfA1 -> A1
-A1 : MSE source buffer
-PRN -> PfAN
-PfAN : transmux (if needed)
-PfAN -> AN
-AN : MSE source buffer
-
-AN --> [*]
-
-@enduml
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/expected-flow.plantuml.png b/node_modules/@videojs/http-streaming/docs/lhls/expected-flow.plantuml.png
deleted file mode 100644
index a05759e..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/lhls/expected-flow.plantuml.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/index.md b/node_modules/@videojs/http-streaming/docs/lhls/index.md
deleted file mode 100644
index 7b8f37a..0000000
--- a/node_modules/@videojs/http-streaming/docs/lhls/index.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# LHLS
-
-### Table of Contents
-
-* [Background](#background)
-* [Current Support for LHLS in VHS](#current-support-for-lhls-in-vhs)
-* [Request a Segment in Pieces](#request-a-segment-in-pieces)
-* [Transmux and Append Segment Pieces](#transmux-and-append-segment-pieces)
- * [videojs-contrib-media-sources background](#videojs-contrib-media-sources-background)
- * [Transmux Before Append](#transmux-before-append)
- * [Transmux Within media-segment-request](#transmux-within-media-segment-request)
- * [mux.js](#muxjs)
- * [The New Flow](#the-new-flow)
-* [Resources](#resources)
-
-### Background
-
-LHLS stands for Low-Latency HLS (see [Periscope's post](https://medium.com/@periscopecode/introducing-lhls-media-streaming-eb6212948bef)). It's meant to be used for ultra low latency live streaming, where a server can send pieces of a segment before the segment is done being written to, and the player can append those pieces to the browser, allowing sub segment duration latency from true live.
-
-In order to support LHLS, a few components are required:
-
-* A server that supports [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding).
-* A client that can:
- * request segment pieces
- * transmux segment pieces (for browsers that don't natively support the media type)
- * append segment pieces
-
-### Current Support for LHLS in VHS
-
-At the moment, VHS doesn't support any of the client requirements. It waits until a request is completed and the transmuxer expects full segments.
-
-Current flow:
-
-
-
-Expected flow:
-
-
-
-### Request Segment Pieces
-
-The first change was to request pieces of a segment. There are a few approaches to accomplish this:
-
-* [Range Requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests)
- * requires server support
- * more round trips
-* [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
- * limited browser support
- * doesn't support aborts
-* [Plain text MIME type](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data)
- * slightly non-standard
- * incurs a cost of converting from string to bytes
-
-*Plain text MIME type* was chosen because of its wide support. It provides a mechanism to access progressive bytes downloaded on [XMLHttpRequest progress events](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onprogress).
-
-This change was made in [media-segment-request](https://github.com/videojs/http-streaming/blob/master/src/media-segment-request.js).
-
-### Transmux and Append Segment Pieces
-
-Getting the progress bytes is easy. Supporting partial transmuxing and appending is harder.
-
-Current flow:
-
-
-
-In order to support partial transmuxing and appending in the current flow, videojs-contrib-media-sources would have to get more complicated.
-
-##### videojs-contrib-media-sources background
-
-Browsers, via MSE source buffers, only support a limited set of media types. For most browsers, this means MP4/fragmented MP4. HLS uses TS segments (it also supports fragmented MP4, but that case is less common). This is why transmuxing is necessary.
-
-Just like Video.js is a wrapper around the browser video element, bridging compatibility and adding support to extend features, videojs-contrib-media-sources provides support for more media types across different browsers by building in a transmuxer.
-
-Not only did videojs-contrib-media-sources allow us to transmux TS to FMP4, but it also allowed us to transmux TS to FLV for flash support.
-
-Over time, the complexity of logic grew in videojs-contrib-media-sources, and it coupled tightly with videojs-contrib-hls and videojs-http-streaming, firing events to communicate between the two.
-
-Once flash support was moved to a distinct flash module, [via flashls](https://github.com/brightcove/videojs-flashls-source-handler), it was decided to move the videojs-contrib-media-sources logic into VHS, and to remove coupled logic by using only the native source buffers (instead of the wrapper) and transmuxing somewhere within VHS before appending.
-
-##### Transmux Before Append
-
-As the LHLS work started, and videojs-contrib-media-sources needed more logic, the native media source [abstraction leaked](https://en.wikipedia.org/wiki/Leaky_abstraction), adding non-standard functions to work around limitations. In addition, the logic in videojs-contrib-media-sources required more conditional paths, leading to more confusing code.
-
-It was decided that it would be easier to do the transmux before append work in the process of adding support for LHLS. This was widely considered a *good decision*, and provided a means of reducing tech debt while adding in a new feature.
-
-##### Transmux Within media-segment-request
-
-Work started by moving transmuxing into segment-loader, however, we quickly realized that media-segment-request provided a better home.
-
-media-segment-request already handled decrypting segments. If it handled transmuxing as well, then segment-loader could stick with only deciding which segment to request, getting bytes as FMP4, and appending them.
-
-The transmuxing logic moved to a new module called segment-transmuxer, which wrapped around the [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker) that wrapped around mux.js (the transmuxer itself).
-
-##### mux.js
-
-While most of the [mux.js pipeline](https://github.com/videojs/mux.js/blob/master/docs/diagram.png) supports pushing pieces of data (and should support LHLS by default), its "flushes" to send transmuxed data back to the caller expected full segments.
-
-Much of the pipeline was reused, however, the top level audio and video segment streams, as well as the entry point, were rewritten so that instead of providing a full segment on flushes, each frame of video was provided individually (audio frames still flush as a group). The new concept of partial flushes was added into the pipeline to handle this case.
-
-##### The New Flow
-
-One benefit to transmuxing before appending is the possibility of extracting track and timing information from the segments. Previously, this required a separate parsing step to happen on the full segment. Now, it is included in the transmuxing pipeline, and comes back to us on separate callbacks.
-
-
-
-### Resources
-
-* https://medium.com/@periscopecode/introducing-lhls-media-streaming-eb6212948bef
-* https://github.com/jordicenzano/webserver-chunked-growingfiles
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/new-segment-loader-sequence.plantuml b/node_modules/@videojs/http-streaming/docs/lhls/new-segment-loader-sequence.plantuml
deleted file mode 100644
index 9ffc759..0000000
--- a/node_modules/@videojs/http-streaming/docs/lhls/new-segment-loader-sequence.plantuml
+++ /dev/null
@@ -1,118 +0,0 @@
-@startuml
-
-participant SegmentLoader order 1
-participant "media-segment-request" order 2
-participant XMLHttpRequest order 3
-participant "segment-transmuxer" order 4
-participant mux.js order 5
-
-SegmentLoader -> "media-segment-request" : mediaSegmentRequest(...)
-"media-segment-request" -> XMLHttpRequest : request for segment/key/init segment
-
-group Request
- XMLHttpRequest -> "media-segment-request" : //segment progress//
- note over "media-segment-request" #moccasin
- If handling partial data,
- tries to transmux new
- segment bytes.
- end note
- "media-segment-request" -> SegmentLoader : progressFn(...)
- note left
- Forwards "progress" events from
- the XML HTTP Request.
- end note
- group Transmux
- "media-segment-request" -> "segment-transmuxer" : transmux(...)
-
- "segment-transmuxer" -> mux.js : postMessage(...setAudioAppendStart...)
- note left
- Used for checking for overlap when
- prefixing audio with silence.
- end note
- "segment-transmuxer" -> mux.js : postMessage(...alignGopsWith...)
- note left
- Used for aligning gops when overlapping
- content (switching renditions) to fix
- some browser glitching.
- end note
-
- "segment-transmuxer" -> mux.js : postMessage(...push...)
- note left
- Pushes bytes into the transmuxer pipeline.
- end note
-
- "segment-transmuxer" -> mux.js : postMessage(...partialFlush...)
- note left #moccasin
- Collates any complete frame data
- from partial segment and
- caches remainder.
- end note
- "segment-transmuxer" -> mux.js : postMessage(...flush...)
- note left
- Collates any complete frame data
- from segment, caches only data
- required between segments.
- end note
-
- "mux.js" -> "segment-transmuxer" : postMessage(...trackinfo...)
- "segment-transmuxer" -> "media-segment-request" : onTrackInfo(...)
- "media-segment-request" -> SegmentLoader : trackInfoFn(...)
- note left
- Gets whether the segment
- has audio and/or video.
- end note
- "mux.js" -> "segment-transmuxer" : postMessage(...audioTimingInfo...)
- "segment-transmuxer" -> "media-segment-request" : onAudioTimingInfo(...)
- "mux.js" -> "segment-transmuxer" : postMessage(...videoTimingInfo...)
- "segment-transmuxer" -> "media-segment-request" : onVideoTimingInfo(...)
- "media-segment-request" -> SegmentLoader : timingInfoFn(...)
- note left
- Gets the audio/video
- start/end times.
- end note
-
- "mux.js" -> "segment-transmuxer" : postMessage(...caption...)
- "segment-transmuxer" -> "media-segment-request" : onCaptions(...)
- "media-segment-request" -> SegmentLoader : captionsFn(...)
- note left
- Gets captions from transmux.
- end note
-
- "mux.js" -> "segment-transmuxer" : postMessage(...id3Frame...)
- "segment-transmuxer" -> "media-segment-request" : onId3(...)
- "media-segment-request" -> SegmentLoader : id3Fn(...)
- note left
- Gets metadata from transmux.
- end note
-
- "mux.js" -> "segment-transmuxer" : postMessage(...data...)
- "segment-transmuxer" -> "media-segment-request" : onData(...)
- "media-segment-request" -> SegmentLoader : dataFn(...)
- note left
- Gets an fmp4 segment
- ready to be appended.
- end note
-
- "mux.js" -> "segment-transmuxer" : postMessage(...done...)
- note left
- Gathers GOP info, and calls
- done callback.
- end note
- "segment-transmuxer" -> "media-segment-request" : onDone(...)
- "media-segment-request" -> SegmentLoader : doneFn(...)
- note left
- Queues callbacks on source
- buffer queue to wait for
- appends to complete.
- end note
- end
- XMLHttpRequest -> "media-segment-request" : //segment request finished//
-end
-
-SegmentLoader -> SegmentLoader : handleAppendsDone_()
-note left
- Saves segment timing info
- and starts next request.
-end note
-
-@enduml
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/new-segment-loader-sequence.plantuml.png b/node_modules/@videojs/http-streaming/docs/lhls/new-segment-loader-sequence.plantuml.png
deleted file mode 100644
index 9ee7ef4..0000000
Binary files a/node_modules/@videojs/http-streaming/docs/lhls/new-segment-loader-sequence.plantuml.png and /dev/null differ
diff --git a/node_modules/@videojs/http-streaming/docs/lhls/transmux-before-append-changes.md b/node_modules/@videojs/http-streaming/docs/lhls/transmux-before-append-changes.md
deleted file mode 100644
index c266541..0000000
--- a/node_modules/@videojs/http-streaming/docs/lhls/transmux-before-append-changes.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Transmux Before Append Changes
-
-## Overview
-
-In moving our transmuxing stage from after append (to a virtual source buffer from videojs-contrib-media-sources) to before appending (to a native source buffer), some changes were required, and others made the logic simpler. What follows are some details into some of the changes made, why they were made, and what impact they will have.
-
-### Source Buffer Creation
-
-In a pre-TBA (transmux before append) world, videojs-contrib-media-source's source buffers provided an abstraction around the native source buffers. They also required a bit more information than the native buffers. For instance, they used the full mime types instead of simply relying on the codec information, when creating the source buffers. This provided the container types, which let the virtual source buffer know whether the media needed to be transmuxed or not. In a post-TBA world, the container type is no longer required, therefore only the codec strings are passed along.
-
-In terms of when the source buffers are created, in the post-TBA world, the creation of source buffers is delayed until we are sure we have all of the information we need. This means that we don't create the native source buffers until the PMT is parsed from the main media. Even if the content is demuxed, we only need to parse the main media, since, for now, we don't rely on codec information from the segment itself, and instead use the manifest-provided codec info, or default codecs. While we could create the source buffers earlier if the codec information is provided in the manifest, delaying provides a simpler, single, code path, and more opportunity for us to be flexible with how much codec info is provided by the attribute. While the HLS specification requires this information, other formats may not, and we have seen content that plays fine but does not adhere to the strict rules of providing all necessary codec information.
-
-### Appending Init Segments
-
-Previously, init segments were handled by videojs-contrib-media-sources for TS segments and segment-loader for FMP4 segments.
-
-videojs-contrib-media-sources and TS:
-* video segments
- * append the video init segment returned from the transmuxer with every segment
-* audio segments
- * append the audio init segment returned from the transmuxer only in the following cases:
- * first append
- * after timestampOffset is set
- * audio track events: change/addtrack/removetrack
- * 'mediachange' event
-
-segment-loader and FMP4:
-* if segment.map is set:
- * save (cache) the init segment after the request finished
- * append the init segment directly to the source buffer if the segment loader's activeInitSegmentId doesn't match the segment.map generated init segment ID
-
-With the transmux before append and LHLS changes, we only append video init segments on changes as well. This is more important with LHLS, as prepending an init segment before every frame of video would be wasteful.
-
-### Test Changes
-
-Some tests were removed because they were no longer relevant after the change to creating source buffers later. For instance, `waits for both main and audio loaders to finish before calling endOfStream if main loader starting media is unknown` no longer can be tested by waiting for an audio loader response and checking for end of stream, as the test will time out since MasterPlaylistController will wait for track info from the main loader before the source buffers are created. That condition is checked elsewhere.
diff --git a/node_modules/@videojs/http-streaming/docs/media.md b/node_modules/@videojs/http-streaming/docs/media.md
deleted file mode 100644
index 1744571..0000000
--- a/node_modules/@videojs/http-streaming/docs/media.md
+++ /dev/null
@@ -1,29 +0,0 @@
-This doc is just a stub right now. Check back later for updates.
-
-# General
-When we talk about video, we normally think about it as one monolithic thing. If you ponder it for a moment though, you'll realize it's actually two distinct sorts of information that are presented to the viewer in tandem: a series of pictures and a sequence of audio samples. The temporal nature of audio and video is shared but the techniques used to efficiently transmit them are very different and necessitate a lot of the complexity in video file formats. Bundling up these (at least) two streams into a single package is the first of many issues introduced by the need to serialize video data and is solved by meta-formats called _containers_.
-
-Containers formats are probably the most recongnizable of the video components because they get the honor of determining the file extension. You've probably heard of MP4, MOV, and WMV, all of which are container formats. Containers specify how to serialize audio, video, and metadata streams into a sequential series of bits and how to unpack them for decoding. Containers are basically a box that can hold video information and timed media data:
-
-
-
-- codecs
-- containers, multiplexing
-
-# MPEG2-TS
-
-
-
-
-- streaming vs storage
-- program table
-- program map table
-- history, context
-
-# H.264
-- NAL units
-- Annex B vs MP4 elementary stream
-- access unit -> sample
-
-# MP4
-- origins: quicktime
diff --git a/node_modules/@videojs/http-streaming/docs/mse.md b/node_modules/@videojs/http-streaming/docs/mse.md
deleted file mode 100644
index 5fe048d..0000000
--- a/node_modules/@videojs/http-streaming/docs/mse.md
+++ /dev/null
@@ -1,75 +0,0 @@
-# Media Source Extensions Notes
-A collection of findings experimenting with Media Source Extensions on
-Chrome 36.
-
-* Specifying an audio and video codec when creating a source buffer
- but passing in an initialization segment with only a video track
- results in a decode error
-
-## ISO Base Media File Format (BMFF)
-
-### Init Segment
-A working initialization segment is outlined below. It may be possible
-to trim this structure down further.
-
-- `ftyp`
-- `moov`
- - `mvhd`
- - `trak`
- - `tkhd`
- - `mdia`
- - `mdhd`
- - `hdlr`
- - `minf`
- - `mvex`
-
-### Media Segment
-The structure of a minimal media segment that actually encapsulates
-movie data is outlined below:
-
-- `moof`
- - `mfhd`
- - `traf`
- - `tfhd`
- - `tfdt`
- - `trun` containing samples
-- `mdat`
-
-### Structure
-
-sample: time {number}, data {array}
-chunk: samples {array}
-track: samples {array}
-segment: moov {box}, mdats {array} | moof {box}, mdats {array}, data {array}
-
-track
- chunk
- sample
-
-movie fragment -> track fragment -> [samples]
-
-### Sample Data Offsets
-Movie-fragment Relative Addressing: all trun data offsets are relative
-to the containing moof (?).
-
-Without default-base-is-moof, the base data offset for each trun in
-trafs after the first is the *end* of the previous traf.
-
-#### iso5/DASH Style
-moof
-|- traf (default-base-is-moof)
-| |- trun_0 + 0
-| `- trun_1 + 100
-`- traf (default-base-is-moof)
- `- trun_2 + 300
-mdat
-|- samples_for_trun_0 (100 bytes)
-|- samples_for_trun_1 (200 bytes)
-`- samples_for_trun_2
-
-#### Single Track Style
-moof
-`- traf
- `- trun_0 + 0
-mdat
-`- samples_for_trun_0
\ No newline at end of file
diff --git a/node_modules/@videojs/http-streaming/docs/multiple-alternative-audio-tracks.md b/node_modules/@videojs/http-streaming/docs/multiple-alternative-audio-tracks.md
deleted file mode 100644
index f19c321..0000000
--- a/node_modules/@videojs/http-streaming/docs/multiple-alternative-audio-tracks.md
+++ /dev/null
@@ -1,96 +0,0 @@
-# Multiple Alternative Audio Tracks
-## General
-m3u8 manifests with multiple audio streams will have those streams added to `video.js` in an `AudioTrackList`. The `AudioTrackList` can be accessed using `player.audioTracks()` or `tech.audioTracks()`.
-
-## Mapping m3u8 metadata to AudioTracks
-The mapping between `AudioTrack` and the parsed m3u8 file is fairly straight forward. The table below shows the mapping
-
-| m3u8 | AudioTrack |
-|---------|------------|
-| label | label |
-| lang | language |
-| default | enabled |
-| ??? | kind |
-| ??? | id |
-
-As you can see m3u8's do not have a property for `AudioTrack.id`, which means that we let `video.js` randomly generate the id for `AudioTrack`s. This will have no real impact on any part of the system as we do not use the `id` anywhere.
-
-The other property that does not have a mapping in the m3u8 is `AudioTrack.kind`. It was decided that we would set the `kind` to `main` when `default` is set to `true` and in other cases we set it to `alternative` unless the track has `characteristics` which include `public.accessibility.describes-video`, in which case we set it to `main-desc` (note that this `kind` indicates that the track is a mix of the main track and description, so it can be played *instead* of the main track; a track with kind `description` *only* has the description, not the main track).
-
-Below is a basic example of a mapping
-m3u8 layout
-``` JavaScript
-{
- 'media-group-1': [{
- 'audio-track-1': {
- default: true,
- lang: 'eng'
- },
- 'audio-track-2': {
- default: false,
- lang: 'fr'
- },
- 'audio-track-3': {
- default: false,
- lang: 'eng',
- characteristics: 'public.accessibility.describes-video'
- }
- }]
-}
-```
-
-Corresponding AudioTrackList when media-group-1 is used (before any tracks have been changed)
-``` JavaScript
-[{
- label: 'audio-tracks-1',
- enabled: true,
- language: 'eng',
- kind: 'main',
- id: 'random'
-}, {
- label: 'audio-tracks-2',
- enabled: false,
- language: 'fr',
- kind: 'alternative',
- id: 'random'
-}, {
- label: 'audio-tracks-3',
- enabled: false,
- language: 'eng',
- kind: 'main-desc',
- id: 'random'
-}]
-```
-
-## Startup (how tracks are added and used)
-> AudioTrack & AudioTrackList live in video.js
-
-1. `HLS` creates a `MasterPlaylistController` and watches for the `loadedmetadata` event
-1. `HLS` parses the m3u8 using the `MasterPlaylistController`
-1. `MasterPlaylistController` creates a `PlaylistLoader` for the master m3u8
-1. `MasterPlaylistController` creates `PlaylistLoader`s for every audio playlist
-1. `MasterPlaylistController` creates a `SegmentLoader` for the main m3u8
-1. `MasterPlaylistController` creates a `SegmentLoader` for a potential audio playlist
-1. `HLS` sees the `loadedmetadata` and finds the currently selected MediaGroup and all the metadata
-1. `HLS` removes all `AudioTrack`s from the `AudioTrackList`
-1. `HLS` created `AudioTrack`s for the MediaGroup and adds them to the `AudioTrackList`
-1. `HLS` calls `MasterPlaylistController`s `useAudio` with no arguments (causes it to use the currently enabled audio)
-1. `MasterPlaylistController` turns off the current audio `PlaylistLoader` if it is on
-1. `MasterPlaylistController` maps the `label` to the `PlaylistLoader` containing the audio
-1. `MasterPlaylistController` turns on that `PlaylistLoader` and the Corresponding `SegmentLoader` (master or audio only)
-1. `MediaSource`/`mux.js` determine how to mux
-
-## How tracks are switched
-> AudioTrack & AudioTrackList live in video.js
-
-1. `HLS` is setup to watch for the `changed` event on the `AudioTrackList`
-1. User selects a new `AudioTrack` from a menu (where only one track can be enabled)
-1. `AudioTrackList` enables the new `Audiotrack` and disables all others
-1. `AudioTrackList` triggers a `changed` event
-1. `HLS` sees the `changed` event and finds the newly enabled `AudioTrack`
-1. `HLS` sends the `label` for the new `AudioTrack` to `MasterPlaylistController`s `useAudio` function
-1. `MasterPlaylistController` turns off the current audio `PlaylistLoader` if it is on
-1. `MasterPlaylistController` maps the `label` to the `PlaylistLoader` containing the audio
-1. `MasterPlaylistController` maps the `label` to the `PlaylistLoader` containing the audio
-1. `MasterPlaylistController` turns on that `PlaylistLoader` and the Corresponding `SegmentLoader` (master or audio only)
-1. `MediaSource`/`mux.js` determine how to mux
diff --git a/node_modules/@videojs/http-streaming/docs/player-time-to-program-time.md b/node_modules/@videojs/http-streaming/docs/player-time-to-program-time.md
deleted file mode 100644
index 9a3c0a0..0000000
--- a/node_modules/@videojs/http-streaming/docs/player-time-to-program-time.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# How to get player time from program time
-
-NOTE: See the doc on [Program Time to Player Time](program-time-to-player-time.md) for definitions and an overview of the conversion process.
-
-## Overview
-
-To convert a program time to a player time, the following steps must be taken:
-
-1. Find the right segment by sequentially searching through the playlist until the program time requested is >= the EXT-X-PROGRAM-DATE-TIME of the segment, and < the EXT-X-PROGRAM-DATE-TIME of the following segment (or the end of the playlist is reached).
-2. Determine the segment's start and end player times.
-
-To accomplish #2, the segment must be downloaded and transmuxed (right now only TS segments are handled, and TS is always transmuxed to FMP4). This will obtain start and end times post transmuxer modifications. These are the times that the source buffer will recieve and report for the segment's newly created MP4 fragment.
-
-Since there isn't a simple code path for downloading a segment without appending, the easiest approach is to seek to the estimated start time of that segment using the playlist duration calculation function. Because this process is not always accurate (manifest timing values are almost never accurate), a few seeks may be required to accurately seek into that segment.
-
-If all goes well, and the target segment is downloaded and transmuxed, the player time may be found by taking the difference between the requested program time and the EXT-X-PROGRAM-DATE-TIME of the segment, then adding that difference to `segment.videoTimingInfo.transmuxedPresentationStart`.
diff --git a/node_modules/@videojs/http-streaming/docs/playlist-loader.md b/node_modules/@videojs/http-streaming/docs/playlist-loader.md
deleted file mode 100644
index 03f8ec4..0000000
--- a/node_modules/@videojs/http-streaming/docs/playlist-loader.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# Playlist Loader
-
-## Purpose
-
-The [PlaylistLoader][pl] (PL) is responsible for requesting m3u8s, parsing them and keeping track of the media "playlists" associated with the manifest. The [PL] is used with a [SegmentLoader] to load ts or fmp4 fragments from an HLS source.
-
-## Basic Responsibilities
-
-1. To request an m3u8.
-2. To parse a m3u8 into a format [videojs-http-streaming][vhs] can understand.
-3. To allow selection of a specific media stream.
-4. To refresh a live master m3u8 for changes.
-
-## Design
-
-### States
-
-
-
-- `HAVE_NOTHING` the state before the m3u8 is received and parsed.
-- `HAVE_MASTER` the state before a media manifest is parsed and setup but after the master manifest has been parsed and setup.
-- `HAVE_METADATA` the state after a media stream is setup.
-- `SWITCHING_MEDIA` the intermediary state we go though while changing to a newly selected media playlist
-- `HAVE_CURRENT_METADATA` a temporary state after requesting a refresh of the live manifest and before receiving the update
-
-### API
-
-- `load()` this will either start or kick the loader during playback.
-- `start()` this will start the [PL] and request the m3u8.
-- `media()` this will return the currently active media stream or set a new active media stream.
-
-### Events
-
-- `loadedplaylist` signals the setup of a master playlist, representing the HLS source as a whole, from the m3u8; or a media playlist, representing a media stream.
-- `loadedmetadata` signals initial setup of a media stream.
-- `playlistunchanged` signals that no changes have been made to a m3u8.
-- `mediaupdatetimeout` signals that a live m3u8 and media stream must be refreshed.
-- `mediachanging` signals that the currently active media stream is going to be changed.
-- `mediachange` signals that the new media stream has been updated.
-
-### Interaction with Other Modules
-
-
-
-[pl]: ../src/playlist-loader.js
-[sl]: ../src/segment-loader.js
-[vhs]: intro.md
diff --git a/node_modules/@videojs/http-streaming/docs/program-time-from-player-time.md b/node_modules/@videojs/http-streaming/docs/program-time-from-player-time.md
deleted file mode 100644
index c2ddb40..0000000
--- a/node_modules/@videojs/http-streaming/docs/program-time-from-player-time.md
+++ /dev/null
@@ -1,141 +0,0 @@
-# How to get program time from player time
-
-## Definitions
-
-NOTE: All times referenced in seconds unless otherwise specified.
-
-*Player Time*: any time that can be gotten/set from player.currentTime() (e.g., any time within player.seekable().start(0) to player.seekable().end(0)).
-*Stream Time*: any time within one of the stream's segments. Used by video frames (e.g., dts, pts, base media decode time). While these times natively use clock values, throughout the document the times are referenced in seconds.
-*Program Time*: any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME).
-*Start of Segment*: the pts (presentation timestamp) value of the first frame in a segment.
-
-## Overview
-
-In order to convert from a *player time* to a *stream time*, an "anchor point" is required to match up a *player time*, *stream time*, and *program time*.
-
-Two anchor points that are usable are the time since the start of a new timeline (e.g., the time since the last discontinuity or start of the stream), and the start of a segment. Because, in our requirements for this conversion, each segment is tagged with its *program time* in the form of an [EXT-X-PROGRAM-DATE-TIME tag](https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.6), using the segment start as the anchor point is the easiest solution. It's the closest potential anchor point to the time to convert, and it doesn't require us to track time changes across segments (e.g., trimmed or prepended content).
-
-Those time changes are the result of the transmuxer, which can add/remove content in order to keep the content playable (without gaps or other breaking changes between segments), particularly when a segment doesn't start with a key frame.
-
-In order to make use of the segment start, and to calculate the offset between the segment start and the time to convert, a few properties are needed:
-
-1. The start of the segment before transmuxing
-1. Time changes made to the segment during transmuxing
-1. The start of the segment after transmuxing
-
-While the start of the segment before and after transmuxing is trivial to retrieve, getting the time changes made during transmuxing is more complicated, as we must account for any trimming, prepending, and gap filling made during the transmux stage. However, the required use-case only needs the position of a video frame, allowing us to ignore any changes made to the audio timeline (because VHS uses video as the timeline of truth), as well as a couple of the video modifications.
-
-What follows are the changes made to a video stream by the transmuxer that could alter the timeline, and if they must be accounted for in the conversion:
-
-* Keyframe Pulling
- * Used when: the segment doesn't start with a keyframe.
- * Impact: the keyframe with the lowest dts value in the segment is "pulled" back to the first dts value in the segment, and all frames in-between are dropped.
- * Need to account in time conversion? No. If a keyframe is pulled, and frames before it are dropped, then the segment will maintain the same segment duration, and the viewer is only seeing the keyframe during that period.
-* GOP Fusion
- * Used when: the segment doesn't start with a keyframe.
- * Impact: if GOPs were saved from previous segment appends, the last GOP will be prepended to the segment.
- * Need to account in time conversion? Yes. The segment is artificially extended, so while it shouldn't impact the stream time itself (since it will overlap with content already appended), it will impact the post transmux start of segment.
-* GOPS to Align With
- * Used when: switching renditions, or appending segments with overlapping GOPs (intersecting time ranges).
- * Impact: GOPs in the segment will be dropped until there are no overlapping GOPs with previous segments.
- * Need to account in time conversion? No. So long as we aren't switching renditions, and the content is sane enough to not contain overlapping GOPs, this should not have a meaningful impact.
-
-Among the changes, with only GOP Fusion having an impact, the task is simplified. Instead of accounting for any changes to the video stream, only those from GOP Fusion should be accounted for. Since GOP fusion will potentially only prepend frames to the segment, we just need the number of seconds prepended to the segment when offsetting the time. As such, we can add the following properties to each segment:
-
-```
-segment: {
- // calculated start of segment from either end of previous segment or end of last buffer
- // (in stream time)
- start,
- ...
- videoTimingInfo: {
- // number of seconds prepended by GOP fusion
- transmuxerPrependedSeconds
- // start of transmuxed segment (in player time)
- transmuxedPresentationStart
- }
-}
-```
-
-## The Formula
-
-With the properties listed above, calculating a *program time* from a *player time* is given as follows:
-
-```
-const playerTimeToProgramTime = (playerTime, segment) => {
- if (!segment.dateTimeObject) {
- // Can't convert without an "anchor point" for the program time (i.e., a time that can
- // be used to map the start of a segment with a real world time).
- return null;
- }
-
- const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
- const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart;
-
- // get the start of the content from before old content is prepended
- const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
- const offsetFromSegmentStart = playerTime - startOfSegment;
-
- return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
-};
-```
-
-## Examples
-
-```
-// Program Times:
-// segment1: 2018-11-10T00:00:30.1Z => 2018-11-10T00:00:32.1Z
-// segment2: 2018-11-10T00:00:32.1Z => 2018-11-10T00:00:34.1Z
-// segment3: 2018-11-10T00:00:34.1Z => 2018-11-10T00:00:36.1Z
-//
-// Player Times:
-// segment1: 0 => 2
-// segment2: 2 => 4
-// segment3: 4 => 6
-
-const segment1 = {
- dateTimeObject: 2018-11-10T00:00:30.1Z
- videoTimingInfo: {
- transmuxerPrependedSeconds: 0,
- transmuxedPresentationStart: 0
- }
-};
-playerTimeToProgramTime(0.1, segment1);
-// startOfSegment = 0 + 0 = 0
-// offsetFromSegmentStart = 0.1 - 0 = 0.1
-// return 2018-11-10T00:00:30.1Z + 0.1 = 2018-11-10T00:00:30.2Z
-
-const segment2 = {
- dateTimeObject: 2018-11-10T00:00:32.1Z
- videoTimingInfo: {
- transmuxerPrependedSeconds: 0.3,
- transmuxedPresentationStart: 1.7
- }
-};
-playerTimeToProgramTime(2.5, segment2);
-// startOfSegment = 1.7 + 0.3 = 2
-// offsetFromSegmentStart = 2.5 - 2 = 0.5
-// return 2018-11-10T00:00:32.1Z + 0.5 = 2018-11-10T00:00:32.6Z
-
-const segment3 = {
- dateTimeObject: 2018-11-10T00:00:34.1Z
- videoTimingInfo: {
- transmuxerPrependedSeconds: 0.2,
- transmuxedPresentationStart: 3.8
- }
-};
-playerTimeToProgramTime(4, segment3);
-// startOfSegment = 3.8 + 0.2 = 4
-// offsetFromSegmentStart = 4 - 4 = 0
-// return 2018-11-10T00:00:34.1Z + 0 = 2018-11-10T00:00:34.1Z
-```
-
-## Transmux Before Append Changes
-
-Even though segment timing values are retained for transmux before append, the formula does not need to change, as all that matters for calculation is the offset from the transmuxed segment start, which can then be applied to the stream time start of segment, or the program time start of segment.
-
-## Getting the Right Segment
-
-In order to make use of the above calculation, the right segment must be chosen for a given player time. This time may be retrieved by simply using the times of the segment after transmuxing (as the start/end pts/dts values then reflect the player time it should slot into in the source buffer). These are included in `videoTimingInfo` as `transmuxedPresentationStart` and `transmuxedPresentationEnd`.
-
-Although there may be a small amount of overlap due to `transmuxerPrependedSeconds`, as long as the search is sequential from the beginning of the playlist to the end, the right segment will be found, as the prepended times will only come from content from prior segments.
diff --git a/node_modules/@videojs/http-streaming/docs/reload-source-on-error.md b/node_modules/@videojs/http-streaming/docs/reload-source-on-error.md
deleted file mode 100644
index 41de13d..0000000
--- a/node_modules/@videojs/http-streaming/docs/reload-source-on-error.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# Using the reloadSourceOnError Plugin
-Call the plugin to activate it:
-
-```js
-player.reloadSourceOnError()
-```
-Now if the player encounters a fatal error during playback, it will automatically
-attempt to reload the current source. If the error was caused by a transient
-browser or networking problem, this can allow playback to continue with a minimum
-of disruption to your viewers.
-
-The plugin will only restart your player once in a 30 second time span so that your
-player doesn't get into a reload loop if it encounters non-transient errors. You
-can tweak the amount of time required between restarts by adjusting the
-`errorInterval` option.
-
-If your video URLs are time-sensitive, the original source could be invalid by the
-time an error occurs. If that's the case, you can provide a `getSource` callback
-to regenerate a valid source object. In your callback, the `this` keyword is a
-reference to the player that errored. The first argument to `getSource` is a
-function. Invoke that function and pass in your new source object when you're ready.
-
-```js
-player.reloadSourceOnError({
-
- // getSource allows you to override the source object used when an error occurs
- getSource: function(reload) {
- console.log('Reloading because of an error');
-
- // call reload() with a fresh source object
- // you can do this step asynchronously if you want (but the error dialog will
- // show up while you're waiting)
- reload({
- src: 'https://example.com/index.m3u8?token=abc123ef789',
- type: 'application/x-mpegURL'
- });
- },
-
- // errorInterval specifies the minimum amount of seconds that must pass before
- // another reload will be attempted
- errorInterval: 5
-});
-```
diff --git a/node_modules/@videojs/http-streaming/docs/supported-features.md b/node_modules/@videojs/http-streaming/docs/supported-features.md
deleted file mode 100644
index 887c333..0000000
--- a/node_modules/@videojs/http-streaming/docs/supported-features.md
+++ /dev/null
@@ -1,289 +0,0 @@
-# Supported Features
-
-## Browsers
-
-Any browser that supports [MSE] (media source extensions). See
-https://caniuse.com/#feat=mediasource
-
-Note that browsers with native HLS support may play content with the native player, unless
-the [overrideNative] option is used. Some notable browsers with native HLS players are:
-
-* Safari (macOS and iOS)
-* Chrome Android
-* Firefox Android
-
-However, due to the limited features offered by some of the native players, the only
-browser on which VHS defaults to using the native player is Safari (macOS and iOS).
-
-## Streaming Formats and Media Types
-
-### Streaming Formats
-
-VHS aims to be mostly streaming format agnostic. So long as the manifest can be parsed to
-a common JSON representation, VHS should be able to play it. However, due to some large
-differences between the major streaming formats (HLS and DASH), some format specific code
-is included in VHS. If you have another format you would like supported, please reach out
-to us (e.g., file an issue).
-
-* [HLS] (HTTP Live Streaming)
-* [MPEG-DASH] (Dynamic Adaptive Streaming over HTTP)
-
-### Media Container Formats
-
-* [TS] (MPEG Transport Stream)
-* [MP4] (MPEG-4 Part 14: MP4, M4A, M4V, M4S, MPA), ISOBMFF
-* [AAC] (Advanced Audio Coding)
-
-### Codecs
-
-If the content is packaged in an [MP4] container, then any codec supported by the browser
-is supported. If the content is packaged in a [TS] container, then the codec must be
-supported by [the transmuxer]. The following codecs are supported by the transmuxer:
-
-* [AVC] (Advanced Video Coding, h.264)
-* [AVC1] (Advnced Video Coding, h.265)
-* [HE-AAC] (High Efficiency Advanced Audio Coding, mp4a.40.5)
-* LC-AAC (Low Complexity Advanced Audio Coding, mp4a.40.2)
-
-## General Notable Features
-
-The following is a list of some, but not all, common streaming features supported by VHS.
-It is meant to highlight some common use cases (and provide for easy searching), but is
-not meant serve as an exhaustive list.
-
-* VOD (video on demand)
-* LIVE
-* Multiple audio tracks
-* Timed [ID3] Metadata is automatically translated into HTML5 metedata text tracks
-* Cross-domain credentials support with [CORS]
-* Any browser supported resolution (e.g., 4k)
-* Any browser supported framerate (e.g., 60fps)
-* [DRM] via [videojs-contrib-eme]
-* Audio only (non DASH)
-* Video only (non DASH)
-* In-manifest [WebVTT] subtitles are automatically translated into standard HTML5 subtitle
- tracks
-* [AES-128] segment encryption
-
-## Notable Missing Features
-
-Note that the following features have not yet been implemented or may work but are not
-currently suppported in browsers that do not rely on the native player. For browsers that
-use the native player (e.g., Safari for HLS), please refer to their documentation.
-
-### Container Formats
-
-* [WebM]
-* [WAV]
-* [MP3]
-* [OGG]
-
-### Codecs
-
-If the content is packaged within an [MP4] container and the browser supports the codec, it
-will play. However, the following are some codecs that are not routinely tested, or are not
-supported when packaged within [TS].
-
-* [MP3]
-* [Vorbis]
-* [WAV]
-* [FLAC]
-* [Opus]
-* [VP8]
-* [VP9]
-* [Dolby Vision] (DVHE)
-* [Dolby Digital] Audio (AC-3)
-* [Dolby Digital Plus] (E-AC-3)
-
-### HLS Missing Features
-
-Note: features for low latency HLS in the [2nd edition of HTTP Live Streaming] are on the
-roadmap, but not currently available.
-
-VHS strives to support all of the features in the HLS specification, however, some have
-not yet been implemented. VHS currently supports everything in the
-[HLS specification v7, revision 23], except the following:
-
-* Use of [EXT-X-MAP] with [TS] segments
- * [EXT-X-MAP] is currently supported for [MP4] segments, but not yet for TS
-* I-Frame playlists via [EXT-X-I-FRAMES-ONLY] and [EXT-X-I-FRAME-STREAM-INF]
-* [MP3] Audio
-* [Dolby Digital] Audio (AC-3)
-* [Dolby Digital Plus] Audio (E-AC-3)
-* KEYFORMATVERSIONS of [EXT-X-KEY]
-* [EXT-X-DATERANGE]
-* [EXT-X-SESSION-DATA]
-* [EXT-X-SESSION-KEY]
-* [EXT-X-INDEPENDENT-SEGMENTS]
-* Use of [EXT-X-START] (value parsed but not used)
-* Alternate video via [EXT-X-MEDIA] of type video
-* ASSOC-LANGUAGE in [EXT-X-MEDIA]
-* CHANNELS in [EXT-X-MEDIA]
-* Use of AVERAGE-BANDWIDTH in [EXT-X-STREAM-INF] (value parsed but not used)
-* Use of FRAME-RATE in [EXT-X-STREAM-INF] (value parsed but not used)
-* Use of HDCP-LEVEL in [EXT-X-STREAM-INF]
-* SAMPLE-AES segment encryption
-
-In the event of encoding changes within a playlist (see
-https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.3.3), the
-behavior will depend on the browser.
-
-### DASH Missing Features
-
-DASH support is more recent than HLS support in VHS, however, VHS strives to achieve as
-complete compatibility as possible with the DASH spec. The following are some notable
-features in the DASH specification that are not yet implemented in VHS:
-
-Note that many of the following are parsed by [mpd-parser] but are either not yet used, or
-simply take on their default values (in the case where they have valid defaults).
-
-* Audio and video only streams
-* Audio rendition switching
- * Each video rendition is paired with an audio rendition for the duration of playback.
-* MPD
- * @id
- * @profiles
- * @availabilityStartTime
- * @availabilityEndTime
- * @minBufferTime
- * @maxSegmentDuration
- * @maxSubsegmentDuration
- * ProgramInformation
- * Metrics
-* Period
- * @xlink:href
- * @xlink:actuate
- * @id
- * @duration
- * Normally used for determing the PeriodStart of the next period, VHS instead relies
- on segment durations to determine timing of each segment and timeline
- * @bitstreamSwitching
- * Subset
-* AdaptationSet
- * @xlink:href
- * @xlink:actuate
- * @id
- * @group
- * @par (picture aspect ratio)
- * @minBandwidth
- * @maxBandwidth
- * @minWidth
- * @maxWidth
- * @minHeight
- * @maxHeight
- * @minFrameRate
- * @maxFrameRate
- * @segmentAlignment
- * @bitstreamSwitching
- * @subsegmentAlignment
- * @subsegmentStartsWithSAP
- * Accessibility
- * Rating
- * Viewpoint
- * ContentComponent
-* Representation
- * @id (used for SegmentTemplate but not exposed otherwise)
- * @qualityRanking
- * @dependencyId (dependent representation)
- * @mediaStreamStructureId
- * SubRepresentation
-* CommonAttributesElements (for AdaptationSet, Representation and SubRepresentation elements)
- * @profiles
- * @sar
- * @frameRate
- * @audioSamplingRate
- * @segmentProfiles
- * @maximumSAPPeriod
- * @startWithSAP
- * @maxPlayoutRate
- * @codingDependency
- * @scanType
- * FramePacking
- * AudioChannelConfiguration
-* SegmentBase
- * @presentationTimeOffset
- * @indexRangeExact
- * RepresentationIndex
-* MultipleSegmentBaseInformation elements
-* SegmentList
- * @xlink:href
- * @xlink:actuate
- * MultipleSegmentBaseInformation
- * SegmentURL
- * @index
- * @indexRange
-* SegmentTemplate
- * MultipleSegmentBaseInformation
- * @index
- * @bitstreamSwitching
-* BaseURL
- * @serviceLocation
-* Template-based Segment URL construction
- * Live DASH assets that use $Time$ in a SegmentTemplate, and also have a SegmentTimeline
- where only the first S has a t and the rest only have a d do not update on playlist
- refreshes
- See: https://github.com/videojs/http-streaming#dash-assets-with-time-interpolation-and-segmenttimelines-with-no-t
-* ContentComponent elements
- * Right now manifests are assumed to have a single content component, with the properties
- described directly on the AdaptationSet element
-* SubRepresentation elements
-* Subset elements
-* Early Available Periods (may work, but has not been tested)
-* Access to subsegments via a subsegment index ('ssix')
-* The @profiles attribute is ignored (best support for all profiles is attempted, without
- consideration of the specific profile). For descriptions on profiles, see section 8 of
- the DASH spec.
-* Construction of byte range URLs via a BaseURL byteRange template (Annex E.2)
-* Multiperiod content where the representation sets are not the same across periods
-* In the event that an S element has a t attribute that is greater than what is expected,
- it is not treated as a discontinuity, but instead retains its segment value, and may
- result in a gap in the content
-
-[MSE]: https://www.w3.org/TR/media-source/
-[HLS]: https://en.wikipedia.org/wiki/HTTP_Live_Streaming
-[MPEG-DASH]: https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
-[TS]: https://en.wikipedia.org/wiki/MPEG_transport_stream
-[MP4]: https://en.wikipedia.org/wiki/MPEG-4_Part_14
-[AAC]: https://en.wikipedia.org/wiki/Advanced_Audio_Coding
-[AVC]: https://en.wikipedia.org/wiki/Advanced_Video_Coding
-[AVC1]: https://en.wikipedia.org/wiki/Advanced_Video_Coding
-[HE-AAC]: https://en.wikipedia.org/wiki/High-Efficiency_Advanced_Audio_Coding
-[ID3]: https://en.wikipedia.org/wiki/ID3
-[CORS]: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
-[DRM]: https://en.wikipedia.org/wiki/Digital_rights_management
-[WebVTT]: https://www.w3.org/TR/webvtt1/
-[AES-128]: https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
-[WebM]: https://en.wikipedia.org/wiki/WebM
-[WAV]: https://en.wikipedia.org/wiki/WAV
-[MP3]: https://en.wikipedia.org/wiki/MP3
-[OGG]: https://en.wikipedia.org/wiki/Ogg
-[Vorbis]: https://en.wikipedia.org/wiki/Vorbis
-[FLAC]: https://en.wikipedia.org/wiki/FLAC
-[Opus]: https://en.wikipedia.org/wiki/Opus_(audio_format)
-[VP8]: https://en.wikipedia.org/wiki/VP8
-[VP9]: https://en.wikipedia.org/wiki/VP9
-
-[overrideNative]: https://github.com/videojs/http-streaming#overridenative
-[the transmuxer]: https://github.com/videojs/mux.js
-[videojs-contrib-eme]: https://github.com/videojs/videojs-contrib-eme
-
-[2nd edition of HTTP Live Streaming]: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-07.html
-[HLS specification v7, revision 23]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23
-
-[EXT-X-MAP]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
-[EXT-X-STREAM-INF]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.4.2
-[EXT-X-SESSION-DATA]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.4.4
-[EXT-X-DATERANGE]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.7
-[EXT-X-KEY]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.7
-[EXT-X-I-FRAMES-ONLY]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.6
-[EXT-X-I-FRAME-STREAM-INF]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.4.3
-[EXT-X-SESSION-KEY]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.4.5
-[EXT-X-INDEPENDENT-SEGMENTS]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.5.1
-[EXT-X-START]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.5.2
-[EXT-X-MEDIA]: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.4.1
-
-[Dolby Vision]: https://en.wikipedia.org/wiki/High-dynamic-range_video#Dolby_Vision
-[Dolby Digital]: https://en.wikipedia.org/wiki/Dolby_Digital
-[Dolby Digital Plus]: https://en.wikipedia.org/wiki/Dolby_Digital_Plus
-
-[mpd-parser]: https://github.com/videojs/mpd-parser
diff --git a/node_modules/@videojs/http-streaming/docs/troubleshooting.md b/node_modules/@videojs/http-streaming/docs/troubleshooting.md
deleted file mode 100644
index 2dea554..0000000
--- a/node_modules/@videojs/http-streaming/docs/troubleshooting.md
+++ /dev/null
@@ -1,67 +0,0 @@
-# Troubleshooting Guide
-
-## Other troubleshooting guides
-
-For issues around data embedded into media segments (e.g., 608 captions), see the [mux.js troubleshooting guide](https://github.com/videojs/mux.js/blob/master/docs/troubleshooting.md).
-
-## Tools
-
-### Thumbcoil
-
-Thumbcoil is a video inspector tool that can unpackage various media containers and inspect the bitstreams therein. Thumbcoil runs entirely within your browser so that none of your video data is ever transmitted to a server.
-
-http://thumb.co.il
-http://beta.thumb.co.il
-https://github.com/videojs/thumbcoil
-
-## Table of Contents
-- [Content plays on Mac but not on Windows](#content-plays-on-mac-but-not-windows)
-- ["No compatible source was found" on IE11 Win 7](#no-compatible-source-was-found-on-ie11-win-7)
-- [CORS: No Access-Control-Allow-Origin header](#cors-no-access-control-allow-origin-header)
-- [Desktop Safari/iOS Safari/Android Chrome/Edge exhibit different behavior from other browsers](#desktop-safariios-safariandroid-chromeedge-exhibit-different-behavior-from-other-browsers)
-- [MEDIA_ERR_DECODE error on Desktop Safari](#media_err_decode-error-on-desktop-safari)
-- [Network requests are still being made while paused](#network-requests-are-still-being-made-while-paused)
-
-## Content plays on Mac but not Windows
-
-Some browsers may not be able to play audio sample rates higher than 48 kHz. See https://docs.microsoft.com/en-gb/windows/desktop/medfound/aac-decoder#format-constraints
-
-Potential solution: re-encode with a Windows supported audio sample rate
-
-## "No compatible source was found" on IE11 Win 7
-
-videojs-http-streaming does not support Flash HLS playback (like the videojs-contrib-hls plugin does)
-
-Solution: include the FlasHLS source handler https://github.com/brightcove/videojs-flashls-source-handler#usage
-
-## CORS: No Access-Control-Allow-Origin header
-
-If you see an error along the lines of
-
-```
-XMLHttpRequest cannot load ... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ... is therefore not allowed access.
-```
-
-you need to properly configure CORS on your server: https://github.com/videojs/http-streaming#hosting-considerations
-
-## Desktop Safari/iOS Safari/Android Chrome/Edge exhibit different behavior from other browsers
-
-Some browsers support native playback of certain streaming formats. By default, we defer to the native players. However, this means that features specific to videojs-http-streaming will not be available.
-
-On Edge and mobile Chrome, 608 captions, ID3 tags or live streaming may not work as expected with native playback, it is recommended that `overrideNative` be used on those platforms if necessary.
-
-Solution: use videojs-http-streaming based playback on those devices: https://github.com/videojs/http-streaming#overridenative
-
-## MEDIA_ERR_DECODE error on Desktop Safari
-
-This error may occur for a number of reasons, as it is particularly common for misconfigured content. One instance of misconfiguration is if the source manifest has `CLOSED-CAPTIONS=NONE` and an external text track is loaded into the player. Safari does not allow the inclusion any captions if the manifest indicates that captions will not be provided.
-
-Solution: remove `CLOSED-CAPTIONS=NONE` from the manifest
-
-## Network requests are still being made while paused
-
-There are a couple of cases where network requests will still be made by VHS when the video is paused.
-
-1) If the forward buffer (buffered content ahead of the playhead) has not reached the GOAL\_BUFFER\_LENGTH. For instance, if the playhead is at time 10 seconds, the buffered range goes from 5 seconds to 20 seconds, and the GOAL\_BUFFER\_LENGTH is set to 30 seconds, then segments will continue to be requested, even while paused, until the buffer ends at a time greater than or equal to 10 seconds (current time) + 30 seconds (GOAL\_BUFFER\_LENGTH) = 40 seconds. This is expected behavior in order to provide a better playback experience.
-
-2) If the stream is LIVE, then the manifest will continue to be refreshed even while paused. This is because it is easier to keep playback in sync if we receieve manifest updates consistently.
diff --git a/node_modules/@videojs/http-streaming/index.html b/node_modules/@videojs/http-streaming/index.html
deleted file mode 100644
index 41897a0..0000000
--- a/node_modules/@videojs/http-streaming/index.html
+++ /dev/null
@@ -1,139 +0,0 @@
-
-
-
-
- videojs-http-streaming Demo
-
-
-
-
-
-
-
-
-
- Representations
-
- Options
-
-
-
-
- Minified VHS (reloads player)
-
-
-
- Synchronous Web Workers (reloads player)
-
-
-
- Enable the live UI (reloads player)
-
-
-
- Debug Logging
-
-
-
- Muted
-
-
-
- Autoplay
-
-
-
- [EXPERIMENTAL] Enables support for ll-hls (reloads player)
-
-
-
- [EXPERIMENTAL] Use Buffer Level for ABR (reloads player)
-
-
-
- Override Native (reloads player)
-
-
-
- Mirror sources from player.src (reloads player, uses EXPERIMENTAL sourceset option)
-
-
- Preload (reloads player)
-
- auto
- none
- metadata
-
-
-
- Load a URL
- Url:
-
- Type: (uses url extension if blank, usually application/x-mpegURL or application/dash+xml)
-
- Optional Keystems JSON:
-
- Load
- Load a Source
-
-
-
-
-
-
-
-
-
-
-
-
- Navigation
-
-
-
-
-
-
diff --git a/node_modules/@videojs/http-streaming/package.json b/node_modules/@videojs/http-streaming/package.json
deleted file mode 100644
index fe25170..0000000
--- a/node_modules/@videojs/http-streaming/package.json
+++ /dev/null
@@ -1,148 +0,0 @@
-{
- "_from": "@videojs/http-streaming@2.9.1",
- "_id": "@videojs/http-streaming@2.9.1",
- "_inBundle": false,
- "_integrity": "sha512-QAtlrBBILOflrei1KE0GcSDDWiP888ZOySck6zWlQNYi/pXOm6QXTJHzOMIKiRQOndyJIZRTfLHedeUdUIDNLA==",
- "_location": "/@videojs/http-streaming",
- "_phantomChildren": {},
- "_requested": {
- "type": "version",
- "registry": true,
- "raw": "@videojs/http-streaming@2.9.1",
- "name": "@videojs/http-streaming",
- "escapedName": "@videojs%2fhttp-streaming",
- "scope": "@videojs",
- "rawSpec": "2.9.1",
- "saveSpec": null,
- "fetchSpec": "2.9.1"
- },
- "_requiredBy": [
- "/video.js"
- ],
- "_resolved": "https://registry.npmjs.org/@videojs/http-streaming/-/http-streaming-2.9.1.tgz",
- "_shasum": "16b59efe24a832b89b5bd6a6c52f0d80ad7996a2",
- "_spec": "@videojs/http-streaming@2.9.1",
- "_where": "F:\\Documents\\websites\\BMM\\node_modules\\video.js",
- "author": {
- "name": "Brightcove, Inc"
- },
- "browserslist": [
- "defaults",
- "ie 11"
- ],
- "bugs": {
- "url": "https://github.com/videojs/http-streaming/issues"
- },
- "bundleDependencies": false,
- "dependencies": {
- "@babel/runtime": "^7.12.5",
- "@videojs/vhs-utils": "^3.0.2",
- "aes-decrypter": "3.1.2",
- "global": "^4.4.0",
- "m3u8-parser": "4.7.0",
- "mpd-parser": "0.17.0",
- "mux.js": "5.11.1",
- "video.js": "^6 || ^7"
- },
- "deprecated": false,
- "description": "Play back HLS and DASH with Video.js, even where it's not natively supported",
- "devDependencies": {
- "@rollup/plugin-replace": "^2.3.4",
- "@rollup/plugin-strip": "^2.0.1",
- "@videojs/generator-helpers": "~2.0.1",
- "d3": "^3.4.8",
- "es5-shim": "^4.5.13",
- "es6-shim": "^0.35.5",
- "jsdoc": "~3.6.6",
- "karma": "^5.2.3",
- "lodash": "^4.17.4",
- "lodash-compat": "^3.10.0",
- "nomnoml": "^0.3.0",
- "rollup": "^2.36.1",
- "rollup-plugin-worker-factory": "0.5.5",
- "shelljs": "^0.8.4",
- "sinon": "^8.1.1",
- "url-toolkit": "^2.2.1",
- "videojs-contrib-eme": "^3.8.1",
- "videojs-contrib-quality-levels": "^2.0.4",
- "videojs-generate-karma-config": "^7.1.0",
- "videojs-generate-rollup-config": "~6.1.0",
- "videojs-generator-verify": "~3.0.1",
- "videojs-http-source-selector": "^1.1.6",
- "videojs-standard": "^8.0.4"
- },
- "engines": {
- "node": ">=8",
- "npm": ">=5"
- },
- "files": [
- "CONTRIBUTING.md",
- "dist/",
- "docs/",
- "index.html",
- "scripts/",
- "src/"
- ],
- "generator-videojs-plugin": {
- "version": "7.6.3"
- },
- "homepage": "https://github.com/videojs/http-streaming#readme",
- "husky": {
- "hooks": {
- "pre-commit": "lint-staged"
- }
- },
- "keywords": [
- "videojs",
- "videojs-plugin"
- ],
- "license": "Apache-2.0",
- "lint-staged": {
- "*.js": "vjsstandard --fix",
- "README.md": "doctoc --notitle"
- },
- "main": "dist/videojs-http-streaming.cjs.js",
- "module": "dist/videojs-http-streaming.es.js",
- "name": "@videojs/http-streaming",
- "peerDependencies": {
- "video.js": "^6 || ^7"
- },
- "repository": {
- "type": "git",
- "url": "git+ssh://git@github.com/videojs/http-streaming.git"
- },
- "scripts": {
- "build": "npm-run-all -s clean -p build:*",
- "build-prod": "cross-env-shell NO_TEST_BUNDLE=1 'npm run build'",
- "build-test": "cross-env-shell TEST_BUNDLE_ONLY=1 'npm run build'",
- "build:js": "rollup -c scripts/rollup.config.js",
- "clean": "shx rm -rf ./dist ./test/dist && shx mkdir -p ./dist ./test/dist",
- "docs": "npm-run-all docs:*",
- "docs:api": "jsdoc src -g plugins/markdown -r -d docs/api",
- "docs:images": "node ./scripts/create-docs-images.js",
- "docs:toc": "doctoc --notitle README.md",
- "lint": "vjsstandard",
- "netlify": "node scripts/netlify.js",
- "posttest": "[ \"$CI_TEST_TYPE\" != 'coverage' ] || shx cat test/dist/coverage/text.txt",
- "prenetlify": "npm run build",
- "prepublishOnly": "npm-run-all build-prod && vjsverify --verbose",
- "server": "karma start scripts/karma.conf.js --singleRun=false --auto-watch",
- "start": "npm-run-all -p server watch",
- "test": "npm-run-all lint build-test && karma start scripts/karma.conf.js",
- "update-changelog": "conventional-changelog -p videojs -i CHANGELOG.md -s",
- "version": "is-prerelease || npm run update-changelog && git add CHANGELOG.md",
- "watch": "npm-run-all -p watch:*",
- "watch:js": "npm run build:js -- -w"
- },
- "version": "2.9.1",
- "vjsstandard": {
- "ignore": [
- "dist",
- "docs",
- "deploy",
- "test/dist",
- "utils",
- "src/*.worker.js"
- ]
- }
-}
diff --git a/node_modules/@videojs/http-streaming/scripts/create-docs-images.js b/node_modules/@videojs/http-streaming/scripts/create-docs-images.js
deleted file mode 100644
index bda7f4d..0000000
--- a/node_modules/@videojs/http-streaming/scripts/create-docs-images.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* eslint-disable no-console */
-const nomnoml = require('nomnoml');
-const fs = require('fs');
-const path = require('path');
-
-const basePath = path.resolve(__dirname, '..');
-const docImageDir = path.join(basePath, 'docs/images');
-const nomnomlSourceDir = path.join(basePath, 'docs/images/sources');
-
-const buildImages = {
- build() {
- const files = fs.readdirSync(nomnomlSourceDir);
-
- while (files.length > 0) {
- const file = path.resolve(nomnomlSourceDir, files.shift());
- const basename = path.basename(file, 'txt');
-
- if (/.nomnoml/.test(basename)) {
- const fileContents = fs.readFileSync(file, 'utf-8');
- const generated = nomnoml.renderSvg(fileContents);
- const newFilePath = path.join(docImageDir, basename) + 'svg';
- const outFile = fs.createWriteStream(newFilePath);
-
- console.log(`wrote file ${newFilePath}`);
- outFile.write(generated);
- }
- }
- }
-};
-
-buildImages.build();
diff --git a/node_modules/@videojs/http-streaming/scripts/create-test-data.js b/node_modules/@videojs/http-streaming/scripts/create-test-data.js
deleted file mode 100644
index 64e960d..0000000
--- a/node_modules/@videojs/http-streaming/scripts/create-test-data.js
+++ /dev/null
@@ -1,115 +0,0 @@
-/* global window */
-const fs = require('fs');
-const path = require('path');
-const baseDir = path.join(__dirname, '..');
-const manifestsDir = path.join(baseDir, 'test', 'manifests');
-const segmentsDir = path.join(baseDir, 'test', 'segments');
-
-const base64ToUint8Array = function(base64) {
- const decoded = window.atob(base64);
- const uint8Array = new Uint8Array(new ArrayBuffer(decoded.length));
-
- for (let i = 0; i < decoded.length; i++) {
- uint8Array[i] = decoded.charCodeAt(i);
- }
-
- return uint8Array;
-};
-
-const getManifests = () => (fs.readdirSync(manifestsDir) || [])
- .filter((f) => ((/\.(m3u8|mpd)/).test(path.extname(f))))
- .map((f) => path.resolve(manifestsDir, f));
-
-const getSegments = () => (fs.readdirSync(segmentsDir) || [])
- .filter((f) => ((/\.(ts|mp4|key|webm|aac|ac3)/).test(path.extname(f))))
- .map((f) => path.resolve(segmentsDir, f));
-
-const buildManifestString = function() {
- let manifests = 'export default {\n';
-
- getManifests().forEach((file) => {
- // translate this manifest
- manifests += ' \'' + path.basename(file, path.extname(file)) + '\': ';
- manifests += fs.readFileSync(file, 'utf8')
- .split(/\r\n|\n/)
- // quote and concatenate
- .map((line) => ' \'' + line + '\\n\' +\n')
- .join('')
- // strip leading spaces and the trailing '+'
- .slice(4, -3);
- manifests += ',\n';
- });
-
- // clean up and close the objects
- manifests = manifests.slice(0, -2);
- manifests += '\n};\n';
-
- return manifests;
-};
-
-const buildSegmentString = function() {
- const segmentData = {};
-
- getSegments().forEach((file) => {
- // read the file directly as a buffer before converting to base64
- const base64Segment = fs.readFileSync(file).toString('base64');
-
- segmentData[path.basename(file, path.extname(file))] = base64Segment;
- });
-
- const segmentDataExportStrings = Object.keys(segmentData).reduce((acc, key) => {
- // use a function since the segment may be cleared out on usage
- acc.push(`export const ${key} = () => {
- cache.${key} = cache.${key} || base64ToUint8Array('${segmentData[key]}');
- const dest = new Uint8Array(cache.${key}.byteLength);
- dest.set(cache.${key});
- return dest;
- };`);
-
- return acc;
- }, []);
-
- const segmentsFile =
- 'const cache = {};\n' +
- `const base64ToUint8Array = ${base64ToUint8Array.toString()};\n` +
- segmentDataExportStrings.join('\n');
-
- return segmentsFile;
-};
-
-/* we refer to them as .js, so that babel and other plugins can work on them */
-const segmentsKey = 'create-test-data!segments.js';
-const manifestsKey = 'create-test-data!manifests.js';
-
-module.exports = function() {
- return {
- name: 'createTestData',
- buildStart() {
- this.addWatchFile(segmentsDir);
- this.addWatchFile(manifestsDir);
-
- [].concat(getSegments())
- .concat(getManifests())
- .forEach((file) => this.addWatchFile(file));
- },
- resolveId(importee, importer) {
- // if this is not an id we can resolve return
- if (importee.indexOf('create-test-data!') !== 0) {
- return;
- }
-
- const name = importee.split('!')[1];
-
- return (name.indexOf('segments') === 0) ? segmentsKey : manifestsKey;
- },
- load(id) {
- if (id === segmentsKey) {
- return buildSegmentString.call(this);
- }
-
- if (id === manifestsKey) {
- return buildManifestString.call(this);
- }
- }
- };
-};
diff --git a/node_modules/@videojs/http-streaming/scripts/index-demo-page.js b/node_modules/@videojs/http-streaming/scripts/index-demo-page.js
deleted file mode 100644
index 53a0c92..0000000
--- a/node_modules/@videojs/http-streaming/scripts/index-demo-page.js
+++ /dev/null
@@ -1,518 +0,0 @@
-/* global window document */
-/* eslint-disable vars-on-top, no-var, object-shorthand, no-console */
-(function(window) {
- var representationsEl = document.getElementById('representations');
-
- representationsEl.addEventListener('change', function() {
- var selectedIndex = representationsEl.selectedIndex;
-
- if (!selectedIndex || selectedIndex < 1 || !window.vhs) {
- return;
- }
- var selectedOption = representationsEl.options[representationsEl.selectedIndex];
-
- if (!selectedOption) {
- return;
- }
-
- var id = selectedOption.value;
-
- window.vhs.representations().forEach(function(rep) {
- rep.playlist.disabled = rep.id !== id;
- });
-
- window.mpc.fastQualityChange_();
- });
- var hlsOptGroup = document.querySelector('[label="hls"]');
- var dashOptGroup = document.querySelector('[label="dash"]');
- var drmOptGroup = document.querySelector('[label="drm"]');
- var liveOptGroup = document.querySelector('[label="live"]');
- var llliveOptGroup = document.querySelector('[label="low latency live"]');
-
- // get the sources list squared away
- var xhr = new window.XMLHttpRequest();
-
- xhr.addEventListener('load', function() {
- var sources = JSON.parse(xhr.responseText);
-
- sources.forEach(function(source) {
- var option = document.createElement('option');
-
- option.innerText = source.name;
- option.value = source.uri;
-
- if (source.keySystems) {
- option.setAttribute('data-key-systems', JSON.stringify(source.keySystems, null, 2));
- }
-
- if (source.mimetype) {
- option.setAttribute('data-mimetype', source.mimetype);
- }
-
- if (source.features.indexOf('low-latency') !== -1) {
- llliveOptGroup.appendChild(option);
- } else if (source.features.indexOf('live') !== -1) {
- liveOptGroup.appendChild(option);
- } else if (source.keySystems) {
- drmOptGroup.appendChild(option);
- } else if (source.mimetype === 'application/x-mpegurl') {
- hlsOptGroup.appendChild(option);
- } else if (source.mimetype === 'application/dash+xml') {
- dashOptGroup.appendChild(option);
- }
- });
- });
- xhr.open('GET', './scripts/sources.json');
- xhr.send();
-
- // all relevant elements
- var urlButton = document.getElementById('load-url');
- var sources = document.getElementById('load-source');
- var stateEls = {};
-
- var getInputValue = function(el) {
- if (el.type === 'url' || el.type === 'text' || el.nodeName.toLowerCase() === 'textarea') {
- return encodeURIComponent(el.value);
- } else if (el.type === 'select-one') {
- return el.options[el.selectedIndex].value;
- } else if (el.type === 'checkbox') {
- return el.checked;
- }
-
- console.warn('unhandled input type ' + el.type);
- return '';
- };
-
- var setInputValue = function(el, value) {
- if (el.type === 'url' || el.type === 'text' || el.nodeName.toLowerCase() === 'textarea') {
- el.value = decodeURIComponent(value);
- } else if (el.type === 'select-one') {
- for (var i = 0; i < el.options.length; i++) {
- if (el.options[i].value === value) {
- el.options[i].selected = true;
- }
- }
- } else {
- // get the `value` into a Boolean.
- el.checked = JSON.parse(value);
- }
-
- };
-
- var newEvent = function(name) {
- var event;
-
- if (typeof window.Event === 'function') {
- event = new window.Event(name);
- } else {
- event = document.createEvent('Event');
- event.initEvent(name, true, true);
- }
-
- return event;
- };
-
- // taken from video.js
- var getFileExtension = function(path) {
- var splitPathRe;
- var pathParts;
-
- if (typeof path === 'string') {
- splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]*?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i;
- pathParts = splitPathRe.exec(path);
-
- if (pathParts) {
- return pathParts.pop().toLowerCase();
- }
- }
-
- return '';
- };
-
- var saveState = function() {
- var query = '';
-
- if (!window.history.replaceState) {
- return;
- }
-
- Object.keys(stateEls).forEach(function(elName) {
- var symbol = query.length ? '&' : '?';
-
- query += symbol + elName + '=' + getInputValue(stateEls[elName]);
- });
-
- window.history.replaceState({}, 'vhs demo', query);
- };
-
- window.URLSearchParams = window.URLSearchParams || function(locationSearch) {
- this.get = function(name) {
- var results = new RegExp('[\?&]' + name + '=([^]*)').exec(locationSearch);
-
- return results ? decodeURIComponent(results[1]) : null;
- };
- };
-
- // eslint-disable-next-line
- var loadState = function() {
- var params = new window.URLSearchParams(window.location.search);
-
- return Object.keys(stateEls).reduce(function(acc, elName) {
- acc[elName] = typeof params.get(elName) !== 'object' ? params.get(elName) : getInputValue(stateEls[elName]);
- return acc;
- }, {});
- };
-
- // eslint-disable-next-line
- var reloadScripts = function(urls, cb) {
- var el = document.getElementById('reload-scripts');
-
- if (!el) {
- el = document.createElement('div');
- el.id = 'reload-scripts';
- document.body.appendChild(el);
- }
-
- while (el.firstChild) {
- el.removeChild(el.firstChild);
- }
-
- var loaded = [];
-
- var checkDone = function() {
- if (loaded.length === urls.length) {
- cb();
- }
- };
-
- urls.forEach(function(url) {
- var script = document.createElement('script');
-
- // scripts marked as defer will be loaded asynchronously but will be executed in the order they are in the DOM
- script.defer = true;
- // dynamically created scripts are async by default unless otherwise specified
- // async scripts are loaded asynchronously but also executed as soon as they are loaded
- // we want to load them in the order they are added therefore we want to turn off async
- script.async = false;
- script.src = url;
- script.onload = function() {
- loaded.push(url);
- checkDone();
- };
- el.appendChild(script);
- });
- };
-
- var regenerateRepresentations = function() {
- while (representationsEl.firstChild) {
- representationsEl.removeChild(representationsEl.firstChild);
- }
-
- var selectedIndex;
-
- window.vhs.representations().forEach(function(rep, i) {
- var option = document.createElement('option');
-
- option.value = rep.id;
- option.innerText = JSON.stringify({
- id: rep.id,
- videoCodec: rep.codecs.video,
- audioCodec: rep.codecs.audio,
- bandwidth: rep.bandwidth,
- heigth: rep.heigth,
- width: rep.width
- });
-
- if (window.mpc.media().id === rep.id) {
- selectedIndex = i;
- }
-
- representationsEl.appendChild(option);
- });
-
- representationsEl.selectedIndex = selectedIndex;
- };
-
- [
- 'debug',
- 'autoplay',
- 'muted',
- 'minified',
- 'sync-workers',
- 'liveui',
- 'llhls',
- 'url',
- 'type',
- 'keysystems',
- 'buffer-water',
- 'override-native',
- 'preload',
- 'mirror-source'
- ].forEach(function(name) {
- stateEls[name] = document.getElementById(name);
- });
-
- window.startDemo = function(cb) {
- var state = loadState();
-
- Object.keys(state).forEach(function(elName) {
- setInputValue(stateEls[elName], state[elName]);
- });
-
- Array.prototype.forEach.call(sources.options, function(s, i) {
- if (s.value === state.url) {
- sources.selectedIndex = i;
- }
- });
-
- stateEls.muted.addEventListener('change', function(event) {
- saveState();
- window.player.muted(event.target.checked);
- });
-
- stateEls.autoplay.addEventListener('change', function(event) {
- saveState();
- window.player.autoplay(event.target.checked);
- });
-
- stateEls['mirror-source'].addEventListener('change', function(event) {
- saveState();
-
- // reload the player and scripts
- stateEls.minified.dispatchEvent(newEvent('change'));
- });
-
- stateEls['sync-workers'].addEventListener('change', function(event) {
- saveState();
-
- // reload the player and scripts
- stateEls.minified.dispatchEvent(newEvent('change'));
- });
-
- stateEls.preload.addEventListener('change', function(event) {
- saveState();
- // reload the player and scripts
- stateEls.minified.dispatchEvent(newEvent('change'));
- });
-
- stateEls.debug.addEventListener('change', function(event) {
- saveState();
- window.videojs.log.level(event.target.checked ? 'debug' : 'info');
- });
-
- stateEls.llhls.addEventListener('change', function(event) {
- saveState();
-
- // reload the player and scripts
- stateEls.minified.dispatchEvent(newEvent('change'));
- });
-
- stateEls['buffer-water'].addEventListener('change', function(event) {
- saveState();
-
- // reload the player and scripts
- stateEls.minified.dispatchEvent(newEvent('change'));
- });
-
- stateEls['override-native'].addEventListener('change', function(event) {
- saveState();
-
- // reload the player and scripts
- stateEls.minified.dispatchEvent(newEvent('change'));
- });
-
- stateEls.liveui.addEventListener('change', function(event) {
- saveState();
-
- stateEls.minified.dispatchEvent(newEvent('change'));
- });
-
- stateEls.minified.addEventListener('change', function(event) {
- var urls = [
- 'node_modules/video.js/dist/alt/video.core',
- 'node_modules/videojs-contrib-eme/dist/videojs-contrib-eme',
- 'node_modules/videojs-contrib-quality-levels/dist/videojs-contrib-quality-levels',
- 'node_modules/videojs-http-source-selector/dist/videojs-http-source-selector'
- ].map(function(url) {
- return url + (event.target.checked ? '.min' : '') + '.js';
- });
-
- if (stateEls['sync-workers'].checked) {
- urls.push('dist/videojs-http-streaming-sync-workers.js');
- } else {
- urls.push('dist/videojs-http-streaming' + (event.target.checked ? '.min' : '') + '.js');
- }
-
- saveState();
-
- if (window.player) {
- window.player.dispose();
- delete window.player;
- }
- if (window.videojs) {
- delete window.videojs;
- }
-
- reloadScripts(urls, function() {
- var player;
- var fixture = document.getElementById('player-fixture');
- var videoEl = document.createElement('video-js');
-
- videoEl.setAttribute('controls', '');
- videoEl.setAttribute('preload', stateEls.preload.options[stateEls.preload.selectedIndex].value || 'auto');
- videoEl.className = 'vjs-default-skin';
- fixture.appendChild(videoEl);
-
- var mirrorSource = getInputValue(stateEls['mirror-source']);
-
- player = window.player = window.videojs(videoEl, {
- plugins: {
- httpSourceSelector: {
- default: 'auto'
- }
- },
- liveui: stateEls.liveui.checked,
- enableSourceset: mirrorSource,
- html5: {
- vhs: {
- overrideNative: getInputValue(stateEls['override-native']),
- experimentalBufferBasedABR: getInputValue(stateEls['buffer-water']),
- experimentalLLHLS: getInputValue(stateEls.llhls)
- }
- }
- });
-
- player.on('sourceset', function() {
- var source = player.currentSource();
-
- if (source.keySystems) {
- var copy = JSON.parse(JSON.stringify(source.keySystems));
-
- // have to delete pssh as it will often make keySystems too big
- // for a uri
- Object.keys(copy).forEach(function(key) {
- if (copy[key].hasOwnProperty('pssh')) {
- delete copy[key].pssh;
- }
- });
-
- stateEls.keysystems.value = JSON.stringify(copy, null, 2);
- }
-
- if (source.src) {
- stateEls.url.value = encodeURI(source.src);
- }
-
- if (source.type) {
- stateEls.type.value = source.type;
- }
-
- saveState();
- });
-
- player.width(640);
- player.height(264);
-
- // configure videojs-contrib-eme
- player.eme();
-
- stateEls.debug.dispatchEvent(newEvent('change'));
- stateEls.muted.dispatchEvent(newEvent('change'));
- stateEls.autoplay.dispatchEvent(newEvent('change'));
-
- // run the load url handler for the intial source
- if (stateEls.url.value) {
- urlButton.dispatchEvent(newEvent('click'));
- } else {
- sources.dispatchEvent(newEvent('change'));
- }
- player.on('loadedmetadata', function() {
- if (player.tech_.vhs) {
- window.vhs = player.tech_.vhs;
- window.mpc = player.tech_.vhs.masterPlaylistController_;
- window.mpc.masterPlaylistLoader_.on('mediachange', regenerateRepresentations);
- regenerateRepresentations();
-
- } else {
- window.vhs = null;
- window.mpc = null;
- }
- });
- cb(player);
- });
- });
-
- var urlButtonClick = function(event) {
- var ext;
- var type = stateEls.type.value;
-
- if (!type.trim()) {
- ext = getFileExtension(stateEls.url.value);
-
- if (ext === 'mpd') {
- type = 'application/dash+xml';
- } else if (ext === 'm3u8') {
- type = 'application/x-mpegURL';
- }
- }
-
- saveState();
-
- var source = {
- src: stateEls.url.value,
- type: type
- };
-
- if (stateEls.keysystems.value) {
- source.keySystems = JSON.parse(stateEls.keysystems.value);
- }
-
- sources.selectedIndex = -1;
-
- Array.prototype.forEach.call(sources.options, function(s, i) {
- if (s.value === stateEls.url.value) {
- sources.selectedIndex = i;
- }
- });
-
- window.player.src(source);
- };
-
- urlButton.addEventListener('click', urlButtonClick);
- urlButton.addEventListener('tap', urlButtonClick);
-
- sources.addEventListener('change', function(event) {
- var selectedOption = sources.options[sources.selectedIndex];
-
- if (!selectedOption) {
- return;
- }
- var src = selectedOption.value;
-
- stateEls.url.value = src;
- stateEls.type.value = selectedOption.getAttribute('data-mimetype');
- stateEls.keysystems.value = selectedOption.getAttribute('data-key-systems');
-
- urlButton.dispatchEvent(newEvent('click'));
- });
-
- stateEls.url.addEventListener('keyup', function(event) {
- if (event.key === 'Enter') {
- urlButton.click();
- }
- });
- stateEls.url.addEventListener('input', function(event) {
- if (stateEls.type.value.length) {
- stateEls.type.value = '';
- }
- });
- stateEls.type.addEventListener('keyup', function(event) {
- if (event.key === 'Enter') {
- urlButton.click();
- }
- });
-
- // run the change handler for the first time
- stateEls.minified.dispatchEvent(newEvent('change'));
- };
-}(window));
diff --git a/node_modules/@videojs/http-streaming/scripts/karma.conf.js b/node_modules/@videojs/http-streaming/scripts/karma.conf.js
deleted file mode 100644
index 5c7d212..0000000
--- a/node_modules/@videojs/http-streaming/scripts/karma.conf.js
+++ /dev/null
@@ -1,47 +0,0 @@
-const generate = require('videojs-generate-karma-config');
-const CI_TEST_TYPE = process.env.CI_TEST_TYPE || '';
-
-module.exports = function(config) {
-
- // see https://github.com/videojs/videojs-generate-karma-config
- // for options
- const options = {
- coverage: CI_TEST_TYPE === 'coverage' ? true : false,
- preferHeadless: false,
- browsers(aboutToRun) {
- return aboutToRun.filter(function(launcherName) {
- return !(/^(Safari|Chromium)/).test(launcherName);
- });
- },
- files(defaults) {
- defaults.unshift('node_modules/es5-shim/es5-shim.js');
- defaults.unshift('node_modules/es6-shim/es6-shim.js');
-
- defaults.splice(
- defaults.indexOf('node_modules/video.js/dist/video.js'),
- 1,
- 'node_modules/video.js/dist/alt/video.core.js'
- );
-
- return defaults;
- },
- browserstackLaunchers(defaults) {
- delete defaults.bsSafariMojave;
- delete defaults.bsSafariElCapitan;
-
- // do not run on browserstack for coverage
- if (CI_TEST_TYPE === 'coverage') {
- defaults = {};
- }
-
- return defaults;
- },
- serverBrowsers() {
- return [];
- }
- };
-
- config = generate(config, options);
-
- // any other custom stuff not supported by options here!
-};
diff --git a/node_modules/@videojs/http-streaming/scripts/netlify.js b/node_modules/@videojs/http-streaming/scripts/netlify.js
deleted file mode 100644
index 493f54f..0000000
--- a/node_modules/@videojs/http-streaming/scripts/netlify.js
+++ /dev/null
@@ -1,35 +0,0 @@
-const path = require('path');
-const sh = require('shelljs');
-
-const deployDir = 'deploy';
-const files = [
- 'node_modules/video.js/dist/video-js.css',
- 'node_modules/video.js/dist/alt/video.core.js',
- 'node_modules/video.js/dist/alt/video.core.min.js',
- 'node_modules/videojs-contrib-eme/dist/videojs-contrib-eme.js',
- 'node_modules/videojs-contrib-eme/dist/videojs-contrib-eme.min.js',
- 'node_modules/videojs-contrib-quality-levels/dist/videojs-contrib-quality-levels.js',
- 'node_modules/videojs-contrib-quality-levels/dist/videojs-contrib-quality-levels.min.js',
- 'node_modules/videojs-http-source-selector/dist/videojs-http-source-selector.css',
- 'node_modules/videojs-http-source-selector/dist/videojs-http-source-selector.js',
- 'node_modules/videojs-http-source-selector/dist/videojs-http-source-selector.min.js',
- 'node_modules/d3/d3.min.js',
- 'logo.svg',
- 'scripts/sources.json',
- 'scripts/index-demo-page.js'
-];
-
-// cleanup previous deploy
-sh.rm('-rf', deployDir);
-// make sure the directory exists
-sh.mkdir('-p', deployDir);
-
-// create nested directories
-files
- .map((file) => path.dirname(file))
- .forEach((dir) => sh.mkdir('-p', path.join(deployDir, dir)));
-
-// copy files/folders to deploy dir
-files
- .concat('dist', 'index.html', 'utils')
- .forEach((file) => sh.cp('-r', file, path.join(deployDir, file)));
diff --git a/node_modules/@videojs/http-streaming/scripts/rollup.config.js b/node_modules/@videojs/http-streaming/scripts/rollup.config.js
deleted file mode 100644
index 41cb5f7..0000000
--- a/node_modules/@videojs/http-streaming/scripts/rollup.config.js
+++ /dev/null
@@ -1,133 +0,0 @@
-const generate = require('videojs-generate-rollup-config');
-const worker = require('rollup-plugin-worker-factory');
-const {terser} = require('rollup-plugin-terser');
-const createTestData = require('./create-test-data.js');
-const replace = require('@rollup/plugin-replace');
-const strip = require('@rollup/plugin-strip');
-
-const CI_TEST_TYPE = process.env.CI_TEST_TYPE || '';
-
-let syncWorker;
-// see https://github.com/videojs/videojs-generate-rollup-config
-// for options
-const options = {
- input: 'src/videojs-http-streaming.js',
- distName: 'videojs-http-streaming',
- excludeCoverage(defaults) {
- defaults.push(/^rollup-plugin-worker-factory/);
- defaults.push(/^create-test-data!/);
-
- return defaults;
- },
- globals(defaults) {
- defaults.browser.xmldom = 'window';
- defaults.test.xmldom = 'window';
- return defaults;
- },
- externals(defaults) {
- return Object.assign(defaults, {
- module: defaults.module.concat([
- 'aes-decrypter',
- 'm3u8-parser',
- 'mpd-parser',
- 'mux.js',
- '@videojs/vhs-utils'
- ])
- });
- },
- plugins(defaults) {
- // add worker and createTestData to the front of plugin lists
- defaults.module.unshift('worker');
- defaults.browser.unshift('worker');
- // change this to `syncWorker` for syncronous web worker
- // during unit tests
- if (CI_TEST_TYPE === 'coverage') {
- defaults.test.unshift('syncWorker');
- } else {
- defaults.test.unshift('worker');
- }
- defaults.test.unshift('createTestData');
-
- if (CI_TEST_TYPE === 'playback-min') {
- defaults.test.push('uglify');
- }
-
- // istanbul is only in the list for regular builds and not watch
- if (CI_TEST_TYPE !== 'coverage' && defaults.test.indexOf('istanbul') !== -1) {
- defaults.test.splice(defaults.test.indexOf('istanbul'), 1);
- }
- defaults.module.unshift('replace');
-
- defaults.module.unshift('strip');
- defaults.browser.unshift('strip');
-
- return defaults;
- },
- primedPlugins(defaults) {
- defaults = Object.assign(defaults, {
- replace: replace({
- // single quote replace
- "require('@videojs/vhs-utils/es": "require('@videojs/vhs-utils/cjs",
- // double quote replace
- 'require("@videojs/vhs-utils/es': 'require("@videojs/vhs-utils/cjs'
- }),
- uglify: terser({
- output: {comments: 'some'},
- compress: {passes: 2}
- }),
- strip: strip({
- functions: ['TEST_ONLY_*']
- }),
- createTestData: createTestData()
- });
-
- defaults.worker = worker({type: 'browser', plugins: [
- defaults.resolve,
- defaults.json,
- defaults.commonjs,
- defaults.babel
- ]});
-
- defaults.syncWorker = syncWorker = worker({type: 'mock', plugins: [
- defaults.resolve,
- defaults.json,
- defaults.commonjs,
- defaults.babel
- ]});
-
- return defaults;
- },
- babel(defaults) {
- const presetEnvSettings = defaults.presets[0][1];
-
- presetEnvSettings.exclude = presetEnvSettings.exclude || [];
- presetEnvSettings.exclude.push('@babel/plugin-transform-typeof-symbol');
-
- return defaults;
- }
-};
-
-if (CI_TEST_TYPE === 'playback' || CI_TEST_TYPE === 'playback-min') {
- options.testInput = 'test/playback.test.js';
-} else if (CI_TEST_TYPE === 'unit' || CI_TEST_TYPE === 'coverage') {
- options.testInput = {include: ['test/**/*.test.js'], exclude: ['test/playback.test.js']};
-}
-
-const config = generate(options);
-
-if (config.builds.browser) {
- config.builds.syncWorkers = config.makeBuild('browser', {
- output: {
- name: 'httpStreaming',
- format: 'umd',
- file: 'dist/videojs-http-streaming-sync-workers.js'
- }
- });
-
- config.builds.syncWorkers.plugins[0] = syncWorker;
-}
-
-// Add additonal builds/customization here!
-
-// export the builds to rollup
-export default Object.values(config.builds);
diff --git a/node_modules/@videojs/http-streaming/scripts/sources.json b/node_modules/@videojs/http-streaming/scripts/sources.json
deleted file mode 100644
index 4f03ff2..0000000
--- a/node_modules/@videojs/http-streaming/scripts/sources.json
+++ /dev/null
@@ -1,391 +0,0 @@
-[
- {
- "name": "Bipbop - Muxed TS with 1 alt Audio, 5 captions",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "FMP4 and ts both muxed",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/ts-fmp4/index.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Advanced Bipbop - ts and captions muxed",
- "uri": "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_ts/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Advanced Bipbop - FMP4 and captions muxed",
- "uri": "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Advanced Bipbop - FMP4 hevc, demuxed",
- "uri": "https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Angel One - FMP4 demuxed, many audio/captions",
- "uri": "https://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Parkour - FMP4 demuxed",
- "uri": "https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s-fmp4/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Song - ts Audio only",
- "uri": "https://s3.amazonaws.com/qa.jwplayer.com/~alex/121628/new_master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Coit Tower drone footage - 4 8 second segment",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/CoitTower/master_ts_segtimes.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Disney's Oceans trailer - HLSe, ts Encrypted",
- "uri": "https://playertest.longtailvideo.com/adaptive/oceans_aes/oceans_aes.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Sintel - ts with audio/subs and a 4k rendtion",
- "uri": "https://bitmovin-a.akamaihd.net/content/sintel/hls/playlist.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Boat Ipsum Subs - HLS + subtitles",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/hls-webvtt/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Boat Video Only",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/video-only/out.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Boat Audio Only",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/audio-only/out.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Boat 4K",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/4k-hls/out.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Boat Misaligned - 3, 5, 7, second segment playlists",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/misaligned-playlists/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "BBB-CMIF: Big Buck Bunny Dark Truths - demuxed, fmp4",
- "uri": "https://storage.googleapis.com/shaka-demo-assets/bbb-dark-truths-hls/hls.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Big Buck Bunny - demuxed audio/video, includes 4K, burns in frame, pts, resolution, bitrate values",
- "uri": "https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "Angel One - fmp4, webm, subs (TODO: subs are broken), alternate audio tracks",
- "uri": "https://storage.googleapis.com/shaka-demo-assets/angel-one/dash.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "Angel One - Widevine, fmp4, webm, subs, alternate audio tracks",
- "uri": "https://storage.googleapis.com/shaka-demo-assets/angel-one-widevine/dash.mpd",
- "mimetype": "application/dash+xml",
- "features": [],
- "keySystems": {
- "com.widevine.alpha": "https://cwip-shaka-proxy.appspot.com/no_auth"
- }
- },
- {
- "name": "BBB-CMIF: Big Buck Bunny Dark Truths - demuxed, fmp4",
- "uri": "https://storage.googleapis.com/shaka-demo-assets/bbb-dark-truths/dash.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "SIDX demuxed, 2 audio",
- "uri": "https://dash.akamaized.net/dash264/TestCases/10a/1/iis_forest_short_poem_multi_lang_480p_single_adapt_aaclc_sidx.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "SIDX bipbop-like",
- "uri": "https://download.tsi.telecom-paristech.fr/gpac/DASH_CONFORMANCE/TelecomParisTech/mp4-onDemand/mp4-onDemand-mpd-AV.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "Google self-driving car - SIDX",
- "uri": "https://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-manifest.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "Sintel - single rendition",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/sintel_dash/sintel_vod.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "HLS - Live - Axinom live stream, may not always be available",
- "uri": "https://akamai-axtest.akamaized.net/routes/lapd-v1-acceptance/www_c4/Manifest.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": ["live"]
- },
- {
- "name": "DASH - Live - Axinom live stream, may not always be available",
- "uri": "https://akamai-axtest.akamaized.net/routes/lapd-v1-acceptance/www_c4/Manifest.mpd",
- "mimetype": "application/dash+xml",
- "features": ["live"]
- },
- {
- "name": "DASH - Live simulated DASH from DASH IF",
- "uri": "https://livesim.dashif.org/livesim/mup_30/testpic_2s/Manifest.mpd",
- "mimetype": "application/dash+xml",
- "features": ["live"]
- },
- {
- "name": "DASH - Shaka Player Source Simulated Live",
- "uri": "https://storage.googleapis.com/shaka-live-assets/player-source.mpd",
- "mimetype": "application/dash+xml",
- "features": ["live"]
- },
- {
- "name": "Apple's LL-HLS test stream",
- "uri": "https://ll-hls-test.apple.com/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": ["live", "low-latency"]
- },
- {
- "name": "Apple's LL-HLS test stream, cmaf, fmp4",
- "uri": "https://ll-hls-test.apple.com/cmaf/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": ["live", "low-latency"]
- },
- {
- "name": "Axinom Multi DRM - DASH, 4k, HEVC, Playready, Widevine",
- "uri": "https://media.axprod.net/TestVectors/v7-MultiDRM-SingleKey/Manifest.mpd",
- "mimetype": "application/dash+xml",
- "features": [],
- "keySystems": {
- "com.microsoft.playready": {
- "url": "https://drm-playready-licensing.axtest.net/AcquireLicense",
- "licenseHeaders": {
- "X-AxDRM-Message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2ZXJzaW9uIjoxLCJjb21fa2V5X2lkIjoiYjMzNjRlYjUtNTFmNi00YWUzLThjOTgtMzNjZWQ1ZTMxYzc4IiwibWVzc2FnZSI6eyJ0eXBlIjoiZW50aXRsZW1lbnRfbWVzc2FnZSIsImtleXMiOlt7ImlkIjoiOWViNDA1MGQtZTQ0Yi00ODAyLTkzMmUtMjdkNzUwODNlMjY2IiwiZW5jcnlwdGVkX2tleSI6ImxLM09qSExZVzI0Y3Iya3RSNzRmbnc9PSJ9XX19.4lWwW46k-oWcah8oN18LPj5OLS5ZU-_AQv7fe0JhNjA"
- }
- },
- "com.widevine.alpha": {
- "url": "https://drm-widevine-licensing.axtest.net/AcquireLicense",
- "licenseHeaders": {
- "X-AxDRM-Message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2ZXJzaW9uIjoxLCJjb21fa2V5X2lkIjoiYjMzNjRlYjUtNTFmNi00YWUzLThjOTgtMzNjZWQ1ZTMxYzc4IiwibWVzc2FnZSI6eyJ0eXBlIjoiZW50aXRsZW1lbnRfbWVzc2FnZSIsImtleXMiOlt7ImlkIjoiOWViNDA1MGQtZTQ0Yi00ODAyLTkzMmUtMjdkNzUwODNlMjY2IiwiZW5jcnlwdGVkX2tleSI6ImxLM09qSExZVzI0Y3Iya3RSNzRmbnc9PSJ9XX19.4lWwW46k-oWcah8oN18LPj5OLS5ZU-_AQv7fe0JhNjA"
- }
- }
- }
- },
- {
- "name": "Axinom Multi DRM, Multi Period - DASH, 4k, HEVC, Playready, Widevine",
- "uri": "https://media.axprod.net/TestVectors/v7-MultiDRM-MultiKey-MultiPeriod/Manifest.mpd",
- "mimetype": "application/dash+xml",
- "features": [],
- "keySystems": {
- "com.microsoft.playready": {
- "url": "https://drm-playready-licensing.axtest.net/AcquireLicense",
- "licenseHeaders": {
- "X-AxDRM-Message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2ZXJzaW9uIjoxLCJjb21fa2V5X2lkIjoiYjMzNjRlYjUtNTFmNi00YWUzLThjOTgtMzNjZWQ1ZTMxYzc4IiwibWVzc2FnZSI6eyJ0eXBlIjoiZW50aXRsZW1lbnRfbWVzc2FnZSIsImtleXMiOlt7ImlkIjoiMDg3Mjc4NmUtZjllNy00NjVmLWEzYTItNGU1YjBlZjhmYTQ1IiwiZW5jcnlwdGVkX2tleSI6IlB3NitlRVlOY3ZqWWJmc2gzWDNmbWc9PSJ9LHsiaWQiOiJjMTRmMDcwOS1mMmI5LTQ0MjctOTE2Yi02MWI1MjU4NjUwNmEiLCJlbmNyeXB0ZWRfa2V5IjoiLzErZk5paDM4bXFSdjR5Y1l6bnQvdz09In0seyJpZCI6IjhiMDI5ZTUxLWQ1NmEtNDRiZC05MTBmLWQ0YjVmZDkwZmJhMiIsImVuY3J5cHRlZF9rZXkiOiJrcTBKdVpFanBGTjhzYVRtdDU2ME9nPT0ifSx7ImlkIjoiMmQ2ZTkzODctNjBjYS00MTQ1LWFlYzItYzQwODM3YjRiMDI2IiwiZW5jcnlwdGVkX2tleSI6IlRjUlFlQld4RW9IT0tIcmFkNFNlVlE9PSJ9LHsiaWQiOiJkZTAyZjA3Zi1hMDk4LTRlZTAtYjU1Ni05MDdjMGQxN2ZiYmMiLCJlbmNyeXB0ZWRfa2V5IjoicG9lbmNTN0dnbWVHRmVvSjZQRUFUUT09In0seyJpZCI6IjkxNGU2OWY0LTBhYjMtNDUzNC05ZTlmLTk4NTM2MTVlMjZmNiIsImVuY3J5cHRlZF9rZXkiOiJlaUkvTXNsbHJRNHdDbFJUL0xObUNBPT0ifSx7ImlkIjoiZGE0NDQ1YzItZGI1ZS00OGVmLWIwOTYtM2VmMzQ3YjE2YzdmIiwiZW5jcnlwdGVkX2tleSI6IjJ3K3pkdnFycERWM3hSMGJKeTR1Z3c9PSJ9LHsiaWQiOiIyOWYwNWU4Zi1hMWFlLTQ2ZTQtODBlOS0yMmRjZDQ0Y2Q3YTEiLCJlbmNyeXB0ZWRfa2V5IjoiL3hsU0hweHdxdTNnby9nbHBtU2dhUT09In0seyJpZCI6IjY5ZmU3MDc3LWRhZGQtNGI1NS05NmNkLWMzZWRiMzk5MTg1MyIsImVuY3J5cHRlZF9rZXkiOiJ6dTZpdXpOMnBzaTBaU3hRaUFUa1JRPT0ifV19fQ.BXr93Et1krYMVs-CUnf7F3ywJWFRtxYdkR7Qn4w3-to"
- }
- },
- "com.widevine.alpha": {
- "url": "https://drm-widevine-licensing.axtest.net/AcquireLicense",
- "licenseHeaders": {
- "X-AxDRM-Message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2ZXJzaW9uIjoxLCJjb21fa2V5X2lkIjoiYjMzNjRlYjUtNTFmNi00YWUzLThjOTgtMzNjZWQ1ZTMxYzc4IiwibWVzc2FnZSI6eyJ0eXBlIjoiZW50aXRsZW1lbnRfbWVzc2FnZSIsImtleXMiOlt7ImlkIjoiMDg3Mjc4NmUtZjllNy00NjVmLWEzYTItNGU1YjBlZjhmYTQ1IiwiZW5jcnlwdGVkX2tleSI6IlB3NitlRVlOY3ZqWWJmc2gzWDNmbWc9PSJ9LHsiaWQiOiJjMTRmMDcwOS1mMmI5LTQ0MjctOTE2Yi02MWI1MjU4NjUwNmEiLCJlbmNyeXB0ZWRfa2V5IjoiLzErZk5paDM4bXFSdjR5Y1l6bnQvdz09In0seyJpZCI6IjhiMDI5ZTUxLWQ1NmEtNDRiZC05MTBmLWQ0YjVmZDkwZmJhMiIsImVuY3J5cHRlZF9rZXkiOiJrcTBKdVpFanBGTjhzYVRtdDU2ME9nPT0ifSx7ImlkIjoiMmQ2ZTkzODctNjBjYS00MTQ1LWFlYzItYzQwODM3YjRiMDI2IiwiZW5jcnlwdGVkX2tleSI6IlRjUlFlQld4RW9IT0tIcmFkNFNlVlE9PSJ9LHsiaWQiOiJkZTAyZjA3Zi1hMDk4LTRlZTAtYjU1Ni05MDdjMGQxN2ZiYmMiLCJlbmNyeXB0ZWRfa2V5IjoicG9lbmNTN0dnbWVHRmVvSjZQRUFUUT09In0seyJpZCI6IjkxNGU2OWY0LTBhYjMtNDUzNC05ZTlmLTk4NTM2MTVlMjZmNiIsImVuY3J5cHRlZF9rZXkiOiJlaUkvTXNsbHJRNHdDbFJUL0xObUNBPT0ifSx7ImlkIjoiZGE0NDQ1YzItZGI1ZS00OGVmLWIwOTYtM2VmMzQ3YjE2YzdmIiwiZW5jcnlwdGVkX2tleSI6IjJ3K3pkdnFycERWM3hSMGJKeTR1Z3c9PSJ9LHsiaWQiOiIyOWYwNWU4Zi1hMWFlLTQ2ZTQtODBlOS0yMmRjZDQ0Y2Q3YTEiLCJlbmNyeXB0ZWRfa2V5IjoiL3hsU0hweHdxdTNnby9nbHBtU2dhUT09In0seyJpZCI6IjY5ZmU3MDc3LWRhZGQtNGI1NS05NmNkLWMzZWRiMzk5MTg1MyIsImVuY3J5cHRlZF9rZXkiOiJ6dTZpdXpOMnBzaTBaU3hRaUFUa1JRPT0ifV19fQ.BXr93Et1krYMVs-CUnf7F3ywJWFRtxYdkR7Qn4w3-to"
- }
- }
- }
- },
- {
- "name": "Axinom Clear - DASH, 4k, HEVC",
- "uri": "https://media.axprod.net/TestVectors/v7-Clear/Manifest.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "Axinom Clear MultiPeriod - DASH, 4k, HEVC",
- "uri": "https://media.axprod.net/TestVectors/v7-Clear/Manifest_MultiPeriod.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "DASH-IF simulated live",
- "uri": "https://livesim.dashif.org/livesim/testpic_2s/Manifest.mpd",
- "mimetype": "application/dash+xml",
- "features": ["live"]
- },
- {
- "name": "Tears of Steal - Widevine (Unified Streaming)",
- "uri": "https://demo.unified-streaming.com/video/tears-of-steel/tears-of-steel-dash-widevine.ism/.mpd",
- "mimetype": "application/dash+xml",
- "features": [],
- "keySystems": {
- "com.widevine.alpha": "https://widevine-proxy.appspot.com/proxy"
- }
- },
- {
- "name": "Tears of Steal - PlayReady (Unified Streaming)",
- "uri": "https://demo.unified-streaming.com/video/tears-of-steel/tears-of-steel-dash-playready.ism/.mpd",
- "mimetype": "application/dash+xml",
- "features": [],
- "keySystems": {
- "com.microsoft.playready": "https://test.playready.microsoft.com/service/rightsmanager.asmx"
- }
- },
- {
- "name": "Unified Streaming Live DASH",
- "uri": "https://live.unified-streaming.com/scte35/scte35.isml/.mpd",
- "mimetype": "application/dash+xml",
- "features": ["live"]
- },
- {
- "name": "Unified Streaming Live HLS",
- "uri": "https://live.unified-streaming.com/scte35/scte35.isml/.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": ["live"]
- },
- {
- "name": "DOESN'T WORK - Bayerrischer Rundfunk Recorded Loop - DASH, may not always be available",
- "uri": "https://irtdashreference-i.akamaihd.net/dash/live/901161/keepixo1/manifestBR2.mpd",
- "mimetype": "application/dash+xml",
- "features": ["live"]
- },
- {
- "name": "DOESN'T WORK - Bayerrischer Rundfunk Recorded Loop - HLS, may not always be available",
- "uri": "https://irtdashreference-i.akamaihd.net/dash/live/901161/keepixo1/playlistBR2.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": ["live"]
- },
- {
- "name": "Big Buck Bunny - Azure - DASH, Widevine, PlayReady",
- "uri": "https://amssamples.streaming.mediaservices.windows.net/622b189f-ec39-43f2-93a2-201ac4e31ce1/BigBuckBunny.ism/manifest(format=mpd-time-csf)",
- "mimetype": "application/dash+xml",
- "features": [],
- "keySystems": {
- "com.widevine.alpha": "https://amssamples.keydelivery.mediaservices.windows.net/Widevine/?KID=1ab45440-532c-4399-94dc-5c5ad9584bac",
- "com.microsoft.playready": "https://amssamples.keydelivery.mediaservices.windows.net/PlayReady/"
- }
- },
- {
- "name": "Big Buck Bunny Audio only, groups have same uri as renditons",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/audio-only-dupe-groups/prog_index.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Big Buck Bunny Demuxed av, audio only rendition same as group",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/demuxed-ts-with-audio-only-rendition/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "sidx v1 dash",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/sidx-v1-dash/Dog.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "fmp4 x264/flac no manifest codecs",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/fmp4-flac-no-manifest-codecs/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "fmp4 x264/opus no manifest codecs",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/fmp4-opus-no-manifest-codecs/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "fmp4 h264/aac no manifest codecs",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/fmp4-muxed-no-playlist-codecs/index.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "ts one valid codec among many invalid",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/ts-one-valid-many-invalid-codecs/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Legacy AVC Codec",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/legacy-avc-codec/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Pseudo-Live PDT test source",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/pdt-test-source/no-endlist.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": ["live"]
- },
- {
- "name": "PDT test source",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/pdt-test-source/endlist.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "audio only dash, two groups",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/audio-only-dash/dash.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "video only dash, two renditions",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/video-only-dash/dash.mpd",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "encrypted init segment",
- "uri": "https://d2zihajmogu5jn.cloudfront.net/encrypted-init-segment/master.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- },
- {
- "name": "Dash data uri for https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps.mpd",
- "uri": "data:application/dash+xml;charset=utf-8,%3CMPD%20mediaPresentationDuration=%22PT634.566S%22%20minBufferTime=%22PT2.00S%22%20profiles=%22urn:hbbtv:dash:profile:isoff-live:2012,urn:mpeg:dash:profile:isoff-live:2011%22%20type=%22static%22%20xmlns=%22urn:mpeg:dash:schema:mpd:2011%22%20xmlns:xsi=%22http://www.w3.org/2001/XMLSchema-instance%22%20xsi:schemaLocation=%22urn:mpeg:DASH:schema:MPD:2011%20DASH-MPD.xsd%22%3E%20%3CBaseURL%3Ehttps://dash.akamaized.net/akamai/bbb_30fps/%3C/BaseURL%3E%20%3CPeriod%3E%20%20%3CAdaptationSet%20mimeType=%22video/mp4%22%20contentType=%22video%22%20subsegmentAlignment=%22true%22%20subsegmentStartsWithSAP=%221%22%20par=%2216:9%22%3E%20%20%20%3CSegmentTemplate%20duration=%22120%22%20timescale=%2230%22%20media=%22$RepresentationID$/$RepresentationID$_$Number$.m4v%22%20startNumber=%221%22%20initialization=%22$RepresentationID$/$RepresentationID$_0.m4v%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_1024x576_2500k%22%20codecs=%22avc1.64001f%22%20bandwidth=%223134488%22%20width=%221024%22%20height=%22576%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_1280x720_4000k%22%20codecs=%22avc1.64001f%22%20bandwidth=%224952892%22%20width=%221280%22%20height=%22720%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_1920x1080_8000k%22%20codecs=%22avc1.640028%22%20bandwidth=%229914554%22%20width=%221920%22%20height=%221080%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_320x180_200k%22%20codecs=%22avc1.64000d%22%20bandwidth=%22254320%22%20width=%22320%22%20height=%22180%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_320x180_400k%22%20codecs=%22avc1.64000d%22%20bandwidth=%22507246%22%20width=%22320%22%20height=%22180%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_480x270_600k%22%20codecs=%22avc1.640015%22%20bandwidth=%22759798%22%20width=%22480%22%20height=%22270%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_640x360_1000k%22%20codecs=%22avc1.64001e%22%20bandwidth=%221254758%22%20width=%22640%22%20height=%22360%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_640x360_800k%22%20codecs=%22avc1.64001e%22%20bandwidth=%221013310%22%20width=%22640%22%20height=%22360%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_768x432_1500k%22%20codecs=%22avc1.64001e%22%20bandwidth=%221883700%22%20width=%22768%22%20height=%22432%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_30fps_3840x2160_12000k%22%20codecs=%22avc1.640033%22%20bandwidth=%2214931538%22%20width=%223840%22%20height=%222160%22%20frameRate=%2230%22%20sar=%221:1%22%20scanType=%22progressive%22/%3E%20%20%3C/AdaptationSet%3E%20%20%3CAdaptationSet%20mimeType=%22audio/mp4%22%20contentType=%22audio%22%20subsegmentAlignment=%22true%22%20subsegmentStartsWithSAP=%221%22%3E%20%20%20%3CAccessibility%20schemeIdUri=%22urn:tva:metadata:cs:AudioPurposeCS:2007%22%20value=%226%22/%3E%20%20%20%3CRole%20schemeIdUri=%22urn:mpeg:dash:role:2011%22%20value=%22main%22/%3E%20%20%20%3CSegmentTemplate%20duration=%22192512%22%20timescale=%2248000%22%20media=%22$RepresentationID$/$RepresentationID$_$Number$.m4a%22%20startNumber=%221%22%20initialization=%22$RepresentationID$/$RepresentationID$_0.m4a%22/%3E%20%20%20%3CRepresentation%20id=%22bbb_a64k%22%20codecs=%22mp4a.40.5%22%20bandwidth=%2267071%22%20audioSamplingRate=%2248000%22%3E%20%20%20%20%3CAudioChannelConfiguration%20schemeIdUri=%22urn:mpeg:dash:23003:3:audio_channel_configuration:2011%22%20value=%222%22/%3E%20%20%20%3C/Representation%3E%20%20%3C/AdaptationSet%3E%20%3C/Period%3E%3C/MPD%3E",
- "mimetype": "application/dash+xml",
- "features": []
- },
- {
- "name": "HLS data uri for https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8",
- "uri": "data:application/x-mpegurl;charset=utf-8,%23EXTM3U%0D%0A%0D%0A%23EXT-X-MEDIA%3ATYPE%3DAUDIO%2CGROUP-ID%3D%22bipbop_audio%22%2CLANGUAGE%3D%22eng%22%2CNAME%3D%22BipBop%20Audio%201%22%2CAUTOSELECT%3DYES%2CDEFAULT%3DYES%0D%0A%23EXT-X-MEDIA%3ATYPE%3DAUDIO%2CGROUP-ID%3D%22bipbop_audio%22%2CLANGUAGE%3D%22eng%22%2CNAME%3D%22BipBop%20Audio%202%22%2CAUTOSELECT%3DNO%2CDEFAULT%3DNO%2CURI%3D%22https%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Falternate_audio_aac_sinewave%2Fprog_index.m3u8%22%0D%0A%0D%0A%0D%0A%23EXT-X-MEDIA%3ATYPE%3DSUBTITLES%2CGROUP-ID%3D%22subs%22%2CNAME%3D%22English%22%2CDEFAULT%3DYES%2CAUTOSELECT%3DYES%2CFORCED%3DNO%2CLANGUAGE%3D%22en%22%2CCHARACTERISTICS%3D%22public.accessibility.transcribes-spoken-dialog%2C%20public.accessibility.describes-music-and-sound%22%2CURI%3D%22https%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fsubtitles%2Feng%2Fprog_index.m3u8%22%0D%0A%23EXT-X-MEDIA%3ATYPE%3DSUBTITLES%2CGROUP-ID%3D%22subs%22%2CNAME%3D%22English%20%28Forced%29%22%2CDEFAULT%3DNO%2CAUTOSELECT%3DNO%2CFORCED%3DYES%2CLANGUAGE%3D%22en%22%2CURI%3D%22https%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fsubtitles%2Feng_forced%2Fprog_index.m3u8%22%0D%0A%23EXT-X-MEDIA%3ATYPE%3DSUBTITLES%2CGROUP-ID%3D%22subs%22%2CNAME%3D%22Fran%C3%83%C2%A7ais%22%2CDEFAULT%3DNO%2CAUTOSELECT%3DYES%2CFORCED%3DNO%2CLANGUAGE%3D%22fr%22%2CCHARACTERISTICS%3D%22public.accessibility.transcribes-spoken-dialog%2C%20public.accessibility.describes-music-and-sound%22%2CURI%3D%22https%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fsubtitles%2Ffra%2Fprog_index.m3u8%22%0D%0A%23EXT-X-MEDIA%3ATYPE%3DSUBTITLES%2CGROUP-ID%3D%22subs%22%2CNAME%3D%22Fran%C3%83%C2%A7ais%20%28Forced%29%22%2CDEFAULT%3DNO%2CAUTOSELECT%3DNO%2CFORCED%3DYES%2CLANGUAGE%3D%22fr%22%2CURI%3D%22https%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fsubtitles%2Ffra_forced%2Fprog_index.m3u8%22%0D%0A%23EXT-X-MEDIA%3ATYPE%3DSUBTITLES%2CGROUP-ID%3D%22subs%22%2CNAME%3D%22Espa%C3%83%C2%B1ol%22%2CDEFAULT%3DNO%2CAUTOSELECT%3DYES%2CFORCED%3DNO%2CLANGUAGE%3D%22es%22%2CCHARACTERISTICS%3D%22public.accessibility.transcribes-spoken-dialog%2C%20public.accessibility.describes-music-and-sound%22%2CURI%3D%22https%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fsubtitles%2Fspa%2Fprog_index.m3u8%22%0D%0A%23EXT-X-MEDIA%3ATYPE%3DSUBTITLES%2CGROUP-ID%3D%22subs%22%2CNAME%3D%22Espa%C3%83%C2%B1ol%20%28Forced%29%22%2CDEFAULT%3DNO%2CAUTOSELECT%3DNO%2CFORCED%3DYES%2CLANGUAGE%3D%22es%22%2CURI%3D%22https%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fsubtitles%2Fspa_forced%2Fprog_index.m3u8%22%0D%0A%23EXT-X-MEDIA%3ATYPE%3DSUBTITLES%2CGROUP-ID%3D%22subs%22%2CNAME%3D%22%C3%A6%C2%97%C2%A5%C3%A6%C2%9C%C2%AC%C3%A8%C2%AA%C2%9E%22%2CDEFAULT%3DNO%2CAUTOSELECT%3DYES%2CFORCED%3DNO%2CLANGUAGE%3D%22ja%22%2CCHARACTERISTICS%3D%22public.accessibility.transcribes-spoken-dialog%2C%20public.accessibility.describes-music-and-sound%22%2CURI%3D%22https%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fsubtitles%2Fjpn%2Fprog_index.m3u8%22%0D%0A%23EXT-X-MEDIA%3ATYPE%3DSUBTITLES%2CGROUP-ID%3D%22subs%22%2CNAME%3D%22%C3%A6%C2%97%C2%A5%C3%A6%C2%9C%C2%AC%C3%A8%C2%AA%C2%9E%20%28Forced%29%22%2CDEFAULT%3DNO%2CAUTOSELECT%3DNO%2CFORCED%3DYES%2CLANGUAGE%3D%22ja%22%2CURI%3D%22https%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fsubtitles%2Fjpn_forced%2Fprog_index.m3u8%22%0D%0A%0D%0A%0D%0A%23EXT-X-STREAM-INF%3ABANDWIDTH%3D263851%2CCODECS%3D%22mp4a.40.2%2C%20avc1.4d400d%22%2CRESOLUTION%3D416x234%2CAUDIO%3D%22bipbop_audio%22%2CSUBTITLES%3D%22subs%22%0D%0Ahttps%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fgear1%2Fprog_index.m3u8%0D%0A%0D%0A%23EXT-X-STREAM-INF%3ABANDWIDTH%3D577610%2CCODECS%3D%22mp4a.40.2%2C%20avc1.4d401e%22%2CRESOLUTION%3D640x360%2CAUDIO%3D%22bipbop_audio%22%2CSUBTITLES%3D%22subs%22%0D%0Ahttps%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fgear2%2Fprog_index.m3u8%0D%0A%0D%0A%23EXT-X-STREAM-INF%3ABANDWIDTH%3D915905%2CCODECS%3D%22mp4a.40.2%2C%20avc1.4d401f%22%2CRESOLUTION%3D960x540%2CAUDIO%3D%22bipbop_audio%22%2CSUBTITLES%3D%22subs%22%0D%0Ahttps%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fgear3%2Fprog_index.m3u8%0D%0A%0D%0A%23EXT-X-STREAM-INF%3ABANDWIDTH%3D1030138%2CCODECS%3D%22mp4a.40.2%2C%20avc1.4d401f%22%2CRESOLUTION%3D1280x720%2CAUDIO%3D%22bipbop_audio%22%2CSUBTITLES%3D%22subs%22%0D%0Ahttps%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fgear4%2Fprog_index.m3u8%0D%0A%0D%0A%23EXT-X-STREAM-INF%3ABANDWIDTH%3D1924009%2CCODECS%3D%22mp4a.40.2%2C%20avc1.4d401f%22%2CRESOLUTION%3D1920x1080%2CAUDIO%3D%22bipbop_audio%22%2CSUBTITLES%3D%22subs%22%0D%0Ahttps%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fgear5%2Fprog_index.m3u8%0D%0A%0D%0A%23EXT-X-STREAM-INF%3ABANDWIDTH%3D41457%2CCODECS%3D%22mp4a.40.2%22%2CAUDIO%3D%22bipbop_audio%22%2CSUBTITLES%3D%22subs%22%0D%0Ahttps%3A%2F%2Fd2zihajmogu5jn.cloudfront.net%2Fbipbop-advanced%2Fgear0%2Fprog_index.m3u8",
- "mimetype": "application/x-mpegurl",
- "features": []
- }
-]
diff --git a/node_modules/@videojs/http-streaming/src/ad-cue-tags.js b/node_modules/@videojs/http-streaming/src/ad-cue-tags.js
deleted file mode 100644
index 8710803..0000000
--- a/node_modules/@videojs/http-streaming/src/ad-cue-tags.js
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * @file ad-cue-tags.js
- */
-import window from 'global/window';
-
-/**
- * Searches for an ad cue that overlaps with the given mediaTime
- *
- * @param {Object} track
- * the track to find the cue for
- *
- * @param {number} mediaTime
- * the time to find the cue at
- *
- * @return {Object|null}
- * the found cue or null
- */
-export const findAdCue = function(track, mediaTime) {
- const cues = track.cues;
-
- for (let i = 0; i < cues.length; i++) {
- const cue = cues[i];
-
- if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
- return cue;
- }
- }
- return null;
-};
-
-export const updateAdCues = function(media, track, offset = 0) {
- if (!media.segments) {
- return;
- }
-
- let mediaTime = offset;
- let cue;
-
- for (let i = 0; i < media.segments.length; i++) {
- const segment = media.segments[i];
-
- if (!cue) {
- // Since the cues will span for at least the segment duration, adding a fudge
- // factor of half segment duration will prevent duplicate cues from being
- // created when timing info is not exact (e.g. cue start time initialized
- // at 10.006677, but next call mediaTime is 10.003332 )
- cue = findAdCue(track, mediaTime + (segment.duration / 2));
- }
-
- if (cue) {
- if ('cueIn' in segment) {
- // Found a CUE-IN so end the cue
- cue.endTime = mediaTime;
- cue.adEndTime = mediaTime;
- mediaTime += segment.duration;
- cue = null;
- continue;
- }
-
- if (mediaTime < cue.endTime) {
- // Already processed this mediaTime for this cue
- mediaTime += segment.duration;
- continue;
- }
-
- // otherwise extend cue until a CUE-IN is found
- cue.endTime += segment.duration;
-
- } else {
- if ('cueOut' in segment) {
- cue = new window.VTTCue(
- mediaTime,
- mediaTime + segment.duration,
- segment.cueOut
- );
- cue.adStartTime = mediaTime;
- // Assumes tag format to be
- // #EXT-X-CUE-OUT:30
- cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
- track.addCue(cue);
- }
-
- if ('cueOutCont' in segment) {
- // Entered into the middle of an ad cue
- // Assumes tag formate to be
- // #EXT-X-CUE-OUT-CONT:10/30
- const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
-
- cue = new window.VTTCue(
- mediaTime,
- mediaTime + segment.duration,
- ''
- );
- cue.adStartTime = mediaTime - adOffset;
- cue.adEndTime = cue.adStartTime + adTotal;
- track.addCue(cue);
- }
- }
- mediaTime += segment.duration;
- }
-};
diff --git a/node_modules/@videojs/http-streaming/src/bin-utils.js b/node_modules/@videojs/http-streaming/src/bin-utils.js
deleted file mode 100644
index ae675bc..0000000
--- a/node_modules/@videojs/http-streaming/src/bin-utils.js
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- * @file bin-utils.js
- */
-
-/**
- * convert a TimeRange to text
- *
- * @param {TimeRange} range the timerange to use for conversion
- * @param {number} i the iterator on the range to convert
- * @return {string} the range in string format
- */
-const textRange = function(range, i) {
- return range.start(i) + '-' + range.end(i);
-};
-
-/**
- * format a number as hex string
- *
- * @param {number} e The number
- * @param {number} i the iterator
- * @return {string} the hex formatted number as a string
- */
-const formatHexString = function(e, i) {
- const value = e.toString(16);
-
- return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
-};
-const formatAsciiString = function(e) {
- if (e >= 0x20 && e < 0x7e) {
- return String.fromCharCode(e);
- }
- return '.';
-};
-
-/**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-export const createTransferableMessage = function(message) {
- const transferable = {};
-
- Object.keys(message).forEach((key) => {
- const value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
-
- return transferable;
-};
-
-/**
- * Returns a unique string identifier for a media initialization
- * segment.
- *
- * @param {Object} initSegment
- * the init segment object.
- *
- * @return {string} the generated init segment id
- */
-export const initSegmentId = function(initSegment) {
- const byterange = initSegment.byterange || {
- length: Infinity,
- offset: 0
- };
-
- return [
- byterange.length, byterange.offset, initSegment.resolvedUri
- ].join(',');
-};
-
-/**
- * Returns a unique string identifier for a media segment key.
- *
- * @param {Object} key the encryption key
- * @return {string} the unique id for the media segment key.
- */
-export const segmentKeyId = function(key) {
- return key.resolvedUri;
-};
-
-/**
- * utils to help dump binary data to the console
- *
- * @param {Array|TypedArray} data
- * data to dump to a string
- *
- * @return {string} the data as a hex string.
- */
-export const hexDump = (data) => {
- const bytes = Array.prototype.slice.call(data);
- const step = 16;
- let result = '';
- let hex;
- let ascii;
-
- for (let j = 0; j < bytes.length / step; j++) {
- hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
- ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
- result += hex + ' ' + ascii + '\n';
- }
-
- return result;
-};
-
-export const tagDump = ({ bytes }) => hexDump(bytes);
-
-export const textRanges = (ranges) => {
- let result = '';
- let i;
-
- for (i = 0; i < ranges.length; i++) {
- result += textRange(ranges, i) + ' ';
- }
- return result;
-};
diff --git a/node_modules/@videojs/http-streaming/src/config.js b/node_modules/@videojs/http-streaming/src/config.js
deleted file mode 100644
index 6a0a007..0000000
--- a/node_modules/@videojs/http-streaming/src/config.js
+++ /dev/null
@@ -1,21 +0,0 @@
-export default {
- GOAL_BUFFER_LENGTH: 30,
- MAX_GOAL_BUFFER_LENGTH: 60,
- BACK_BUFFER_LENGTH: 30,
- GOAL_BUFFER_LENGTH_RATE: 1,
- // 0.5 MB/s
- INITIAL_BANDWIDTH: 4194304,
- // A fudge factor to apply to advertised playlist bitrates to account for
- // temporary flucations in client bandwidth
- BANDWIDTH_VARIANCE: 1.2,
- // How much of the buffer must be filled before we consider upswitching
- BUFFER_LOW_WATER_LINE: 0,
- MAX_BUFFER_LOW_WATER_LINE: 30,
-
- // TODO: Remove this when experimentalBufferBasedABR is removed
- EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
-
- BUFFER_LOW_WATER_LINE_RATE: 1,
- // If the buffer is greater than the high water line, we won't switch down
- BUFFER_HIGH_WATER_LINE: 30
-};
diff --git a/node_modules/@videojs/http-streaming/src/dash-playlist-loader.js b/node_modules/@videojs/http-streaming/src/dash-playlist-loader.js
deleted file mode 100644
index e032c43..0000000
--- a/node_modules/@videojs/http-streaming/src/dash-playlist-loader.js
+++ /dev/null
@@ -1,855 +0,0 @@
-import videojs from 'video.js';
-import {
- parse as parseMpd,
- addSidxSegmentsToPlaylist,
- generateSidxKey,
- parseUTCTiming
-} from 'mpd-parser';
-import {
- refreshDelay,
- updateMaster as updatePlaylist,
- isPlaylistUnchanged
-} from './playlist-loader';
-import { resolveUrl, resolveManifestRedirect } from './resolve-url';
-import parseSidx from 'mux.js/lib/tools/parse-sidx';
-import { segmentXhrHeaders } from './xhr';
-import window from 'global/window';
-import {
- forEachMediaGroup,
- addPropertiesToMaster
-} from './manifest';
-import containerRequest from './util/container-request.js';
-import {toUint8} from '@videojs/vhs-utils/es/byte-helpers';
-import logger from './util/logger';
-
-const { EventTarget, mergeOptions } = videojs;
-
-const dashPlaylistUnchanged = function(a, b) {
- if (!isPlaylistUnchanged(a, b)) {
- return false;
- }
-
- // for dash the above check will often return true in scenarios where
- // the playlist actually has changed because mediaSequence isn't a
- // dash thing, and we often set it to 1. So if the playlists have the same amount
- // of segments we return true.
- // So for dash we need to make sure that the underlying segments are different.
-
- // if sidx changed then the playlists are different.
- if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
- return false;
- } else if ((!a.sidx && b.sidx) || (a.sidx && !b.sidx)) {
- return false;
- }
-
- // one or the other does not have segments
- // there was a change.
- if (a.segments && !b.segments || !a.segments && b.segments) {
- return false;
- }
-
- // neither has segments nothing changed
- if (!a.segments && !b.segments) {
- return true;
- }
-
- // check segments themselves
- for (let i = 0; i < a.segments.length; i++) {
- const aSegment = a.segments[i];
- const bSegment = b.segments[i];
-
- // if uris are different between segments there was a change
- if (aSegment.uri !== bSegment.uri) {
- return false;
- }
-
- // neither segment has a byterange, there will be no byterange change.
- if (!aSegment.byterange && !bSegment.byterange) {
- continue;
- }
- const aByterange = aSegment.byterange;
- const bByterange = bSegment.byterange;
-
- // if byterange only exists on one of the segments, there was a change.
- if ((aByterange && !bByterange) || (!aByterange && bByterange)) {
- return false;
- }
-
- // if both segments have byterange with different offsets, there was a change.
- if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
- return false;
- }
- }
-
- // if everything was the same with segments, this is the same playlist.
- return true;
-};
-
-/**
- * Parses the master XML string and updates playlist URI references.
- *
- * @param {Object} config
- * Object of arguments
- * @param {string} config.masterXml
- * The mpd XML
- * @param {string} config.srcUrl
- * The mpd URL
- * @param {Date} config.clientOffset
- * A time difference between server and client
- * @param {Object} config.sidxMapping
- * SIDX mappings for moof/mdat URIs and byte ranges
- * @return {Object}
- * The parsed mpd manifest object
- */
-export const parseMasterXml = ({ masterXml, srcUrl, clientOffset, sidxMapping }) => {
- const master = parseMpd(masterXml, {
- manifestUri: srcUrl,
- clientOffset,
- sidxMapping
- });
-
- addPropertiesToMaster(master, srcUrl);
-
- return master;
-};
-
-/**
- * Returns a new master manifest that is the result of merging an updated master manifest
- * into the original version.
- *
- * @param {Object} oldMaster
- * The old parsed mpd object
- * @param {Object} newMaster
- * The updated parsed mpd object
- * @return {Object}
- * A new object representing the original master manifest with the updated media
- * playlists merged in
- */
-export const updateMaster = (oldMaster, newMaster, sidxMapping) => {
- let noChanges = true;
- let update = mergeOptions(oldMaster, {
- // These are top level properties that can be updated
- duration: newMaster.duration,
- minimumUpdatePeriod: newMaster.minimumUpdatePeriod
- });
-
- // First update the playlists in playlist list
- for (let i = 0; i < newMaster.playlists.length; i++) {
- const playlist = newMaster.playlists[i];
-
- if (playlist.sidx) {
- const sidxKey = generateSidxKey(playlist.sidx);
-
- // add sidx segments to the playlist if we have all the sidx info already
- if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
- addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
- }
- }
- const playlistUpdate = updatePlaylist(update, playlist, dashPlaylistUnchanged);
-
- if (playlistUpdate) {
- update = playlistUpdate;
- noChanges = false;
- }
- }
-
- // Then update media group playlists
- forEachMediaGroup(newMaster, (properties, type, group, label) => {
- if (properties.playlists && properties.playlists.length) {
- const id = properties.playlists[0].id;
- const playlistUpdate = updatePlaylist(update, properties.playlists[0], dashPlaylistUnchanged);
-
- if (playlistUpdate) {
- update = playlistUpdate;
- // update the playlist reference within media groups
- update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
- noChanges = false;
- }
- }
- });
-
- if (newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
- noChanges = false;
- }
-
- if (noChanges) {
- return null;
- }
-
- return update;
-};
-
-// SIDX should be equivalent if the URI and byteranges of the SIDX match.
-// If the SIDXs have maps, the two maps should match,
-// both `a` and `b` missing SIDXs is considered matching.
-// If `a` or `b` but not both have a map, they aren't matching.
-const equivalentSidx = (a, b) => {
- const neitherMap = Boolean(!a.map && !b.map);
-
- const equivalentMap = neitherMap || Boolean(a.map && b.map &&
- a.map.byterange.offset === b.map.byterange.offset &&
- a.map.byterange.length === b.map.byterange.length);
-
- return equivalentMap &&
- a.uri === b.uri &&
- a.byterange.offset === b.byterange.offset &&
- a.byterange.length === b.byterange.length;
-};
-
-// exported for testing
-export const compareSidxEntry = (playlists, oldSidxMapping) => {
- const newSidxMapping = {};
-
- for (const id in playlists) {
- const playlist = playlists[id];
- const currentSidxInfo = playlist.sidx;
-
- if (currentSidxInfo) {
- const key = generateSidxKey(currentSidxInfo);
-
- if (!oldSidxMapping[key]) {
- break;
- }
-
- const savedSidxInfo = oldSidxMapping[key].sidxInfo;
-
- if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
- newSidxMapping[key] = oldSidxMapping[key];
- }
- }
- }
-
- return newSidxMapping;
-};
-
-/**
- * A function that filters out changed items as they need to be requested separately.
- *
- * The method is exported for testing
- *
- * @param {Object} master the parsed mpd XML returned via mpd-parser
- * @param {Object} oldSidxMapping the SIDX to compare against
- */
-export const filterChangedSidxMappings = (master, oldSidxMapping) => {
- const videoSidx = compareSidxEntry(master.playlists, oldSidxMapping);
- let mediaGroupSidx = videoSidx;
-
- forEachMediaGroup(master, (properties, mediaType, groupKey, labelKey) => {
- if (properties.playlists && properties.playlists.length) {
- const playlists = properties.playlists;
-
- mediaGroupSidx = mergeOptions(
- mediaGroupSidx,
- compareSidxEntry(playlists, oldSidxMapping)
- );
- }
- });
-
- return mediaGroupSidx;
-};
-
-export default class DashPlaylistLoader extends EventTarget {
- // DashPlaylistLoader must accept either a src url or a playlist because subsequent
- // playlist loader setups from media groups will expect to be able to pass a playlist
- // (since there aren't external URLs to media playlists with DASH)
- constructor(srcUrlOrPlaylist, vhs, options = { }, masterPlaylistLoader) {
- super();
-
- this.masterPlaylistLoader_ = masterPlaylistLoader || this;
- if (!masterPlaylistLoader) {
- this.isMaster_ = true;
- }
-
- const { withCredentials = false, handleManifestRedirects = false } = options;
-
- this.vhs_ = vhs;
- this.withCredentials = withCredentials;
- this.handleManifestRedirects = handleManifestRedirects;
-
- if (!srcUrlOrPlaylist) {
- throw new Error('A non-empty playlist URL or object is required');
- }
-
- // event naming?
- this.on('minimumUpdatePeriod', () => {
- this.refreshXml_();
- });
-
- // live playlist staleness timeout
- this.on('mediaupdatetimeout', () => {
- this.refreshMedia_(this.media().id);
- });
-
- this.state = 'HAVE_NOTHING';
- this.loadedPlaylists_ = {};
- this.logger_ = logger('DashPlaylistLoader');
-
- // initialize the loader state
- // The masterPlaylistLoader will be created with a string
- if (this.isMaster_) {
- this.masterPlaylistLoader_.srcUrl = srcUrlOrPlaylist;
- // TODO: reset sidxMapping between period changes
- // once multi-period is refactored
- this.masterPlaylistLoader_.sidxMapping_ = {};
- } else {
- this.childPlaylist_ = srcUrlOrPlaylist;
- }
- }
-
- requestErrored_(err, request, startingState) {
- // disposed
- if (!this.request) {
- return true;
- }
-
- // pending request is cleared
- this.request = null;
-
- if (err) {
- // use the provided error object or create one
- // based on the request/response
- this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
- status: request.status,
- message: 'DASH request error at URL: ' + request.uri,
- response: request.response,
- // MEDIA_ERR_NETWORK
- code: 2
- };
- if (startingState) {
- this.state = startingState;
- }
-
- this.trigger('error');
- return true;
- }
- }
-
- /**
- * Verify that the container of the sidx segment can be parsed
- * and if it can, get and parse that segment.
- */
- addSidxSegments_(playlist, startingState, cb) {
- const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx);
-
- // playlist lacks sidx or sidx segments were added to this playlist already.
- if (!playlist.sidx || !sidxKey || this.masterPlaylistLoader_.sidxMapping_[sidxKey]) {
- // keep this function async
- this.mediaRequest_ = window.setTimeout(() => cb(false), 0);
- return;
- }
-
- // resolve the segment URL relative to the playlist
- const uri = resolveManifestRedirect(this.handleManifestRedirects, playlist.sidx.resolvedUri);
-
- const fin = (err, request) => {
- if (this.requestErrored_(err, request, startingState)) {
- return;
- }
-
- const sidxMapping = this.masterPlaylistLoader_.sidxMapping_;
- let sidx;
-
- try {
- sidx = parseSidx(toUint8(request.response).subarray(8));
- } catch (e) {
- // sidx parsing failed.
- this.requestErrored_(e, request, startingState);
- return;
- }
-
- sidxMapping[sidxKey] = {
- sidxInfo: playlist.sidx,
- sidx
- };
-
- addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
-
- return cb(true);
- };
-
- this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
- if (err) {
- return fin(err, request);
- }
-
- if (!container || container !== 'mp4') {
- return fin({
- status: request.status,
- message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
- // response is just bytes in this case
- // but we really don't want to return that.
- response: '',
- playlist,
- internal: true,
- blacklistDuration: Infinity,
- // MEDIA_ERR_NETWORK
- code: 2
- }, request);
- }
-
- // if we already downloaded the sidx bytes in the container request, use them
- const {offset, length} = playlist.sidx.byterange;
-
- if (bytes.length >= (length + offset)) {
- return fin(err, {
- response: bytes.subarray(offset, offset + length),
- status: request.status,
- uri: request.uri
- });
- }
-
- // otherwise request sidx bytes
- this.request = this.vhs_.xhr({
- uri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders({byterange: playlist.sidx.byterange})
- }, fin);
- });
- }
-
- dispose() {
- this.trigger('dispose');
- this.stopRequest();
- this.loadedPlaylists_ = {};
- window.clearTimeout(this.minimumUpdatePeriodTimeout_);
- window.clearTimeout(this.mediaRequest_);
- window.clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- this.mediaRequest_ = null;
- this.minimumUpdatePeriodTimeout_ = null;
-
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
-
- this.off();
- }
-
- hasPendingRequest() {
- return this.request || this.mediaRequest_;
- }
-
- stopRequest() {
- if (this.request) {
- const oldRequest = this.request;
-
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- }
-
- media(playlist) {
- // getter
- if (!playlist) {
- return this.media_;
- }
-
- // setter
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- }
-
- const startingState = this.state;
-
- // find the playlist object if the target playlist has been specified by URI
- if (typeof playlist === 'string') {
- if (!this.masterPlaylistLoader_.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
- playlist = this.masterPlaylistLoader_.master.playlists[playlist];
- }
-
- const mediaChange = !this.media_ || playlist.id !== this.media_.id;
-
- // switch to previously loaded playlists immediately
- if (mediaChange &&
- this.loadedPlaylists_[playlist.id] &&
- this.loadedPlaylists_[playlist.id].endList) {
- this.state = 'HAVE_METADATA';
- this.media_ = playlist;
-
- // trigger media change if the active media has been updated
- if (mediaChange) {
- this.trigger('mediachanging');
- this.trigger('mediachange');
- }
- return;
- }
-
- // switching to the active playlist is a no-op
- if (!mediaChange) {
- return;
- }
-
- // switching from an already loaded playlist
- if (this.media_) {
- this.trigger('mediachanging');
- }
- this.addSidxSegments_(playlist, startingState, (sidxChanged) => {
- // everything is ready just continue to haveMetadata
- this.haveMetadata({startingState, playlist});
- });
- }
-
- haveMetadata({startingState, playlist}) {
- this.state = 'HAVE_METADATA';
- this.loadedPlaylists_[playlist.id] = playlist;
- this.mediaRequest_ = null;
-
- // This will trigger loadedplaylist
- this.refreshMedia_(playlist.id);
-
- // fire loadedmetadata the first time a media playlist is loaded
- // to resolve setup of media groups
- if (startingState === 'HAVE_MASTER') {
- this.trigger('loadedmetadata');
- } else {
- // trigger media change if the active media has been updated
- this.trigger('mediachange');
- }
- }
-
- pause() {
- if (this.masterPlaylistLoader_.createMupOnMedia_) {
- this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
- this.masterPlaylistLoader_.createMupOnMedia_ = null;
- }
- this.stopRequest();
- window.clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
- if (this.isMaster_) {
- window.clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_);
- this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
- }
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- }
- }
-
- load(isFinalRendition) {
- window.clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = null;
-
- const media = this.media();
-
- if (isFinalRendition) {
- const delay = media ? (media.targetDuration / 2) * 1000 : 5 * 1000;
-
- this.mediaUpdateTimeout = window.setTimeout(() => this.load(), delay);
- return;
- }
-
- // because the playlists are internal to the manifest, load should either load the
- // main manifest, or do nothing but trigger an event
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- // Check to see if this is the master loader and the MUP was cleared (this happens
- // when the loader was paused). `media` should be set at this point since one is always
- // set during `start()`.
- if (this.isMaster_ && !this.minimumUpdatePeriodTimeout_) {
- // Trigger minimumUpdatePeriod to refresh the master manifest
- this.trigger('minimumUpdatePeriod');
- // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
- this.updateMinimumUpdatePeriodTimeout_();
- }
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- }
-
- start() {
- this.started = true;
-
- // We don't need to request the master manifest again
- // Call this asynchronously to match the xhr request behavior below
- if (!this.isMaster_) {
- this.mediaRequest_ = window.setTimeout(() => this.haveMaster_(), 0);
- return;
- }
-
- this.requestMaster_((req, masterChanged) => {
- this.haveMaster_();
-
- if (!this.hasPendingRequest() && !this.media_) {
- this.media(this.masterPlaylistLoader_.master.playlists[0]);
- }
- });
- }
-
- requestMaster_(cb) {
- this.request = this.vhs_.xhr({
- uri: this.masterPlaylistLoader_.srcUrl,
- withCredentials: this.withCredentials
- }, (error, req) => {
- if (this.requestErrored_(error, req)) {
- if (this.state === 'HAVE_NOTHING') {
- this.started = false;
- }
- return;
- }
-
- const masterChanged = req.responseText !== this.masterPlaylistLoader_.masterXml_;
-
- this.masterPlaylistLoader_.masterXml_ = req.responseText;
-
- if (req.responseHeaders && req.responseHeaders.date) {
- this.masterLoaded_ = Date.parse(req.responseHeaders.date);
- } else {
- this.masterLoaded_ = Date.now();
- }
-
- this.masterPlaylistLoader_.srcUrl = resolveManifestRedirect(this.handleManifestRedirects, this.masterPlaylistLoader_.srcUrl, req);
-
- if (masterChanged) {
- this.handleMaster_();
- this.syncClientServerClock_(() => {
- return cb(req, masterChanged);
- });
- return;
- }
-
- return cb(req, masterChanged);
- });
-
- }
-
- /**
- * Parses the master xml for UTCTiming node to sync the client clock to the server
- * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
- *
- * @param {Function} done
- * Function to call when clock sync has completed
- */
- syncClientServerClock_(done) {
- const utcTiming = parseUTCTiming(this.masterPlaylistLoader_.masterXml_);
-
- // No UTCTiming element found in the mpd. Use Date header from mpd request as the
- // server clock
- if (utcTiming === null) {
- this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
- return done();
- }
-
- if (utcTiming.method === 'DIRECT') {
- this.masterPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
- return done();
- }
-
- this.request = this.vhs_.xhr({
- uri: resolveUrl(this.masterPlaylistLoader_.srcUrl, utcTiming.value),
- method: utcTiming.method,
- withCredentials: this.withCredentials
- }, (error, req) => {
- // disposed
- if (!this.request) {
- return;
- }
-
- if (error) {
- // sync request failed, fall back to using date header from mpd
- // TODO: log warning
- this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
- return done();
- }
-
- let serverTime;
-
- if (utcTiming.method === 'HEAD') {
- if (!req.responseHeaders || !req.responseHeaders.date) {
- // expected date header not preset, fall back to using date header from mpd
- // TODO: log warning
- serverTime = this.masterLoaded_;
- } else {
- serverTime = Date.parse(req.responseHeaders.date);
- }
- } else {
- serverTime = Date.parse(req.responseText);
- }
-
- this.masterPlaylistLoader_.clientOffset_ = serverTime - Date.now();
-
- done();
- });
- }
-
- haveMaster_() {
- this.state = 'HAVE_MASTER';
- if (this.isMaster_) {
- // We have the master playlist at this point, so
- // trigger this to allow MasterPlaylistController
- // to make an initial playlist selection
- this.trigger('loadedplaylist');
- } else if (!this.media_) {
- // no media playlist was specifically selected so select
- // the one the child playlist loader was created with
- this.media(this.childPlaylist_);
- }
- }
-
- handleMaster_() {
- // clear media request
- this.mediaRequest_ = null;
-
- let newMaster = parseMasterXml({
- masterXml: this.masterPlaylistLoader_.masterXml_,
- srcUrl: this.masterPlaylistLoader_.srcUrl,
- clientOffset: this.masterPlaylistLoader_.clientOffset_,
- sidxMapping: this.masterPlaylistLoader_.sidxMapping_
- });
- const oldMaster = this.masterPlaylistLoader_.master;
-
- // if we have an old master to compare the new master against
- if (oldMaster) {
- newMaster = updateMaster(oldMaster, newMaster, this.masterPlaylistLoader_.sidxMapping_);
- }
-
- // only update master if we have a new master
- this.masterPlaylistLoader_.master = newMaster ? newMaster : oldMaster;
- const location = this.masterPlaylistLoader_.master.locations && this.masterPlaylistLoader_.master.locations[0];
-
- if (location && location !== this.masterPlaylistLoader_.srcUrl) {
- this.masterPlaylistLoader_.srcUrl = location;
- }
-
- if (!oldMaster || (newMaster && newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod)) {
- this.updateMinimumUpdatePeriodTimeout_();
- }
-
- return Boolean(newMaster);
- }
-
- updateMinimumUpdatePeriodTimeout_() {
- const mpl = this.masterPlaylistLoader_;
-
- // cancel any pending creation of mup on media
- // a new one will be added if needed.
- if (mpl.createMupOnMedia_) {
- mpl.off('loadedmetadata', mpl.createMupOnMedia_);
- mpl.createMupOnMedia_ = null;
- }
-
- // clear any pending timeouts
- if (mpl.minimumUpdatePeriodTimeout_) {
- window.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
- mpl.minimumUpdatePeriodTimeout_ = null;
- }
-
- let mup = mpl.master && mpl.master.minimumUpdatePeriod;
-
- // If the minimumUpdatePeriod has a value of 0, that indicates that the current
- // MPD has no future validity, so a new one will need to be acquired when new
- // media segments are to be made available. Thus, we use the target duration
- // in this case
- if (mup === 0) {
- if (mpl.media()) {
- mup = mpl.media().targetDuration * 1000;
- } else {
- mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
- mpl.one('loadedmetadata', mpl.createMupOnMedia_);
- }
- }
-
- // if minimumUpdatePeriod is invalid or <= zero, which
- // can happen when a live video becomes VOD. skip timeout
- // creation.
- if (typeof mup !== 'number' || mup <= 0) {
- if (mup < 0) {
- this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
- }
- return;
- }
-
- this.createMUPTimeout_(mup);
- }
-
- createMUPTimeout_(mup) {
- const mpl = this.masterPlaylistLoader_;
-
- mpl.minimumUpdatePeriodTimeout_ = window.setTimeout(() => {
- mpl.minimumUpdatePeriodTimeout_ = null;
- mpl.trigger('minimumUpdatePeriod');
- mpl.createMUPTimeout_(mup);
- }, mup);
- }
-
- /**
- * Sends request to refresh the master xml and updates the parsed master manifest
- */
- refreshXml_() {
- this.requestMaster_((req, masterChanged) => {
- if (!masterChanged) {
- return;
- }
-
- if (this.media_) {
- this.media_ = this.masterPlaylistLoader_.master.playlists[this.media_.id];
- }
-
- // This will filter out updated sidx info from the mapping
- this.masterPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(
- this.masterPlaylistLoader_.master,
- this.masterPlaylistLoader_.sidxMapping_
- );
-
- this.addSidxSegments_(this.media(), this.state, (sidxChanged) => {
- // TODO: do we need to reload the current playlist?
- this.refreshMedia_(this.media().id);
- });
- });
- }
-
- /**
- * Refreshes the media playlist by re-parsing the master xml and updating playlist
- * references. If this is an alternate loader, the updated parsed manifest is retrieved
- * from the master loader.
- */
- refreshMedia_(mediaID) {
- if (!mediaID) {
- throw new Error('refreshMedia_ must take a media id');
- }
-
- // for master we have to reparse the master xml
- // to re-create segments based on current timing values
- // which may change media. We only skip updating master
- // if this is the first time this.media_ is being set.
- // as master was just parsed in that case.
- if (this.media_ && this.isMaster_) {
- this.handleMaster_();
- }
-
- const playlists = this.masterPlaylistLoader_.master.playlists;
- const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
-
- if (mediaChanged) {
- this.media_ = playlists[mediaID];
- } else {
- this.trigger('playlistunchanged');
- }
-
- if (!this.mediaUpdateTimeout) {
- const createMediaUpdateTimeout = () => {
- if (this.media().endList) {
- return;
- }
-
- this.mediaUpdateTimeout = window.setTimeout(() => {
- this.trigger('mediaupdatetimeout');
- createMediaUpdateTimeout();
- }, refreshDelay(this.media(), Boolean(mediaChanged)));
- };
-
- createMediaUpdateTimeout();
- }
-
- this.trigger('loadedplaylist');
- }
-}
diff --git a/node_modules/@videojs/http-streaming/src/decrypter-worker.js b/node_modules/@videojs/http-streaming/src/decrypter-worker.js
deleted file mode 100644
index 7551594..0000000
--- a/node_modules/@videojs/http-streaming/src/decrypter-worker.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* global self */
-import { Decrypter } from 'aes-decrypter';
-import { createTransferableMessage } from './bin-utils';
-
-/**
- * Our web worker interface so that things can talk to aes-decrypter
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- */
-self.onmessage = function(event) {
- const data = event.data;
- const encrypted = new Uint8Array(
- data.encrypted.bytes,
- data.encrypted.byteOffset,
- data.encrypted.byteLength
- );
- const key = new Uint32Array(
- data.key.bytes,
- data.key.byteOffset,
- data.key.byteLength / 4
- );
- const iv = new Uint32Array(
- data.iv.bytes,
- data.iv.byteOffset,
- data.iv.byteLength / 4
- );
-
- /* eslint-disable no-new, handle-callback-err */
- new Decrypter(
- encrypted,
- key,
- iv,
- function(err, bytes) {
- self.postMessage(createTransferableMessage({
- source: data.source,
- decrypted: bytes
- }), [bytes.buffer]);
- }
- );
- /* eslint-enable */
-};
diff --git a/node_modules/@videojs/http-streaming/src/decrypter-worker.worker.js b/node_modules/@videojs/http-streaming/src/decrypter-worker.worker.js
deleted file mode 100644
index 3745dfe..0000000
--- a/node_modules/@videojs/http-streaming/src/decrypter-worker.worker.js
+++ /dev/null
@@ -1,654 +0,0 @@
-/*! @name @videojs/http-streaming @version 2.5.0 @license Apache-2.0 */
-var decrypterWorker = (function () {
- 'use strict';
-
- 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);
- }
- }
-
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
-
- var createClass = _createClass;
-
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- subClass.__proto__ = superClass;
- }
-
- var inheritsLoose = _inheritsLoose;
-
- /**
- * @file stream.js
- */
-
- /**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
- var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
- }();
-
- /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
- /**
- * Returns the subarray of a Uint8Array without PKCS#7 padding.
- *
- * @param padded {Uint8Array} unencrypted bytes that have been padded
- * @return {Uint8Array} the unpadded bytes
- * @see http://tools.ietf.org/html/rfc5652
- */
-
- function unpad(padded) {
- return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
- }
-
- /*! @name aes-decrypter @version 3.1.2 @license Apache-2.0 */
- /**
- * @file aes.js
- *
- * This file contains an adaptation of the AES decryption algorithm
- * from the Standford Javascript Cryptography Library. That work is
- * covered by the following copyright and permissions notice:
- *
- * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. 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 AUTHORS ``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 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.
- *
- * The views and conclusions contained in the software and documentation
- * are those of the authors and should not be interpreted as representing
- * official policies, either expressed or implied, of the authors.
- */
-
- /**
- * Expand the S-box tables.
- *
- * @private
- */
-
- var precompute = function precompute() {
- var tables = [[[], [], [], [], []], [[], [], [], [], []]];
- var encTable = tables[0];
- var decTable = tables[1];
- var sbox = encTable[4];
- var sboxInv = decTable[4];
- var i;
- var x;
- var xInv;
- var d = [];
- var th = [];
- var x2;
- var x4;
- var x8;
- var s;
- var tEnc;
- var tDec; // Compute double and third tables
-
- for (i = 0; i < 256; i++) {
- th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
- }
-
- for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
- // Compute sbox
- s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
- s = s >> 8 ^ s & 255 ^ 99;
- sbox[x] = s;
- sboxInv[s] = x; // Compute MixColumns
-
- x8 = d[x4 = d[x2 = d[x]]];
- tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- tEnc = d[s] * 0x101 ^ s * 0x1010100;
-
- for (i = 0; i < 4; i++) {
- encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
- decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
- }
- } // Compactify. Considerable speedup on Firefox.
-
-
- for (i = 0; i < 5; i++) {
- encTable[i] = encTable[i].slice(0);
- decTable[i] = decTable[i].slice(0);
- }
-
- return tables;
- };
-
- var aesTables = null;
- /**
- * Schedule out an AES key for both encryption and decryption. This
- * is a low-level class. Use a cipher mode to do bulk encryption.
- *
- * @class AES
- * @param key {Array} The key as an array of 4, 6 or 8 words.
- */
-
- var AES = /*#__PURE__*/function () {
- function AES(key) {
- /**
- * The expanded S-box and inverse S-box tables. These will be computed
- * on the client so that we don't have to send them down the wire.
- *
- * There are two tables, _tables[0] is for encryption and
- * _tables[1] is for decryption.
- *
- * The first 4 sub-tables are the expanded S-box with MixColumns. The
- * last (_tables[01][4]) is the S-box itself.
- *
- * @private
- */
- // if we have yet to precompute the S-box tables
- // do so now
- if (!aesTables) {
- aesTables = precompute();
- } // then make a copy of that object for use
-
-
- this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
- var i;
- var j;
- var tmp;
- var sbox = this._tables[0][4];
- var decTable = this._tables[1];
- var keyLen = key.length;
- var rcon = 1;
-
- if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
- throw new Error('Invalid aes key size');
- }
-
- var encKey = key.slice(0);
- var decKey = [];
- this._key = [encKey, decKey]; // schedule encryption keys
-
- for (i = keyLen; i < 4 * keyLen + 28; i++) {
- tmp = encKey[i - 1]; // apply sbox
-
- if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
- tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
-
- if (i % keyLen === 0) {
- tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
- rcon = rcon << 1 ^ (rcon >> 7) * 283;
- }
- }
-
- encKey[i] = encKey[i - keyLen] ^ tmp;
- } // schedule decryption keys
-
-
- for (j = 0; i; j++, i--) {
- tmp = encKey[j & 3 ? i : i - 4];
-
- if (i <= 4 || j < 4) {
- decKey[j] = tmp;
- } else {
- decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
- }
- }
- }
- /**
- * Decrypt 16 bytes, specified as four 32-bit words.
- *
- * @param {number} encrypted0 the first word to decrypt
- * @param {number} encrypted1 the second word to decrypt
- * @param {number} encrypted2 the third word to decrypt
- * @param {number} encrypted3 the fourth word to decrypt
- * @param {Int32Array} out the array to write the decrypted words
- * into
- * @param {number} offset the offset into the output array to start
- * writing results
- * @return {Array} The plaintext.
- */
-
-
- var _proto = AES.prototype;
-
- _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
- var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
-
- var a = encrypted0 ^ key[0];
- var b = encrypted3 ^ key[1];
- var c = encrypted2 ^ key[2];
- var d = encrypted1 ^ key[3];
- var a2;
- var b2;
- var c2; // key.length === 2 ?
-
- var nInnerRounds = key.length / 4 - 2;
- var i;
- var kIndex = 4;
- var table = this._tables[1]; // load up the tables
-
- var table0 = table[0];
- var table1 = table[1];
- var table2 = table[2];
- var table3 = table[3];
- var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
-
- for (i = 0; i < nInnerRounds; i++) {
- a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
- b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
- c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
- d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
- kIndex += 4;
- a = a2;
- b = b2;
- c = c2;
- } // Last round.
-
-
- for (i = 0; i < 4; i++) {
- out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
- a2 = a;
- a = b;
- b = c;
- c = d;
- d = a2;
- }
- };
-
- return AES;
- }();
- /**
- * A wrapper around the Stream class to use setTimeout
- * and run stream "jobs" Asynchronously
- *
- * @class AsyncStream
- * @extends Stream
- */
-
-
- var AsyncStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(AsyncStream, _Stream);
-
- function AsyncStream() {
- var _this;
-
- _this = _Stream.call(this, Stream) || this;
- _this.jobs = [];
- _this.delay = 1;
- _this.timeout_ = null;
- return _this;
- }
- /**
- * process an async job
- *
- * @private
- */
-
-
- var _proto = AsyncStream.prototype;
-
- _proto.processJob_ = function processJob_() {
- this.jobs.shift()();
-
- if (this.jobs.length) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- } else {
- this.timeout_ = null;
- }
- }
- /**
- * push a job into the stream
- *
- * @param {Function} job the job to push into the stream
- */
- ;
-
- _proto.push = function push(job) {
- this.jobs.push(job);
-
- if (!this.timeout_) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- }
- };
-
- return AsyncStream;
- }(Stream);
- /**
- * Convert network-order (big-endian) bytes into their little-endian
- * representation.
- */
-
-
- var ntoh = function ntoh(word) {
- return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
- };
- /**
- * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * use for the first round of CBC.
- * @return {Uint8Array} the decrypted bytes
- *
- * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
- * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
- * @see https://tools.ietf.org/html/rfc2315
- */
-
-
- var decrypt = function decrypt(encrypted, key, initVector) {
- // word-level access to the encrypted bytes
- var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
- var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
-
- var decrypted = new Uint8Array(encrypted.byteLength);
- var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
- // decrypted data
-
- var init0;
- var init1;
- var init2;
- var init3;
- var encrypted0;
- var encrypted1;
- var encrypted2;
- var encrypted3; // iteration variable
-
- var wordIx; // pull out the words of the IV to ensure we don't modify the
- // passed-in reference and easier access
-
- init0 = initVector[0];
- init1 = initVector[1];
- init2 = initVector[2];
- init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
- // to each decrypted block
-
- for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
- // convert big-endian (network order) words into little-endian
- // (javascript order)
- encrypted0 = ntoh(encrypted32[wordIx]);
- encrypted1 = ntoh(encrypted32[wordIx + 1]);
- encrypted2 = ntoh(encrypted32[wordIx + 2]);
- encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
-
- decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
- // plaintext
-
- decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
- decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
- decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
- decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
-
- init0 = encrypted0;
- init1 = encrypted1;
- init2 = encrypted2;
- init3 = encrypted3;
- }
-
- return decrypted;
- };
- /**
- * The `Decrypter` class that manages decryption of AES
- * data through `AsyncStream` objects and the `decrypt`
- * function
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * @param {Function} done the function to run when done
- * @class Decrypter
- */
-
-
- var Decrypter = /*#__PURE__*/function () {
- function Decrypter(encrypted, key, initVector, done) {
- var step = Decrypter.STEP;
- var encrypted32 = new Int32Array(encrypted.buffer);
- var decrypted = new Uint8Array(encrypted.byteLength);
- var i = 0;
- this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
-
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
-
- for (i = step; i < encrypted32.length; i += step) {
- initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
- } // invoke the done() callback when everything is finished
-
-
- this.asyncStream_.push(function () {
- // remove pkcs#7 padding from the decrypted bytes
- done(null, unpad(decrypted));
- });
- }
- /**
- * a getter for step the maximum number of bytes to process at one time
- *
- * @return {number} the value of step 32000
- */
-
-
- var _proto = Decrypter.prototype;
- /**
- * @private
- */
-
- _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
- return function () {
- var bytes = decrypt(encrypted, key, initVector);
- decrypted.set(bytes, encrypted.byteOffset);
- };
- };
-
- createClass(Decrypter, null, [{
- key: "STEP",
- get: function get() {
- // 4 * 8000;
- return 32000;
- }
- }]);
-
- return Decrypter;
- }();
-
- /**
- * @file bin-utils.js
- */
- /**
- * Creates an object for sending to a web worker modifying properties that are TypedArrays
- * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
- *
- * @param {Object} message
- * Object of properties and values to send to the web worker
- * @return {Object}
- * Modified message with TypedArray values expanded
- * @function createTransferableMessage
- */
-
-
- var createTransferableMessage = function createTransferableMessage(message) {
- var transferable = {};
- Object.keys(message).forEach(function (key) {
- var value = message[key];
-
- if (ArrayBuffer.isView(value)) {
- transferable[key] = {
- bytes: value.buffer,
- byteOffset: value.byteOffset,
- byteLength: value.byteLength
- };
- } else {
- transferable[key] = value;
- }
- });
- return transferable;
- };
-
- /* global self */
- /**
- * Our web worker interface so that things can talk to aes-decrypter
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- *
- * @param {Object} self
- * the scope for the web worker
- */
-
- var DecrypterWorker = function DecrypterWorker(self) {
- self.onmessage = function (event) {
- var data = event.data;
- var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
- var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
- var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
- /* eslint-disable no-new, handle-callback-err */
-
- new Decrypter(encrypted, key, iv, function (err, bytes) {
- self.postMessage(createTransferableMessage({
- source: data.source,
- decrypted: bytes
- }), [bytes.buffer]);
- });
- /* eslint-enable */
- };
- };
-
- var decrypterWorker = new DecrypterWorker(self);
-
- return decrypterWorker;
-
-}());
diff --git a/node_modules/@videojs/http-streaming/src/error-codes.js b/node_modules/@videojs/http-streaming/src/error-codes.js
deleted file mode 100644
index 241c0c3..0000000
--- a/node_modules/@videojs/http-streaming/src/error-codes.js
+++ /dev/null
@@ -1,2 +0,0 @@
-// https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
-export const QUOTA_EXCEEDED_ERR = 22;
diff --git a/node_modules/@videojs/http-streaming/src/manifest.js b/node_modules/@videojs/http-streaming/src/manifest.js
deleted file mode 100644
index 9958749..0000000
--- a/node_modules/@videojs/http-streaming/src/manifest.js
+++ /dev/null
@@ -1,322 +0,0 @@
-import videojs from 'video.js';
-import window from 'global/window';
-import { Parser as M3u8Parser } from 'm3u8-parser';
-import { resolveUrl } from './resolve-url';
-import { getLastParts } from './playlist.js';
-
-const { log } = videojs;
-
-export const createPlaylistID = (index, uri) => {
- return `${index}-${uri}`;
-};
-
-/**
- * Parses a given m3u8 playlist
- *
- * @param {Function} [onwarn]
- * a function to call when the parser triggers a warning event.
- * @param {Function} [oninfo]
- * a function to call when the parser triggers an info event.
- * @param {string} manifestString
- * The downloaded manifest string
- * @param {Object[]} [customTagParsers]
- * An array of custom tag parsers for the m3u8-parser instance
- * @param {Object[]} [customTagMappers]
- * An array of custom tag mappers for the m3u8-parser instance
- * @param {boolean} [experimentalLLHLS=false]
- * Whether to keep ll-hls features in the manifest after parsing.
- * @return {Object}
- * The manifest object
- */
-export const parseManifest = ({
- onwarn,
- oninfo,
- manifestString,
- customTagParsers = [],
- customTagMappers = [],
- experimentalLLHLS
-}) => {
- const parser = new M3u8Parser();
-
- if (onwarn) {
- parser.on('warn', onwarn);
- }
- if (oninfo) {
- parser.on('info', oninfo);
- }
-
- customTagParsers.forEach(customParser => parser.addParser(customParser));
- customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
-
- parser.push(manifestString);
- parser.end();
-
- const manifest = parser.manifest;
-
- // remove llhls features from the parsed manifest
- // if we don't want llhls support.
- if (!experimentalLLHLS) {
- [
- 'preloadSegment',
- 'skip',
- 'serverControl',
- 'renditionReports',
- 'partInf',
- 'partTargetDuration'
- ].forEach(function(k) {
- if (manifest.hasOwnProperty(k)) {
- delete manifest[k];
- }
- });
-
- if (manifest.segments) {
- manifest.segments.forEach(function(segment) {
- ['parts', 'preloadHints'].forEach(function(k) {
- if (segment.hasOwnProperty(k)) {
- delete segment[k];
- }
- });
- });
- }
- }
- if (!manifest.targetDuration) {
- let targetDuration = 10;
-
- if (manifest.segments && manifest.segments.length) {
- targetDuration = manifest
- .segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
- }
-
- if (onwarn) {
- onwarn(`manifest has no targetDuration defaulting to ${targetDuration}`);
- }
- manifest.targetDuration = targetDuration;
- }
-
- const parts = getLastParts(manifest);
-
- if (parts.length && !manifest.partTargetDuration) {
- const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
-
- if (onwarn) {
- onwarn(`manifest has no partTargetDuration defaulting to ${partTargetDuration}`);
- log.error('LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.');
- }
- manifest.partTargetDuration = partTargetDuration;
- }
-
- return manifest;
-};
-
-/**
- * Loops through all supported media groups in master and calls the provided
- * callback for each group
- *
- * @param {Object} master
- * The parsed master manifest object
- * @param {Function} callback
- * Callback to call for each media group
- */
-export const forEachMediaGroup = (master, callback) => {
- if (!master.mediaGroups) {
- return;
- }
- ['AUDIO', 'SUBTITLES'].forEach((mediaType) => {
- if (!master.mediaGroups[mediaType]) {
- return;
- }
- for (const groupKey in master.mediaGroups[mediaType]) {
- for (const labelKey in master.mediaGroups[mediaType][groupKey]) {
- const mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
-
- callback(mediaProperties, mediaType, groupKey, labelKey);
- }
- }
- });
-};
-
-/**
- * Adds properties and attributes to the playlist to keep consistent functionality for
- * playlists throughout VHS.
- *
- * @param {Object} config
- * Arguments object
- * @param {Object} config.playlist
- * The media playlist
- * @param {string} [config.uri]
- * The uri to the media playlist (if media playlist is not from within a master
- * playlist)
- * @param {string} id
- * ID to use for the playlist
- */
-export const setupMediaPlaylist = ({ playlist, uri, id }) => {
- playlist.id = id;
- playlist.playlistErrors_ = 0;
-
- if (uri) {
- // For media playlists, m3u8-parser does not have access to a URI, as HLS media
- // playlists do not contain their own source URI, but one is needed for consistency in
- // VHS.
- playlist.uri = uri;
- }
-
- // For HLS master playlists, even though certain attributes MUST be defined, the
- // stream may still be played without them.
- // For HLS media playlists, m3u8-parser does not attach an attributes object to the
- // manifest.
- //
- // To avoid undefined reference errors through the project, and make the code easier
- // to write/read, add an empty attributes object for these cases.
- playlist.attributes = playlist.attributes || {};
-};
-
-/**
- * Adds ID, resolvedUri, and attributes properties to each playlist of the master, where
- * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
- * playlist references to the playlists array.
- *
- * @param {Object} master
- * The master playlist
- */
-export const setupMediaPlaylists = (master) => {
- let i = master.playlists.length;
-
- while (i--) {
- const playlist = master.playlists[i];
-
- setupMediaPlaylist({
- playlist,
- id: createPlaylistID(i, playlist.uri)
- });
- playlist.resolvedUri = resolveUrl(master.uri, playlist.uri);
- master.playlists[playlist.id] = playlist;
- // URI reference added for backwards compatibility
- master.playlists[playlist.uri] = playlist;
-
- // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
- // the stream can be played without it. Although an attributes property may have been
- // added to the playlist to prevent undefined references, issue a warning to fix the
- // manifest.
- if (!playlist.attributes.BANDWIDTH) {
- log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
- }
- }
-};
-
-/**
- * Adds resolvedUri properties to each media group.
- *
- * @param {Object} master
- * The master playlist
- */
-export const resolveMediaGroupUris = (master) => {
- forEachMediaGroup(master, (properties) => {
- if (properties.uri) {
- properties.resolvedUri = resolveUrl(master.uri, properties.uri);
- }
- });
-};
-
-/**
- * Creates a master playlist wrapper to insert a sole media playlist into.
- *
- * @param {Object} media
- * Media playlist
- * @param {string} uri
- * The media URI
- *
- * @return {Object}
- * Master playlist
- */
-export const masterForMedia = (media, uri) => {
- const id = createPlaylistID(0, uri);
- const master = {
- mediaGroups: {
- 'AUDIO': {},
- 'VIDEO': {},
- 'CLOSED-CAPTIONS': {},
- 'SUBTITLES': {}
- },
- uri: window.location.href,
- resolvedUri: window.location.href,
- playlists: [{
- uri,
- id,
- resolvedUri: uri,
- // m3u8-parser does not attach an attributes property to media playlists so make
- // sure that the property is attached to avoid undefined reference errors
- attributes: {}
- }]
- };
-
- // set up ID reference
- master.playlists[id] = master.playlists[0];
- // URI reference added for backwards compatibility
- master.playlists[uri] = master.playlists[0];
-
- return master;
-};
-
-/**
- * Does an in-place update of the master manifest to add updated playlist URI references
- * as well as other properties needed by VHS that aren't included by the parser.
- *
- * @param {Object} master
- * Master manifest object
- * @param {string} uri
- * The source URI
- */
-export const addPropertiesToMaster = (master, uri) => {
- master.uri = uri;
-
- for (let i = 0; i < master.playlists.length; i++) {
- if (!master.playlists[i].uri) {
- // Set up phony URIs for the playlists since playlists are referenced by their URIs
- // throughout VHS, but some formats (e.g., DASH) don't have external URIs
- // TODO: consider adding dummy URIs in mpd-parser
- const phonyUri = `placeholder-uri-${i}`;
-
- master.playlists[i].uri = phonyUri;
- }
- }
-
- forEachMediaGroup(master, (properties, mediaType, groupKey, labelKey) => {
- const groupId = `placeholder-uri-${mediaType}-${groupKey}-${labelKey}`;
-
- if (!properties.playlists || !properties.playlists.length) {
- properties.playlists = [Object.assign({}, properties)];
- }
-
- properties.playlists.forEach(function(p, i) {
- const id = createPlaylistID(i, groupId);
-
- if (p.uri) {
- p.resolvedUri = p.resolvedUri || resolveUrl(master.uri, p.uri);
- } else {
- // DEPRECATED, this has been added to prevent a breaking change.
- // previously we only ever had a single media group playlist, so
- // we mark the first playlist uri without prepending the index as we used to
- // ideally we would do all of the playlists the same way.
- p.uri = i === 0 ? groupId : id;
-
- // don't resolve a placeholder uri to an absolute url, just use
- // the placeholder again
- p.resolvedUri = p.uri;
- }
-
- p.id = p.id || id;
-
- // add an empty attributes object, all playlists are
- // expected to have this.
- p.attributes = p.attributes || {};
-
- // setup ID and URI references (URI for backwards compatibility)
- master.playlists[p.id] = p;
- master.playlists[p.uri] = p;
- });
-
- });
-
- setupMediaPlaylists(master);
- resolveMediaGroupUris(master);
-};
diff --git a/node_modules/@videojs/http-streaming/src/master-playlist-controller.js b/node_modules/@videojs/http-streaming/src/master-playlist-controller.js
deleted file mode 100644
index 949fb25..0000000
--- a/node_modules/@videojs/http-streaming/src/master-playlist-controller.js
+++ /dev/null
@@ -1,1944 +0,0 @@
-/**
- * @file master-playlist-controller.js
- */
-import window from 'global/window';
-import PlaylistLoader from './playlist-loader';
-import DashPlaylistLoader from './dash-playlist-loader';
-import { isEnabled, isLowestEnabledRendition } from './playlist.js';
-import SegmentLoader from './segment-loader';
-import SourceUpdater from './source-updater';
-import VTTSegmentLoader from './vtt-segment-loader';
-import * as Ranges from './ranges';
-import videojs from 'video.js';
-import { updateAdCues } from './ad-cue-tags';
-import SyncController from './sync-controller';
-import TimelineChangeController from './timeline-change-controller';
-import Decrypter from 'worker!./decrypter-worker.js';
-import Config from './config';
-import {
- parseCodecs,
- browserSupportsCodec,
- muxerSupportsCodec,
- DEFAULT_AUDIO_CODEC,
- DEFAULT_VIDEO_CODEC
-} from '@videojs/vhs-utils/es/codecs.js';
-import { codecsForPlaylist, unwrapCodecList, codecCount } from './util/codecs.js';
-import { createMediaTypes, setupMediaGroups } from './media-groups';
-import logger from './util/logger';
-
-const ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
-
-let Vhs;
-
-// SegmentLoader stats that need to have each loader's
-// values summed to calculate the final value
-const loaderStats = [
- 'mediaRequests',
- 'mediaRequestsAborted',
- 'mediaRequestsTimedout',
- 'mediaRequestsErrored',
- 'mediaTransferDuration',
- 'mediaBytesTransferred',
- 'mediaAppends'
-];
-const sumLoaderStat = function(stat) {
- return this.audioSegmentLoader_[stat] +
- this.mainSegmentLoader_[stat];
-};
-const shouldSwitchToMedia = function({
- currentPlaylist,
- nextPlaylist,
- forwardBuffer,
- bufferLowWaterLine,
- bufferHighWaterLine,
- duration,
- experimentalBufferBasedABR,
- log
-}) {
- // we have no other playlist to switch to
- if (!nextPlaylist) {
- videojs.log.warn('We received no playlist to switch to. Please check your stream.');
- return false;
- }
-
- const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
-
- // If the playlist is live, then we want to not take low water line into account.
- // This is because in LIVE, the player plays 3 segments from the end of the
- // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
- // in those segments, a viewer will never experience a rendition upswitch.
- if (!currentPlaylist || !currentPlaylist.endList) {
- log(`${sharedLogLine} as current playlist ` + (!currentPlaylist ? 'is not set' : 'is live'));
- return true;
- }
-
- // no need to switch playlist is the same
- if (nextPlaylist.id === currentPlaylist.id) {
- return false;
- }
-
- const maxBufferLowWaterLine = experimentalBufferBasedABR ?
- Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE;
-
- // For the same reason as LIVE, we ignore the low water line when the VOD
- // duration is below the max potential low water line
- if (duration < maxBufferLowWaterLine) {
- log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
- return true;
- }
-
- const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
- const currBandwidth = currentPlaylist.attributes.BANDWIDTH;
-
- // when switching down, if our buffer is lower than the high water line,
- // we can switch down
- if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
- let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
-
- if (experimentalBufferBasedABR) {
- logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
- }
- log(logLine);
- return true;
- }
-
- // and if our buffer is higher than the low water line,
- // we can switch up
- if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
- let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
-
- if (experimentalBufferBasedABR) {
- logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
- }
- log(logLine);
- return true;
- }
-
- log(`not ${sharedLogLine} as no switching criteria met`);
-
- return false;
-};
-
-/**
- * the master playlist controller controller all interactons
- * between playlists and segmentloaders. At this time this mainly
- * involves a master playlist and a series of audio playlists
- * if they are available
- *
- * @class MasterPlaylistController
- * @extends videojs.EventTarget
- */
-export class MasterPlaylistController extends videojs.EventTarget {
- constructor(options) {
- super();
-
- const {
- src,
- handleManifestRedirects,
- withCredentials,
- tech,
- bandwidth,
- externVhs,
- useCueTags,
- blacklistDuration,
- enableLowInitialPlaylist,
- sourceType,
- cacheEncryptionKeys,
- experimentalBufferBasedABR
- } = options;
-
- if (!src) {
- throw new Error('A non-empty playlist URL or JSON manifest string is required');
- }
-
- let { maxPlaylistRetries } = options;
-
- if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
- maxPlaylistRetries = Infinity;
- }
-
- Vhs = externVhs;
-
- this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
- this.withCredentials = withCredentials;
- this.tech_ = tech;
- this.vhs_ = tech.vhs;
- this.sourceType_ = sourceType;
- this.useCueTags_ = useCueTags;
- this.blacklistDuration = blacklistDuration;
- this.maxPlaylistRetries = maxPlaylistRetries;
- this.enableLowInitialPlaylist = enableLowInitialPlaylist;
- if (this.useCueTags_) {
- this.cueTagsTrack_ = this.tech_.addTextTrack(
- 'metadata',
- 'ad-cues'
- );
- this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
- }
-
- this.requestOptions_ = {
- withCredentials,
- handleManifestRedirects,
- maxPlaylistRetries,
- timeout: null
- };
-
- this.on('error', this.pauseLoading);
-
- this.mediaTypes_ = createMediaTypes();
-
- this.mediaSource = new window.MediaSource();
-
- this.handleDurationChange_ = this.handleDurationChange_.bind(this);
- this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
- this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
-
- this.mediaSource.addEventListener('durationchange', this.handleDurationChange_);
-
- // load the media source into the player
- this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
- this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_);
- // we don't have to handle sourceclose since dispose will handle termination of
- // everything, and the MediaSource should not be detached without a proper disposal
-
- this.seekable_ = videojs.createTimeRanges();
- this.hasPlayed_ = false;
-
- this.syncController_ = new SyncController(options);
- this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'segment-metadata'
- }, false).track;
-
- this.decrypter_ = new Decrypter();
- this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
- this.inbandTextTracks_ = {};
- this.timelineChangeController_ = new TimelineChangeController();
-
- const segmentLoaderSettings = {
- vhs: this.vhs_,
- parse708captions: options.parse708captions,
- mediaSource: this.mediaSource,
- currentTime: this.tech_.currentTime.bind(this.tech_),
- seekable: () => this.seekable(),
- seeking: () => this.tech_.seeking(),
- duration: () => this.duration(),
- hasPlayed: () => this.hasPlayed_,
- goalBufferLength: () => this.goalBufferLength(),
- bandwidth,
- syncController: this.syncController_,
- decrypter: this.decrypter_,
- sourceType: this.sourceType_,
- inbandTextTracks: this.inbandTextTracks_,
- cacheEncryptionKeys,
- sourceUpdater: this.sourceUpdater_,
- timelineChangeController: this.timelineChangeController_
- };
-
- // The source type check not only determines whether a special DASH playlist loader
- // should be used, but also covers the case where the provided src is a vhs-json
- // manifest object (instead of a URL). In the case of vhs-json, the default
- // PlaylistLoader should be used.
- this.masterPlaylistLoader_ = this.sourceType_ === 'dash' ?
- new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) :
- new PlaylistLoader(src, this.vhs_, this.requestOptions_);
- this.setupMasterPlaylistLoaderListeners_();
-
- // setup segment loaders
- // combined audio/video or just video when alternate audio track is selected
- this.mainSegmentLoader_ =
- new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
- segmentMetadataTrack: this.segmentMetadataTrack_,
- loaderType: 'main'
- }), options);
-
- // alternate audio track
- this.audioSegmentLoader_ =
- new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
- loaderType: 'audio'
- }), options);
-
- this.subtitleSegmentLoader_ =
- new VTTSegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
- loaderType: 'vtt',
- featuresNativeTextTracks: this.tech_.featuresNativeTextTracks
- }), options);
-
- this.setupSegmentLoaderListeners_();
-
- if (this.experimentalBufferBasedABR) {
- this.masterPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
- this.tech_.on('pause', () => this.stopABRTimer_());
- this.tech_.on('play', () => this.startABRTimer_());
- }
-
- // Create SegmentLoader stat-getters
- // mediaRequests_
- // mediaRequestsAborted_
- // mediaRequestsTimedout_
- // mediaRequestsErrored_
- // mediaTransferDuration_
- // mediaBytesTransferred_
- // mediaAppends_
- loaderStats.forEach((stat) => {
- this[stat + '_'] = sumLoaderStat.bind(this, stat);
- });
-
- this.logger_ = logger('MPC');
-
- this.triggeredFmp4Usage = false;
- if (this.tech_.preload() === 'none') {
- this.loadOnPlay_ = () => {
- this.loadOnPlay_ = null;
- this.masterPlaylistLoader_.load();
- };
-
- this.tech_.one('play', this.loadOnPlay_);
- } else {
- this.masterPlaylistLoader_.load();
- }
-
- this.timeToLoadedData__ = -1;
- this.mainAppendsToLoadedData__ = -1;
- this.audioAppendsToLoadedData__ = -1;
-
- const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart';
-
- // start the first frame timer on loadstart or play (for preload none)
- this.tech_.one(event, () => {
- const timeToLoadedDataStart = Date.now();
-
- this.tech_.one('loadeddata', () => {
- this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
- this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
- this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
- });
- });
- }
-
- mainAppendsToLoadedData_() {
- return this.mainAppendsToLoadedData__;
- }
-
- audioAppendsToLoadedData_() {
- return this.audioAppendsToLoadedData__;
- }
-
- appendsToLoadedData_() {
- const main = this.mainAppendsToLoadedData_();
- const audio = this.audioAppendsToLoadedData_();
-
- if (main === -1 || audio === -1) {
- return -1;
- }
-
- return main + audio;
- }
-
- timeToLoadedData_() {
- return this.timeToLoadedData__;
- }
-
- /**
- * Run selectPlaylist and switch to the new playlist if we should
- *
- * @private
- *
- */
- checkABR_() {
- const nextPlaylist = this.selectPlaylist();
-
- if (this.shouldSwitchToMedia_(nextPlaylist)) {
- this.switchMedia_(nextPlaylist, 'abr');
- }
- }
-
- switchMedia_(playlist, cause, delay) {
- const oldMedia = this.media();
- const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
- const newId = playlist.id || playlist.uri;
-
- if (oldId && oldId !== newId) {
- this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
- this.tech_.trigger({type: 'usage', name: `vhs-rendition-change-${cause}`});
- }
- this.masterPlaylistLoader_.media(playlist, delay);
- }
-
- /**
- * Start a timer that periodically calls checkABR_
- *
- * @private
- */
- startABRTimer_() {
- this.stopABRTimer_();
- this.abrTimer_ = window.setInterval(() => this.checkABR_(), 250);
- }
-
- /**
- * Stop the timer that periodically calls checkABR_
- *
- * @private
- */
- stopABRTimer_() {
- // if we're scrubbing, we don't need to pause.
- // This getter will be added to Video.js in version 7.11.
- if (this.tech_.scrubbing && this.tech_.scrubbing()) {
- return;
- }
- window.clearInterval(this.abrTimer_);
- this.abrTimer_ = null;
- }
-
- /**
- * Get a list of playlists for the currently selected audio playlist
- *
- * @return {Array} the array of audio playlists
- */
- getAudioTrackPlaylists_() {
- const master = this.master();
-
- // if we don't have any audio groups then we can only
- // assume that the audio tracks are contained in masters
- // playlist array, use that or an empty array.
- if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
- return master && master.playlists || [];
- }
-
- const AUDIO = master.mediaGroups.AUDIO;
- const groupKeys = Object.keys(AUDIO);
- let track;
-
- // get the current active track
- if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
- track = this.mediaTypes_.AUDIO.activeTrack();
- // or get the default track from master if mediaTypes_ isn't setup yet
- } else {
- // default group is `main` or just the first group.
- const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
-
- for (const label in defaultGroup) {
- if (defaultGroup[label].default) {
- track = {label};
- break;
- }
- }
- }
-
- // no active track no playlists.
- if (!track) {
- return [];
- }
-
- const playlists = [];
-
- // get all of the playlists that are possible for the
- // active track.
- for (const group in AUDIO) {
- if (AUDIO[group][track.label]) {
- const properties = AUDIO[group][track.label];
-
- if (properties.playlists) {
- playlists.push.apply(playlists, properties.playlists);
- } else {
- playlists.push(properties);
- }
- }
- }
-
- return playlists;
- }
-
- /**
- * Register event handlers on the master playlist loader. A helper
- * function for construction time.
- *
- * @private
- */
- setupMasterPlaylistLoaderListeners_() {
- this.masterPlaylistLoader_.on('loadedmetadata', () => {
- const media = this.masterPlaylistLoader_.media();
- const requestTimeout = (media.targetDuration * 1.5) * 1000;
-
- // If we don't have any more available playlists, we don't want to
- // timeout the request.
- if (isLowestEnabledRendition(this.masterPlaylistLoader_.master, this.masterPlaylistLoader_.media())) {
- this.requestOptions_.timeout = 0;
- } else {
- this.requestOptions_.timeout = requestTimeout;
- }
-
- // if this isn't a live video and preload permits, start
- // downloading segments
- if (media.endList && this.tech_.preload() !== 'none') {
- this.mainSegmentLoader_.playlist(media, this.requestOptions_);
- this.mainSegmentLoader_.load();
- }
-
- setupMediaGroups({
- sourceType: this.sourceType_,
- segmentLoaders: {
- AUDIO: this.audioSegmentLoader_,
- SUBTITLES: this.subtitleSegmentLoader_,
- main: this.mainSegmentLoader_
- },
- tech: this.tech_,
- requestOptions: this.requestOptions_,
- masterPlaylistLoader: this.masterPlaylistLoader_,
- vhs: this.vhs_,
- master: this.master(),
- mediaTypes: this.mediaTypes_,
- blacklistCurrentPlaylist: this.blacklistCurrentPlaylist.bind(this)
- });
-
- this.triggerPresenceUsage_(this.master(), media);
- this.setupFirstPlay();
-
- if (!this.mediaTypes_.AUDIO.activePlaylistLoader ||
- this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
- this.trigger('selectedinitialmedia');
- } else {
- // We must wait for the active audio playlist loader to
- // finish setting up before triggering this event so the
- // representations API and EME setup is correct
- this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
- this.trigger('selectedinitialmedia');
- });
- }
-
- });
-
- this.masterPlaylistLoader_.on('loadedplaylist', () => {
- if (this.loadOnPlay_) {
- this.tech_.off('play', this.loadOnPlay_);
- }
- let updatedPlaylist = this.masterPlaylistLoader_.media();
-
- if (!updatedPlaylist) {
- // exclude any variants that are not supported by the browser before selecting
- // an initial media as the playlist selectors do not consider browser support
- this.excludeUnsupportedVariants_();
-
- let selectedMedia;
-
- if (this.enableLowInitialPlaylist) {
- selectedMedia = this.selectInitialPlaylist();
- }
-
- if (!selectedMedia) {
- selectedMedia = this.selectPlaylist();
- }
-
- if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
- return;
- }
-
- this.initialMedia_ = selectedMedia;
-
- this.switchMedia_(this.initialMedia_, 'initial');
-
- // Under the standard case where a source URL is provided, loadedplaylist will
- // fire again since the playlist will be requested. In the case of vhs-json
- // (where the manifest object is provided as the source), when the media
- // playlist's `segments` list is already available, a media playlist won't be
- // requested, and loadedplaylist won't fire again, so the playlist handler must be
- // called on its own here.
- const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
-
- if (!haveJsonSource) {
- return;
- }
- updatedPlaylist = this.initialMedia_;
- }
-
- this.handleUpdatedMediaPlaylist(updatedPlaylist);
- });
-
- this.masterPlaylistLoader_.on('error', () => {
- this.blacklistCurrentPlaylist(this.masterPlaylistLoader_.error);
- });
-
- this.masterPlaylistLoader_.on('mediachanging', () => {
- this.mainSegmentLoader_.abort();
- this.mainSegmentLoader_.pause();
- });
-
- this.masterPlaylistLoader_.on('mediachange', () => {
- const media = this.masterPlaylistLoader_.media();
- const requestTimeout = (media.targetDuration * 1.5) * 1000;
-
- // If we don't have any more available playlists, we don't want to
- // timeout the request.
- if (isLowestEnabledRendition(this.masterPlaylistLoader_.master, this.masterPlaylistLoader_.media())) {
- this.requestOptions_.timeout = 0;
- } else {
- this.requestOptions_.timeout = requestTimeout;
- }
-
- // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `loadedplaylist`
- this.mainSegmentLoader_.playlist(media, this.requestOptions_);
-
- this.mainSegmentLoader_.load();
-
- this.tech_.trigger({
- type: 'mediachange',
- bubbles: true
- });
- });
-
- this.masterPlaylistLoader_.on('playlistunchanged', () => {
- const updatedPlaylist = this.masterPlaylistLoader_.media();
-
- // ignore unchanged playlists that have already been
- // excluded for not-changing. We likely just have a really slowly updating
- // playlist.
- if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
- return;
- }
-
- const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
-
- if (playlistOutdated) {
- // Playlist has stopped updating and we're stuck at its end. Try to
- // blacklist it and switch to another playlist in the hope that that
- // one is updating (and give the player a chance to re-adjust to the
- // safe live point).
- this.blacklistCurrentPlaylist({
- message: 'Playlist no longer updating.',
- reason: 'playlist-unchanged'
- });
- // useful for monitoring QoS
- this.tech_.trigger('playliststuck');
- }
- });
-
- this.masterPlaylistLoader_.on('renditiondisabled', () => {
- this.tech_.trigger({type: 'usage', name: 'vhs-rendition-disabled'});
- this.tech_.trigger({type: 'usage', name: 'hls-rendition-disabled'});
- });
- this.masterPlaylistLoader_.on('renditionenabled', () => {
- this.tech_.trigger({type: 'usage', name: 'vhs-rendition-enabled'});
- this.tech_.trigger({type: 'usage', name: 'hls-rendition-enabled'});
- });
- }
-
- /**
- * Given an updated media playlist (whether it was loaded for the first time, or
- * refreshed for live playlists), update any relevant properties and state to reflect
- * changes in the media that should be accounted for (e.g., cues and duration).
- *
- * @param {Object} updatedPlaylist the updated media playlist object
- *
- * @private
- */
- handleUpdatedMediaPlaylist(updatedPlaylist) {
- if (this.useCueTags_) {
- this.updateAdCues_(updatedPlaylist);
- }
-
- // TODO: Create a new event on the PlaylistLoader that signals
- // that the segments have changed in some way and use that to
- // update the SegmentLoader instead of doing it twice here and
- // on `mediachange`
- this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
- this.updateDuration(!updatedPlaylist.endList);
-
- // If the player isn't paused, ensure that the segment loader is running,
- // as it is possible that it was temporarily stopped while waiting for
- // a playlist (e.g., in case the playlist errored and we re-requested it).
- if (!this.tech_.paused()) {
- this.mainSegmentLoader_.load();
- if (this.audioSegmentLoader_) {
- this.audioSegmentLoader_.load();
- }
- }
- }
-
- /**
- * A helper function for triggerring presence usage events once per source
- *
- * @private
- */
- triggerPresenceUsage_(master, media) {
- const mediaGroups = master.mediaGroups || {};
- let defaultDemuxed = true;
- const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
-
- for (const mediaGroup in mediaGroups.AUDIO) {
- for (const label in mediaGroups.AUDIO[mediaGroup]) {
- const properties = mediaGroups.AUDIO[mediaGroup][label];
-
- if (!properties.uri) {
- defaultDemuxed = false;
- }
- }
- }
-
- if (defaultDemuxed) {
- this.tech_.trigger({type: 'usage', name: 'vhs-demuxed'});
- this.tech_.trigger({type: 'usage', name: 'hls-demuxed'});
- }
-
- if (Object.keys(mediaGroups.SUBTITLES).length) {
- this.tech_.trigger({type: 'usage', name: 'vhs-webvtt'});
- this.tech_.trigger({type: 'usage', name: 'hls-webvtt'});
- }
-
- if (Vhs.Playlist.isAes(media)) {
- this.tech_.trigger({type: 'usage', name: 'vhs-aes'});
- this.tech_.trigger({type: 'usage', name: 'hls-aes'});
- }
-
- if (audioGroupKeys.length &&
- Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
- this.tech_.trigger({type: 'usage', name: 'vhs-alternate-audio'});
- this.tech_.trigger({type: 'usage', name: 'hls-alternate-audio'});
- }
-
- if (this.useCueTags_) {
- this.tech_.trigger({type: 'usage', name: 'vhs-playlist-cue-tags'});
- this.tech_.trigger({type: 'usage', name: 'hls-playlist-cue-tags'});
- }
- }
-
- shouldSwitchToMedia_(nextPlaylist) {
- const currentPlaylist = this.masterPlaylistLoader_.media();
- const buffered = this.tech_.buffered();
- const forwardBuffer = buffered.length ?
- buffered.end(buffered.length - 1) - this.tech_.currentTime() : 0;
-
- const bufferLowWaterLine = this.bufferLowWaterLine();
- const bufferHighWaterLine = this.bufferHighWaterLine();
-
- return shouldSwitchToMedia({
- currentPlaylist,
- nextPlaylist,
- forwardBuffer,
- bufferLowWaterLine,
- bufferHighWaterLine,
- duration: this.duration(),
- experimentalBufferBasedABR: this.experimentalBufferBasedABR,
- log: this.logger_
- });
- }
- /**
- * Register event handlers on the segment loaders. A helper function
- * for construction time.
- *
- * @private
- */
- setupSegmentLoaderListeners_() {
- if (!this.experimentalBufferBasedABR) {
- this.mainSegmentLoader_.on('bandwidthupdate', () => {
- const nextPlaylist = this.selectPlaylist();
-
- if (this.shouldSwitchToMedia_(nextPlaylist)) {
- this.switchMedia_(nextPlaylist, 'bandwidthupdate');
- }
-
- this.tech_.trigger('bandwidthupdate');
- });
-
- this.mainSegmentLoader_.on('progress', () => {
- this.trigger('progress');
- });
- }
-
- this.mainSegmentLoader_.on('error', () => {
- this.blacklistCurrentPlaylist(this.mainSegmentLoader_.error());
- });
-
- this.mainSegmentLoader_.on('appenderror', () => {
- this.error = this.mainSegmentLoader_.error_;
- this.trigger('error');
- });
-
- this.mainSegmentLoader_.on('syncinfoupdate', () => {
- this.onSyncInfoUpdate_();
- });
-
- this.mainSegmentLoader_.on('timestampoffset', () => {
- this.tech_.trigger({type: 'usage', name: 'vhs-timestamp-offset'});
- this.tech_.trigger({type: 'usage', name: 'hls-timestamp-offset'});
- });
- this.audioSegmentLoader_.on('syncinfoupdate', () => {
- this.onSyncInfoUpdate_();
- });
-
- this.audioSegmentLoader_.on('appenderror', () => {
- this.error = this.audioSegmentLoader_.error_;
- this.trigger('error');
- });
-
- this.mainSegmentLoader_.on('ended', () => {
- this.logger_('main segment loader ended');
- this.onEndOfStream();
- });
-
- this.mainSegmentLoader_.on('earlyabort', (event) => {
- // never try to early abort with the new ABR algorithm
- if (this.experimentalBufferBasedABR) {
- return;
- }
-
- this.delegateLoaders_('all', ['abort']);
-
- this.blacklistCurrentPlaylist({
- message: 'Aborted early because there isn\'t enough bandwidth to complete the ' +
- 'request without rebuffering.'
- }, ABORT_EARLY_BLACKLIST_SECONDS);
- });
-
- const updateCodecs = () => {
- if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
- return this.tryToCreateSourceBuffers_();
- }
-
- const codecs = this.getCodecsOrExclude_();
-
- // no codecs means that the playlist was excluded
- if (!codecs) {
- return;
- }
-
- this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
- };
-
- this.mainSegmentLoader_.on('trackinfo', updateCodecs);
- this.audioSegmentLoader_.on('trackinfo', updateCodecs);
-
- this.mainSegmentLoader_.on('fmp4', () => {
- if (!this.triggeredFmp4Usage) {
- this.tech_.trigger({type: 'usage', name: 'vhs-fmp4'});
- this.tech_.trigger({type: 'usage', name: 'hls-fmp4'});
- this.triggeredFmp4Usage = true;
- }
- });
-
- this.audioSegmentLoader_.on('fmp4', () => {
- if (!this.triggeredFmp4Usage) {
- this.tech_.trigger({type: 'usage', name: 'vhs-fmp4'});
- this.tech_.trigger({type: 'usage', name: 'hls-fmp4'});
- this.triggeredFmp4Usage = true;
- }
- });
-
- this.audioSegmentLoader_.on('ended', () => {
- this.logger_('audioSegmentLoader ended');
- this.onEndOfStream();
- });
- }
-
- mediaSecondsLoaded_() {
- return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded +
- this.mainSegmentLoader_.mediaSecondsLoaded);
- }
-
- /**
- * Call load on our SegmentLoaders
- */
- load() {
- this.mainSegmentLoader_.load();
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.load();
- }
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.load();
- }
- }
-
- /**
- * Re-tune playback quality level for the current player
- * conditions without performing destructive actions, like
- * removing already buffered content
- *
- * @private
- * @deprecated
- */
- smoothQualityChange_(media = this.selectPlaylist()) {
- this.fastQualityChange_(media);
- }
-
- /**
- * Re-tune playback quality level for the current player
- * conditions. This method will perform destructive actions like removing
- * already buffered content in order to readjust the currently active
- * playlist quickly. This is good for manual quality changes
- *
- * @private
- */
- fastQualityChange_(media = this.selectPlaylist()) {
- if (media === this.masterPlaylistLoader_.media()) {
- this.logger_('skipping fastQualityChange because new media is same as old');
- return;
- }
-
- this.switchMedia_(media, 'fast-quality');
-
- // Delete all buffered data to allow an immediate quality switch, then seek to give
- // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
- // ahead is roughly the minimum that will accomplish this across a variety of content
- // in IE and Edge, but seeking in place is sufficient on all other browsers)
- // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
- // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
- this.mainSegmentLoader_.resetEverything(() => {
- // Since this is not a typical seek, we avoid the seekTo method which can cause segments
- // from the previously enabled rendition to load before the new playlist has finished loading
- if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
- this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
- } else {
- this.tech_.setCurrentTime(this.tech_.currentTime());
- }
- });
-
- // don't need to reset audio as it is reset when media changes
- }
-
- /**
- * Begin playback.
- */
- play() {
- if (this.setupFirstPlay()) {
- return;
- }
-
- if (this.tech_.ended()) {
- this.tech_.setCurrentTime(0);
- }
-
- if (this.hasPlayed_) {
- this.load();
- }
-
- const seekable = this.tech_.seekable();
-
- // if the viewer has paused and we fell out of the live window,
- // seek forward to the live point
- if (this.tech_.duration() === Infinity) {
- if (this.tech_.currentTime() < seekable.start(0)) {
- return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
- }
- }
- }
-
- /**
- * Seek to the latest media position if this is a live video and the
- * player and video are loaded and initialized.
- */
- setupFirstPlay() {
- const media = this.masterPlaylistLoader_.media();
-
- // Check that everything is ready to begin buffering for the first call to play
- // If 1) there is no active media
- // 2) the player is paused
- // 3) the first play has already been setup
- // then exit early
- if (!media || this.tech_.paused() || this.hasPlayed_) {
- return false;
- }
-
- // when the video is a live stream
- if (!media.endList) {
- const seekable = this.seekable();
-
- if (!seekable.length) {
- // without a seekable range, the player cannot seek to begin buffering at the live
- // point
- return false;
- }
-
- if (videojs.browser.IE_VERSION &&
- this.tech_.readyState() === 0) {
- // IE11 throws an InvalidStateError if you try to set currentTime while the
- // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
- this.tech_.one('loadedmetadata', () => {
- this.trigger('firstplay');
- this.tech_.setCurrentTime(seekable.end(0));
- this.hasPlayed_ = true;
- });
-
- return false;
- }
-
- // trigger firstplay to inform the source handler to ignore the next seek event
- this.trigger('firstplay');
- // seek to the live point
- this.tech_.setCurrentTime(seekable.end(0));
- }
-
- this.hasPlayed_ = true;
- // we can begin loading now that everything is ready
- this.load();
- return true;
- }
-
- /**
- * handle the sourceopen event on the MediaSource
- *
- * @private
- */
- handleSourceOpen_() {
- // Only attempt to create the source buffer if none already exist.
- // handleSourceOpen is also called when we are "re-opening" a source buffer
- // after `endOfStream` has been called (in response to a seek for instance)
- this.tryToCreateSourceBuffers_();
-
- // if autoplay is enabled, begin playback. This is duplicative of
- // code in video.js but is required because play() must be invoked
- // *after* the media source has opened.
- if (this.tech_.autoplay()) {
- const playPromise = this.tech_.play();
-
- // Catch/silence error when a pause interrupts a play request
- // on browsers which return a promise
- if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
- playPromise.then(null, (e) => {});
- }
- }
-
- this.trigger('sourceopen');
- }
-
- /**
- * handle the sourceended event on the MediaSource
- *
- * @private
- */
- handleSourceEnded_() {
- if (!this.inbandTextTracks_.metadataTrack_) {
- return;
- }
-
- const cues = this.inbandTextTracks_.metadataTrack_.cues;
-
- if (!cues || !cues.length) {
- return;
- }
-
- const duration = this.duration();
-
- cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ?
- Number.MAX_VALUE : duration;
- }
-
- /**
- * handle the durationchange event on the MediaSource
- *
- * @private
- */
- handleDurationChange_() {
- this.tech_.trigger('durationchange');
- }
-
- /**
- * Calls endOfStream on the media source when all active stream types have called
- * endOfStream
- *
- * @param {string} streamType
- * Stream type of the segment loader that called endOfStream
- * @private
- */
- onEndOfStream() {
- let isEndOfStream = this.mainSegmentLoader_.ended_;
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- // if the audio playlist loader exists, then alternate audio is active
- if (!this.mainSegmentLoader_.currentMediaInfo_ ||
- this.mainSegmentLoader_.currentMediaInfo_.hasVideo) {
- // if we do not know if the main segment loader contains video yet or if we
- // definitively know the main segment loader contains video, then we need to wait
- // for both main and audio segment loaders to call endOfStream
- isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
- } else {
- // otherwise just rely on the audio loader
- isEndOfStream = this.audioSegmentLoader_.ended_;
- }
- }
-
- if (!isEndOfStream) {
- return;
- }
-
- this.stopABRTimer_();
- this.sourceUpdater_.endOfStream();
- }
-
- /**
- * Check if a playlist has stopped being updated
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist has stopped being updated or not
- */
- stuckAtPlaylistEnd_(playlist) {
- const seekable = this.seekable();
-
- if (!seekable.length) {
- // playlist doesn't have enough information to determine whether we are stuck
- return false;
- }
-
- const expired =
- this.syncController_.getExpiredTime(playlist, this.duration());
-
- if (expired === null) {
- return false;
- }
-
- // does not use the safe live end to calculate playlist end, since we
- // don't want to say we are stuck while there is still content
- const absolutePlaylistEnd = Vhs.Playlist.playlistEnd(playlist, expired);
- const currentTime = this.tech_.currentTime();
- const buffered = this.tech_.buffered();
-
- if (!buffered.length) {
- // return true if the playhead reached the absolute end of the playlist
- return absolutePlaylistEnd - currentTime <= Ranges.SAFE_TIME_DELTA;
- }
- const bufferedEnd = buffered.end(buffered.length - 1);
-
- // return true if there is too little buffer left and buffer has reached absolute
- // end of playlist
- return bufferedEnd - currentTime <= Ranges.SAFE_TIME_DELTA &&
- absolutePlaylistEnd - bufferedEnd <= Ranges.SAFE_TIME_DELTA;
- }
-
- /**
- * Blacklists a playlist when an error occurs for a set amount of time
- * making it unavailable for selection by the rendition selection algorithm
- * and then forces a new playlist (rendition) selection.
- *
- * @param {Object=} error an optional error that may include the playlist
- * to blacklist
- * @param {number=} blacklistDuration an optional number of seconds to blacklist the
- * playlist
- */
- blacklistCurrentPlaylist(error = {}, blacklistDuration) {
- // If the `error` was generated by the playlist loader, it will contain
- // the playlist we were trying to load (but failed) and that should be
- // blacklisted instead of the currently selected playlist which is likely
- // out-of-date in this scenario
- const currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
-
- blacklistDuration = blacklistDuration ||
- error.blacklistDuration ||
- this.blacklistDuration;
-
- // If there is no current playlist, then an error occurred while we were
- // trying to load the master OR while we were disposing of the tech
- if (!currentPlaylist) {
- this.error = error;
-
- if (this.mediaSource.readyState !== 'open') {
- this.trigger('error');
- } else {
- this.sourceUpdater_.endOfStream('network');
- }
-
- return;
- }
-
- currentPlaylist.playlistErrors_++;
-
- const playlists = this.masterPlaylistLoader_.master.playlists;
- const enabledPlaylists = playlists.filter(isEnabled);
- const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === currentPlaylist;
-
- // Don't blacklist the only playlist unless it was blacklisted
- // forever
- if (playlists.length === 1 && blacklistDuration !== Infinity) {
- videojs.log.warn(`Problem encountered with playlist ${currentPlaylist.id}. ` +
- 'Trying again since it is the only playlist.');
-
- this.tech_.trigger('retryplaylist');
- // if this is a final rendition, we should delay
- return this.masterPlaylistLoader_.load(isFinalRendition);
- }
-
- if (isFinalRendition) {
- // Since we're on the final non-blacklisted playlist, and we're about to blacklist
- // it, instead of erring the player or retrying this playlist, clear out the current
- // blacklist. This allows other playlists to be attempted in case any have been
- // fixed.
- let reincluded = false;
-
- playlists.forEach((playlist) => {
- // skip current playlist which is about to be blacklisted
- if (playlist === currentPlaylist) {
- return;
- }
- const excludeUntil = playlist.excludeUntil;
-
- // a playlist cannot be reincluded if it wasn't excluded to begin with.
- if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
- reincluded = true;
- delete playlist.excludeUntil;
- }
- });
-
- if (reincluded) {
- videojs.log.warn('Removing other playlists from the exclusion list because the last ' +
- 'rendition is about to be excluded.');
- // Technically we are retrying a playlist, in that we are simply retrying a previous
- // playlist. This is needed for users relying on the retryplaylist event to catch a
- // case where the player might be stuck and looping through "dead" playlists.
- this.tech_.trigger('retryplaylist');
- }
- }
-
- // Blacklist this playlist
- let excludeUntil;
-
- if (currentPlaylist.playlistErrors_ > this.maxPlaylistRetries) {
- excludeUntil = Infinity;
- } else {
- excludeUntil = Date.now() + (blacklistDuration * 1000);
- }
-
- currentPlaylist.excludeUntil = excludeUntil;
-
- if (error.reason) {
- currentPlaylist.lastExcludeReason_ = error.reason;
- }
- this.tech_.trigger('blacklistplaylist');
- this.tech_.trigger({type: 'usage', name: 'vhs-rendition-blacklisted'});
- this.tech_.trigger({type: 'usage', name: 'hls-rendition-blacklisted'});
-
- // TODO: should we select a new playlist if this blacklist wasn't for the currentPlaylist?
- // Would be something like media().id !=== currentPlaylist.id and we would need something
- // like `pendingMedia` in playlist loaders to check against that too. This will prevent us
- // from loading a new playlist on any blacklist.
- // Select a new playlist
- const nextPlaylist = this.selectPlaylist();
-
- if (!nextPlaylist) {
- this.error = 'Playback cannot continue. No available working or supported playlists.';
- this.trigger('error');
- return;
- }
-
- const logFn = error.internal ? this.logger_ : videojs.log.warn;
- const errorMessage = error.message ? (' ' + error.message) : '';
-
- logFn(`${(error.internal ? 'Internal problem' : 'Problem')} encountered with playlist ${currentPlaylist.id}.` +
- `${errorMessage} Switching to playlist ${nextPlaylist.id}.`);
-
- // if audio group changed reset audio loaders
- if (nextPlaylist.attributes.AUDIO !== currentPlaylist.attributes.AUDIO) {
- this.delegateLoaders_('audio', ['abort', 'pause']);
- }
-
- // if subtitle group changed reset subtitle loaders
- if (nextPlaylist.attributes.SUBTITLES !== currentPlaylist.attributes.SUBTITLES) {
- this.delegateLoaders_('subtitle', ['abort', 'pause']);
- }
-
- this.delegateLoaders_('main', ['abort', 'pause']);
-
- const delayDuration = (nextPlaylist.targetDuration / 2) * 1000 || 5 * 1000;
- const shouldDelay = typeof nextPlaylist.lastRequest === 'number' &&
- (Date.now() - nextPlaylist.lastRequest) <= delayDuration;
-
- // delay if it's a final rendition or if the last refresh is sooner than half targetDuration
- return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
- }
-
- /**
- * Pause all segment/playlist loaders
- */
- pauseLoading() {
- this.delegateLoaders_('all', ['abort', 'pause']);
- this.stopABRTimer_();
- }
-
- /**
- * Call a set of functions in order on playlist loaders, segment loaders,
- * or both types of loaders.
- *
- * @param {string} filter
- * Filter loaders that should call fnNames using a string. Can be:
- * * all - run on all loaders
- * * audio - run on all audio loaders
- * * subtitle - run on all subtitle loaders
- * * main - run on the main/master loaders
- *
- * @param {Array|string} fnNames
- * A string or array of function names to call.
- */
- delegateLoaders_(filter, fnNames) {
- const loaders = [];
-
- const dontFilterPlaylist = filter === 'all';
-
- if (dontFilterPlaylist || filter === 'main') {
- loaders.push(this.masterPlaylistLoader_);
- }
-
- const mediaTypes = [];
-
- if (dontFilterPlaylist || filter === 'audio') {
- mediaTypes.push('AUDIO');
- }
-
- if (dontFilterPlaylist || filter === 'subtitle') {
- mediaTypes.push('CLOSED-CAPTIONS');
- mediaTypes.push('SUBTITLES');
- }
-
- mediaTypes.forEach((mediaType) => {
- const loader = this.mediaTypes_[mediaType] &&
- this.mediaTypes_[mediaType].activePlaylistLoader;
-
- if (loader) {
- loaders.push(loader);
- }
- });
-
- ['main', 'audio', 'subtitle'].forEach((name) => {
- const loader = this[`${name}SegmentLoader_`];
-
- if (loader && (filter === name || filter === 'all')) {
- loaders.push(loader);
- }
- });
-
- loaders.forEach((loader) => fnNames.forEach((fnName) => {
- if (typeof loader[fnName] === 'function') {
- loader[fnName]();
- }
- }));
- }
-
- /**
- * set the current time on all segment loaders
- *
- * @param {TimeRange} currentTime the current time to set
- * @return {TimeRange} the current time
- */
- setCurrentTime(currentTime) {
- const buffered = Ranges.findRange(this.tech_.buffered(), currentTime);
-
- if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
- // return immediately if the metadata is not ready yet
- return 0;
- }
-
- // it's clearly an edge-case but don't thrown an error if asked to
- // seek within an empty playlist
- if (!this.masterPlaylistLoader_.media().segments) {
- return 0;
- }
-
- // if the seek location is already buffered, continue buffering as usual
- if (buffered && buffered.length) {
- return currentTime;
- }
-
- // cancel outstanding requests so we begin buffering at the new
- // location
- this.mainSegmentLoader_.resetEverything();
- this.mainSegmentLoader_.abort();
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- this.audioSegmentLoader_.resetEverything();
- this.audioSegmentLoader_.abort();
- }
- if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
- this.subtitleSegmentLoader_.resetEverything();
- this.subtitleSegmentLoader_.abort();
- }
-
- // start segment loader loading in case they are paused
- this.load();
- }
-
- /**
- * get the current duration
- *
- * @return {TimeRange} the duration
- */
- duration() {
- if (!this.masterPlaylistLoader_) {
- return 0;
- }
-
- const media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- // no playlists loaded yet, so can't determine a duration
- return 0;
- }
-
- // Don't rely on the media source for duration in the case of a live playlist since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, just return Infinity.
- if (!media.endList) {
- return Infinity;
- }
-
- // Since this is a VOD video, it is safe to rely on the media source's duration (if
- // available). If it's not available, fall back to a playlist-calculated estimate.
-
- if (this.mediaSource) {
- return this.mediaSource.duration;
- }
-
- return Vhs.Playlist.duration(media);
- }
-
- /**
- * check the seekable range
- *
- * @return {TimeRange} the seekable range
- */
- seekable() {
- return this.seekable_;
- }
-
- onSyncInfoUpdate_() {
- let audioSeekable;
-
- if (!this.masterPlaylistLoader_) {
- return;
- }
-
- let media = this.masterPlaylistLoader_.media();
-
- if (!media) {
- return;
- }
-
- let expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- // not enough information to update seekable
- return;
- }
-
- const master = this.masterPlaylistLoader_.master;
- const mainSeekable = Vhs.Playlist.seekable(
- media,
- expired,
- Vhs.Playlist.liveEdgeDelay(master, media)
- );
-
- if (mainSeekable.length === 0) {
- return;
- }
-
- if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
- media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
- expired = this.syncController_.getExpiredTime(media, this.duration());
-
- if (expired === null) {
- return;
- }
-
- audioSeekable = Vhs.Playlist.seekable(
- media,
- expired,
- Vhs.Playlist.liveEdgeDelay(master, media)
- );
-
- if (audioSeekable.length === 0) {
- return;
- }
- }
-
- let oldEnd;
- let oldStart;
-
- if (this.seekable_ && this.seekable_.length) {
- oldEnd = this.seekable_.end(0);
- oldStart = this.seekable_.start(0);
- }
-
- if (!audioSeekable) {
- // seekable has been calculated based on buffering video data so it
- // can be returned directly
- this.seekable_ = mainSeekable;
- } else if (audioSeekable.start(0) > mainSeekable.end(0) ||
- mainSeekable.start(0) > audioSeekable.end(0)) {
- // seekables are pretty far off, rely on main
- this.seekable_ = mainSeekable;
- } else {
- this.seekable_ = videojs.createTimeRanges([[
- (audioSeekable.start(0) > mainSeekable.start(0)) ? audioSeekable.start(0) :
- mainSeekable.start(0),
- (audioSeekable.end(0) < mainSeekable.end(0)) ? audioSeekable.end(0) :
- mainSeekable.end(0)
- ]]);
- }
-
- // seekable is the same as last time
- if (this.seekable_ && this.seekable_.length) {
- if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
- return;
- }
- }
-
- this.logger_(`seekable updated [${Ranges.printableRange(this.seekable_)}]`);
-
- this.tech_.trigger('seekablechanged');
- }
-
- /**
- * Update the player duration
- */
- updateDuration(isLive) {
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- this.updateDuration_ = null;
- }
- if (this.mediaSource.readyState !== 'open') {
- this.updateDuration_ = this.updateDuration.bind(this, isLive);
- this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
- return;
- }
-
- if (isLive) {
- const seekable = this.seekable();
-
- if (!seekable.length) {
- return;
- }
-
- // Even in the case of a live playlist, the native MediaSource's duration should not
- // be set to Infinity (even though this would be expected for a live playlist), since
- // setting the native MediaSource's duration to infinity ends up with consequences to
- // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
- //
- // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
- // however, few browsers have support for setLiveSeekableRange()
- // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
- //
- // Until a time when the duration of the media source can be set to infinity, and a
- // seekable range specified across browsers, the duration should be greater than or
- // equal to the last possible seekable value.
-
- // MediaSource duration starts as NaN
- // It is possible (and probable) that this case will never be reached for many
- // sources, since the MediaSource reports duration as the highest value without
- // accounting for timestamp offset. For example, if the timestamp offset is -100 and
- // we buffered times 0 to 100 with real times of 100 to 200, even though current
- // time will be between 0 and 100, the native media source may report the duration
- // as 200. However, since we report duration separate from the media source (as
- // Infinity), and as long as the native media source duration value is greater than
- // our reported seekable range, seeks will work as expected. The large number as
- // duration for live is actually a strategy used by some players to work around the
- // issue of live seekable ranges cited above.
- if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
- this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
- }
- return;
- }
-
- const buffered = this.tech_.buffered();
- let duration = Vhs.Playlist.duration(this.masterPlaylistLoader_.media());
-
- if (buffered.length > 0) {
- duration = Math.max(duration, buffered.end(buffered.length - 1));
- }
-
- if (this.mediaSource.duration !== duration) {
- this.sourceUpdater_.setDuration(duration);
- }
- }
-
- /**
- * dispose of the MasterPlaylistController and everything
- * that it controls
- */
- dispose() {
- this.trigger('dispose');
- this.decrypter_.terminate();
- this.masterPlaylistLoader_.dispose();
- this.mainSegmentLoader_.dispose();
-
- if (this.loadOnPlay_) {
- this.tech_.off('play', this.loadOnPlay_);
- }
-
- ['AUDIO', 'SUBTITLES'].forEach((type) => {
- const groups = this.mediaTypes_[type].groups;
-
- for (const id in groups) {
- groups[id].forEach((group) => {
- if (group.playlistLoader) {
- group.playlistLoader.dispose();
- }
- });
- }
- });
-
- this.audioSegmentLoader_.dispose();
- this.subtitleSegmentLoader_.dispose();
- this.sourceUpdater_.dispose();
- this.timelineChangeController_.dispose();
-
- this.stopABRTimer_();
-
- if (this.updateDuration_) {
- this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
- }
-
- this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_);
-
- // load the media source into the player
- this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
- this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
- this.off();
- }
-
- /**
- * return the master playlist object if we have one
- *
- * @return {Object} the master playlist object that we parsed
- */
- master() {
- return this.masterPlaylistLoader_.master;
- }
-
- /**
- * return the currently selected playlist
- *
- * @return {Object} the currently selected playlist object that we parsed
- */
- media() {
- // playlist loader will not return media if it has not been fully loaded
- return this.masterPlaylistLoader_.media() || this.initialMedia_;
- }
-
- areMediaTypesKnown_() {
- const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
-
- // one or both loaders has not loaded sufficently to get codecs
- if (!this.mainSegmentLoader_.currentMediaInfo_ || (usingAudioLoader && !this.audioSegmentLoader_.currentMediaInfo_)) {
- return false;
- }
-
- return true;
- }
-
- getCodecsOrExclude_() {
- const media = {
- main: this.mainSegmentLoader_.currentMediaInfo_ || {},
- audio: this.audioSegmentLoader_.currentMediaInfo_ || {}
- };
-
- // set "main" media equal to video
- media.video = media.main;
- const playlistCodecs = codecsForPlaylist(this.master(), this.media());
- const codecs = {};
- const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
-
- if (media.main.hasVideo) {
- codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
- }
-
- if (media.main.isMuxed) {
- codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;
- }
-
- if ((media.main.hasAudio && !media.main.isMuxed) || media.audio.hasAudio || usingAudioLoader) {
- codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC;
- // set audio isFmp4 so we use the correct "supports" function below
- media.audio.isFmp4 = (media.main.hasAudio && !media.main.isMuxed) ? media.main.isFmp4 : media.audio.isFmp4;
- }
-
- // no codecs, no playback.
- if (!codecs.audio && !codecs.video) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: 'Could not determine codecs for playlist.',
- blacklistDuration: Infinity
- });
- return;
- }
-
- // fmp4 relies on browser support, while ts relies on muxer support
- const supportFunction = (isFmp4, codec) => (isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec));
- const unsupportedCodecs = {};
- let unsupportedAudio;
-
- ['video', 'audio'].forEach(function(type) {
- if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
- const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
-
- unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
- unsupportedCodecs[supporter].push(codecs[type]);
-
- if (type === 'audio') {
- unsupportedAudio = supporter;
- }
- }
- });
-
- if (usingAudioLoader && unsupportedAudio && this.media().attributes.AUDIO) {
- const audioGroup = this.media().attributes.AUDIO;
-
- this.master().playlists.forEach(variant => {
- const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
-
- if (variantAudioGroup === audioGroup && variant !== this.media()) {
- variant.excludeUntil = Infinity;
- }
- });
- this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
- }
-
- // if we have any unsupported codecs blacklist this playlist.
- if (Object.keys(unsupportedCodecs).length) {
- const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
-
- if (acc) {
- acc += ', ';
- }
-
- acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
-
- return acc;
- }, '') + '.';
-
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- internal: true,
- message,
- blacklistDuration: Infinity
- });
- return;
- }
- // check if codec switching is happening
- if (
- this.sourceUpdater_.hasCreatedSourceBuffers() &&
- !this.sourceUpdater_.canChangeType()
- ) {
- const switchMessages = [];
-
- ['video', 'audio'].forEach((type) => {
- const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
- const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
-
- if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
- switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
- }
- });
-
- if (switchMessages.length) {
- this.blacklistCurrentPlaylist({
- playlist: this.media(),
- message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
- blacklistDuration: Infinity,
- internal: true
- });
- return;
- }
- }
-
- // TODO: when using the muxer shouldn't we just return
- // the codecs that the muxer outputs?
- return codecs;
- }
-
- /**
- * Create source buffers and exlude any incompatible renditions.
- *
- * @private
- */
- tryToCreateSourceBuffers_() {
- // media source is not ready yet or sourceBuffers are already
- // created.
- if (
- this.mediaSource.readyState !== 'open' ||
- this.sourceUpdater_.hasCreatedSourceBuffers()
- ) {
- return;
- }
-
- if (!this.areMediaTypesKnown_()) {
- return;
- }
-
- const codecs = this.getCodecsOrExclude_();
-
- // no codecs means that the playlist was excluded
- if (!codecs) {
- return;
- }
-
- this.sourceUpdater_.createSourceBuffers(codecs);
-
- const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
-
- this.excludeIncompatibleVariants_(codecString);
- }
-
- /**
- * Excludes playlists with codecs that are unsupported by the muxer and browser.
- */
- excludeUnsupportedVariants_() {
- const playlists = this.master().playlists;
- const ids = [];
-
- // TODO: why don't we have a property to loop through all
- // playlist? Why did we ever mix indexes and keys?
- Object.keys(playlists).forEach(key => {
- const variant = playlists[key];
-
- // check if we already processed this playlist.
- if (ids.indexOf(variant.id) !== -1) {
- return;
- }
-
- ids.push(variant.id);
-
- const codecs = codecsForPlaylist(this.master, variant);
- const unsupported = [];
-
- if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
- unsupported.push(`audio codec ${codecs.audio}`);
- }
-
- if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
- unsupported.push(`video codec ${codecs.video}`);
- }
-
- if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
- unsupported.push(`text codec ${codecs.text}`);
- }
-
- if (unsupported.length) {
- variant.excludeUntil = Infinity;
- this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
- }
- });
- }
-
- /**
- * Blacklist playlists that are known to be codec or
- * stream-incompatible with the SourceBuffer configuration. For
- * instance, Media Source Extensions would cause the video element to
- * stall waiting for video data if you switched from a variant with
- * video and audio to an audio-only one.
- *
- * @param {Object} media a media playlist compatible with the current
- * set of SourceBuffers. Variants in the current master playlist that
- * do not appear to have compatible codec or stream configurations
- * will be excluded from the default playlist selection algorithm
- * indefinitely.
- * @private
- */
- excludeIncompatibleVariants_(codecString) {
- const ids = [];
- const playlists = this.master().playlists;
- const codecs = unwrapCodecList(parseCodecs(codecString));
- const codecCount_ = codecCount(codecs);
- const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
- const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
-
- Object.keys(playlists).forEach((key) => {
- const variant = playlists[key];
-
- // check if we already processed this playlist.
- // or it if it is already excluded forever.
- if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
- return;
- }
-
- ids.push(variant.id);
- const blacklistReasons = [];
-
- // get codecs from the playlist for this variant
- const variantCodecs = codecsForPlaylist(this.masterPlaylistLoader_.master, variant);
- const variantCodecCount = codecCount(variantCodecs);
-
- // if no codecs are listed, we cannot determine that this
- // variant is incompatible. Wait for mux.js to probe
- if (!variantCodecs.audio && !variantCodecs.video) {
- return;
- }
-
- // TODO: we can support this by removing the
- // old media source and creating a new one, but it will take some work.
- // The number of streams cannot change
- if (variantCodecCount !== codecCount_) {
- blacklistReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
- }
-
- // only exclude playlists by codec change, if codecs cannot switch
- // during playback.
- if (!this.sourceUpdater_.canChangeType()) {
- const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
- const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null;
-
- // the video codec cannot change
- if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
- blacklistReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
- }
-
- // the audio codec cannot change
- if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
- blacklistReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
- }
- }
-
- if (blacklistReasons.length) {
- variant.excludeUntil = Infinity;
- this.logger_(`blacklisting ${variant.id}: ${blacklistReasons.join(' && ')}`);
- }
- });
- }
-
- updateAdCues_(media) {
- let offset = 0;
- const seekable = this.seekable();
-
- if (seekable.length) {
- offset = seekable.start(0);
- }
-
- updateAdCues(media, this.cueTagsTrack_, offset);
- }
-
- /**
- * Calculates the desired forward buffer length based on current time
- *
- * @return {number} Desired forward buffer length in seconds
- */
- goalBufferLength() {
- const currentTime = this.tech_.currentTime();
- const initial = Config.GOAL_BUFFER_LENGTH;
- const rate = Config.GOAL_BUFFER_LENGTH_RATE;
- const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
-
- return Math.min(initial + currentTime * rate, max);
- }
-
- /**
- * Calculates the desired buffer low water line based on current time
- *
- * @return {number} Desired buffer low water line in seconds
- */
- bufferLowWaterLine() {
- const currentTime = this.tech_.currentTime();
- const initial = Config.BUFFER_LOW_WATER_LINE;
- const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
- const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
- const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
-
- return Math.min(initial + currentTime * rate, this.experimentalBufferBasedABR ? newMax : max);
- }
-
- bufferHighWaterLine() {
- return Config.BUFFER_HIGH_WATER_LINE;
- }
-
-}
diff --git a/node_modules/@videojs/http-streaming/src/media-groups.js b/node_modules/@videojs/http-streaming/src/media-groups.js
deleted file mode 100644
index c88fdf4..0000000
--- a/node_modules/@videojs/http-streaming/src/media-groups.js
+++ /dev/null
@@ -1,964 +0,0 @@
-import videojs from 'video.js';
-import PlaylistLoader from './playlist-loader';
-import DashPlaylistLoader from './dash-playlist-loader';
-import noop from './util/noop';
-import {isAudioOnly, playlistMatch} from './playlist.js';
-import logger from './util/logger';
-
-/**
- * Convert the properties of an HLS track into an audioTrackKind.
- *
- * @private
- */
-const audioTrackKind_ = (properties) => {
- let kind = properties.default ? 'main' : 'alternative';
-
- if (properties.characteristics &&
- properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
- kind = 'main-desc';
- }
-
- return kind;
-};
-
-/**
- * Pause provided segment loader and playlist loader if active
- *
- * @param {SegmentLoader} segmentLoader
- * SegmentLoader to pause
- * @param {Object} mediaType
- * Active media type
- * @function stopLoaders
- */
-export const stopLoaders = (segmentLoader, mediaType) => {
- segmentLoader.abort();
- segmentLoader.pause();
-
- if (mediaType && mediaType.activePlaylistLoader) {
- mediaType.activePlaylistLoader.pause();
- mediaType.activePlaylistLoader = null;
- }
-};
-
-/**
- * Start loading provided segment loader and playlist loader
- *
- * @param {PlaylistLoader} playlistLoader
- * PlaylistLoader to start loading
- * @param {Object} mediaType
- * Active media type
- * @function startLoaders
- */
-export const startLoaders = (playlistLoader, mediaType) => {
- // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
- // playlist loader
- mediaType.activePlaylistLoader = playlistLoader;
- playlistLoader.load();
-};
-
-/**
- * Returns a function to be called when the media group changes. It performs a
- * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
- * change of group is merely a rendition switch of the same content at another encoding,
- * rather than a change of content, such as switching audio from English to Spanish.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a non-destructive resync of SegmentLoader when the active media
- * group changes.
- * @function onGroupChanged
- */
-export const onGroupChanged = (type, settings) => () => {
- const {
- segmentLoaders: {
- [type]: segmentLoader,
- main: mainSegmentLoader
- },
- mediaTypes: { [type]: mediaType }
- } = settings;
- const activeTrack = mediaType.activeTrack();
- const activeGroup = mediaType.getActiveGroup();
- const previousActiveLoader = mediaType.activePlaylistLoader;
- const lastGroup = mediaType.lastGroup_;
-
- // the group did not change do nothing
- if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
-
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup || activeGroup.isMasterPlaylist) {
- // there is no group active or active group is a main playlist and won't change
- return;
- }
-
- if (!activeGroup.playlistLoader) {
- if (previousActiveLoader) {
- // The previous group had a playlist loader but the new active group does not
- // this means we are switching from demuxed to muxed audio. In this case we want to
- // do a destructive reset of the main segment loader and not restart the audio
- // loaders.
- mainSegmentLoader.resetEverything();
- }
- return;
- }
-
- // Non-destructive resync
- segmentLoader.resyncLoader();
-
- startLoaders(activeGroup.playlistLoader, mediaType);
-};
-
-export const onGroupChanging = (type, settings) => () => {
- const {
- segmentLoaders: {
- [type]: segmentLoader
- },
- mediaTypes: { [type]: mediaType }
- } = settings;
-
- mediaType.lastGroup_ = null;
-
- segmentLoader.abort();
- segmentLoader.pause();
-};
-
-/**
- * Returns a function to be called when the media track changes. It performs a
- * destructive reset of the SegmentLoader to ensure we start loading as close to
- * currentTime as possible.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Handler for a destructive reset of SegmentLoader when the active media
- * track changes.
- * @function onTrackChanged
- */
-export const onTrackChanged = (type, settings) => () => {
- const {
- masterPlaylistLoader,
- segmentLoaders: {
- [type]: segmentLoader,
- main: mainSegmentLoader
- },
- mediaTypes: { [type]: mediaType }
- } = settings;
- const activeTrack = mediaType.activeTrack();
- const activeGroup = mediaType.getActiveGroup();
- const previousActiveLoader = mediaType.activePlaylistLoader;
- const lastTrack = mediaType.lastTrack_;
-
- // track did not change, do nothing
- if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
- return;
- }
-
- mediaType.lastGroup_ = activeGroup;
- mediaType.lastTrack_ = activeTrack;
-
- stopLoaders(segmentLoader, mediaType);
-
- if (!activeGroup) {
- // there is no group active so we do not want to restart loaders
- return;
- }
-
- if (activeGroup.isMasterPlaylist) {
- // track did not change, do nothing
- if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
- return;
- }
-
- const mpc = settings.vhs.masterPlaylistController_;
- const newPlaylist = mpc.selectPlaylist();
-
- // media will not change do nothing
- if (mpc.media() === newPlaylist) {
- return;
- }
-
- mediaType.logger_(`track change. Switching master audio from ${lastTrack.id} to ${activeTrack.id}`);
- masterPlaylistLoader.pause();
- mainSegmentLoader.resetEverything();
- mpc.fastQualityChange_(newPlaylist);
-
- return;
- }
-
- if (type === 'AUDIO') {
- if (!activeGroup.playlistLoader) {
- // when switching from demuxed audio/video to muxed audio/video (noted by no
- // playlist loader for the audio group), we want to do a destructive reset of the
- // main segment loader and not restart the audio loaders
- mainSegmentLoader.setAudio(true);
- // don't have to worry about disabling the audio of the audio segment loader since
- // it should be stopped
- mainSegmentLoader.resetEverything();
- return;
- }
-
- // although the segment loader is an audio segment loader, call the setAudio
- // function to ensure it is prepared to re-append the init segment (or handle other
- // config changes)
- segmentLoader.setAudio(true);
- mainSegmentLoader.setAudio(false);
- }
-
- if (previousActiveLoader === activeGroup.playlistLoader) {
- // Nothing has actually changed. This can happen because track change events can fire
- // multiple times for a "single" change. One for enabling the new active track, and
- // one for disabling the track that was active
- startLoaders(activeGroup.playlistLoader, mediaType);
- return;
- }
-
- if (segmentLoader.track) {
- // For WebVTT, set the new text track in the segmentloader
- segmentLoader.track(activeTrack);
- }
-
- // destructive reset
- segmentLoader.resetEverything();
-
- startLoaders(activeGroup.playlistLoader, mediaType);
-};
-
-export const onError = {
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning (or error if the playlist is blacklisted) to
- * console and switches back to default audio track.
- * @function onError.AUDIO
- */
- AUDIO: (type, settings) => () => {
- const {
- segmentLoaders: { [type]: segmentLoader},
- mediaTypes: { [type]: mediaType },
- blacklistCurrentPlaylist
- } = settings;
-
- stopLoaders(segmentLoader, mediaType);
-
- // switch back to default audio track
- const activeTrack = mediaType.activeTrack();
- const activeGroup = mediaType.activeGroup();
- const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
- const defaultTrack = mediaType.tracks[id];
-
- if (activeTrack === defaultTrack) {
- // Default track encountered an error. All we can do now is blacklist the current
- // rendition and hope another will switch audio groups
- blacklistCurrentPlaylist({
- message: 'Problem encountered loading the default audio track.'
- });
- return;
- }
-
- videojs.log.warn('Problem encountered loading the alternate audio track.' +
- 'Switching back to default.');
-
- for (const trackId in mediaType.tracks) {
- mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
- }
-
- mediaType.onTrackChanged();
- },
- /**
- * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
- * an error.
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Error handler. Logs warning to console and disables the active subtitle track
- * @function onError.SUBTITLES
- */
- SUBTITLES: (type, settings) => () => {
- const {
- segmentLoaders: { [type]: segmentLoader},
- mediaTypes: { [type]: mediaType }
- } = settings;
-
- videojs.log.warn('Problem encountered loading the subtitle track.' +
- 'Disabling subtitle track.');
-
- stopLoaders(segmentLoader, mediaType);
-
- const track = mediaType.activeTrack();
-
- if (track) {
- track.mode = 'disabled';
- }
-
- mediaType.onTrackChanged();
- }
-};
-
-export const setupListeners = {
- /**
- * Setup event listeners for audio playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.AUDIO
- */
- AUDIO: (type, playlistLoader, settings) => {
- if (!playlistLoader) {
- // no playlist loader means audio will be muxed with the video
- return;
- }
-
- const {
- tech,
- requestOptions,
- segmentLoaders: { [type]: segmentLoader }
- } = settings;
-
- playlistLoader.on('loadedmetadata', () => {
- const media = playlistLoader.media();
-
- segmentLoader.playlist(media, requestOptions);
-
- // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
- if (!tech.paused() || (media.endList && tech.preload() !== 'none')) {
- segmentLoader.load();
- }
- });
-
- playlistLoader.on('loadedplaylist', () => {
- segmentLoader.playlist(playlistLoader.media(), requestOptions);
-
- // If the player isn't paused, ensure that the segment loader is running
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
-
- playlistLoader.on('error', onError[type](type, settings));
- },
- /**
- * Setup event listeners for subtitle playlist loader
- *
- * @param {string} type
- * MediaGroup type
- * @param {PlaylistLoader|null} playlistLoader
- * PlaylistLoader to register listeners on
- * @param {Object} settings
- * Object containing required information for media groups
- * @function setupListeners.SUBTITLES
- */
- SUBTITLES: (type, playlistLoader, settings) => {
- const {
- tech,
- requestOptions,
- segmentLoaders: { [type]: segmentLoader },
- mediaTypes: { [type]: mediaType }
- } = settings;
-
- playlistLoader.on('loadedmetadata', () => {
- const media = playlistLoader.media();
-
- segmentLoader.playlist(media, requestOptions);
- segmentLoader.track(mediaType.activeTrack());
-
- // if the video is already playing, or if this isn't a live video and preload
- // permits, start downloading segments
- if (!tech.paused() || (media.endList && tech.preload() !== 'none')) {
- segmentLoader.load();
- }
- });
-
- playlistLoader.on('loadedplaylist', () => {
- segmentLoader.playlist(playlistLoader.media(), requestOptions);
-
- // If the player isn't paused, ensure that the segment loader is running
- if (!tech.paused()) {
- segmentLoader.load();
- }
- });
-
- playlistLoader.on('error', onError[type](type, settings));
- }
-};
-
-export const initialize = {
- /**
- * Setup PlaylistLoaders and AudioTracks for the audio groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.AUDIO
- */
- 'AUDIO': (type, settings) => {
- const {
- vhs,
- sourceType,
- segmentLoaders: { [type]: segmentLoader },
- requestOptions,
- master: {mediaGroups},
- mediaTypes: {
- [type]: {
- groups,
- tracks,
- logger_
- }
- },
- masterPlaylistLoader
- } = settings;
-
- const audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master);
-
- // force a default if we have none
- if (!mediaGroups[type] ||
- Object.keys(mediaGroups[type]).length === 0) {
- mediaGroups[type] = { main: { default: { default: true } } };
- }
-
- for (const groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
- for (const variantLabel in mediaGroups[type][groupId]) {
- let properties = mediaGroups[type][groupId][variantLabel];
-
- let playlistLoader;
-
- if (audioOnlyMaster) {
- logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a master playlist`);
- properties.isMasterPlaylist = true;
- playlistLoader = null;
-
- // if vhs-json was provided as the source, and the media playlist was resolved,
- // use the resolved media playlist object
- } else if (sourceType === 'vhs-json' && properties.playlists) {
- playlistLoader = new PlaylistLoader(
- properties.playlists[0],
- vhs,
- requestOptions
- );
- } else if (properties.resolvedUri) {
- playlistLoader = new PlaylistLoader(
- properties.resolvedUri,
- vhs,
- requestOptions
- );
- // TODO: dash isn't the only type with properties.playlists
- // should we even have properties.playlists in this check.
- } else if (properties.playlists && sourceType === 'dash') {
- playlistLoader = new DashPlaylistLoader(
- properties.playlists[0],
- vhs,
- requestOptions,
- masterPlaylistLoader
- );
- } else {
- // no resolvedUri means the audio is muxed with the video when using this
- // audio track
- playlistLoader = null;
- }
-
- properties = videojs.mergeOptions(
- { id: variantLabel, playlistLoader },
- properties
- );
-
- setupListeners[type](type, properties.playlistLoader, settings);
-
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- const track = new videojs.AudioTrack({
- id: variantLabel,
- kind: audioTrackKind_(properties),
- enabled: false,
- language: properties.language,
- default: properties.default,
- label: variantLabel
- });
-
- tracks[variantLabel] = track;
- }
- }
- }
-
- // setup single error event handler for the segment loader
- segmentLoader.on('error', onError[type](type, settings));
- },
- /**
- * Setup PlaylistLoaders and TextTracks for the subtitle groups
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize.SUBTITLES
- */
- 'SUBTITLES': (type, settings) => {
- const {
- tech,
- vhs,
- sourceType,
- segmentLoaders: { [type]: segmentLoader },
- requestOptions,
- master: { mediaGroups },
- mediaTypes: {
- [type]: {
- groups,
- tracks
- }
- },
- masterPlaylistLoader
- } = settings;
-
- for (const groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (const variantLabel in mediaGroups[type][groupId]) {
- if (mediaGroups[type][groupId][variantLabel].forced) {
- // Subtitle playlists with the forced attribute are not selectable in Safari.
- // According to Apple's HLS Authoring Specification:
- // If content has forced subtitles and regular subtitles in a given language,
- // the regular subtitles track in that language MUST contain both the forced
- // subtitles and the regular subtitles for that language.
- // Because of this requirement and that Safari does not add forced subtitles,
- // forced subtitles are skipped here to maintain consistent experience across
- // all platforms
- continue;
- }
-
- let properties = mediaGroups[type][groupId][variantLabel];
-
- let playlistLoader;
-
- if (sourceType === 'hls') {
- playlistLoader =
- new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
- } else if (sourceType === 'dash') {
- const playlists = properties.playlists.filter((p) => p.excludeUntil !== Infinity);
-
- if (!playlists.length) {
- return;
- }
- playlistLoader = new DashPlaylistLoader(
- properties.playlists[0],
- vhs,
- requestOptions,
- masterPlaylistLoader
- );
- } else if (sourceType === 'vhs-json') {
- playlistLoader = new PlaylistLoader(
- // if the vhs-json object included the media playlist, use the media playlist
- // as provided, otherwise use the resolved URI to load the playlist
- properties.playlists ? properties.playlists[0] : properties.resolvedUri,
- vhs,
- requestOptions
- );
- }
-
- properties = videojs.mergeOptions({
- id: variantLabel,
- playlistLoader
- }, properties);
-
- setupListeners[type](type, properties.playlistLoader, settings);
-
- groups[groupId].push(properties);
-
- if (typeof tracks[variantLabel] === 'undefined') {
- const track = tech.addRemoteTextTrack({
- id: variantLabel,
- kind: 'subtitles',
- default: properties.default && properties.autoselect,
- language: properties.language,
- label: variantLabel
- }, false).track;
-
- tracks[variantLabel] = track;
- }
- }
- }
-
- // setup single error event handler for the segment loader
- segmentLoader.on('error', onError[type](type, settings));
- },
- /**
- * Setup TextTracks for the closed-caption groups
- *
- * @param {String} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @function initialize['CLOSED-CAPTIONS']
- */
- 'CLOSED-CAPTIONS': (type, settings) => {
- const {
- tech,
- master: { mediaGroups },
- mediaTypes: {
- [type]: {
- groups,
- tracks
- }
- }
- } = settings;
-
- for (const groupId in mediaGroups[type]) {
- if (!groups[groupId]) {
- groups[groupId] = [];
- }
-
- for (const variantLabel in mediaGroups[type][groupId]) {
- const properties = mediaGroups[type][groupId][variantLabel];
-
- // Look for either 608 (CCn) or 708 (SERVICEn) caption services
- if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
- continue;
- }
-
- const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
-
- let newProps = {
- label: variantLabel,
- language: properties.language,
- instreamId: properties.instreamId,
- default: properties.default && properties.autoselect
- };
-
- if (captionServices[newProps.instreamId]) {
- newProps = videojs.mergeOptions(newProps, captionServices[newProps.instreamId]);
- }
-
- if (newProps.default === undefined) {
- delete newProps.default;
- }
-
- // No PlaylistLoader is required for Closed-Captions because the captions are
- // embedded within the video stream
- groups[groupId].push(videojs.mergeOptions({ id: variantLabel }, properties));
-
- if (typeof tracks[variantLabel] === 'undefined') {
- const track = tech.addRemoteTextTrack({
- id: newProps.instreamId,
- kind: 'captions',
- default: newProps.default,
- language: newProps.language,
- label: newProps.label
- }, false).track;
-
- tracks[variantLabel] = track;
- }
- }
- }
- }
-};
-
-const groupMatch = (list, media) => {
- for (let i = 0; i < list.length; i++) {
- if (playlistMatch(media, list[i])) {
- return true;
- }
-
- if (list[i].playlists && groupMatch(list[i].playlists, media)) {
- return true;
- }
- }
-
- return false;
-};
-
-/**
- * Returns a function used to get the active group of the provided type
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media group for the provided type. Takes an
- * optional parameter {TextTrack} track. If no track is provided, a list of all
- * variants in the group, otherwise the variant corresponding to the provided
- * track is returned.
- * @function activeGroup
- */
-export const activeGroup = (type, settings) => (track) => {
- const {
- masterPlaylistLoader,
- mediaTypes: { [type]: { groups } }
- } = settings;
-
- const media = masterPlaylistLoader.media();
-
- if (!media) {
- return null;
- }
-
- let variants = null;
-
- // set to variants to main media active group
- if (media.attributes[type]) {
- variants = groups[media.attributes[type]];
- }
-
- const groupKeys = Object.keys(groups);
-
- if (!variants) {
- // find the masterPlaylistLoader media
- // that is in a media group if we are dealing
- // with audio only
- if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.master)) {
- for (let i = 0; i < groupKeys.length; i++) {
- const groupPropertyList = groups[groupKeys[i]];
-
- if (groupMatch(groupPropertyList, media)) {
- variants = groupPropertyList;
- break;
- }
- }
- // use the main group if it exists
- } else if (groups.main) {
- variants = groups.main;
- // only one group, use that one
- } else if (groupKeys.length === 1) {
- variants = groups[groupKeys[0]];
- }
- }
-
- if (typeof track === 'undefined') {
- return variants;
- }
-
- if (track === null || !variants) {
- // An active track was specified so a corresponding group is expected. track === null
- // means no track is currently active so there is no corresponding group
- return null;
- }
-
- return variants.filter((props) => props.id === track.id)[0] || null;
-};
-
-export const activeTrack = {
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.AUDIO
- */
- AUDIO: (type, settings) => () => {
- const { mediaTypes: { [type]: { tracks } } } = settings;
-
- for (const id in tracks) {
- if (tracks[id].enabled) {
- return tracks[id];
- }
- }
-
- return null;
- },
- /**
- * Returns a function used to get the active track of type provided
- *
- * @param {string} type
- * MediaGroup type
- * @param {Object} settings
- * Object containing required information for media groups
- * @return {Function}
- * Function that returns the active media track for the provided type. Returns
- * null if no track is active
- * @function activeTrack.SUBTITLES
- */
- SUBTITLES: (type, settings) => () => {
- const { mediaTypes: { [type]: { tracks } } } = settings;
-
- for (const id in tracks) {
- if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
- return tracks[id];
- }
- }
-
- return null;
- }
-};
-
-export const getActiveGroup = (type, {mediaTypes}) => () => {
- const activeTrack_ = mediaTypes[type].activeTrack();
-
- if (!activeTrack_) {
- return null;
- }
-
- return mediaTypes[type].activeGroup(activeTrack_);
-};
-
-/**
- * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
- * Closed-Captions) specified in the master manifest.
- *
- * @param {Object} settings
- * Object containing required information for setting up the media groups
- * @param {Tech} settings.tech
- * The tech of the player
- * @param {Object} settings.requestOptions
- * XHR request options used by the segment loaders
- * @param {PlaylistLoader} settings.masterPlaylistLoader
- * PlaylistLoader for the master source
- * @param {VhsHandler} settings.vhs
- * VHS SourceHandler
- * @param {Object} settings.master
- * The parsed master manifest
- * @param {Object} settings.mediaTypes
- * Object to store the loaders, tracks, and utility methods for each media type
- * @param {Function} settings.blacklistCurrentPlaylist
- * Blacklists the current rendition and forces a rendition switch.
- * @function setupMediaGroups
- */
-export const setupMediaGroups = (settings) => {
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach((type) => {
- initialize[type](type, settings);
- });
-
- const {
- mediaTypes,
- masterPlaylistLoader,
- tech,
- vhs,
- segmentLoaders: {
- ['AUDIO']: audioSegmentLoader,
- main: mainSegmentLoader
- }
- } = settings;
-
- // setup active group and track getters and change event handlers
- ['AUDIO', 'SUBTITLES'].forEach((type) => {
- mediaTypes[type].activeGroup = activeGroup(type, settings);
- mediaTypes[type].activeTrack = activeTrack[type](type, settings);
- mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
- mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
- mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
- mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
- });
-
- // DO NOT enable the default subtitle or caption track.
- // DO enable the default audio track
- const audioGroup = mediaTypes.AUDIO.activeGroup();
-
- if (audioGroup) {
- const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
-
- mediaTypes.AUDIO.tracks[groupId].enabled = true;
- mediaTypes.AUDIO.onGroupChanged();
- mediaTypes.AUDIO.onTrackChanged();
-
- const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup();
-
- // a similar check for handling setAudio on each loader is run again each time the
- // track is changed, but needs to be handled here since the track may not be considered
- // changed on the first call to onTrackChanged
- if (!activeAudioGroup.playlistLoader) {
- // either audio is muxed with video or the stream is audio only
- mainSegmentLoader.setAudio(true);
- } else {
- // audio is demuxed
- mainSegmentLoader.setAudio(false);
- audioSegmentLoader.setAudio(true);
- }
- }
-
- masterPlaylistLoader.on('mediachange', () => {
- ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
- });
-
- masterPlaylistLoader.on('mediachanging', () => {
- ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
- });
-
- // custom audio track change event handler for usage event
- const onAudioTrackChanged = () => {
- mediaTypes.AUDIO.onTrackChanged();
- tech.trigger({ type: 'usage', name: 'vhs-audio-change' });
- tech.trigger({ type: 'usage', name: 'hls-audio-change' });
- };
-
- tech.audioTracks().addEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().addEventListener(
- 'change',
- mediaTypes.SUBTITLES.onTrackChanged
- );
-
- vhs.on('dispose', () => {
- tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
- tech.remoteTextTracks().removeEventListener(
- 'change',
- mediaTypes.SUBTITLES.onTrackChanged
- );
- });
-
- // clear existing audio tracks and add the ones we just created
- tech.clearTracks('audio');
-
- for (const id in mediaTypes.AUDIO.tracks) {
- tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
- }
-};
-
-/**
- * Creates skeleton object used to store the loaders, tracks, and utility methods for each
- * media type
- *
- * @return {Object}
- * Object to store the loaders, tracks, and utility methods for each media type
- * @function createMediaTypes
- */
-export const createMediaTypes = () => {
- const mediaTypes = {};
-
- ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach((type) => {
- mediaTypes[type] = {
- groups: {},
- tracks: {},
- activePlaylistLoader: null,
- activeGroup: noop,
- activeTrack: noop,
- getActiveGroup: noop,
- onGroupChanged: noop,
- onTrackChanged: noop,
- lastTrack_: null,
- logger_: logger(`MediaGroups[${type}]`)
- };
- });
-
- return mediaTypes;
-};
diff --git a/node_modules/@videojs/http-streaming/src/media-segment-request.js b/node_modules/@videojs/http-streaming/src/media-segment-request.js
deleted file mode 100644
index 1f71132..0000000
--- a/node_modules/@videojs/http-streaming/src/media-segment-request.js
+++ /dev/null
@@ -1,1048 +0,0 @@
-import videojs from 'video.js';
-import { createTransferableMessage } from './bin-utils';
-import { stringToArrayBuffer } from './util/string-to-array-buffer';
-import { transmux } from './segment-transmuxer';
-import { segmentXhrHeaders } from './xhr';
-import {workerCallback} from './util/worker-callback.js';
-import {
- detectContainerForBytes,
- isLikelyFmp4MediaSegment
-} from '@videojs/vhs-utils/es/containers';
-
-export const REQUEST_ERRORS = {
- FAILURE: 2,
- TIMEOUT: -101,
- ABORTED: -102
-};
-
-/**
- * Abort all requests
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- */
-const abortAll = (activeXhrs) => {
- activeXhrs.forEach((xhr) => {
- xhr.abort();
- });
-};
-
-/**
- * Gather important bandwidth stats once a request has completed
- *
- * @param {Object} request - the XHR request from which to gather stats
- */
-const getRequestStats = (request) => {
- return {
- bandwidth: request.bandwidth,
- bytesReceived: request.bytesReceived || 0,
- roundTripTime: request.roundTripTime || 0
- };
-};
-
-/**
- * If possible gather bandwidth stats as a request is in
- * progress
- *
- * @param {Event} progressEvent - an event object from an XHR's progress event
- */
-const getProgressStats = (progressEvent) => {
- const request = progressEvent.target;
- const roundTripTime = Date.now() - request.requestTime;
- const stats = {
- bandwidth: Infinity,
- bytesReceived: 0,
- roundTripTime: roundTripTime || 0
- };
-
- stats.bytesReceived = progressEvent.loaded;
- // This can result in Infinity if stats.roundTripTime is 0 but that is ok
- // because we should only use bandwidth stats on progress to determine when
- // abort a request early due to insufficient bandwidth
- stats.bandwidth = Math.floor((stats.bytesReceived / stats.roundTripTime) * 8 * 1000);
-
- return stats;
-};
-
-/**
- * Handle all error conditions in one place and return an object
- * with all the information
- *
- * @param {Error|null} error - if non-null signals an error occured with the XHR
- * @param {Object} request - the XHR request that possibly generated the error
- */
-const handleErrors = (error, request) => {
- if (request.timedout) {
- return {
- status: request.status,
- message: 'HLS request timed-out at URL: ' + request.uri,
- code: REQUEST_ERRORS.TIMEOUT,
- xhr: request
- };
- }
-
- if (request.aborted) {
- return {
- status: request.status,
- message: 'HLS request aborted at URL: ' + request.uri,
- code: REQUEST_ERRORS.ABORTED,
- xhr: request
- };
- }
-
- if (error) {
- return {
- status: request.status,
- message: 'HLS request errored at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
- return {
- status: request.status,
- message: 'Empty HLS response at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- };
- }
-
- return null;
-};
-
-/**
- * Handle responses for key data and convert the key data to the correct format
- * for the decryption step later
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Array} objects - objects to add the key bytes to.
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
- const response = request.response;
- const errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- if (response.byteLength !== 16) {
- return finishProcessingFn({
- status: request.status,
- message: 'Invalid HLS key at URL: ' + request.uri,
- code: REQUEST_ERRORS.FAILURE,
- xhr: request
- }, segment);
- }
-
- const view = new DataView(response);
- const bytes = new Uint32Array([
- view.getUint32(0),
- view.getUint32(4),
- view.getUint32(8),
- view.getUint32(12)
- ]);
-
- for (let i = 0; i < objects.length; i++) {
- objects[i].bytes = bytes;
- }
-
- return finishProcessingFn(null, segment);
-};
-
-const parseInitSegment = (segment, callback) => {
- const type = detectContainerForBytes(segment.map.bytes);
-
- // TODO: We should also handle ts init segments here, but we
- // only know how to parse mp4 init segments at the moment
- if (type !== 'mp4') {
- const uri = segment.map.resolvedUri || segment.map.uri;
-
- return callback({
- internal: true,
- message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
- code: REQUEST_ERRORS.FAILURE
- });
- }
-
- workerCallback({
- action: 'probeMp4Tracks',
- data: segment.map.bytes,
- transmuxer: segment.transmuxer,
- callback: ({tracks, data}) => {
- // transfer bytes back to us
- segment.map.bytes = data;
-
- tracks.forEach(function(track) {
- segment.map.tracks = segment.map.tracks || {};
-
- // only support one track of each type for now
- if (segment.map.tracks[track.type]) {
- return;
- }
-
- segment.map.tracks[track.type] = track;
-
- if (typeof track.id === 'number' && track.timescale) {
- segment.map.timescales = segment.map.timescales || {};
- segment.map.timescales[track.id] = track.timescale;
- }
-
- });
-
- return callback(null);
- }
- });
-};
-
-/**
- * Handle init-segment responses
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-const handleInitSegmentResponse =
-({segment, finishProcessingFn}) => (error, request) => {
- const errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
- const bytes = new Uint8Array(request.response);
-
- // init segment is encypted, we will have to wait
- // until the key request is done to decrypt.
- if (segment.map.key) {
- segment.map.encryptedBytes = bytes;
- return finishProcessingFn(null, segment);
- }
-
- segment.map.bytes = bytes;
-
- parseInitSegment(segment, function(parseError) {
- if (parseError) {
- parseError.xhr = request;
- parseError.status = request.status;
-
- return finishProcessingFn(parseError, segment);
- }
-
- finishProcessingFn(null, segment);
- });
-};
-
-/**
- * Response handler for segment-requests being sure to set the correct
- * property depending on whether the segment is encryped or not
- * Also records and keeps track of stats that are used for ABR purposes
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} finishProcessingFn - a callback to execute to continue processing
- * this request
- */
-const handleSegmentResponse = ({
- segment,
- finishProcessingFn,
- responseType
-}) => (error, request) => {
- const errorObj = handleErrors(error, request);
-
- if (errorObj) {
- return finishProcessingFn(errorObj, segment);
- }
-
- const newBytes =
- // although responseText "should" exist, this guard serves to prevent an error being
- // thrown for two primary cases:
- // 1. the mime type override stops working, or is not implemented for a specific
- // browser
- // 2. when using mock XHR libraries like sinon that do not allow the override behavior
- (responseType === 'arraybuffer' || !request.responseText) ?
- request.response :
- stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
-
- segment.stats = getRequestStats(request);
-
- if (segment.key) {
- segment.encryptedBytes = new Uint8Array(newBytes);
- } else {
- segment.bytes = new Uint8Array(newBytes);
- }
-
- return finishProcessingFn(null, segment);
-};
-
-const transmuxAndNotify = ({
- segment,
- bytes,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
-}) => {
- const fmp4Tracks = segment.map && segment.map.tracks || {};
- const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video);
-
- // Keep references to each function so we can null them out after we're done with them.
- // One reason for this is that in the case of full segments, we want to trust start
- // times from the probe, rather than the transmuxer.
- let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
- const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
- let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
- const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
-
- const finish = () => transmux({
- bytes,
- transmuxer: segment.transmuxer,
- audioAppendStart: segment.audioAppendStart,
- gopsToAlignWith: segment.gopsToAlignWith,
- remux: isMuxed,
- onData: (result) => {
- result.type = result.type === 'combined' ? 'video' : result.type;
- dataFn(segment, result);
- },
- onTrackInfo: (trackInfo) => {
- if (trackInfoFn) {
- if (isMuxed) {
- trackInfo.isMuxed = true;
- }
- trackInfoFn(segment, trackInfo);
- }
- },
- onAudioTimingInfo: (audioTimingInfo) => {
- // we only want the first start value we encounter
- if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
- audioStartFn(audioTimingInfo.start);
- audioStartFn = null;
- }
- // we want to continually update the end time
- if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
- audioEndFn(audioTimingInfo.end);
- }
- },
- onVideoTimingInfo: (videoTimingInfo) => {
- // we only want the first start value we encounter
- if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
- videoStartFn(videoTimingInfo.start);
- videoStartFn = null;
- }
- // we want to continually update the end time
- if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
- videoEndFn(videoTimingInfo.end);
- }
- },
- onVideoSegmentTimingInfo: (videoSegmentTimingInfo) => {
- videoSegmentTimingInfoFn(videoSegmentTimingInfo);
- },
- onAudioSegmentTimingInfo: (audioSegmentTimingInfo) => {
- audioSegmentTimingInfoFn(audioSegmentTimingInfo);
- },
- onId3: (id3Frames, dispatchType) => {
- id3Fn(segment, id3Frames, dispatchType);
- },
- onCaptions: (captions) => {
- captionsFn(segment, [captions]);
- },
- isEndOfTimeline,
- onEndedTimeline: () => {
- endedTimelineFn();
- },
- onDone: (result) => {
- if (!doneFn) {
- return;
- }
- result.type = result.type === 'combined' ? 'video' : result.type;
- doneFn(null, segment, result);
- }
- });
-
- // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
- // Meaning cached frame data may corrupt our notion of where this segment
- // really starts. To get around this, probe for the info needed.
- workerCallback({
- action: 'probeTs',
- transmuxer: segment.transmuxer,
- data: bytes,
- baseStartTime: segment.baseStartTime,
- callback: (data) => {
- segment.bytes = bytes = data.data;
-
- const probeResult = data.result;
-
- if (probeResult) {
- trackInfoFn(segment, {
- hasAudio: probeResult.hasAudio,
- hasVideo: probeResult.hasVideo,
- isMuxed
- });
- trackInfoFn = null;
-
- if (probeResult.hasAudio && !isMuxed) {
- audioStartFn(probeResult.audioStart);
- }
- if (probeResult.hasVideo) {
- videoStartFn(probeResult.videoStart);
- }
- audioStartFn = null;
- videoStartFn = null;
- }
-
- finish();
- }
- });
-};
-
-const handleSegmentBytes = ({
- segment,
- bytes,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
-}) => {
- let bytesAsUint8Array = new Uint8Array(bytes);
-
- // TODO:
- // We should have a handler that fetches the number of bytes required
- // to check if something is fmp4. This will allow us to save bandwidth
- // because we can only blacklist a playlist and abort requests
- // by codec after trackinfo triggers.
- if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
- segment.isFmp4 = true;
- const {tracks} = segment.map;
-
- const trackInfo = {
- isFmp4: true,
- hasVideo: !!tracks.video,
- hasAudio: !!tracks.audio
- };
-
- // if we have a audio track, with a codec that is not set to
- // encrypted audio
- if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
- trackInfo.audioCodec = tracks.audio.codec;
- }
-
- // if we have a video track, with a codec that is not set to
- // encrypted video
- if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
- trackInfo.videoCodec = tracks.video.codec;
- }
-
- if (tracks.video && tracks.audio) {
- trackInfo.isMuxed = true;
- }
-
- // since we don't support appending fmp4 data on progress, we know we have the full
- // segment here
- trackInfoFn(segment, trackInfo);
- // The probe doesn't provide the segment end time, so only callback with the start
- // time. The end time can be roughly calculated by the receiver using the duration.
- //
- // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
- // that is the true start of the segment (where the playback engine should begin
- // decoding).
- const finishLoading = (captions) => {
- // if the track still has audio at this point it is only possible
- // for it to be audio only. See `tracks.video && tracks.audio` if statement
- // above.
- // we make sure to use segment.bytes here as that
- dataFn(segment, {
- data: bytesAsUint8Array,
- type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
- });
- if (captions && captions.length) {
- captionsFn(segment, captions);
- }
- doneFn(null, segment, {});
- };
-
- workerCallback({
- action: 'probeMp4StartTime',
- timescales: segment.map.timescales,
- data: bytesAsUint8Array,
- transmuxer: segment.transmuxer,
- callback: ({data, startTime}) => {
- // transfer bytes back to us
- bytes = data.buffer;
- segment.bytes = bytesAsUint8Array = data;
-
- if (trackInfo.hasAudio && !trackInfo.isMuxed) {
- timingInfoFn(segment, 'audio', 'start', startTime);
- }
-
- if (trackInfo.hasVideo) {
- timingInfoFn(segment, 'video', 'start', startTime);
- }
-
- // Run through the CaptionParser in case there are captions.
- // Initialize CaptionParser if it hasn't been yet
- if (!tracks.video || !data.byteLength || !segment.transmuxer) {
- finishLoading();
- return;
- }
-
- workerCallback({
- action: 'pushMp4Captions',
- endAction: 'mp4Captions',
- transmuxer: segment.transmuxer,
- data: bytesAsUint8Array,
- timescales: segment.map.timescales,
- trackIds: [tracks.video.id],
- callback: (message) => {
- // transfer bytes back to us
- bytes = message.data.buffer;
- segment.bytes = bytesAsUint8Array = message.data;
- finishLoading(message.captions);
- }
- });
- }
- });
- return;
- }
-
- // VTT or other segments that don't need processing
- if (!segment.transmuxer) {
- doneFn(null, segment, {});
- return;
- }
-
- if (typeof segment.container === 'undefined') {
- segment.container = detectContainerForBytes(bytesAsUint8Array);
- }
-
- if (segment.container !== 'ts' && segment.container !== 'aac') {
- trackInfoFn(segment, {hasAudio: false, hasVideo: false});
- doneFn(null, segment, {});
- return;
- }
-
- // ts or aac
- transmuxAndNotify({
- segment,
- bytes,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
- });
-};
-
-const decrypt = function({id, key, encryptedBytes, decryptionWorker}, callback) {
- const decryptionHandler = (event) => {
- if (event.data.source === id) {
- decryptionWorker.removeEventListener('message', decryptionHandler);
- const decrypted = event.data.decrypted;
-
- callback(new Uint8Array(
- decrypted.bytes,
- decrypted.byteOffset,
- decrypted.byteLength
- ));
- }
- };
-
- decryptionWorker.addEventListener('message', decryptionHandler);
-
- let keyBytes;
-
- if (key.bytes.slice) {
- keyBytes = key.bytes.slice();
- } else {
- keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
- }
-
- // incrementally decrypt the bytes
- decryptionWorker.postMessage(createTransferableMessage({
- source: id,
- encrypted: encryptedBytes,
- key: keyBytes,
- iv: key.iv
- }), [
- encryptedBytes.buffer,
- keyBytes.buffer
- ]);
-};
-
-/**
- * Decrypt the segment via the decryption web worker
- *
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after decryption has completed
- */
-const decryptSegment = ({
- decryptionWorker,
- segment,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
-}) => {
- decrypt({
- id: segment.requestId,
- key: segment.key,
- encryptedBytes: segment.encryptedBytes,
- decryptionWorker
- }, (decryptedBytes) => {
- segment.bytes = decryptedBytes;
-
- handleSegmentBytes({
- segment,
- bytes: segment.bytes,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
- });
- });
-};
-
-/**
- * This function waits for all XHRs to finish (with either success or failure)
- * before continueing processing via it's callback. The function gathers errors
- * from each request into a single errors array so that the error status for
- * each request can be examined later.
- *
- * @param {Object} activeXhrs - an object that tracks all XHR requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
- * routines
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Function} doneFn - a callback that is executed after all resources have been
- * downloaded and any decryption completed
- */
-const waitForCompletion = ({
- activeXhrs,
- decryptionWorker,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
-}) => {
- let count = 0;
- let didError = false;
-
- return (error, segment) => {
- if (didError) {
- return;
- }
-
- if (error) {
- didError = true;
- // If there are errors, we have to abort any outstanding requests
- abortAll(activeXhrs);
-
- // Even though the requests above are aborted, and in theory we could wait until we
- // handle the aborted events from those requests, there are some cases where we may
- // never get an aborted event. For instance, if the network connection is lost and
- // there were two requests, the first may have triggered an error immediately, while
- // the second request remains unsent. In that case, the aborted algorithm will not
- // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
- //
- // We also can't rely on the ready state of the XHR, since the request that
- // triggered the connection error may also show as a ready state of 0 (unsent).
- // Therefore, we have to finish this group of requests immediately after the first
- // seen error.
- return doneFn(error, segment);
- }
-
- count += 1;
-
- if (count === activeXhrs.length) {
- const segmentFinish = function() {
- if (segment.encryptedBytes) {
- return decryptSegment({
- decryptionWorker,
- segment,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
- });
- }
- // Otherwise, everything is ready just continue
- handleSegmentBytes({
- segment,
- bytes: segment.bytes,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
- });
- };
-
- // Keep track of when *all* of the requests have completed
- segment.endOfAllRequests = Date.now();
- if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
- return decrypt({
- decryptionWorker,
- // add -init to the "id" to differentiate between segment
- // and init segment decryption, just in case they happen
- // at the same time at some point in the future.
- id: segment.requestId + '-init',
- encryptedBytes: segment.map.encryptedBytes,
- key: segment.map.key
- }, (decryptedBytes) => {
- segment.map.bytes = decryptedBytes;
-
- parseInitSegment(segment, (parseError) => {
- if (parseError) {
- abortAll(activeXhrs);
- return doneFn(parseError, segment);
- }
-
- segmentFinish();
- });
-
- });
- }
-
- segmentFinish();
- }
- };
-};
-
-/**
- * Calls the abort callback if any request within the batch was aborted. Will only call
- * the callback once per batch of requests, even if multiple were aborted.
- *
- * @param {Object} loadendState - state to check to see if the abort function was called
- * @param {Function} abortFn - callback to call for abort
- */
-const handleLoadEnd = ({ loadendState, abortFn }) => (event) => {
- const request = event.target;
-
- if (request.aborted && abortFn && !loadendState.calledAbortFn) {
- abortFn();
- loadendState.calledAbortFn = true;
- }
-};
-
-/**
- * Simple progress event callback handler that gathers some stats before
- * executing a provided callback with the `segment` object
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} progressFn - a callback that is executed each time a progress event
- * is received
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that is executed when segment bytes are available
- * and ready to use
- * @param {Event} event - the progress event object from XMLHttpRequest
- */
-const handleProgress = ({
- segment,
- progressFn,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn
-}) => (event) => {
- const request = event.target;
-
- if (request.aborted) {
- return;
- }
-
- segment.stats = videojs.mergeOptions(segment.stats, getProgressStats(event));
-
- // record the time that we receive the first byte of data
- if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
- segment.stats.firstBytesReceivedAt = Date.now();
- }
-
- return progressFn(event, segment);
-};
-
-/**
- * Load all resources and does any processing necessary for a media-segment
- *
- * Features:
- * decrypts the media-segment if it has a key uri and an iv
- * aborts *all* requests if *any* one request fails
- *
- * The segment object, at minimum, has the following format:
- * {
- * resolvedUri: String,
- * [transmuxer]: Object,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [key]: {
- * resolvedUri: String
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * iv: {
- * bytes: Uint32Array
- * }
- * },
- * [map]: {
- * resolvedUri: String,
- * [byterange]: {
- * offset: Number,
- * length: Number
- * },
- * [bytes]: Uint8Array
- * }
- * }
- * ...where [name] denotes optional properties
- *
- * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
- * @param {Object} xhrOptions - the base options to provide to all xhr requests
- * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
- * decryption routines
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- * @param {Function} abortFn - a callback called (only once) if any piece of a request was
- * aborted
- * @param {Function} progressFn - a callback that receives progress events from the main
- * segment's xhr request
- * @param {Function} trackInfoFn - a callback that receives track info
- * @param {Function} timingInfoFn - a callback that receives timing info
- * @param {Function} videoSegmentTimingInfoFn
- * a callback that receives video timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} audioSegmentTimingInfoFn
- * a callback that receives audio timing info based on media times and
- * any adjustments made by the transmuxer
- * @param {Function} id3Fn - a callback that receives ID3 metadata
- * @param {Function} captionsFn - a callback that receives captions
- * @param {boolean} isEndOfTimeline
- * true if this segment represents the last segment in a timeline
- * @param {Function} endedTimelineFn
- * a callback made when a timeline is ended, will only be called if
- * isEndOfTimeline is true
- * @param {Function} dataFn - a callback that receives data from the main segment's xhr
- * request, transmuxed if needed
- * @param {Function} doneFn - a callback that is executed only once all requests have
- * succeeded or failed
- * @return {Function} a function that, when invoked, immediately aborts all
- * outstanding requests
- */
-export const mediaSegmentRequest = ({
- xhr,
- xhrOptions,
- decryptionWorker,
- segment,
- abortFn,
- progressFn,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
-}) => {
- const activeXhrs = [];
- const finishProcessingFn = waitForCompletion({
- activeXhrs,
- decryptionWorker,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn,
- doneFn
- });
-
- // optionally, request the decryption key
- if (segment.key && !segment.key.bytes) {
- const objects = [segment.key];
-
- if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
- objects.push(segment.map.key);
- }
- const keyRequestOptions = videojs.mergeOptions(xhrOptions, {
- uri: segment.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
- const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
-
- activeXhrs.push(keyXhr);
- }
-
- // optionally, request the associated media init segment
- if (segment.map && !segment.map.bytes) {
- const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
-
- if (differentMapKey) {
- const mapKeyRequestOptions = videojs.mergeOptions(xhrOptions, {
- uri: segment.map.key.resolvedUri,
- responseType: 'arraybuffer'
- });
- const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
- const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
-
- activeXhrs.push(mapKeyXhr);
- }
- const initSegmentOptions = videojs.mergeOptions(xhrOptions, {
- uri: segment.map.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment.map)
- });
- const initSegmentRequestCallback = handleInitSegmentResponse({segment, finishProcessingFn});
- const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
-
- activeXhrs.push(initSegmentXhr);
- }
-
- const segmentRequestOptions = videojs.mergeOptions(xhrOptions, {
- uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
- responseType: 'arraybuffer',
- headers: segmentXhrHeaders(segment)
- });
-
- const segmentRequestCallback = handleSegmentResponse({
- segment,
- finishProcessingFn,
- responseType: segmentRequestOptions.responseType
- });
- const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
-
- segmentXhr.addEventListener(
- 'progress',
- handleProgress({
- segment,
- progressFn,
- trackInfoFn,
- timingInfoFn,
- videoSegmentTimingInfoFn,
- audioSegmentTimingInfoFn,
- id3Fn,
- captionsFn,
- isEndOfTimeline,
- endedTimelineFn,
- dataFn
- })
- );
- activeXhrs.push(segmentXhr);
-
- // since all parts of the request must be considered, but should not make callbacks
- // multiple times, provide a shared state object
- const loadendState = {};
-
- activeXhrs.forEach((activeXhr) => {
- activeXhr.addEventListener(
- 'loadend',
- handleLoadEnd({ loadendState, abortFn })
- );
- });
-
- return () => abortAll(activeXhrs);
-};
diff --git a/node_modules/@videojs/http-streaming/src/playback-watcher.js b/node_modules/@videojs/http-streaming/src/playback-watcher.js
deleted file mode 100644
index ff1afda..0000000
--- a/node_modules/@videojs/http-streaming/src/playback-watcher.js
+++ /dev/null
@@ -1,641 +0,0 @@
-/**
- * @file playback-watcher.js
- *
- * Playback starts, and now my watch begins. It shall not end until my death. I shall
- * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
- * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
- * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
- * my life and honor to the Playback Watch, for this Player and all the Players to come.
- */
-
-import window from 'global/window';
-import * as Ranges from './ranges';
-import logger from './util/logger';
-
-// Set of events that reset the playback-watcher time check logic and clear the timeout
-const timerCancelEvents = [
- 'seeking',
- 'seeked',
- 'pause',
- 'playing',
- 'error'
-];
-
-/**
- * Returns whether or not the current time should be considered close to buffered content,
- * taking into consideration whether there's enough buffered content for proper playback.
- *
- * @param {Object} options
- * Options object
- * @param {TimeRange} options.buffered
- * Current buffer
- * @param {number} options.targetDuration
- * The active playlist's target duration
- * @param {number} options.currentTime
- * The current time of the player
- * @return {boolean}
- * Whether the current time should be considered close to the buffer
- */
-export const closeToBufferedContent = ({ buffered, targetDuration, currentTime }) => {
- if (!buffered.length) {
- return false;
- }
-
- // At least two to three segments worth of content should be buffered before there's a
- // full enough buffer to consider taking any actions.
- if (buffered.end(0) - buffered.start(0) < targetDuration * 2) {
- return false;
- }
-
- // It's possible that, on seek, a remove hasn't completed and the buffered range is
- // somewhere past the current time. In that event, don't consider the buffered content
- // close.
- if (currentTime > buffered.start(0)) {
- return false;
- }
-
- // Since target duration generally represents the max (or close to max) duration of a
- // segment, if the buffer is within a segment of the current time, the gap probably
- // won't be closed, and current time should be considered close to buffered content.
- return buffered.start(0) - currentTime < targetDuration;
-};
-
-/**
- * @class PlaybackWatcher
- */
-export default class PlaybackWatcher {
- /**
- * Represents an PlaybackWatcher object.
- *
- * @class
- * @param {Object} options an object that includes the tech and settings
- */
- constructor(options) {
- this.masterPlaylistController_ = options.masterPlaylistController;
- this.tech_ = options.tech;
- this.seekable = options.seekable;
- this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
- this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
- this.media = options.media;
-
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = null;
- this.timer_ = null;
- this.checkCurrentTimeTimeout_ = null;
- this.logger_ = logger('PlaybackWatcher');
-
- this.logger_('initialize');
-
- const playHandler = () => this.monitorCurrentTime_();
- const canPlayHandler = () => this.monitorCurrentTime_();
- const waitingHandler = () => this.techWaiting_();
- const cancelTimerHandler = () => this.cancelTimer_();
- const fixesBadSeeksHandler = () => this.fixesBadSeeks_();
-
- const mpc = this.masterPlaylistController_;
-
- const loaderTypes = ['main', 'subtitle', 'audio'];
- const loaderChecks = {};
-
- loaderTypes.forEach((type) => {
- loaderChecks[type] = {
- reset: () => this.resetSegmentDownloads_(type),
- updateend: () => this.checkSegmentDownloads_(type)
- };
-
- mpc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend);
- // If a rendition switch happens during a playback stall where the buffer
- // isn't changing we want to reset. We cannot assume that the new rendition
- // will also be stalled, until after new appends.
- mpc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset);
- // Playback stalls should not be detected right after seeking.
- // This prevents one segment playlists (single vtt or single segment content)
- // from being detected as stalling. As the buffer will not change in those cases, since
- // the buffer is the entire video duration.
- this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
- });
-
- this.tech_.on('seekablechanged', fixesBadSeeksHandler);
- this.tech_.on('waiting', waitingHandler);
- this.tech_.on(timerCancelEvents, cancelTimerHandler);
- this.tech_.on('canplay', canPlayHandler);
-
- /*
- An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
- is surfaced in one of two ways:
-
- 1) The `waiting` event is fired before the player has buffered content, making it impossible
- to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
- we can check if playback is stalled due to a gap, and skip the gap if necessary.
- 2) A source with a gap at the beginning of the stream is loaded programatically while the player
- is in a playing state. To catch this case, it's important that our one-time play listener is setup
- even if the player is in a playing state
- */
- this.tech_.one('play', playHandler);
-
- // Define the dispose function to clean up our events
- this.dispose = () => {
- this.logger_('dispose');
- this.tech_.off('seekablechanged', fixesBadSeeksHandler);
- this.tech_.off('waiting', waitingHandler);
- this.tech_.off(timerCancelEvents, cancelTimerHandler);
- this.tech_.off('canplay', canPlayHandler);
- this.tech_.off('play', playHandler);
-
- loaderTypes.forEach((type) => {
- mpc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
- mpc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
- this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
- });
- if (this.checkCurrentTimeTimeout_) {
- window.clearTimeout(this.checkCurrentTimeTimeout_);
- }
- this.cancelTimer_();
- };
- }
-
- /**
- * Periodically check current time to see if playback stopped
- *
- * @private
- */
- monitorCurrentTime_() {
- this.checkCurrentTime_();
-
- if (this.checkCurrentTimeTimeout_) {
- window.clearTimeout(this.checkCurrentTimeTimeout_);
- }
-
- // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
- this.checkCurrentTimeTimeout_ =
- window.setTimeout(this.monitorCurrentTime_.bind(this), 250);
- }
-
- /**
- * Reset stalled download stats for a specific type of loader
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#playlistupdate
- * @listens Tech#seeking
- * @listens Tech#seeked
- */
- resetSegmentDownloads_(type) {
- const loader = this.masterPlaylistController_[`${type}SegmentLoader_`];
-
- if (this[`${type}StalledDownloads_`] > 0) {
- this.logger_(`resetting possible stalled download count for ${type} loader`);
- }
- this[`${type}StalledDownloads_`] = 0;
- this[`${type}Buffered_`] = loader.buffered_();
- }
-
- /**
- * Checks on every segment `appendsdone` to see
- * if segment appends are making progress. If they are not
- * and we are still downloading bytes. We blacklist the playlist.
- *
- * @param {string} type
- * The segment loader type to check.
- *
- * @listens SegmentLoader#appendsdone
- */
- checkSegmentDownloads_(type) {
- const mpc = this.masterPlaylistController_;
- const loader = mpc[`${type}SegmentLoader_`];
- const buffered = loader.buffered_();
- const isBufferedDifferent = Ranges.isRangeDifferent(this[`${type}Buffered_`], buffered);
-
- this[`${type}Buffered_`] = buffered;
-
- // if another watcher is going to fix the issue or
- // the buffered value for this loader changed
- // appends are working
- if (isBufferedDifferent) {
- this.resetSegmentDownloads_(type);
- return;
- }
-
- this[`${type}StalledDownloads_`]++;
-
- this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
- playlistId: loader.playlist_ && loader.playlist_.id,
- buffered: Ranges.timeRangesToArray(buffered)
-
- });
-
- // after 10 possibly stalled appends with no reset, exclude
- if (this[`${type}StalledDownloads_`] < 10) {
- return;
- }
-
- this.logger_(`${type} loader stalled download exclusion`);
- this.resetSegmentDownloads_(type);
- this.tech_.trigger({type: 'usage', name: `vhs-${type}-download-exclusion`});
-
- if (type === 'subtitle') {
- return;
- }
-
- // TODO: should we exclude audio tracks rather than main tracks
- // when type is audio?
- mpc.blacklistCurrentPlaylist({
- message: `Excessive ${type} segment downloading detected.`
- }, Infinity);
- }
-
- /**
- * The purpose of this function is to emulate the "waiting" event on
- * browsers that do not emit it when they are waiting for more
- * data to continue playback
- *
- * @private
- */
- checkCurrentTime_() {
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = this.tech_.currentTime();
- return;
- }
-
- if (this.tech_.paused() || this.tech_.seeking()) {
- return;
- }
-
- const currentTime = this.tech_.currentTime();
- const buffered = this.tech_.buffered();
-
- if (this.lastRecordedTime === currentTime &&
- (!buffered.length ||
- currentTime + Ranges.SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
- // If current time is at the end of the final buffered region, then any playback
- // stall is most likely caused by buffering in a low bandwidth environment. The tech
- // should fire a `waiting` event in this scenario, but due to browser and tech
- // inconsistencies. Calling `techWaiting_` here allows us to simulate
- // responding to a native `waiting` event when the tech fails to emit one.
- return this.techWaiting_();
- }
-
- if (this.consecutiveUpdates >= 5 &&
- currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- this.waiting_();
- } else if (currentTime === this.lastRecordedTime) {
- this.consecutiveUpdates++;
- } else {
- this.consecutiveUpdates = 0;
- this.lastRecordedTime = currentTime;
- }
- }
-
- /**
- * Cancels any pending timers and resets the 'timeupdate' mechanism
- * designed to detect that we are stalled
- *
- * @private
- */
- cancelTimer_() {
- this.consecutiveUpdates = 0;
-
- if (this.timer_) {
- this.logger_('cancelTimer_');
- clearTimeout(this.timer_);
- }
-
- this.timer_ = null;
- }
-
- /**
- * Fixes situations where there's a bad seek
- *
- * @return {boolean} whether an action was taken to fix the seek
- * @private
- */
- fixesBadSeeks_() {
- const seeking = this.tech_.seeking();
-
- if (!seeking) {
- return false;
- }
-
- const seekable = this.seekable();
- const currentTime = this.tech_.currentTime();
- const isAfterSeekableRange = this.afterSeekableWindow_(
- seekable,
- currentTime,
- this.media(),
- this.allowSeeksWithinUnsafeLiveWindow
- );
- let seekTo;
-
- if (isAfterSeekableRange) {
- const seekableEnd = seekable.end(seekable.length - 1);
-
- // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
- seekTo = seekableEnd;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- const seekableStart = seekable.start(0);
-
- // sync to the beginning of the live window
- // provide a buffer of .1 seconds to handle rounding/imprecise numbers
- seekTo = seekableStart +
- // if the playlist is too short and the seekable range is an exact time (can
- // happen in live with a 3 segment playlist), then don't use a time delta
- (seekableStart === seekable.end(0) ? 0 : Ranges.SAFE_TIME_DELTA);
- }
-
- if (typeof seekTo !== 'undefined') {
- this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` +
- `seekable range ${Ranges.printableRange(seekable)}. Seeking to ` +
- `${seekTo}.`);
-
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- const buffered = this.tech_.buffered();
-
- if (
- closeToBufferedContent({
- buffered,
- targetDuration: this.media().targetDuration,
- currentTime
- })
- ) {
- seekTo = buffered.start(0) + Ranges.SAFE_TIME_DELTA;
- this.logger_(`Buffered region starts (${buffered.start(0)}) ` +
- ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
-
- this.tech_.setCurrentTime(seekTo);
- return true;
- }
-
- return false;
- }
-
- /**
- * Handler for situations when we determine the player is waiting.
- *
- * @private
- */
- waiting_() {
- if (this.techWaiting_()) {
- return;
- }
-
- // All tech waiting checks failed. Use last resort correction
- const currentTime = this.tech_.currentTime();
- const buffered = this.tech_.buffered();
- const currentRange = Ranges.findRange(buffered, currentTime);
-
- // Sometimes the player can stall for unknown reasons within a contiguous buffered
- // region with no indication that anything is amiss (seen in Firefox). Seeking to
- // currentTime is usually enough to kickstart the player. This checks that the player
- // is currently within a buffered region before attempting a corrective seek.
- // Chrome does not appear to continue `timeupdate` events after a `waiting` event
- // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
- // make sure there is ~3 seconds of forward buffer before taking any corrective action
- // to avoid triggering an `unknownwaiting` event when the network is slow.
- if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime);
-
- this.logger_(`Stopped at ${currentTime} while inside a buffered region ` +
- `[${currentRange.start(0)} -> ${currentRange.end(0)}]. Attempting to resume ` +
- 'playback by seeking to the current time.');
-
- // unknown waiting corrections may be useful for monitoring QoS
- this.tech_.trigger({type: 'usage', name: 'vhs-unknown-waiting'});
- this.tech_.trigger({type: 'usage', name: 'hls-unknown-waiting'});
- return;
- }
- }
-
- /**
- * Handler for situations when the tech fires a `waiting` event
- *
- * @return {boolean}
- * True if an action (or none) was needed to correct the waiting. False if no
- * checks passed
- * @private
- */
- techWaiting_() {
- const seekable = this.seekable();
- const currentTime = this.tech_.currentTime();
-
- if (this.tech_.seeking() && this.fixesBadSeeks_()) {
- // Tech is seeking or bad seek fixed, no action needed
- return true;
- }
-
- if (this.tech_.seeking() || this.timer_ !== null) {
- // Tech is seeking or already waiting on another action, no action needed
- return true;
- }
-
- if (this.beforeSeekableWindow_(seekable, currentTime)) {
- const livePoint = seekable.end(seekable.length - 1);
-
- this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` +
- `live point (seekable end) ${livePoint}`);
- this.cancelTimer_();
- this.tech_.setCurrentTime(livePoint);
-
- // live window resyncs may be useful for monitoring QoS
- this.tech_.trigger({type: 'usage', name: 'vhs-live-resync'});
- this.tech_.trigger({type: 'usage', name: 'hls-live-resync'});
- return true;
- }
-
- const sourceUpdater = this.tech_.vhs.masterPlaylistController_.sourceUpdater_;
- const buffered = this.tech_.buffered();
- const videoUnderflow = this.videoUnderflow_({
- audioBuffered: sourceUpdater.audioBuffered(),
- videoBuffered: sourceUpdater.videoBuffered(),
- currentTime
- });
-
- if (videoUnderflow) {
- // Even though the video underflowed and was stuck in a gap, the audio overplayed
- // the gap, leading currentTime into a buffered range. Seeking to currentTime
- // allows the video to catch up to the audio position without losing any audio
- // (only suffering ~3 seconds of frozen video and a pause in audio playback).
- this.cancelTimer_();
- this.tech_.setCurrentTime(currentTime);
-
- // video underflow may be useful for monitoring QoS
- this.tech_.trigger({type: 'usage', name: 'vhs-video-underflow'});
- this.tech_.trigger({type: 'usage', name: 'hls-video-underflow'});
- return true;
- }
- const nextRange = Ranges.findNextRange(buffered, currentTime);
-
- // check for gap
- if (nextRange.length > 0) {
- const difference = nextRange.start(0) - currentTime;
-
- this.logger_(`Stopped at ${currentTime}, setting timer for ${difference}, seeking ` +
- `to ${nextRange.start(0)}`);
-
- this.cancelTimer_();
-
- this.timer_ = setTimeout(
- this.skipTheGap_.bind(this),
- difference * 1000,
- currentTime
- );
- return true;
- }
-
- // All checks failed. Returning false to indicate failure to correct waiting
- return false;
- }
-
- afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
- if (!seekable.length) {
- // we can't make a solid case if there's no seekable, default to false
- return false;
- }
-
- let allowedEnd = seekable.end(seekable.length - 1) + Ranges.SAFE_TIME_DELTA;
- const isLive = !playlist.endList;
-
- if (isLive && allowSeeksWithinUnsafeLiveWindow) {
- allowedEnd = seekable.end(seekable.length - 1) + (playlist.targetDuration * 3);
- }
-
- if (currentTime > allowedEnd) {
- return true;
- }
-
- return false;
- }
-
- beforeSeekableWindow_(seekable, currentTime) {
- if (seekable.length &&
- // can't fall before 0 and 0 seekable start identifies VOD stream
- seekable.start(0) > 0 &&
- currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
- return true;
- }
-
- return false;
- }
-
- videoUnderflow_({videoBuffered, audioBuffered, currentTime}) {
- // audio only content will not have video underflow :)
- if (!videoBuffered) {
- return;
- }
- let gap;
-
- // find a gap in demuxed content.
- if (videoBuffered.length && audioBuffered.length) {
- // in Chrome audio will continue to play for ~3s when we run out of video
- // so we have to check that the video buffer did have some buffer in the
- // past.
- const lastVideoRange = Ranges.findRange(videoBuffered, currentTime - 3);
- const videoRange = Ranges.findRange(videoBuffered, currentTime);
- const audioRange = Ranges.findRange(audioBuffered, currentTime);
-
- if (audioRange.length && !videoRange.length && lastVideoRange.length) {
- gap = {start: lastVideoRange.end(0), end: audioRange.end(0)};
- }
-
- // find a gap in muxed content.
- } else {
- const nextRange = Ranges.findNextRange(videoBuffered, currentTime);
-
- // Even if there is no available next range, there is still a possibility we are
- // stuck in a gap due to video underflow.
- if (!nextRange.length) {
- gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
- }
- }
-
- if (gap) {
- this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` +
- `Seeking to current time ${currentTime}`);
-
- return true;
- }
-
- return false;
- }
-
- /**
- * Timer callback. If playback still has not proceeded, then we seek
- * to the start of the next buffered region.
- *
- * @private
- */
- skipTheGap_(scheduledCurrentTime) {
- const buffered = this.tech_.buffered();
- const currentTime = this.tech_.currentTime();
- const nextRange = Ranges.findNextRange(buffered, currentTime);
-
- this.cancelTimer_();
-
- if (nextRange.length === 0 ||
- currentTime !== scheduledCurrentTime) {
- return;
- }
-
- this.logger_(
- 'skipTheGap_:',
- 'currentTime:', currentTime,
- 'scheduled currentTime:', scheduledCurrentTime,
- 'nextRange start:', nextRange.start(0)
- );
-
- // only seek if we still have not played
- this.tech_.setCurrentTime(nextRange.start(0) + Ranges.TIME_FUDGE_FACTOR);
-
- this.tech_.trigger({type: 'usage', name: 'vhs-gap-skip'});
- this.tech_.trigger({type: 'usage', name: 'hls-gap-skip'});
- }
-
- gapFromVideoUnderflow_(buffered, currentTime) {
- // At least in Chrome, if there is a gap in the video buffer, the audio will continue
- // playing for ~3 seconds after the video gap starts. This is done to account for
- // video buffer underflow/underrun (note that this is not done when there is audio
- // buffer underflow/underrun -- in that case the video will stop as soon as it
- // encounters the gap, as audio stalls are more noticeable/jarring to a user than
- // video stalls). The player's time will reflect the playthrough of audio, so the
- // time will appear as if we are in a buffered region, even if we are stuck in a
- // "gap."
- //
- // Example:
- // video buffer: 0 => 10.1, 10.2 => 20
- // audio buffer: 0 => 20
- // overall buffer: 0 => 10.1, 10.2 => 20
- // current time: 13
- //
- // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
- // however, the audio continued playing until it reached ~3 seconds past the gap
- // (13 seconds), at which point it stops as well. Since current time is past the
- // gap, findNextRange will return no ranges.
- //
- // To check for this issue, we see if there is a gap that starts somewhere within
- // a 3 second range (3 seconds +/- 1 second) back from our current time.
- const gaps = Ranges.findGaps(buffered);
-
- for (let i = 0; i < gaps.length; i++) {
- const start = gaps.start(i);
- const end = gaps.end(i);
-
- // gap is starts no more than 4 seconds back
- if (currentTime - start < 4 && currentTime - start > 2) {
- return {
- start,
- end
- };
- }
- }
-
- return null;
- }
-}
diff --git a/node_modules/@videojs/http-streaming/src/playlist-loader.js b/node_modules/@videojs/http-streaming/src/playlist-loader.js
deleted file mode 100644
index 9715ab6..0000000
--- a/node_modules/@videojs/http-streaming/src/playlist-loader.js
+++ /dev/null
@@ -1,862 +0,0 @@
-/**
- * @file playlist-loader.js
- *
- * A state machine that manages the loading, caching, and updating of
- * M3U8 playlists.
- *
- */
-import { resolveUrl, resolveManifestRedirect } from './resolve-url';
-import videojs from 'video.js';
-import window from 'global/window';
-import logger from './util/logger';
-import {
- parseManifest,
- addPropertiesToMaster,
- masterForMedia,
- setupMediaPlaylist,
- forEachMediaGroup
-} from './manifest';
-import {getKnownPartCount} from './playlist.js';
-
-const { mergeOptions, EventTarget } = videojs;
-
-const addLLHLSQueryDirectives = (uri, media) => {
- if (media.endList) {
- return uri;
- }
- const query = [];
-
- if (media.serverControl && media.serverControl.canBlockReload) {
- const {preloadSegment} = media;
- // next msn is a zero based value, length is not.
- let nextMSN = media.mediaSequence + media.segments.length;
-
- // If preload segment has parts then it is likely
- // that we are going to request a part of that preload segment.
- // the logic below is used to determine that.
- if (preloadSegment) {
- const parts = preloadSegment.parts || [];
- // _HLS_part is a zero based index
- const nextPart = getKnownPartCount(media) - 1;
-
- // if nextPart is > -1 and not equal to just the
- // length of parts, then we know we had part preload hints
- // and we need to add the _HLS_part= query
- if (nextPart > -1 && nextPart !== (parts.length - 1)) {
- // add existing parts to our preload hints
- query.push(`_HLS_part=${nextPart}`);
- }
-
- // this if statement makes sure that we request the msn
- // of the preload segment if:
- // 1. the preload segment had parts (and was not yet a full segment)
- // but was added to our segments array
- // 2. the preload segment had preload hints for parts that are not in
- // the manifest yet.
- // in all other cases we want the segment after the preload segment
- // which will be given by using media.segments.length because it is 1 based
- // rather than 0 based.
- if (nextPart > -1 || parts.length) {
- nextMSN--;
- }
- }
-
- // add _HLS_msn= in front of any _HLS_part query
- query.unshift(`_HLS_msn=${nextMSN}`);
- }
-
- if (media.serverControl && media.serverControl.canSkipUntil) {
- // add _HLS_skip= infront of all other queries.
- query.unshift('_HLS_skip=' + (media.serverControl.canSkipDateranges ? 'v2' : 'YES'));
- }
-
- query.forEach(function(str, i) {
- const symbol = i === 0 ? '?' : '&';
-
- uri += `${symbol}${str}`;
- });
-
- return uri;
-};
-
-/**
- * Returns a new segment object with properties and
- * the parts array merged.
- *
- * @param {Object} a the old segment
- * @param {Object} b the new segment
- *
- * @return {Object} the merged segment
- */
-export const updateSegment = (a, b) => {
- if (!a) {
- return b;
- }
-
- const result = mergeOptions(a, b);
-
- // if only the old segment has preload hints
- // and the new one does not, remove preload hints.
- if (a.preloadHints && !b.preloadHints) {
- delete result.preloadHints;
- }
-
- // if only the old segment has parts
- // then the parts are no longer valid
- if (a.parts && !b.parts) {
- delete result.parts;
- // if both segments have parts
- // copy part propeties from the old segment
- // to the new one.
- } else if (a.parts && b.parts) {
- for (let i = 0; i < b.parts.length; i++) {
- if (a.parts && a.parts[i]) {
- result.parts[i] = mergeOptions(a.parts[i], b.parts[i]);
- }
- }
- }
-
- // set skipped to false for segments that have
- // have had information merged from the old segment.
- if (!a.skipped && b.skipped) {
- result.skipped = false;
- }
-
- // set preload to false for segments that have
- // had information added in the new segment.
- if (a.preload && !b.preload) {
- result.preload = false;
- }
-
- return result;
-};
-
-/**
- * Returns a new array of segments that is the result of merging
- * properties from an older list of segments onto an updated
- * list. No properties on the updated playlist will be ovewritten.
- *
- * @param {Array} original the outdated list of segments
- * @param {Array} update the updated list of segments
- * @param {number=} offset the index of the first update
- * segment in the original segment list. For non-live playlists,
- * this should always be zero and does not need to be
- * specified. For live playlists, it should be the difference
- * between the media sequence numbers in the original and updated
- * playlists.
- * @return {Array} a list of merged segment objects
- */
-export const updateSegments = (original, update, offset) => {
- const oldSegments = original.slice();
- const newSegments = update.slice();
-
- offset = offset || 0;
- const result = [];
-
- let currentMap;
-
- for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
- const oldSegment = oldSegments[newIndex + offset];
- const newSegment = newSegments[newIndex];
-
- if (oldSegment) {
- currentMap = oldSegment.map || currentMap;
-
- result.push(updateSegment(oldSegment, newSegment));
- } else {
- // carry over map to new segment if it is missing
- if (currentMap && !newSegment.map) {
- newSegment.map = currentMap;
- }
-
- result.push(newSegment);
-
- }
- }
- return result;
-};
-
-export const resolveSegmentUris = (segment, baseUri) => {
- // preloadSegment will not have a uri at all
- // as the segment isn't actually in the manifest yet, only parts
- if (!segment.resolvedUri && segment.uri) {
- segment.resolvedUri = resolveUrl(baseUri, segment.uri);
- }
- if (segment.key && !segment.key.resolvedUri) {
- segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
- }
- if (segment.map && !segment.map.resolvedUri) {
- segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
- }
-
- if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
- segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
- }
- if (segment.parts && segment.parts.length) {
- segment.parts.forEach((p) => {
- if (p.resolvedUri) {
- return;
- }
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
-
- if (segment.preloadHints && segment.preloadHints.length) {
- segment.preloadHints.forEach((p) => {
- if (p.resolvedUri) {
- return;
- }
- p.resolvedUri = resolveUrl(baseUri, p.uri);
- });
- }
-};
-
-const getAllSegments = function(media) {
- const segments = media.segments || [];
- const preloadSegment = media.preloadSegment;
-
- // a preloadSegment with only preloadHints is not currently
- // a usable segment, only include a preloadSegment that has
- // parts.
- if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
- // if preloadHints has a MAP that means that the
- // init segment is going to change. We cannot use any of the parts
- // from this preload segment.
- if (preloadSegment.preloadHints) {
- for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
- if (preloadSegment.preloadHints[i].type === 'MAP') {
- return segments;
- }
- }
- }
- // set the duration for our preload segment to target duration.
- preloadSegment.duration = media.targetDuration;
- preloadSegment.preload = true;
-
- segments.push(preloadSegment);
- }
-
- return segments;
-};
-
-// consider the playlist unchanged if the playlist object is the same or
-// the number of segments is equal, the media sequence number is unchanged,
-// and this playlist hasn't become the end of the playlist
-export const isPlaylistUnchanged = (a, b) => a === b ||
- (a.segments && b.segments && a.segments.length === b.segments.length &&
- a.endList === b.endList &&
- a.mediaSequence === b.mediaSequence);
-
-/**
- * Returns a new master playlist that is the result of merging an
- * updated media playlist into the original version. If the
- * updated media playlist does not match any of the playlist
- * entries in the original master playlist, null is returned.
- *
- * @param {Object} master a parsed master M3U8 object
- * @param {Object} media a parsed media M3U8 object
- * @return {Object} a new object that represents the original
- * master playlist with the updated media playlist merged in, or
- * null if the merge produced no change.
- */
-export const updateMaster = (master, newMedia, unchangedCheck = isPlaylistUnchanged) => {
- const result = mergeOptions(master, {});
- const oldMedia = result.playlists[newMedia.id];
-
- if (!oldMedia) {
- return null;
- }
-
- if (unchangedCheck(oldMedia, newMedia)) {
- return null;
- }
-
- newMedia.segments = getAllSegments(newMedia);
-
- const mergedPlaylist = mergeOptions(oldMedia, newMedia);
-
- // always use the new media's preload segment
- if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
- delete mergedPlaylist.preloadSegment;
- }
-
- // if the update could overlap existing segment information, merge the two segment lists
- if (oldMedia.segments) {
- if (newMedia.skip) {
- newMedia.segments = newMedia.segments || [];
- // add back in objects for skipped segments, so that we merge
- // old properties into the new segments
- for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
- newMedia.segments.unshift({skipped: true});
- }
- }
- mergedPlaylist.segments = updateSegments(
- oldMedia.segments,
- newMedia.segments,
- newMedia.mediaSequence - oldMedia.mediaSequence
- );
- }
-
- // resolve any segment URIs to prevent us from having to do it later
- mergedPlaylist.segments.forEach((segment) => {
- resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
- });
-
- // TODO Right now in the playlists array there are two references to each playlist, one
- // that is referenced by index, and one by URI. The index reference may no longer be
- // necessary.
- for (let i = 0; i < result.playlists.length; i++) {
- if (result.playlists[i].id === newMedia.id) {
- result.playlists[i] = mergedPlaylist;
- }
- }
- result.playlists[newMedia.id] = mergedPlaylist;
- // URI reference added for backwards compatibility
- result.playlists[newMedia.uri] = mergedPlaylist;
-
- // update media group playlist references.
- forEachMediaGroup(master, (properties, mediaType, groupKey, labelKey) => {
- if (!properties.playlists) {
- return;
- }
- for (let i = 0; i < properties.playlists.length; i++) {
- if (newMedia.id === properties.playlists[i].id) {
- properties.playlists[i] = newMedia;
- }
- }
- });
-
- return result;
-};
-
-/**
- * Calculates the time to wait before refreshing a live playlist
- *
- * @param {Object} media
- * The current media
- * @param {boolean} update
- * True if there were any updates from the last refresh, false otherwise
- * @return {number}
- * The time in ms to wait before refreshing the live playlist
- */
-export const refreshDelay = (media, update) => {
- const lastSegment = media.segments[media.segments.length - 1];
- const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
- const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
-
- if (update && lastDuration) {
- return lastDuration * 1000;
- }
-
- // if the playlist is unchanged since the last reload or last segment duration
- // cannot be determined, try again after half the target duration
- return (media.partTargetDuration || media.targetDuration || 10) * 500;
-};
-
-/**
- * Load a playlist from a remote location
- *
- * @class PlaylistLoader
- * @extends Stream
- * @param {string|Object} src url or object of manifest
- * @param {boolean} withCredentials the withCredentials xhr option
- * @class
- */
-export default class PlaylistLoader extends EventTarget {
- constructor(src, vhs, options = { }) {
- super();
-
- if (!src) {
- throw new Error('A non-empty playlist URL or object is required');
- }
- this.logger_ = logger('PlaylistLoader');
-
- const { withCredentials = false, handleManifestRedirects = false } = options;
-
- this.src = src;
- this.vhs_ = vhs;
- this.withCredentials = withCredentials;
- this.handleManifestRedirects = handleManifestRedirects;
-
- const vhsOptions = vhs.options_;
-
- this.customTagParsers = (vhsOptions && vhsOptions.customTagParsers) || [];
- this.customTagMappers = (vhsOptions && vhsOptions.customTagMappers) || [];
- this.experimentalLLHLS = (vhsOptions && vhsOptions.experimentalLLHLS) || false;
-
- // initialize the loader state
- this.state = 'HAVE_NOTHING';
-
- // live playlist staleness timeout
- this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
- this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
- }
-
- handleMediaupdatetimeout_() {
- if (this.state !== 'HAVE_METADATA') {
- // only refresh the media playlist if no other activity is going on
- return;
- }
- const media = this.media();
-
- let uri = resolveUrl(this.master.uri, media.uri);
-
- if (this.experimentalLLHLS) {
- uri = addLLHLSQueryDirectives(uri, media);
- }
- this.state = 'HAVE_CURRENT_METADATA';
-
- this.request = this.vhs_.xhr({
- uri,
- withCredentials: this.withCredentials
- }, (error, req) => {
- // disposed
- if (!this.request) {
- return;
- }
-
- if (error) {
- return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
- }
-
- this.haveMetadata({
- playlistString: this.request.responseText,
- url: this.media().uri,
- id: this.media().id
- });
- });
-
- }
-
- playlistRequestError(xhr, playlist, startingState) {
- const {
- uri,
- id
- } = playlist;
-
- // any in-flight request is now finished
- this.request = null;
-
- if (startingState) {
- this.state = startingState;
- }
-
- this.error = {
- playlist: this.master.playlists[id],
- status: xhr.status,
- message: `HLS playlist request error at URL: ${uri}.`,
- responseText: xhr.responseText,
- code: (xhr.status >= 500) ? 4 : 2
- };
-
- this.trigger('error');
- }
-
- parseManifest_({url, manifestString}) {
- return parseManifest({
- onwarn: ({message}) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
- oninfo: ({message}) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
- manifestString,
- customTagParsers: this.customTagParsers,
- customTagMappers: this.customTagMappers,
- experimentalLLHLS: this.experimentalLLHLS
- });
- }
-
- /**
- * Update the playlist loader's state in response to a new or updated playlist.
- *
- * @param {string} [playlistString]
- * Playlist string (if playlistObject is not provided)
- * @param {Object} [playlistObject]
- * Playlist object (if playlistString is not provided)
- * @param {string} url
- * URL of playlist
- * @param {string} id
- * ID to use for playlist
- */
- haveMetadata({ playlistString, playlistObject, url, id }) {
- // any in-flight request is now finished
- this.request = null;
- this.state = 'HAVE_METADATA';
-
- const playlist = playlistObject || this.parseManifest_({
- url,
- manifestString: playlistString
- });
-
- playlist.lastRequest = Date.now();
-
- setupMediaPlaylist({
- playlist,
- uri: url,
- id
- });
-
- // merge this playlist into the master
- const update = updateMaster(this.master, playlist);
-
- this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
-
- if (update) {
- this.master = update;
- this.media_ = this.master.playlists[id];
- } else {
- this.trigger('playlistunchanged');
- }
-
- // refresh live playlists after a target duration passes
- if (!this.media().endList) {
- window.clearTimeout(this.mediaUpdateTimeout);
- this.mediaUpdateTimeout = window.setTimeout(() => {
- this.trigger('mediaupdatetimeout');
- }, refreshDelay(this.media(), !!update));
- }
-
- this.trigger('loadedplaylist');
- }
-
- /**
- * Abort any outstanding work and clean up.
- */
- dispose() {
- this.trigger('dispose');
- this.stopRequest();
- window.clearTimeout(this.mediaUpdateTimeout);
- window.clearTimeout(this.finalRenditionTimeout);
-
- this.off();
- }
-
- stopRequest() {
- if (this.request) {
- const oldRequest = this.request;
-
- this.request = null;
- oldRequest.onreadystatechange = null;
- oldRequest.abort();
- }
- }
-
- /**
- * When called without any arguments, returns the currently
- * active media playlist. When called with a single argument,
- * triggers the playlist loader to asynchronously switch to the
- * specified media playlist. Calling this method while the
- * loader is in the HAVE_NOTHING causes an error to be emitted
- * but otherwise has no effect.
- *
- * @param {Object=} playlist the parsed media playlist
- * object to switch to
- * @param {boolean=} shouldDelay whether we should delay the request by half target duration
- *
- * @return {Playlist} the current loaded media
- */
- media(playlist, shouldDelay) {
- // getter
- if (!playlist) {
- return this.media_;
- }
-
- // setter
- if (this.state === 'HAVE_NOTHING') {
- throw new Error('Cannot switch media playlist from ' + this.state);
- }
-
- // find the playlist object if the target playlist has been
- // specified by URI
- if (typeof playlist === 'string') {
- if (!this.master.playlists[playlist]) {
- throw new Error('Unknown playlist URI: ' + playlist);
- }
- playlist = this.master.playlists[playlist];
- }
-
- window.clearTimeout(this.finalRenditionTimeout);
-
- if (shouldDelay) {
- const delay = ((playlist.partTargetDuration || playlist.targetDuration) / 2) * 1000 || 5 * 1000;
-
- this.finalRenditionTimeout =
- window.setTimeout(this.media.bind(this, playlist, false), delay);
- return;
- }
-
- const startingState = this.state;
- const mediaChange = !this.media_ || playlist.id !== this.media_.id;
- const masterPlaylistRef = this.master.playlists[playlist.id];
-
- // switch to fully loaded playlists immediately
- if (masterPlaylistRef && masterPlaylistRef.endList ||
- // handle the case of a playlist object (e.g., if using vhs-json with a resolved
- // media playlist or, for the case of demuxed audio, a resolved audio media group)
- (playlist.endList && playlist.segments.length)) {
-
- // abort outstanding playlist requests
- if (this.request) {
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- }
- this.state = 'HAVE_METADATA';
- this.media_ = playlist;
-
- // trigger media change if the active media has been updated
- if (mediaChange) {
- this.trigger('mediachanging');
-
- if (startingState === 'HAVE_MASTER') {
- // The initial playlist was a master manifest, and the first media selected was
- // also provided (in the form of a resolved playlist object) as part of the
- // source object (rather than just a URL). Therefore, since the media playlist
- // doesn't need to be requested, loadedmetadata won't trigger as part of the
- // normal flow, and needs an explicit trigger here.
- this.trigger('loadedmetadata');
- } else {
- this.trigger('mediachange');
- }
- }
- return;
- }
-
- // switching to the active playlist is a no-op
- if (!mediaChange) {
- return;
- }
-
- this.state = 'SWITCHING_MEDIA';
-
- // there is already an outstanding playlist request
- if (this.request) {
- if (playlist.resolvedUri === this.request.url) {
- // requesting to switch to the same playlist multiple times
- // has no effect after the first
- return;
- }
- this.request.onreadystatechange = null;
- this.request.abort();
- this.request = null;
- }
-
- // request the new playlist
- if (this.media_) {
- this.trigger('mediachanging');
- }
-
- this.request = this.vhs_.xhr({
- uri: playlist.resolvedUri,
- withCredentials: this.withCredentials
- }, (error, req) => {
- // disposed
- if (!this.request) {
- return;
- }
-
- playlist.lastRequest = Date.now();
-
- playlist.resolvedUri = resolveManifestRedirect(this.handleManifestRedirects, playlist.resolvedUri, req);
-
- if (error) {
- return this.playlistRequestError(this.request, playlist, startingState);
- }
-
- this.haveMetadata({
- playlistString: req.responseText,
- url: playlist.uri,
- id: playlist.id
- });
-
- // fire loadedmetadata the first time a media playlist is loaded
- if (startingState === 'HAVE_MASTER') {
- this.trigger('loadedmetadata');
- } else {
- this.trigger('mediachange');
- }
- });
- }
-
- /**
- * pause loading of the playlist
- */
- pause() {
- this.stopRequest();
- window.clearTimeout(this.mediaUpdateTimeout);
- if (this.state === 'HAVE_NOTHING') {
- // If we pause the loader before any data has been retrieved, its as if we never
- // started, so reset to an unstarted state.
- this.started = false;
- }
- // Need to restore state now that no activity is happening
- if (this.state === 'SWITCHING_MEDIA') {
- // if the loader was in the process of switching media, it should either return to
- // HAVE_MASTER or HAVE_METADATA depending on if the loader has loaded a media
- // playlist yet. This is determined by the existence of loader.media_
- if (this.media_) {
- this.state = 'HAVE_METADATA';
- } else {
- this.state = 'HAVE_MASTER';
- }
- } else if (this.state === 'HAVE_CURRENT_METADATA') {
- this.state = 'HAVE_METADATA';
- }
- }
-
- /**
- * start loading of the playlist
- */
- load(shouldDelay) {
- window.clearTimeout(this.mediaUpdateTimeout);
-
- const media = this.media();
-
- if (shouldDelay) {
- const delay = media ? ((media.partTargetDuration || media.targetDuration) / 2) * 1000 : 5 * 1000;
-
- this.mediaUpdateTimeout = window.setTimeout(() => this.load(), delay);
- return;
- }
-
- if (!this.started) {
- this.start();
- return;
- }
-
- if (media && !media.endList) {
- this.trigger('mediaupdatetimeout');
- } else {
- this.trigger('loadedplaylist');
- }
- }
-
- /**
- * start loading of the playlist
- */
- start() {
- this.started = true;
-
- if (typeof this.src === 'object') {
- // in the case of an entirely constructed manifest object (meaning there's no actual
- // manifest on a server), default the uri to the page's href
- if (!this.src.uri) {
- this.src.uri = window.location.href;
- }
-
- // resolvedUri is added on internally after the initial request. Since there's no
- // request for pre-resolved manifests, add on resolvedUri here.
- this.src.resolvedUri = this.src.uri;
-
- // Since a manifest object was passed in as the source (instead of a URL), the first
- // request can be skipped (since the top level of the manifest, at a minimum, is
- // already available as a parsed manifest object). However, if the manifest object
- // represents a master playlist, some media playlists may need to be resolved before
- // the starting segment list is available. Therefore, go directly to setup of the
- // initial playlist, and let the normal flow continue from there.
- //
- // Note that the call to setup is asynchronous, as other sections of VHS may assume
- // that the first request is asynchronous.
- setTimeout(() => {
- this.setupInitialPlaylist(this.src);
- }, 0);
- return;
- }
-
- // request the specified URL
- this.request = this.vhs_.xhr({
- uri: this.src,
- withCredentials: this.withCredentials
- }, (error, req) => {
- // disposed
- if (!this.request) {
- return;
- }
-
- // clear the loader's request reference
- this.request = null;
-
- if (error) {
- this.error = {
- status: req.status,
- message: `HLS playlist request error at URL: ${this.src}.`,
- responseText: req.responseText,
- // MEDIA_ERR_NETWORK
- code: 2
- };
- if (this.state === 'HAVE_NOTHING') {
- this.started = false;
- }
- return this.trigger('error');
- }
-
- this.src = resolveManifestRedirect(this.handleManifestRedirects, this.src, req);
-
- const manifest = this.parseManifest_({
- manifestString: req.responseText,
- url: this.src
- });
-
- this.setupInitialPlaylist(manifest);
- });
- }
-
- srcUri() {
- return typeof this.src === 'string' ? this.src : this.src.uri;
- }
-
- /**
- * Given a manifest object that's either a master or media playlist, trigger the proper
- * events and set the state of the playlist loader.
- *
- * If the manifest object represents a master playlist, `loadedplaylist` will be
- * triggered to allow listeners to select a playlist. If none is selected, the loader
- * will default to the first one in the playlists array.
- *
- * If the manifest object represents a media playlist, `loadedplaylist` will be
- * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
- *
- * In the case of a media playlist, a master playlist object wrapper with one playlist
- * will be created so that all logic can handle playlists in the same fashion (as an
- * assumed manifest object schema).
- *
- * @param {Object} manifest
- * The parsed manifest object
- */
- setupInitialPlaylist(manifest) {
- this.state = 'HAVE_MASTER';
-
- if (manifest.playlists) {
- this.master = manifest;
- addPropertiesToMaster(this.master, this.srcUri());
- // If the initial master playlist has playlists wtih segments already resolved,
- // then resolve URIs in advance, as they are usually done after a playlist request,
- // which may not happen if the playlist is resolved.
- manifest.playlists.forEach((playlist) => {
- playlist.segments = getAllSegments(playlist);
-
- playlist.segments.forEach((segment) => {
- resolveSegmentUris(segment, playlist.resolvedUri);
- });
- });
- this.trigger('loadedplaylist');
- if (!this.request) {
- // no media playlist was specifically selected so start
- // from the first listed one
- this.media(this.master.playlists[0]);
- }
- return;
- }
-
- // In order to support media playlists passed in as vhs-json, the case where the uri
- // is not provided as part of the manifest should be considered, and an appropriate
- // default used.
- const uri = this.srcUri() || window.location.href;
-
- this.master = masterForMedia(manifest, uri);
- this.haveMetadata({
- playlistObject: manifest,
- url: uri,
- id: this.master.playlists[0].id
- });
- this.trigger('loadedmetadata');
- }
-
-}
diff --git a/node_modules/@videojs/http-streaming/src/playlist-selectors.js b/node_modules/@videojs/http-streaming/src/playlist-selectors.js
deleted file mode 100644
index 2dabc08..0000000
--- a/node_modules/@videojs/http-streaming/src/playlist-selectors.js
+++ /dev/null
@@ -1,531 +0,0 @@
-import window from 'global/window';
-import Config from './config';
-import Playlist from './playlist';
-import { codecsForPlaylist } from './util/codecs.js';
-import logger from './util/logger';
-
-const logFn = logger('PlaylistSelector');
-const representationToString = function(representation) {
- if (!representation || !representation.playlist) {
- return;
- }
- const playlist = representation.playlist;
-
- return JSON.stringify({
- id: playlist.id,
- bandwidth: representation.bandwidth,
- width: representation.width,
- height: representation.height,
- codecs: playlist.attributes && playlist.attributes.CODECS || ''
- });
-};
-
-// Utilities
-
-/**
- * Returns the CSS value for the specified property on an element
- * using `getComputedStyle`. Firefox has a long-standing issue where
- * getComputedStyle() may return null when running in an iframe with
- * `display: none`.
- *
- * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
- * @param {HTMLElement} el the htmlelement to work on
- * @param {string} the proprety to get the style for
- */
-const safeGetComputedStyle = function(el, property) {
- if (!el) {
- return '';
- }
-
- const result = window.getComputedStyle(el);
-
- if (!result) {
- return '';
- }
-
- return result[property];
-};
-
-/**
- * Resuable stable sort function
- *
- * @param {Playlists} array
- * @param {Function} sortFn Different comparators
- * @function stableSort
- */
-const stableSort = function(array, sortFn) {
- const newArray = array.slice();
-
- array.sort(function(left, right) {
- const cmp = sortFn(left, right);
-
- if (cmp === 0) {
- return newArray.indexOf(left) - newArray.indexOf(right);
- }
- return cmp;
- });
-};
-
-/**
- * A comparator function to sort two playlist object by bandwidth.
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the bandwidth attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the bandwidth of right is greater than left and
- * exactly zero if the two are equal.
- */
-export const comparePlaylistBandwidth = function(left, right) {
- let leftBandwidth;
- let rightBandwidth;
-
- if (left.attributes.BANDWIDTH) {
- leftBandwidth = left.attributes.BANDWIDTH;
- }
- leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
- if (right.attributes.BANDWIDTH) {
- rightBandwidth = right.attributes.BANDWIDTH;
- }
- rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
-
- return leftBandwidth - rightBandwidth;
-};
-
-/**
- * A comparator function to sort two playlist object by resolution (width).
- *
- * @param {Object} left a media playlist object
- * @param {Object} right a media playlist object
- * @return {number} Greater than zero if the resolution.width attribute of
- * left is greater than the corresponding attribute of right. Less
- * than zero if the resolution.width of right is greater than left and
- * exactly zero if the two are equal.
- */
-export const comparePlaylistResolution = function(left, right) {
- let leftWidth;
- let rightWidth;
-
- if (left.attributes.RESOLUTION &&
- left.attributes.RESOLUTION.width) {
- leftWidth = left.attributes.RESOLUTION.width;
- }
-
- leftWidth = leftWidth || window.Number.MAX_VALUE;
-
- if (right.attributes.RESOLUTION &&
- right.attributes.RESOLUTION.width) {
- rightWidth = right.attributes.RESOLUTION.width;
- }
-
- rightWidth = rightWidth || window.Number.MAX_VALUE;
-
- // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
- // have the same media dimensions/ resolution
- if (leftWidth === rightWidth &&
- left.attributes.BANDWIDTH &&
- right.attributes.BANDWIDTH) {
- return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
- }
- return leftWidth - rightWidth;
-};
-
-/**
- * Chooses the appropriate media playlist based on bandwidth and player size
- *
- * @param {Object} master
- * Object representation of the master manifest
- * @param {number} playerBandwidth
- * Current calculated bandwidth of the player
- * @param {number} playerWidth
- * Current width of the player element (should account for the device pixel ratio)
- * @param {number} playerHeight
- * Current height of the player element (should account for the device pixel ratio)
- * @param {boolean} limitRenditionByPlayerDimensions
- * True if the player width and height should be used during the selection, false otherwise
- * @param {Object} masterPlaylistController
- * the current masterPlaylistController object
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-export let simpleSelector = function(
- master,
- playerBandwidth,
- playerWidth,
- playerHeight,
- limitRenditionByPlayerDimensions,
- masterPlaylistController
-) {
-
- // If we end up getting called before `master` is available, exit early
- if (!master) {
- return;
- }
-
- const options = {
- bandwidth: playerBandwidth,
- width: playerWidth,
- height: playerHeight,
- limitRenditionByPlayerDimensions
- };
-
- let playlists = master.playlists;
-
- // if playlist is audio only, select between currently active audio group playlists.
- if (Playlist.isAudioOnly(master)) {
- playlists = masterPlaylistController.getAudioTrackPlaylists_();
- // add audioOnly to options so that we log audioOnly: true
- // at the buttom of this function for debugging.
- options.audioOnly = true;
- }
- // convert the playlists to an intermediary representation to make comparisons easier
- let sortedPlaylistReps = playlists.map((playlist) => {
- let bandwidth;
- const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
- const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
-
- bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
-
- bandwidth = bandwidth || window.Number.MAX_VALUE;
-
- return {
- bandwidth,
- width,
- height,
- playlist
- };
- });
-
- stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth);
-
- // filter out any playlists that have been excluded due to
- // incompatible configurations
- sortedPlaylistReps = sortedPlaylistReps.filter((rep) => !Playlist.isIncompatible(rep.playlist));
-
- // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
- let enabledPlaylistReps = sortedPlaylistReps.filter((rep) => Playlist.isEnabled(rep.playlist));
-
- if (!enabledPlaylistReps.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylistReps = sortedPlaylistReps.filter((rep) => !Playlist.isDisabled(rep.playlist));
- }
-
- // filter out any variant that has greater effective bitrate
- // than the current estimated bandwidth
- const bandwidthPlaylistReps = enabledPlaylistReps.filter((rep) => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
-
- let highestRemainingBandwidthRep =
- bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1];
-
- // get all of the renditions with the same (highest) bandwidth
- // and then taking the very first element
- const bandwidthBestRep = bandwidthPlaylistReps.filter((rep) => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
-
- // if we're not going to limit renditions by player size, make an early decision.
- if (limitRenditionByPlayerDimensions === false) {
- const chosenRep = (
- bandwidthBestRep ||
- enabledPlaylistReps[0] ||
- sortedPlaylistReps[0]
- );
-
- if (chosenRep && chosenRep.playlist) {
- let type = 'sortedPlaylistReps';
-
- if (bandwidthBestRep) {
- type = 'bandwidthBestRep';
- }
- if (enabledPlaylistReps[0]) {
- type = 'enabledPlaylistReps';
- }
- logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
-
- return chosenRep.playlist;
- }
-
- logFn('could not choose a playlist with options', options);
- return null;
- }
-
- // filter out playlists without resolution information
- const haveResolution = bandwidthPlaylistReps.filter((rep) => rep.width && rep.height);
-
- // sort variants by resolution
- stableSort(haveResolution, (left, right) => left.width - right.width);
-
- // if we have the exact resolution as the player use it
- const resolutionBestRepList = haveResolution.filter((rep) => rep.width === playerWidth && rep.height === playerHeight);
-
- highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1];
- // ensure that we pick the highest bandwidth variant that have exact resolution
- const resolutionBestRep = resolutionBestRepList.filter((rep) => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
-
- let resolutionPlusOneList;
- let resolutionPlusOneSmallest;
- let resolutionPlusOneRep;
-
- // find the smallest variant that is larger than the player
- // if there is no match of exact resolution
- if (!resolutionBestRep) {
- resolutionPlusOneList = haveResolution.filter((rep) => rep.width > playerWidth || rep.height > playerHeight);
-
- // find all the variants have the same smallest resolution
- resolutionPlusOneSmallest = resolutionPlusOneList.filter((rep) => rep.width === resolutionPlusOneList[0].width &&
- rep.height === resolutionPlusOneList[0].height);
-
- // ensure that we also pick the highest bandwidth variant that
- // is just-larger-than the video player
- highestRemainingBandwidthRep =
- resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
- resolutionPlusOneRep = resolutionPlusOneSmallest.filter((rep) => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
- }
-
- // fallback chain of variants
- const chosenRep = (
- resolutionPlusOneRep ||
- resolutionBestRep ||
- bandwidthBestRep ||
- enabledPlaylistReps[0] ||
- sortedPlaylistReps[0]
- );
-
- if (chosenRep && chosenRep.playlist) {
- let type = 'sortedPlaylistReps';
-
- if (resolutionPlusOneRep) {
- type = 'resolutionPlusOneRep';
- } else if (resolutionBestRep) {
- type = 'resolutionBestRep';
- } else if (bandwidthBestRep) {
- type = 'bandwidthBestRep';
- } else if (enabledPlaylistReps[0]) {
- type = 'enabledPlaylistReps';
- }
-
- logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
- return chosenRep.playlist;
- }
- logFn('could not choose a playlist with options', options);
- return null;
-};
-
-export const TEST_ONLY_SIMPLE_SELECTOR = (newSimpleSelector) => {
- const oldSimpleSelector = simpleSelector;
-
- simpleSelector = newSimpleSelector;
-
- return function resetSimpleSelector() {
- simpleSelector = oldSimpleSelector;
- };
-};
-
-// Playlist Selectors
-
-/**
- * Chooses the appropriate media playlist based on the most recent
- * bandwidth estimate and the player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Playlist} the highest bitrate playlist less than the
- * currently detected bandwidth, accounting for some amount of
- * bandwidth variance
- */
-export const lastBandwidthSelector = function() {
- const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
-
- return simpleSelector(
- this.playlists.master,
- this.systemBandwidth,
- parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio,
- parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio,
- this.limitRenditionByPlayerDimensions,
- this.masterPlaylistController_
- );
-};
-
-/**
- * Chooses the appropriate media playlist based on an
- * exponential-weighted moving average of the bandwidth after
- * filtering for player size.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @param {number} decay - a number between 0 and 1. Higher values of
- * this parameter will cause previous bandwidth estimates to lose
- * significance more quickly.
- * @return {Function} a function which can be invoked to create a new
- * playlist selector function.
- * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
- */
-export const movingAverageBandwidthSelector = function(decay) {
- let average = -1;
- let lastSystemBandwidth = -1;
-
- if (decay < 0 || decay > 1) {
- throw new Error('Moving average bandwidth decay must be between 0 and 1.');
- }
-
- return function() {
- const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
-
- if (average < 0) {
- average = this.systemBandwidth;
- lastSystemBandwidth = this.systemBandwidth;
- }
-
- // stop the average value from decaying for every 250ms
- // when the systemBandwidth is constant
- // and
- // stop average from setting to a very low value when the
- // systemBandwidth becomes 0 in case of chunk cancellation
-
- if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
- average = decay * this.systemBandwidth + (1 - decay) * average;
- lastSystemBandwidth = this.systemBandwidth;
- }
-
- return simpleSelector(
- this.playlists.master,
- average,
- parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio,
- parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio,
- this.limitRenditionByPlayerDimensions,
- this.masterPlaylistController_
- );
- };
-};
-
-/**
- * Chooses the appropriate media playlist based on the potential to rebuffer
- *
- * @param {Object} settings
- * Object of information required to use this selector
- * @param {Object} settings.master
- * Object representation of the master manifest
- * @param {number} settings.currentTime
- * The current time of the player
- * @param {number} settings.bandwidth
- * Current measured bandwidth
- * @param {number} settings.duration
- * Duration of the media
- * @param {number} settings.segmentDuration
- * Segment duration to be used in round trip time calculations
- * @param {number} settings.timeUntilRebuffer
- * Time left in seconds until the player has to rebuffer
- * @param {number} settings.currentTimeline
- * The current timeline segments are being loaded from
- * @param {SyncController} settings.syncController
- * SyncController for determining if we have a sync point for a given playlist
- * @return {Object|null}
- * {Object} return.playlist
- * The highest bandwidth playlist with the least amount of rebuffering
- * {Number} return.rebufferingImpact
- * The amount of time in seconds switching to this playlist will rebuffer. A
- * negative value means that switching will cause zero rebuffering.
- */
-export const minRebufferMaxBandwidthSelector = function(settings) {
- const {
- master,
- currentTime,
- bandwidth,
- duration,
- segmentDuration,
- timeUntilRebuffer,
- currentTimeline,
- syncController
- } = settings;
-
- // filter out any playlists that have been excluded due to
- // incompatible configurations
- const compatiblePlaylists = master.playlists.filter(playlist => !Playlist.isIncompatible(playlist));
-
- // filter out any playlists that have been disabled manually through the representations
- // api or blacklisted temporarily due to playback errors.
- let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
-
- if (!enabledPlaylists.length) {
- // if there are no enabled playlists, then they have all been blacklisted or disabled
- // by the user through the representations api. In this case, ignore blacklisting and
- // fallback to what the user wants by using playlists the user has not disabled.
- enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
- }
-
- const bandwidthPlaylists =
- enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
-
- const rebufferingEstimates = bandwidthPlaylists.map((playlist) => {
- const syncPoint = syncController.getSyncPoint(
- playlist,
- duration,
- currentTimeline,
- currentTime
- );
- // If there is no sync point for this playlist, switching to it will require a
- // sync request first. This will double the request time
- const numRequests = syncPoint ? 1 : 2;
- const requestTimeEstimate = Playlist.estimateSegmentRequestTime(
- segmentDuration,
- bandwidth,
- playlist
- );
- const rebufferingImpact = (requestTimeEstimate * numRequests) - timeUntilRebuffer;
-
- return {
- playlist,
- rebufferingImpact
- };
- });
-
- const noRebufferingPlaylists = rebufferingEstimates.filter((estimate) => estimate.rebufferingImpact <= 0);
-
- // Sort by bandwidth DESC
- stableSort(
- noRebufferingPlaylists,
- (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist)
- );
-
- if (noRebufferingPlaylists.length) {
- return noRebufferingPlaylists[0];
- }
-
- stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
-
- return rebufferingEstimates[0] || null;
-};
-
-/**
- * Chooses the appropriate media playlist, which in this case is the lowest bitrate
- * one with video. If no renditions with video exist, return the lowest audio rendition.
- *
- * Expects to be called within the context of an instance of VhsHandler
- *
- * @return {Object|null}
- * {Object} return.playlist
- * The lowest bitrate playlist that contains a video codec. If no such rendition
- * exists pick the lowest audio rendition.
- */
-export const lowestBitrateCompatibleVariantSelector = function() {
- // filter out any playlists that have been excluded due to
- // incompatible configurations or playback errors
- const playlists = this.playlists.master.playlists.filter(Playlist.isEnabled);
-
- // Sort ascending by bitrate
- stableSort(
- playlists,
- (a, b) => comparePlaylistBandwidth(a, b)
- );
-
- // Parse and assume that playlists with no video codec have no video
- // (this is not necessarily true, although it is generally true).
- //
- // If an entire manifest has no valid videos everything will get filtered
- // out.
- const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.master, playlist).video);
-
- return playlistsWithVideo[0] || null;
-};
diff --git a/node_modules/@videojs/http-streaming/src/playlist.js b/node_modules/@videojs/http-streaming/src/playlist.js
deleted file mode 100644
index a1a0532..0000000
--- a/node_modules/@videojs/http-streaming/src/playlist.js
+++ /dev/null
@@ -1,730 +0,0 @@
-/**
- * @file playlist.js
- *
- * Playlist related utilities.
- */
-import videojs from 'video.js';
-import window from 'global/window';
-import {isAudioCodec} from '@videojs/vhs-utils/es/codecs.js';
-import {TIME_FUDGE_FACTOR} from './ranges.js';
-
-const {createTimeRange} = videojs;
-
-/**
- * A function to get a combined list of parts and segments with durations
- * and indexes.
- *
- * @param {Playlist} playlist the playlist to get the list for.
- *
- * @return {Array} The part/segment list.
- */
-export const getPartsAndSegments = (playlist) => (playlist.segments || []).reduce((acc, segment, si) => {
- if (segment.parts) {
- segment.parts.forEach(function(part, pi) {
- acc.push({duration: part.duration, segmentIndex: si, partIndex: pi, part, segment});
- });
- } else {
- acc.push({duration: segment.duration, segmentIndex: si, partIndex: null, segment, part: null});
- }
- return acc;
-}, []);
-
-export const getLastParts = (media) => {
- const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
-
- return lastSegment && lastSegment.parts || [];
-};
-
-export const getKnownPartCount = ({preloadSegment}) => {
- if (!preloadSegment) {
- return;
- }
- const {parts, preloadHints} = preloadSegment;
- let partCount = (preloadHints || [])
- .reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
-
- partCount += (parts && parts.length) ? parts.length : 0;
-
- return partCount;
-};
-/**
- * Get the number of seconds to delay from the end of a
- * live playlist.
- *
- * @param {Playlist} master the master playlist
- * @param {Playlist} media the media playlist
- * @return {number} the hold back in seconds.
- */
-export const liveEdgeDelay = (master, media) => {
- if (media.endList) {
- return 0;
- }
-
- // dash suggestedPresentationDelay trumps everything
- if (master && master.suggestedPresentationDelay) {
- return master.suggestedPresentationDelay;
- }
-
- const hasParts = getLastParts(media).length > 0;
-
- // look for "part" delays from ll-hls first
- if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
- return media.serverControl.partHoldBack;
- } else if (hasParts && media.partTargetDuration) {
- return media.partTargetDuration * 3;
-
- // finally look for full segment delays
- } else if (media.serverControl && media.serverControl.holdBack) {
- return media.serverControl.holdBack;
- } else if (media.targetDuration) {
- return media.targetDuration * 3;
- }
-
- return 0;
-};
-
-/**
- * walk backward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {Number} endSequence the mediaSequence to stop walking on
- */
-
-const backwardDuration = function(playlist, endSequence) {
- let result = 0;
- let i = endSequence - playlist.mediaSequence;
- // if a start time is available for segment immediately following
- // the interval, use it
- let segment = playlist.segments[i];
-
- // Walk backward until we find the latest segment with timeline
- // information that is earlier than endSequence
- if (segment) {
- if (typeof segment.start !== 'undefined') {
- return { result: segment.start, precise: true };
- }
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - segment.duration,
- precise: true
- };
- }
- }
- while (i--) {
- segment = playlist.segments[i];
- if (typeof segment.end !== 'undefined') {
- return { result: result + segment.end, precise: true };
- }
-
- result += segment.duration;
-
- if (typeof segment.start !== 'undefined') {
- return { result: result + segment.start, precise: true };
- }
- }
- return { result, precise: false };
-};
-
-/**
- * walk forward until we find a duration we can use
- * or return a failure
- *
- * @param {Playlist} playlist the playlist to walk through
- * @param {number} endSequence the mediaSequence to stop walking on
- */
-const forwardDuration = function(playlist, endSequence) {
- let result = 0;
- let segment;
- let i = endSequence - playlist.mediaSequence;
- // Walk forward until we find the earliest segment with timeline
- // information
-
- for (; i < playlist.segments.length; i++) {
- segment = playlist.segments[i];
- if (typeof segment.start !== 'undefined') {
- return {
- result: segment.start - result,
- precise: true
- };
- }
-
- result += segment.duration;
-
- if (typeof segment.end !== 'undefined') {
- return {
- result: segment.end - result,
- precise: true
- };
- }
-
- }
- // indicate we didn't find a useful duration estimate
- return { result: -1, precise: false };
-};
-
-/**
- * Calculate the media duration from the segments associated with a
- * playlist. The duration of a subinterval of the available segments
- * may be calculated by specifying an end index.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper boundary
- * for the playlist. Defaults to playlist length.
- * @param {number} expired the amount of time that has dropped
- * off the front of the playlist in a live scenario
- * @return {number} the duration between the first available segment
- * and end index.
- */
-const intervalDuration = function(playlist, endSequence, expired) {
- if (typeof endSequence === 'undefined') {
- endSequence = playlist.mediaSequence + playlist.segments.length;
- }
-
- if (endSequence < playlist.mediaSequence) {
- return 0;
- }
-
- // do a backward walk to estimate the duration
- const backward = backwardDuration(playlist, endSequence);
-
- if (backward.precise) {
- // if we were able to base our duration estimate on timing
- // information provided directly from the Media Source, return
- // it
- return backward.result;
- }
-
- // walk forward to see if a precise duration estimate can be made
- // that way
- const forward = forwardDuration(playlist, endSequence);
-
- if (forward.precise) {
- // we found a segment that has been buffered and so it's
- // position is known precisely
- return forward.result;
- }
-
- // return the less-precise, playlist-based duration estimate
- return backward.result + expired;
-};
-
-/**
- * Calculates the duration of a playlist. If a start and end index
- * are specified, the duration will be for the subset of the media
- * timeline between those two indices. The total duration for live
- * playlists is always Infinity.
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} endSequence an exclusive upper
- * boundary for the playlist. Defaults to the playlist media
- * sequence number plus its length.
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @return {number} the duration between the start index and end
- * index.
- */
-export const duration = function(playlist, endSequence, expired) {
- if (!playlist) {
- return 0;
- }
-
- if (typeof expired !== 'number') {
- expired = 0;
- }
-
- // if a slice of the total duration is not requested, use
- // playlist-level duration indicators when they're present
- if (typeof endSequence === 'undefined') {
- // if present, use the duration specified in the playlist
- if (playlist.totalDuration) {
- return playlist.totalDuration;
- }
-
- // duration should be Infinity for live playlists
- if (!playlist.endList) {
- return window.Infinity;
- }
- }
-
- // calculate the total duration based on the segment durations
- return intervalDuration(
- playlist,
- endSequence,
- expired
- );
-};
-
-/**
- * Calculate the time between two indexes in the current playlist
- * neight the start- nor the end-index need to be within the current
- * playlist in which case, the targetDuration of the playlist is used
- * to approximate the durations of the segments
- *
- * @param {Array} options.durationList list to iterate over for durations.
- * @param {number} options.defaultDuration duration to use for elements before or after the durationList
- * @param {number} options.startIndex partsAndSegments index to start
- * @param {number} options.endIndex partsAndSegments index to end.
- * @return {number} the number of seconds between startIndex and endIndex
- */
-export const sumDurations = function({defaultDuration, durationList, startIndex, endIndex}) {
- let durations = 0;
-
- if (startIndex > endIndex) {
- [startIndex, endIndex] = [endIndex, startIndex];
- }
-
- if (startIndex < 0) {
- for (let i = startIndex; i < Math.min(0, endIndex); i++) {
- durations += defaultDuration;
- }
- startIndex = 0;
- }
-
- for (let i = startIndex; i < endIndex; i++) {
- durations += durationList[i].duration;
- }
-
- return durations;
-};
-
-/**
- * Calculates the playlist end time
- *
- * @param {Object} playlist a media playlist object
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
- * playlist end calculation should consider the safe live end
- * (truncate the playlist end by three segments). This is normally
- * used for calculating the end of the playlist's seekable range.
- * This takes into account the value of liveEdgePadding.
- * Setting liveEdgePadding to 0 is equivalent to setting this to false.
- * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
- * If this is provided, it is used in the safe live end calculation.
- * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {number} the end time of playlist
- * @function playlistEnd
- */
-export const playlistEnd = function(playlist, expired, useSafeLiveEnd, liveEdgePadding) {
- if (!playlist || !playlist.segments) {
- return null;
- }
- if (playlist.endList) {
- return duration(playlist);
- }
-
- if (expired === null) {
- return null;
- }
-
- expired = expired || 0;
-
- let lastSegmentTime = intervalDuration(
- playlist,
- playlist.mediaSequence + playlist.segments.length,
- expired
- );
-
- if (useSafeLiveEnd) {
- liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
- lastSegmentTime -= liveEdgePadding;
- }
-
- // don't return a time less than zero
- return Math.max(0, lastSegmentTime);
-};
-
-/**
- * Calculates the interval of time that is currently seekable in a
- * playlist. The returned time ranges are relative to the earliest
- * moment in the specified playlist that is still available. A full
- * seekable implementation for live streams would need to offset
- * these values by the duration of content that has expired from the
- * stream.
- *
- * @param {Object} playlist a media playlist object
- * dropped off the front of the playlist in a live scenario
- * @param {number=} expired the amount of time that has
- * dropped off the front of the playlist in a live scenario
- * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
- * Corresponds to suggestedPresentationDelay in DASH manifests.
- * @return {TimeRanges} the periods of time that are valid targets
- * for seeking
- */
-export const seekable = function(playlist, expired, liveEdgePadding) {
- const useSafeLiveEnd = true;
- const seekableStart = expired || 0;
- const seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
-
- if (seekableEnd === null) {
- return createTimeRange();
- }
- return createTimeRange(seekableStart, seekableEnd);
-};
-
-/**
- * Determine the index and estimated starting time of the segment that
- * contains a specified playback position in a media playlist.
- *
- * @param {Object} options.playlist the media playlist to query
- * @param {number} options.currentTime The number of seconds since the earliest
- * possible position to determine the containing segment for
- * @param {number} options.startTime the time when the segment/part starts
- * @param {number} options.startingSegmentIndex the segment index to start looking at.
- * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
- *
- * @return {Object} an object with partIndex, segmentIndex, and startTime.
- */
-export const getMediaInfoForTime = function({
- playlist,
- currentTime,
- startingSegmentIndex,
- startingPartIndex,
- startTime
-}) {
-
- let time = currentTime - startTime;
- const partsAndSegments = getPartsAndSegments(playlist);
-
- let startIndex = 0;
-
- for (let i = 0; i < partsAndSegments.length; i++) {
- const partAndSegment = partsAndSegments[i];
-
- if (startingSegmentIndex !== partAndSegment.segmentIndex) {
- continue;
- }
-
- // skip this if part index does not match.
- if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
- continue;
- }
-
- startIndex = i;
- break;
- }
-
- if (time < 0) {
- // Walk backward from startIndex in the playlist, adding durations
- // until we find a segment that contains `time` and return it
- if (startIndex > 0) {
- for (let i = startIndex - 1; i >= 0; i--) {
- const partAndSegment = partsAndSegments[i];
-
- time += partAndSegment.duration;
-
- // TODO: consider not using TIME_FUDGE_FACTOR at all here
- if ((time + TIME_FUDGE_FACTOR) > 0) {
- return {
- partIndex: partAndSegment.partIndex,
- segmentIndex: partAndSegment.segmentIndex,
- startTime: startTime - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex,
- endIndex: i
- })
- };
- }
- }
- }
-
- // We were unable to find a good segment within the playlist
- // so select the first segment
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- }
-
- // When startIndex is negative, we first walk forward to first segment
- // adding target durations. If we "run out of time" before getting to
- // the first segment, return the first segment
- if (startIndex < 0) {
- for (let i = startIndex; i < 0; i++) {
- time -= playlist.targetDuration;
- if (time < 0) {
- return {
- partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
- segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
- startTime: currentTime
- };
- }
- }
- startIndex = 0;
- }
-
- // Walk forward from startIndex in the playlist, subtracting durations
- // until we find a segment that contains `time` and return it
- for (let i = startIndex; i < partsAndSegments.length; i++) {
- const partAndSegment = partsAndSegments[i];
-
- time -= partAndSegment.duration;
-
- // TODO: consider not using TIME_FUDGE_FACTOR at all here
- if ((time - TIME_FUDGE_FACTOR) < 0) {
- return {
- partIndex: partAndSegment.partIndex,
- segmentIndex: partAndSegment.segmentIndex,
- startTime: startTime + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: partsAndSegments,
- startIndex,
- endIndex: i
- })
- };
- }
- }
-
- // We are out of possible candidates so load the last one...
- return {
- segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
- partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
- startTime: currentTime
- };
-};
-
-/**
- * Check whether the playlist is blacklisted or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is blacklisted or not
- * @function isBlacklisted
- */
-export const isBlacklisted = function(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil > Date.now();
-};
-
-/**
- * Check whether the playlist is compatible with current playback configuration or has
- * been blacklisted permanently for being incompatible.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is incompatible or not
- * @function isIncompatible
- */
-export const isIncompatible = function(playlist) {
- return playlist.excludeUntil && playlist.excludeUntil === Infinity;
-};
-
-/**
- * Check whether the playlist is enabled or not.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is enabled or not
- * @function isEnabled
- */
-export const isEnabled = function(playlist) {
- const blacklisted = isBlacklisted(playlist);
-
- return (!playlist.disabled && !blacklisted);
-};
-
-/**
- * Check whether the playlist has been manually disabled through the representations api.
- *
- * @param {Object} playlist the media playlist object
- * @return {boolean} whether the playlist is disabled manually or not
- * @function isDisabled
- */
-export const isDisabled = function(playlist) {
- return playlist.disabled;
-};
-
-/**
- * Returns whether the current playlist is an AES encrypted HLS stream
- *
- * @return {boolean} true if it's an AES encrypted HLS stream
- */
-export const isAes = function(media) {
- for (let i = 0; i < media.segments.length; i++) {
- if (media.segments[i].key) {
- return true;
- }
- }
- return false;
-};
-
-/**
- * Checks if the playlist has a value for the specified attribute
- *
- * @param {string} attr
- * Attribute to check for
- * @param {Object} playlist
- * The media playlist object
- * @return {boolean}
- * Whether the playlist contains a value for the attribute or not
- * @function hasAttribute
- */
-export const hasAttribute = function(attr, playlist) {
- return playlist.attributes && playlist.attributes[attr];
-};
-
-/**
- * Estimates the time required to complete a segment download from the specified playlist
- *
- * @param {number} segmentDuration
- * Duration of requested segment
- * @param {number} bandwidth
- * Current measured bandwidth of the player
- * @param {Object} playlist
- * The media playlist object
- * @param {number=} bytesReceived
- * Number of bytes already received for the request. Defaults to 0
- * @return {number|NaN}
- * The estimated time to request the segment. NaN if bandwidth information for
- * the given playlist is unavailable
- * @function estimateSegmentRequestTime
- */
-export const estimateSegmentRequestTime = function(
- segmentDuration,
- bandwidth,
- playlist,
- bytesReceived = 0
-) {
- if (!hasAttribute('BANDWIDTH', playlist)) {
- return NaN;
- }
-
- const size = segmentDuration * playlist.attributes.BANDWIDTH;
-
- return (size - (bytesReceived * 8)) / bandwidth;
-};
-
-/*
- * Returns whether the current playlist is the lowest rendition
- *
- * @return {Boolean} true if on lowest rendition
- */
-export const isLowestEnabledRendition = (master, media) => {
- if (master.playlists.length === 1) {
- return true;
- }
-
- const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
-
- return (master.playlists.filter((playlist) => {
- if (!isEnabled(playlist)) {
- return false;
- }
-
- return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
-
- }).length === 0);
-};
-
-export const playlistMatch = (a, b) => {
- // both playlits are null
- // or only one playlist is non-null
- // no match
- if (!a && !b || (!a && b) || (a && !b)) {
- return false;
- }
-
- // playlist objects are the same, match
- if (a === b) {
- return true;
- }
-
- // first try to use id as it should be the most
- // accurate
- if (a.id && b.id && a.id === b.id) {
- return true;
- }
-
- // next try to use reslovedUri as it should be the
- // second most accurate.
- if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
- return true;
- }
-
- // finally try to use uri as it should be accurate
- // but might miss a few cases for relative uris
- if (a.uri && b.uri && a.uri === b.uri) {
- return true;
- }
-
- return false;
-};
-
-const someAudioVariant = function(master, callback) {
- const AUDIO = master && master.mediaGroups && master.mediaGroups.AUDIO || {};
- let found = false;
-
- for (const groupName in AUDIO) {
- for (const label in AUDIO[groupName]) {
- found = callback(AUDIO[groupName][label]);
-
- if (found) {
- break;
- }
- }
-
- if (found) {
- break;
- }
- }
-
- return !!found;
-};
-
-export const isAudioOnly = (master) => {
- // we are audio only if we have no main playlists but do
- // have media group playlists.
- if (!master || !master.playlists || !master.playlists.length) {
- // without audio variants or playlists this
- // is not an audio only master.
- const found = someAudioVariant(master, (variant) =>
- (variant.playlists && variant.playlists.length) || variant.uri);
-
- return found;
- }
-
- // if every playlist has only an audio codec it is audio only
- for (let i = 0; i < master.playlists.length; i++) {
- const playlist = master.playlists[i];
- const CODECS = playlist.attributes && playlist.attributes.CODECS;
-
- // all codecs are audio, this is an audio playlist.
- if (CODECS && CODECS.split(',').every((c) => isAudioCodec(c))) {
- continue;
- }
-
- // playlist is in an audio group it is audio only
- const found = someAudioVariant(master, (variant) => playlistMatch(playlist, variant));
-
- if (found) {
- continue;
- }
-
- // if we make it here this playlist isn't audio and we
- // are not audio only
- return false;
- }
-
- // if we make it past every playlist without returning, then
- // this is an audio only playlist.
- return true;
-};
-
-// exports
-export default {
- liveEdgeDelay,
- duration,
- seekable,
- getMediaInfoForTime,
- isEnabled,
- isDisabled,
- isBlacklisted,
- isIncompatible,
- playlistEnd,
- isAes,
- hasAttribute,
- estimateSegmentRequestTime,
- isLowestEnabledRendition,
- isAudioOnly,
- playlistMatch
-};
diff --git a/node_modules/@videojs/http-streaming/src/ranges.js b/node_modules/@videojs/http-streaming/src/ranges.js
deleted file mode 100644
index 9621a6c..0000000
--- a/node_modules/@videojs/http-streaming/src/ranges.js
+++ /dev/null
@@ -1,447 +0,0 @@
-/**
- * ranges
- *
- * Utilities for working with TimeRanges.
- *
- */
-
-import videojs from 'video.js';
-
-// Fudge factor to account for TimeRanges rounding
-export const TIME_FUDGE_FACTOR = 1 / 30;
-// Comparisons between time values such as current time and the end of the buffered range
-// can be misleading because of precision differences or when the current media has poorly
-// aligned audio and video, which can cause values to be slightly off from what you would
-// expect. This value is what we consider to be safe to use in such comparisons to account
-// for these scenarios.
-export const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
-
-/**
- * Clamps a value to within a range
- *
- * @param {number} num - the value to clamp
- * @param {number} start - the start of the range to clamp within, inclusive
- * @param {number} end - the end of the range to clamp within, inclusive
- * @return {number}
- */
-const clamp = function(num, [start, end]) {
- return Math.min(Math.max(start, num), end);
-};
-const filterRanges = function(timeRanges, predicate) {
- const results = [];
- let i;
-
- if (timeRanges && timeRanges.length) {
- // Search for ranges that match the predicate
- for (i = 0; i < timeRanges.length; i++) {
- if (predicate(timeRanges.start(i), timeRanges.end(i))) {
- results.push([timeRanges.start(i), timeRanges.end(i)]);
- }
- }
- }
-
- return videojs.createTimeRanges(results);
-};
-
-/**
- * Attempts to find the buffered TimeRange that contains the specified
- * time.
- *
- * @param {TimeRanges} buffered - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object
- */
-export const findRange = function(buffered, time) {
- return filterRanges(buffered, function(start, end) {
- return start - SAFE_TIME_DELTA <= time &&
- end + SAFE_TIME_DELTA >= time;
- });
-};
-
-/**
- * Returns the TimeRanges that begin later than the specified time.
- *
- * @param {TimeRanges} timeRanges - the TimeRanges object to query
- * @param {number} time - the time to filter on.
- * @return {TimeRanges} a new TimeRanges object.
- */
-export const findNextRange = function(timeRanges, time) {
- return filterRanges(timeRanges, function(start) {
- return start - TIME_FUDGE_FACTOR >= time;
- });
-};
-
-/**
- * Returns gaps within a list of TimeRanges
- *
- * @param {TimeRanges} buffered - the TimeRanges object
- * @return {TimeRanges} a TimeRanges object of gaps
- */
-export const findGaps = function(buffered) {
- if (buffered.length < 2) {
- return videojs.createTimeRanges();
- }
-
- const ranges = [];
-
- for (let i = 1; i < buffered.length; i++) {
- const start = buffered.end(i - 1);
- const end = buffered.start(i);
-
- ranges.push([start, end]);
- }
-
- return videojs.createTimeRanges(ranges);
-};
-
-/**
- * Search for a likely end time for the segment that was just appened
- * based on the state of the `buffered` property before and after the
- * append. If we fin only one such uncommon end-point return it.
- *
- * @param {TimeRanges} original - the buffered time ranges before the update
- * @param {TimeRanges} update - the buffered time ranges after the update
- * @return {number|null} the end time added between `original` and `update`,
- * or null if one cannot be unambiguously determined.
- */
-export const findSoleUncommonTimeRangesEnd = function(original, update) {
- let i;
- let start;
- let end;
- const result = [];
- const edges = [];
-
- // In order to qualify as a possible candidate, the end point must:
- // 1) Not have already existed in the `original` ranges
- // 2) Not result from the shrinking of a range that already existed
- // in the `original` ranges
- // 3) Not be contained inside of a range that existed in `original`
- const overlapsCurrentEnd = function(span) {
- return (span[0] <= end && span[1] >= end);
- };
-
- if (original) {
- // Save all the edges in the `original` TimeRanges object
- for (i = 0; i < original.length; i++) {
- start = original.start(i);
- end = original.end(i);
-
- edges.push([start, end]);
- }
- }
-
- if (update) {
- // Save any end-points in `update` that are not in the `original`
- // TimeRanges object
- for (i = 0; i < update.length; i++) {
- start = update.start(i);
- end = update.end(i);
-
- if (edges.some(overlapsCurrentEnd)) {
- continue;
- }
-
- // at this point it must be a unique non-shrinking end edge
- result.push(end);
- }
- }
-
- // we err on the side of caution and return null if didn't find
- // exactly *one* differing end edge in the search above
- if (result.length !== 1) {
- return null;
- }
-
- return result[0];
-};
-
-/**
- * Calculate the intersection of two TimeRanges
- *
- * @param {TimeRanges} bufferA
- * @param {TimeRanges} bufferB
- * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
- */
-export const bufferIntersection = function(bufferA, bufferB) {
- let start = null;
- let end = null;
- let arity = 0;
- const extents = [];
- const ranges = [];
-
- if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
- return videojs.createTimeRange();
- }
-
- // Handle the case where we have both buffers and create an
- // intersection of the two
- let count = bufferA.length;
-
- // A) Gather up all start and end times
- while (count--) {
- extents.push({time: bufferA.start(count), type: 'start'});
- extents.push({time: bufferA.end(count), type: 'end'});
- }
- count = bufferB.length;
- while (count--) {
- extents.push({time: bufferB.start(count), type: 'start'});
- extents.push({time: bufferB.end(count), type: 'end'});
- }
- // B) Sort them by time
- extents.sort(function(a, b) {
- return a.time - b.time;
- });
-
- // C) Go along one by one incrementing arity for start and decrementing
- // arity for ends
- for (count = 0; count < extents.length; count++) {
- if (extents[count].type === 'start') {
- arity++;
-
- // D) If arity is ever incremented to 2 we are entering an
- // overlapping range
- if (arity === 2) {
- start = extents[count].time;
- }
- } else if (extents[count].type === 'end') {
- arity--;
-
- // E) If arity is ever decremented to 1 we leaving an
- // overlapping range
- if (arity === 1) {
- end = extents[count].time;
- }
- }
-
- // F) Record overlapping ranges
- if (start !== null && end !== null) {
- ranges.push([start, end]);
- start = null;
- end = null;
- }
- }
-
- return videojs.createTimeRanges(ranges);
-};
-
-/**
- * Calculates the percentage of `segmentRange` that overlaps the
- * `buffered` time ranges.
- *
- * @param {TimeRanges} segmentRange - the time range that the segment
- * covers adjusted according to currentTime
- * @param {TimeRanges} referenceRange - the original time range that the
- * segment covers
- * @param {number} currentTime - time in seconds where the current playback
- * is at
- * @param {TimeRanges} buffered - the currently buffered time ranges
- * @return {number} percent of the segment currently buffered
- */
-const calculateBufferedPercent = function(
- adjustedRange,
- referenceRange,
- currentTime,
- buffered
-) {
- const referenceDuration = referenceRange.end(0) - referenceRange.start(0);
- const adjustedDuration = adjustedRange.end(0) - adjustedRange.start(0);
- const bufferMissingFromAdjusted = referenceDuration - adjustedDuration;
- const adjustedIntersection = bufferIntersection(adjustedRange, buffered);
- const referenceIntersection = bufferIntersection(referenceRange, buffered);
- let adjustedOverlap = 0;
- let referenceOverlap = 0;
-
- let count = adjustedIntersection.length;
-
- while (count--) {
- adjustedOverlap += adjustedIntersection.end(count) -
- adjustedIntersection.start(count);
-
- // If the current overlap segment starts at currentTime, then increase the
- // overlap duration so that it actually starts at the beginning of referenceRange
- // by including the difference between the two Range's durations
- // This is a work around for the way Flash has no buffer before currentTime
- // TODO: see if this is still necessary since Flash isn't included
- if (adjustedIntersection.start(count) === currentTime) {
- adjustedOverlap += bufferMissingFromAdjusted;
- }
- }
-
- count = referenceIntersection.length;
-
- while (count--) {
- referenceOverlap += referenceIntersection.end(count) -
- referenceIntersection.start(count);
- }
-
- // Use whichever value is larger for the percentage-buffered since that value
- // is likely more accurate because the only way
- return Math.max(adjustedOverlap, referenceOverlap) / referenceDuration * 100;
-};
-
-/**
- * Return the amount of a range specified by the startOfSegment and segmentDuration
- * overlaps the current buffered content.
- *
- * @param {number} startOfSegment - the time where the segment begins
- * @param {number} segmentDuration - the duration of the segment in seconds
- * @param {number} currentTime - time in seconds where the current playback
- * is at
- * @param {TimeRanges} buffered - the state of the buffer
- * @return {number} percentage of the segment's time range that is
- * already in `buffered`
- */
-export const getSegmentBufferedPercent = function(
- startOfSegment,
- segmentDuration,
- currentTime,
- buffered
-) {
- const endOfSegment = startOfSegment + segmentDuration;
-
- // The entire time range of the segment
- const originalSegmentRange = videojs.createTimeRanges([[
- startOfSegment,
- endOfSegment
- ]]);
-
- // The adjusted segment time range that is setup such that it starts
- // no earlier than currentTime
- // Flash has no notion of a back-buffer so adjustedSegmentRange adjusts
- // for that and the function will still return 100% if a only half of a
- // segment is actually in the buffer as long as the currentTime is also
- // half-way through the segment
- const adjustedSegmentRange = videojs.createTimeRanges([[
- clamp(startOfSegment, [currentTime, endOfSegment]),
- endOfSegment
- ]]);
-
- // This condition happens when the currentTime is beyond the segment's
- // end time
- if (adjustedSegmentRange.start(0) === adjustedSegmentRange.end(0)) {
- return 0;
- }
-
- const percent = calculateBufferedPercent(
- adjustedSegmentRange,
- originalSegmentRange,
- currentTime,
- buffered
- );
-
- // If the segment is reported as having a zero duration, return 0%
- // since it is likely that we will need to fetch the segment
- if (isNaN(percent) || percent === Infinity || percent === -Infinity) {
- return 0;
- }
-
- return percent;
-};
-
-/**
- * Gets a human readable string for a TimeRange
- *
- * @param {TimeRange} range
- * @return {string} a human readable string
- */
-export const printableRange = (range) => {
- const strArr = [];
-
- if (!range || !range.length) {
- return '';
- }
-
- for (let i = 0; i < range.length; i++) {
- strArr.push(range.start(i) + ' => ' + range.end(i));
- }
-
- return strArr.join(', ');
-};
-
-/**
- * Calculates the amount of time left in seconds until the player hits the end of the
- * buffer and causes a rebuffer
- *
- * @param {TimeRange} buffered
- * The state of the buffer
- * @param {Numnber} currentTime
- * The current time of the player
- * @param {number} playbackRate
- * The current playback rate of the player. Defaults to 1.
- * @return {number}
- * Time until the player has to start rebuffering in seconds.
- * @function timeUntilRebuffer
- */
-export const timeUntilRebuffer = function(buffered, currentTime, playbackRate = 1) {
- const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
-
- return (bufferedEnd - currentTime) / playbackRate;
-};
-
-/**
- * Converts a TimeRanges object into an array representation
- *
- * @param {TimeRanges} timeRanges
- * @return {Array}
- */
-export const timeRangesToArray = (timeRanges) => {
- const timeRangesList = [];
-
- for (let i = 0; i < timeRanges.length; i++) {
- timeRangesList.push({
- start: timeRanges.start(i),
- end: timeRanges.end(i)
- });
- }
-
- return timeRangesList;
-};
-
-/**
- * Determines if two time range objects are different.
- *
- * @param {TimeRange} a
- * the first time range object to check
- *
- * @param {TimeRange} b
- * the second time range object to check
- *
- * @return {Boolean}
- * Whether the time range objects differ
- */
-
-export const isRangeDifferent = function(a, b) {
- // same object
- if (a === b) {
- return false;
- }
-
- // one or the other is undefined
- if (!a && b || (!b && a)) {
- return true;
- }
-
- // length is different
- if (a.length !== b.length) {
- return true;
- }
-
- // see if any start/end pair is different
- for (let i = 0; i < a.length; i++) {
- if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
- return true;
- }
- }
-
- // if the length and every pair is the same
- // this is the same time range
- return false;
-};
-
-export const lastBufferedEnd = function(a) {
- if (!a || !a.length || !a.end) {
- return;
- }
-
- return a.end(a.length - 1);
-};
diff --git a/node_modules/@videojs/http-streaming/src/reload-source-on-error.js b/node_modules/@videojs/http-streaming/src/reload-source-on-error.js
deleted file mode 100644
index bb8b78e..0000000
--- a/node_modules/@videojs/http-streaming/src/reload-source-on-error.js
+++ /dev/null
@@ -1,127 +0,0 @@
-import videojs from 'video.js';
-
-const defaultOptions = {
- errorInterval: 30,
- getSource(next) {
- const tech = this.tech({ IWillNotUseThisInPlugins: true });
- const sourceObj = tech.currentSource_ || this.currentSource();
-
- return next(sourceObj);
- }
-};
-
-/**
- * Main entry point for the plugin
- *
- * @param {Player} player a reference to a videojs Player instance
- * @param {Object} [options] an object with plugin options
- * @private
- */
-const initPlugin = function(player, options) {
- let lastCalled = 0;
- let seekTo = 0;
- const localOptions = videojs.mergeOptions(defaultOptions, options);
-
- player.ready(() => {
- player.trigger({type: 'usage', name: 'vhs-error-reload-initialized'});
- player.trigger({type: 'usage', name: 'hls-error-reload-initialized'});
- });
-
- /**
- * Player modifications to perform that must wait until `loadedmetadata`
- * has been triggered
- *
- * @private
- */
- const loadedMetadataHandler = function() {
- if (seekTo) {
- player.currentTime(seekTo);
- }
- };
-
- /**
- * Set the source on the player element, play, and seek if necessary
- *
- * @param {Object} sourceObj An object specifying the source url and mime-type to play
- * @private
- */
- const setSource = function(sourceObj) {
- if (sourceObj === null || sourceObj === undefined) {
- return;
- }
- seekTo = (player.duration() !== Infinity && player.currentTime()) || 0;
-
- player.one('loadedmetadata', loadedMetadataHandler);
-
- player.src(sourceObj);
- player.trigger({type: 'usage', name: 'vhs-error-reload'});
- player.trigger({type: 'usage', name: 'hls-error-reload'});
- player.play();
- };
-
- /**
- * Attempt to get a source from either the built-in getSource function
- * or a custom function provided via the options
- *
- * @private
- */
- const errorHandler = function() {
- // Do not attempt to reload the source if a source-reload occurred before
- // 'errorInterval' time has elapsed since the last source-reload
- if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
- player.trigger({type: 'usage', name: 'vhs-error-reload-canceled'});
- player.trigger({type: 'usage', name: 'hls-error-reload-canceled'});
- return;
- }
-
- if (!localOptions.getSource ||
- typeof localOptions.getSource !== 'function') {
- videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
- return;
- }
- lastCalled = Date.now();
-
- return localOptions.getSource.call(player, setSource);
- };
-
- /**
- * Unbind any event handlers that were bound by the plugin
- *
- * @private
- */
- const cleanupEvents = function() {
- player.off('loadedmetadata', loadedMetadataHandler);
- player.off('error', errorHandler);
- player.off('dispose', cleanupEvents);
- };
-
- /**
- * Cleanup before re-initializing the plugin
- *
- * @param {Object} [newOptions] an object with plugin options
- * @private
- */
- const reinitPlugin = function(newOptions) {
- cleanupEvents();
- initPlugin(player, newOptions);
- };
-
- player.on('error', errorHandler);
- player.on('dispose', cleanupEvents);
-
- // Overwrite the plugin function so that we can correctly cleanup before
- // initializing the plugin
- player.reloadSourceOnError = reinitPlugin;
-};
-
-/**
- * Reload the source when an error is detected as long as there
- * wasn't an error previously within the last 30 seconds
- *
- * @param {Object} [options] an object with plugin options
- */
-const reloadSourceOnError = function(options) {
- initPlugin(this, options);
-};
-
-export default reloadSourceOnError;
diff --git a/node_modules/@videojs/http-streaming/src/rendition-mixin.js b/node_modules/@videojs/http-streaming/src/rendition-mixin.js
deleted file mode 100644
index 26867da..0000000
--- a/node_modules/@videojs/http-streaming/src/rendition-mixin.js
+++ /dev/null
@@ -1,113 +0,0 @@
-import { isIncompatible, isEnabled, isAudioOnly } from './playlist.js';
-import { codecsForPlaylist } from './util/codecs.js';
-
-/**
- * Returns a function that acts as the Enable/disable playlist function.
- *
- * @param {PlaylistLoader} loader - The master playlist loader
- * @param {string} playlistID - id of the playlist
- * @param {Function} changePlaylistFn - A function to be called after a
- * playlist's enabled-state has been changed. Will NOT be called if a
- * playlist's enabled-state is unchanged
- * @param {boolean=} enable - Value to set the playlist enabled-state to
- * or if undefined returns the current enabled-state for the playlist
- * @return {Function} Function for setting/getting enabled
- */
-const enableFunction = (loader, playlistID, changePlaylistFn) => (enable) => {
- const playlist = loader.master.playlists[playlistID];
- const incompatible = isIncompatible(playlist);
- const currentlyEnabled = isEnabled(playlist);
-
- if (typeof enable === 'undefined') {
- return currentlyEnabled;
- }
-
- if (enable) {
- delete playlist.disabled;
- } else {
- playlist.disabled = true;
- }
-
- if (enable !== currentlyEnabled && !incompatible) {
- // Ensure the outside world knows about our changes
- changePlaylistFn();
- if (enable) {
- loader.trigger('renditionenabled');
- } else {
- loader.trigger('renditiondisabled');
- }
- }
- return enable;
-};
-
-/**
- * The representation object encapsulates the publicly visible information
- * in a media playlist along with a setter/getter-type function (enabled)
- * for changing the enabled-state of a particular playlist entry
- *
- * @class Representation
- */
-class Representation {
- constructor(vhsHandler, playlist, id) {
- const {
- masterPlaylistController_: mpc,
- options_: { smoothQualityChange }
- } = vhsHandler;
- // Get a reference to a bound version of the quality change function
- const changeType = smoothQualityChange ? 'smooth' : 'fast';
- const qualityChangeFunction = mpc[`${changeType}QualityChange_`].bind(mpc);
-
- // some playlist attributes are optional
- if (playlist.attributes) {
- const resolution = playlist.attributes.RESOLUTION;
-
- this.width = resolution && resolution.width;
- this.height = resolution && resolution.height;
-
- this.bandwidth = playlist.attributes.BANDWIDTH;
- }
-
- this.codecs = codecsForPlaylist(mpc.master(), playlist);
-
- this.playlist = playlist;
-
- // The id is simply the ordinality of the media playlist
- // within the master playlist
- this.id = id;
-
- // Partially-apply the enableFunction to create a playlist-
- // specific variant
- this.enabled = enableFunction(
- vhsHandler.playlists,
- playlist.id,
- qualityChangeFunction
- );
- }
-}
-
-/**
- * A mixin function that adds the `representations` api to an instance
- * of the VhsHandler class
- *
- * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
- * representation API into
- */
-const renditionSelectionMixin = function(vhsHandler) {
-
- // Add a single API-specific function to the VhsHandler instance
- vhsHandler.representations = () => {
- const master = vhsHandler.masterPlaylistController_.master();
- const playlists = isAudioOnly(master) ?
- vhsHandler.masterPlaylistController_.getAudioTrackPlaylists_() :
- master.playlists;
-
- if (!playlists) {
- return [];
- }
- return playlists
- .filter((media) => !isIncompatible(media))
- .map((e, i) => new Representation(vhsHandler, e, e.id));
- };
-};
-
-export default renditionSelectionMixin;
diff --git a/node_modules/@videojs/http-streaming/src/resolve-url.js b/node_modules/@videojs/http-streaming/src/resolve-url.js
deleted file mode 100644
index 901eb62..0000000
--- a/node_modules/@videojs/http-streaming/src/resolve-url.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * @file resolve-url.js - Handling how URLs are resolved and manipulated
- */
-
-import _resolveUrl from '@videojs/vhs-utils/es/resolve-url.js';
-
-export const resolveUrl = _resolveUrl;
-
-/**
- * Checks whether xhr request was redirected and returns correct url depending
- * on `handleManifestRedirects` option
- *
- * @api private
- *
- * @param {string} url - an url being requested
- * @param {XMLHttpRequest} req - xhr request result
- *
- * @return {string}
- */
-export const resolveManifestRedirect = (handleManifestRedirect, url, req) => {
- // To understand how the responseURL below is set and generated:
- // - https://fetch.spec.whatwg.org/#concept-response-url
- // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
- if (
- handleManifestRedirect &&
- req &&
- req.responseURL &&
- url !== req.responseURL
- ) {
- return req.responseURL;
- }
-
- return url;
-};
-
-export default resolveUrl;
diff --git a/node_modules/@videojs/http-streaming/src/segment-loader.js b/node_modules/@videojs/http-streaming/src/segment-loader.js
deleted file mode 100644
index b5c8c8c..0000000
--- a/node_modules/@videojs/http-streaming/src/segment-loader.js
+++ /dev/null
@@ -1,3095 +0,0 @@
-/**
- * @file segment-loader.js
- */
-import Playlist from './playlist';
-import videojs from 'video.js';
-import Config from './config';
-import window from 'global/window';
-import { initSegmentId, segmentKeyId } from './bin-utils';
-import { mediaSegmentRequest, REQUEST_ERRORS } from './media-segment-request';
-import segmentTransmuxer from './segment-transmuxer';
-import { TIME_FUDGE_FACTOR, timeUntilRebuffer as timeUntilRebuffer_ } from './ranges';
-import { minRebufferMaxBandwidthSelector } from './playlist-selectors';
-import logger from './util/logger';
-import { concatSegments } from './util/segment';
-import {
- createCaptionsTrackIfNotExists,
- createMetadataTrackIfNotExists,
- addMetadata,
- addCaptionData,
- removeCuesFromTrack
-} from './util/text-tracks';
-import { gopsSafeToAlignWith, removeGopBuffer, updateGopBuffer } from './util/gops';
-import shallowEqual from './util/shallow-equal.js';
-import { QUOTA_EXCEEDED_ERR } from './error-codes';
-import { timeRangesToArray } from './ranges';
-import {lastBufferedEnd} from './ranges.js';
-import {getKnownPartCount} from './playlist.js';
-
-/**
- * The segment loader has no recourse except to fetch a segment in the
- * current playlist and use the internal timestamps in that segment to
- * generate a syncPoint. This function returns a good candidate index
- * for that process.
- *
- * @param {Array} segments - the segments array from a playlist.
- * @return {number} An index of a segment from the playlist to load
- */
-export const getSyncSegmentCandidate = function(currentTimeline, segments, targetTime) {
- segments = segments || [];
- const timelineSegments = [];
- let time = 0;
-
- for (let i = 0; i < segments.length; i++) {
- const segment = segments[i];
-
- if (currentTimeline === segment.timeline) {
- timelineSegments.push(i);
- time += segment.duration;
-
- if (time > targetTime) {
- return i;
- }
- }
- }
-
- if (timelineSegments.length === 0) {
- return 0;
- }
-
- // default to the last timeline segment
- return timelineSegments[timelineSegments.length - 1];
-};
-
-// In the event of a quota exceeded error, keep at least one second of back buffer. This
-// number was arbitrarily chosen and may be updated in the future, but seemed reasonable
-// as a start to prevent any potential issues with removing content too close to the
-// playhead.
-const MIN_BACK_BUFFER = 1;
-
-// in ms
-const CHECK_BUFFER_DELAY = 500;
-const finite = (num) => typeof num === 'number' && isFinite(num);
-// With most content hovering around 30fps, if a segment has a duration less than a half
-// frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
-// not accurately reflect the rest of the content.
-const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
-
-export const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
- // Although these checks should most likely cover non 'main' types, for now it narrows
- // the scope of our checks.
- if (loaderType !== 'main' || !startingMedia || !trackInfo) {
- return null;
- }
-
- if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
- return 'Neither audio nor video found in segment.';
- }
-
- if (startingMedia.hasVideo && !trackInfo.hasVideo) {
- return 'Only audio found in segment when we expected video.' +
- ' We can\'t switch to audio only from a stream that had video.' +
- ' To get rid of this message, please add codec information to the manifest.';
- }
-
- if (!startingMedia.hasVideo && trackInfo.hasVideo) {
- return 'Video found in segment when we expected only audio.' +
- ' We can\'t switch to a stream with video from an audio only stream.' +
- ' To get rid of this message, please add codec information to the manifest.';
- }
-
- return null;
-};
-
-/**
- * Calculates a time value that is safe to remove from the back buffer without interrupting
- * playback.
- *
- * @param {TimeRange} seekable
- * The current seekable range
- * @param {number} currentTime
- * The current time of the player
- * @param {number} targetDuration
- * The target duration of the current playlist
- * @return {number}
- * Time that is safe to remove from the back buffer without interrupting playback
- */
-export const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
- // 30 seconds before the playhead provides a safe default for trimming.
- //
- // Choosing a reasonable default is particularly important for high bitrate content and
- // VOD videos/live streams with large windows, as the buffer may end up overfilled and
- // throw an APPEND_BUFFER_ERR.
- let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
-
- if (seekable.length) {
- // Some live playlists may have a shorter window of content than the full allowed back
- // buffer. For these playlists, don't save content that's no longer within the window.
- trimTime = Math.max(trimTime, seekable.start(0));
- }
-
- // Don't remove within target duration of the current time to avoid the possibility of
- // removing the GOP currently being played, as removing it can cause playback stalls.
- const maxTrimTime = currentTime - targetDuration;
-
- return Math.min(maxTrimTime, trimTime);
-};
-
-const segmentInfoString = (segmentInfo) => {
- const {
- startOfSegment,
- duration,
- segment,
- part,
- playlist: {
- mediaSequence: seq,
- id,
- segments = []
- },
- mediaIndex: index,
- partIndex,
- timeline
- } = segmentInfo;
-
- const segmentLen = segments.length - 1;
- let selection = 'mediaIndex/partIndex increment';
-
- if (segmentInfo.getMediaInfoForTime) {
- selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
- } else if (segmentInfo.isSyncRequest) {
- selection = 'getSyncSegmentCandidate (isSyncRequest)';
- }
-
- const hasPartIndex = typeof partIndex === 'number';
- const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
- const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({preloadSegment: segment}) - 1 : 0;
-
- return `${name} [${seq + index}/${seq + segmentLen}]` +
- (hasPartIndex ? ` part [${partIndex}/${zeroBasedPartCount}]` : '') +
- ` segment start/end [${segment.start} => ${segment.end}]` +
- (hasPartIndex ? ` part start/end [${part.start} => ${part.end}]` : '') +
- ` startOfSegment [${startOfSegment}]` +
- ` duration [${duration}]` +
- ` timeline [${timeline}]` +
- ` selected by [${selection}]` +
- ` playlist [${id}]`;
-};
-
-const timingInfoPropertyForMedia = (mediaType) => `${mediaType}TimingInfo`;
-
-/**
- * Returns the timestamp offset to use for the segment.
- *
- * @param {number} segmentTimeline
- * The timeline of the segment
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} startOfSegment
- * The estimated segment start
- * @param {TimeRange[]} buffered
- * The loader's buffer
- * @param {boolean} overrideCheck
- * If true, no checks are made to see if the timestamp offset value should be set,
- * but sets it directly to a value.
- *
- * @return {number|null}
- * Either a number representing a new timestamp offset, or null if the segment is
- * part of the same timeline
- */
-export const timestampOffsetForSegment = ({
- segmentTimeline,
- currentTimeline,
- startOfSegment,
- buffered,
- overrideCheck
-}) => {
- // Check to see if we are crossing a discontinuity to see if we need to set the
- // timestamp offset on the transmuxer and source buffer.
- //
- // Previously, we changed the timestampOffset if the start of this segment was less than
- // the currently set timestampOffset, but this isn't desirable as it can produce bad
- // behavior, especially around long running live streams.
- if (!overrideCheck && segmentTimeline === currentTimeline) {
- return null;
- }
-
- // When changing renditions, it's possible to request a segment on an older timeline. For
- // instance, given two renditions with the following:
- //
- // #EXTINF:10
- // segment1
- // #EXT-X-DISCONTINUITY
- // #EXTINF:10
- // segment2
- // #EXTINF:10
- // segment3
- //
- // And the current player state:
- //
- // current time: 8
- // buffer: 0 => 20
- //
- // The next segment on the current rendition would be segment3, filling the buffer from
- // 20s onwards. However, if a rendition switch happens after segment2 was requested,
- // then the next segment to be requested will be segment1 from the new rendition in
- // order to fill time 8 and onwards. Using the buffered end would result in repeated
- // content (since it would position segment1 of the new rendition starting at 20s). This
- // case can be identified when the new segment's timeline is a prior value. Instead of
- // using the buffered end, the startOfSegment can be used, which, hopefully, will be
- // more accurate to the actual start time of the segment.
- if (segmentTimeline < currentTimeline) {
- return startOfSegment;
- }
-
- // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
- // value uses the end of the last segment if it is available. While this value
- // should often be correct, it's better to rely on the buffered end, as the new
- // content post discontinuity should line up with the buffered end as if it were
- // time 0 for the new content.
- return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
-};
-
-/**
- * Returns whether or not the loader should wait for a timeline change from the timeline
- * change controller before processing the segment.
- *
- * Primary timing in VHS goes by video. This is different from most media players, as
- * audio is more often used as the primary timing source. For the foreseeable future, VHS
- * will continue to use video as the primary timing source, due to the current logic and
- * expectations built around it.
-
- * Since the timing follows video, in order to maintain sync, the video loader is
- * responsible for setting both audio and video source buffer timestamp offsets.
- *
- * Setting different values for audio and video source buffers could lead to
- * desyncing. The following examples demonstrate some of the situations where this
- * distinction is important. Note that all of these cases involve demuxed content. When
- * content is muxed, the audio and video are packaged together, therefore syncing
- * separate media playlists is not an issue.
- *
- * CASE 1: Audio prepares to load a new timeline before video:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the audio loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the video loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the audio loader goes ahead and loads and appends the 6th segment before the video
- * loader crosses the discontinuity, then when appended, the 6th audio segment will use
- * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
- * the audio loader must provide the audioAppendStart value to trim the content in the
- * transmuxer, and that value relies on the audio timestamp offset. Since the audio
- * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
- * segment until that value is provided.
- *
- * CASE 2: Video prepares to load a new timeline before audio:
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, the video loader is preparing to load the 6th segment, the first
- * after a discontinuity, while the audio loader is still loading the 5th segment, before
- * the discontinuity.
- *
- * If the video loader goes ahead and loads and appends the 6th segment, then once the
- * segment is loaded and processed, both the video and audio timestamp offsets will be
- * set, since video is used as the primary timing source. This is to ensure content lines
- * up appropriately, as any modifications to the video timing are reflected by audio when
- * the video loader sets the audio and video timestamp offsets to the same value. However,
- * setting the timestamp offset for audio before audio has had a chance to change
- * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
- * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
- *
- * CASE 3: When seeking, audio prepares to load a new timeline before video
- *
- * Timeline: 0 1
- * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Audio Loader: ^
- * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
- * Video Loader ^
- *
- * In the above example, both audio and video loaders are loading segments from timeline
- * 0, but imagine that the seek originated from timeline 1.
- *
- * When seeking to a new timeline, the timestamp offset will be set based on the expected
- * segment start of the loaded video segment. In order to maintain sync, the audio loader
- * must wait for the video loader to load its segment and update both the audio and video
- * timestamp offsets before it may load and append its own segment. This is the case
- * whether the seek results in a mismatched segment request (e.g., the audio loader
- * chooses to load segment 3 and the video loader chooses to load segment 4) or the
- * loaders choose to load the same segment index from each playlist, as the segments may
- * not be aligned perfectly, even for matching segment indexes.
- *
- * @param {Object} timelinechangeController
- * @param {number} currentTimeline
- * The timeline currently being followed by the loader
- * @param {number} segmentTimeline
- * The timeline of the segment being loaded
- * @param {('main'|'audio')} loaderType
- * The loader type
- * @param {boolean} audioDisabled
- * Whether the audio is disabled for the loader. This should only be true when the
- * loader may have muxed audio in its segment, but should not append it, e.g., for
- * the main loader when an alternate audio playlist is active.
- *
- * @return {boolean}
- * Whether the loader should wait for a timeline change from the timeline change
- * controller before processing the segment
- */
-export const shouldWaitForTimelineChange = ({
- timelineChangeController,
- currentTimeline,
- segmentTimeline,
- loaderType,
- audioDisabled
-}) => {
- if (currentTimeline === segmentTimeline) {
- return false;
- }
-
- if (loaderType === 'audio') {
- const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
- type: 'main'
- });
-
- // Audio loader should wait if:
- //
- // * main hasn't had a timeline change yet (thus has not loaded its first segment)
- // * main hasn't yet changed to the timeline audio is looking to load
- return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
- }
-
- // The main loader only needs to wait for timeline changes if there's demuxed audio.
- // Otherwise, there's nothing to wait for, since audio would be muxed into the main
- // loader's segments (or the content is audio/video only and handled by the main
- // loader).
- if (loaderType === 'main' && audioDisabled) {
- const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
- type: 'audio'
- });
-
- // Main loader should wait for the audio loader if audio is not pending a timeline
- // change to the current timeline.
- //
- // Since the main loader is responsible for setting the timestamp offset for both
- // audio and video, the main loader must wait for audio to be about to change to its
- // timeline before setting the offset, otherwise, if audio is behind in loading,
- // segments from the previous timeline would be adjusted by the new timestamp offset.
- //
- // This requirement means that video will not cross a timeline until the audio is
- // about to cross to it, so that way audio and video will always cross the timeline
- // together.
- //
- // In addition to normal timeline changes, these rules also apply to the start of a
- // stream (going from a non-existent timeline, -1, to timeline 0). It's important
- // that these rules apply to the first timeline change because if they did not, it's
- // possible that the main loader will cross two timelines before the audio loader has
- // crossed one. Logic may be implemented to handle the startup as a special case, but
- // it's easier to simply treat all timeline changes the same.
- if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
- return false;
- }
-
- return true;
- }
-
- return false;
-};
-
-export const mediaDuration = (audioTimingInfo, videoTimingInfo) => {
- const audioDuration =
- audioTimingInfo &&
- typeof audioTimingInfo.start === 'number' &&
- typeof audioTimingInfo.end === 'number' ?
- audioTimingInfo.end - audioTimingInfo.start : 0;
- const videoDuration =
- videoTimingInfo &&
- typeof videoTimingInfo.start === 'number' &&
- typeof videoTimingInfo.end === 'number' ?
- videoTimingInfo.end - videoTimingInfo.start : 0;
-
- return Math.max(audioDuration, videoDuration);
-};
-
-export const segmentTooLong = ({ segmentDuration, maxDuration }) => {
- // 0 duration segments are most likely due to metadata only segments or a lack of
- // information.
- if (!segmentDuration) {
- return false;
- }
-
- // For HLS:
- //
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
- // The EXTINF duration of each Media Segment in the Playlist
- // file, when rounded to the nearest integer, MUST be less than or equal
- // to the target duration; longer segments can trigger playback stalls
- // or other errors.
- //
- // For DASH, the mpd-parser uses the largest reported segment duration as the target
- // duration. Although that reported duration is occasionally approximate (i.e., not
- // exact), a strict check may report that a segment is too long more often in DASH.
- return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
-};
-
-export const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
- // Right now we aren't following DASH's timing model exactly, so only perform
- // this check for HLS content.
- if (sourceType !== 'hls') {
- return null;
- }
-
- const segmentDuration = mediaDuration(
- segmentInfo.audioTimingInfo,
- segmentInfo.videoTimingInfo
- );
-
- // Don't report if we lack information.
- //
- // If the segment has a duration of 0 it is either a lack of information or a
- // metadata only segment and shouldn't be reported here.
- if (!segmentDuration) {
- return null;
- }
-
- const targetDuration = segmentInfo.playlist.targetDuration;
-
- const isSegmentWayTooLong = segmentTooLong({
- segmentDuration,
- maxDuration: targetDuration * 2
- });
- const isSegmentSlightlyTooLong = segmentTooLong({
- segmentDuration,
- maxDuration: targetDuration
- });
-
- const segmentTooLongMessage = `Segment with index ${segmentInfo.mediaIndex} ` +
- `from playlist ${segmentInfo.playlist.id} ` +
- `has a duration of ${segmentDuration} ` +
- `when the reported duration is ${segmentInfo.duration} ` +
- `and the target duration is ${targetDuration}. ` +
- 'For HLS content, a duration in excess of the target duration may result in ' +
- 'playback issues. See the HLS specification section on EXT-X-TARGETDURATION for ' +
- 'more details: ' +
- 'https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1';
-
- if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
- return {
- severity: isSegmentWayTooLong ? 'warn' : 'info',
- message: segmentTooLongMessage
- };
- }
-
- return null;
-};
-
-/**
- * An object that manages segment loading and appending.
- *
- * @class SegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-export default class SegmentLoader extends videojs.EventTarget {
- constructor(settings, options = {}) {
- super();
- // check pre-conditions
- if (!settings) {
- throw new TypeError('Initialization settings are required');
- }
- if (typeof settings.currentTime !== 'function') {
- throw new TypeError('No currentTime getter specified');
- }
- if (!settings.mediaSource) {
- throw new TypeError('No MediaSource specified');
- }
- // public properties
- this.bandwidth = settings.bandwidth;
- this.throughput = {rate: 0, count: 0};
- this.roundTrip = NaN;
- this.resetStats_();
- this.mediaIndex = null;
- this.partIndex = null;
-
- // private settings
- this.hasPlayed_ = settings.hasPlayed;
- this.currentTime_ = settings.currentTime;
- this.seekable_ = settings.seekable;
- this.seeking_ = settings.seeking;
- this.duration_ = settings.duration;
- this.mediaSource_ = settings.mediaSource;
- this.vhs_ = settings.vhs;
- this.loaderType_ = settings.loaderType;
- this.currentMediaInfo_ = void 0;
- this.startingMediaInfo_ = void 0;
- this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
- this.goalBufferLength_ = settings.goalBufferLength;
- this.sourceType_ = settings.sourceType;
- this.sourceUpdater_ = settings.sourceUpdater;
- this.inbandTextTracks_ = settings.inbandTextTracks;
- this.state_ = 'INIT';
- this.timelineChangeController_ = settings.timelineChangeController;
- this.shouldSaveSegmentTimingInfo_ = true;
- this.parse708captions_ = settings.parse708captions;
-
- // private instance variables
- this.checkBufferTimeout_ = null;
- this.error_ = void 0;
- this.currentTimeline_ = -1;
- this.pendingSegment_ = null;
- this.xhrOptions_ = null;
- this.pendingSegments_ = [];
- this.audioDisabled_ = false;
- this.isPendingTimestampOffset_ = false;
- // TODO possibly move gopBuffer and timeMapping info to a separate controller
- this.gopBuffer_ = [];
- this.timeMapping_ = 0;
- this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.playlistOfLastInitSegment_ = {
- audio: null,
- video: null
- };
- this.callQueue_ = [];
- // If the segment loader prepares to load a segment, but does not have enough
- // information yet to start the loading process (e.g., if the audio loader wants to
- // load a segment from the next timeline but the main loader hasn't yet crossed that
- // timeline), then the load call will be added to the queue until it is ready to be
- // processed.
- this.loadQueue_ = [];
- this.metadataQueue_ = {
- id3: [],
- caption: []
- };
- this.waitingOnRemove_ = false;
- this.quotaExceededErrorRetryTimeout_ = null;
-
- // Fragmented mp4 playback
- this.activeInitSegmentId_ = null;
- this.initSegments_ = {};
-
- // HLSe playback
- this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
- this.keyCache_ = {};
-
- this.decrypter_ = settings.decrypter;
-
- // Manages the tracking and generation of sync-points, mappings
- // between a time in the display time and a segment index within
- // a playlist
- this.syncController_ = settings.syncController;
- this.syncPoint_ = {
- segmentIndex: 0,
- time: 0
- };
-
- this.transmuxer_ = this.createTransmuxer_();
- this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
- this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
-
- this.mediaSource_.addEventListener('sourceopen', () => {
- if (!this.isEndOfStream_()) {
- this.ended_ = false;
- }
- });
-
- // ...for determining the fetch location
- this.fetchAtBuffer_ = false;
-
- this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
-
- Object.defineProperty(this, 'state', {
- get() {
- return this.state_;
- },
- set(newState) {
- if (newState !== this.state_) {
- this.logger_(`${this.state_} -> ${newState}`);
- this.state_ = newState;
- this.trigger('statechange');
- }
- }
- });
-
- this.sourceUpdater_.on('ready', () => {
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- });
-
- // Only the main loader needs to listen for pending timeline changes, as the main
- // loader should wait for audio to be ready to change its timeline so that both main
- // and audio timelines change together. For more details, see the
- // shouldWaitForTimelineChange function.
- if (this.loaderType_ === 'main') {
- this.timelineChangeController_.on('pendingtimelinechange', () => {
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- });
- }
- // The main loader only listens on pending timeline changes, but the audio loader,
- // since its loads follow main, needs to listen on timeline changes. For more details,
- // see the shouldWaitForTimelineChange function.
- if (this.loaderType_ === 'audio') {
- this.timelineChangeController_.on('timelinechange', () => {
- if (this.hasEnoughInfoToLoad_()) {
- this.processLoadQueue_();
- }
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- });
- }
- }
-
- createTransmuxer_() {
- return segmentTransmuxer.createTransmuxer({
- remux: false,
- alignGopsAtEnd: this.safeAppend_,
- keepOriginalTimestamps: true,
- parse708captions: this.parse708captions_
- });
- }
-
- /**
- * reset all of our media stats
- *
- * @private
- */
- resetStats_() {
- this.mediaBytesTransferred = 0;
- this.mediaRequests = 0;
- this.mediaRequestsAborted = 0;
- this.mediaRequestsTimedout = 0;
- this.mediaRequestsErrored = 0;
- this.mediaTransferDuration = 0;
- this.mediaSecondsLoaded = 0;
- this.mediaAppends = 0;
- }
-
- /**
- * dispose of the SegmentLoader and reset to the default state
- */
- dispose() {
- this.trigger('dispose');
- this.state = 'DISPOSED';
- this.pause();
- this.abort_();
- if (this.transmuxer_) {
- this.transmuxer_.terminate();
- }
- this.resetStats_();
-
- if (this.checkBufferTimeout_) {
- window.clearTimeout(this.checkBufferTimeout_);
- }
-
- if (this.syncController_ && this.triggerSyncInfoUpdate_) {
- this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
- }
-
- this.off();
- }
-
- setAudio(enable) {
- this.audioDisabled_ = !enable;
- if (enable) {
- this.appendInitSegment_.audio = true;
- } else {
- // remove current track audio if it gets disabled
- this.sourceUpdater_.removeAudio(0, this.duration_());
- }
- }
-
- /**
- * abort anything that is currently doing on with the SegmentLoader
- * and reset to a default state
- */
- abort() {
- if (this.state !== 'WAITING') {
- if (this.pendingSegment_) {
- this.pendingSegment_ = null;
- }
- return;
- }
-
- this.abort_();
-
- // We aborted the requests we were waiting on, so reset the loader's state to READY
- // since we are no longer "waiting" on any requests. XHR callback is not always run
- // when the request is aborted. This will prevent the loader from being stuck in the
- // WAITING state indefinitely.
- this.state = 'READY';
-
- // don't wait for buffer check timeouts to begin fetching the
- // next segment
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
-
- /**
- * abort all pending xhr requests and null any pending segements
- *
- * @private
- */
- abort_() {
- if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
- this.pendingSegment_.abortRequests();
- }
-
- // clear out the segment being processed
- this.pendingSegment_ = null;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
- this.waitingOnRemove_ = false;
- window.clearTimeout(this.quotaExceededErrorRetryTimeout_);
- this.quotaExceededErrorRetryTimeout_ = null;
- }
-
- checkForAbort_(requestId) {
- // If the state is APPENDING, then aborts will not modify the state, meaning the first
- // callback that happens should reset the state to READY so that loading can continue.
- if (this.state === 'APPENDING' && !this.pendingSegment_) {
- this.state = 'READY';
- return true;
- }
-
- if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
- return true;
- }
-
- return false;
- }
-
- /**
- * set an error on the segment loader and null out any pending segements
- *
- * @param {Error} error the error to set on the SegmentLoader
- * @return {Error} the error that was set or that is currently set
- */
- error(error) {
- if (typeof error !== 'undefined') {
- this.logger_('error occurred:', error);
- this.error_ = error;
- }
-
- this.pendingSegment_ = null;
- return this.error_;
- }
-
- endOfStream() {
- this.ended_ = true;
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
- this.gopBuffer_.length = 0;
- this.pause();
- this.trigger('ended');
- }
-
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- buffered_() {
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- return videojs.createTimeRanges();
- }
-
- if (this.loaderType_ === 'main') {
- const { hasAudio, hasVideo, isMuxed } = this.startingMediaInfo_;
-
- if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
- return this.sourceUpdater_.buffered();
- }
-
- if (hasVideo) {
- return this.sourceUpdater_.videoBuffered();
- }
- }
-
- // One case that can be ignored for now is audio only with alt audio,
- // as we don't yet have proper support for that.
- return this.sourceUpdater_.audioBuffered();
- }
-
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- initSegmentForMap(map, set = false) {
- if (!map) {
- return null;
- }
-
- const id = initSegmentId(map);
- let storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: map.bytes,
- tracks: map.tracks,
- timescales: map.timescales
- };
- }
-
- return storedMap || map;
- }
-
- /**
- * Gets and sets key for the provided key
- *
- * @param {Object} key
- * The key object representing the key to get or set
- * @param {boolean=} set
- * If true, the key for the provided key should be saved
- * @return {Object}
- * Key object for desired key
- */
- segmentKey(key, set = false) {
- if (!key) {
- return null;
- }
-
- const id = segmentKeyId(key);
- let storedKey = this.keyCache_[id];
-
- // TODO: We should use the HTTP Expires header to invalidate our cache per
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
- if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
- this.keyCache_[id] = storedKey = {
- resolvedUri: key.resolvedUri,
- bytes: key.bytes
- };
- }
-
- const result = {
- resolvedUri: (storedKey || key).resolvedUri
- };
-
- if (storedKey) {
- result.bytes = storedKey.bytes;
- }
-
- return result;
- }
-
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- couldBeginLoading_() {
- return this.playlist_ && !this.paused();
- }
-
- /**
- * load a playlist and start to fill the buffer
- */
- load() {
- // un-pause
- this.monitorBuffer_();
-
- // if we don't have a playlist yet, keep waiting for one to be
- // specified
- if (!this.playlist_) {
- return;
- }
-
- // if all the configuration is ready, initialize and begin loading
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- }
-
- // if we're in the middle of processing a segment already, don't
- // kick off an additional segment request
- if (!this.couldBeginLoading_() ||
- (this.state !== 'READY' &&
- this.state !== 'INIT')) {
- return;
- }
-
- this.state = 'READY';
- }
-
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- init_() {
- this.state = 'READY';
- // if this is the audio segment loader, and it hasn't been inited before, then any old
- // audio data from the muxed content should be removed
- this.resetEverything();
- return this.monitorBuffer_();
- }
-
- /**
- * set a playlist on the segment loader
- *
- * @param {PlaylistLoader} media the playlist to set on the segment loader
- */
- playlist(newPlaylist, options = {}) {
- if (!newPlaylist) {
- return;
- }
- const oldPlaylist = this.playlist_;
- const segmentInfo = this.pendingSegment_;
-
- this.playlist_ = newPlaylist;
- this.xhrOptions_ = options;
-
- // when we haven't started playing yet, the start of a live playlist
- // is always our zero-time so force a sync update each time the playlist
- // is refreshed from the server
- //
- // Use the INIT state to determine if playback has started, as the playlist sync info
- // should be fixed once requests begin (as sync points are generated based on sync
- // info), but not before then.
- if (this.state === 'INIT') {
- newPlaylist.syncInfo = {
- mediaSequence: newPlaylist.mediaSequence,
- time: 0
- };
- // Setting the date time mapping means mapping the program date time (if available)
- // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
- // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
- // be updated as the playlist is refreshed before the loader starts loading, the
- // program date time mapping needs to be updated as well.
- //
- // This mapping is only done for the main loader because a program date time should
- // map equivalently between playlists.
- if (this.loaderType_ === 'main') {
- this.syncController_.setDateTimeMappingForStart(newPlaylist);
- }
- }
-
- let oldId = null;
-
- if (oldPlaylist) {
- if (oldPlaylist.id) {
- oldId = oldPlaylist.id;
- } else if (oldPlaylist.uri) {
- oldId = oldPlaylist.uri;
- }
- }
-
- this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`);
-
- // in VOD, this is always a rendition switch (or we updated our syncInfo above)
- // in LIVE, we always want to update with new playlists (including refreshes)
- this.trigger('syncinfoupdate');
-
- // if we were unpaused but waiting for a playlist, start
- // buffering now
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- return this.init_();
- }
-
- if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
- if (this.mediaIndex !== null) {
- // we must "resync" the segment loader when we switch renditions and
- // the segment loader is already synced to the previous rendition
- this.resyncLoader();
- }
- this.currentMediaInfo_ = void 0;
- this.trigger('playlistupdate');
-
- // the rest of this function depends on `oldPlaylist` being defined
- return;
- }
-
- // we reloaded the same playlist so we are in a live scenario
- // and we will likely need to adjust the mediaIndex
- const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
-
- this.logger_(`live window shift [${mediaSequenceDiff}]`);
-
- // update the mediaIndex on the SegmentLoader
- // this is important because we can abort a request and this value must be
- // equal to the last appended mediaIndex
- if (this.mediaIndex !== null) {
- this.mediaIndex -= mediaSequenceDiff;
-
- // this can happen if we are going to load the first segment, but get a playlist
- // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
- // new playlist was incremented by 1.
- if (this.mediaIndex < 0) {
- this.mediaIndex = null;
- this.partIndex = null;
- } else {
- const segment = this.playlist_.segments[this.mediaIndex];
-
- // partIndex should remain the same for the same segment
- // unless parts fell off of the playlist for this segment.
- // In that case we need to reset partIndex and resync
- if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
- const mediaIndex = this.mediaIndex;
-
- this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
- this.resetLoader();
-
- // We want to throw away the partIndex and the data associated with it,
- // as the part was dropped from our current playlists segment.
- // The mediaIndex will still be valid so keep that around.
- this.mediaIndex = mediaIndex;
- }
- }
- }
-
- // update the mediaIndex on the SegmentInfo object
- // this is important because we will update this.mediaIndex with this value
- // in `handleAppendsDone_` after the segment has been successfully appended
- if (segmentInfo) {
- segmentInfo.mediaIndex -= mediaSequenceDiff;
-
- if (segmentInfo.mediaIndex < 0) {
- segmentInfo.mediaIndex = null;
- segmentInfo.partIndex = null;
- } else {
- // we need to update the referenced segment so that timing information is
- // saved for the new playlist's segment, however, if the segment fell off the
- // playlist, we can leave the old reference and just lose the timing info
- if (segmentInfo.mediaIndex >= 0) {
- segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
- }
-
- if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
- segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
- }
- }
- }
-
- this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
- }
-
- /**
- * Prevent the loader from fetching additional segments. If there
- * is a segment request outstanding, it will finish processing
- * before the loader halts. A segment loader can be unpaused by
- * calling load().
- */
- pause() {
- if (this.checkBufferTimeout_) {
- window.clearTimeout(this.checkBufferTimeout_);
-
- this.checkBufferTimeout_ = null;
- }
- }
-
- /**
- * Returns whether the segment loader is fetching additional
- * segments when given the opportunity. This property can be
- * modified through calls to pause() and load().
- */
- paused() {
- return this.checkBufferTimeout_ === null;
- }
-
- /**
- * Delete all the buffered data and reset the SegmentLoader
- *
- * @param {Function} [done] an optional callback to be executed when the remove
- * operation is complete
- */
- resetEverything(done) {
- this.ended_ = false;
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- this.resetLoader();
-
- // remove from 0, the earliest point, to Infinity, to signify removal of everything.
- // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
- // we then clamp the value to duration if necessary.
- this.remove(0, Infinity, done);
-
- // clears fmp4 captions
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
-
- /**
- * Force the SegmentLoader to resync and start loading around the currentTime instead
- * of starting at the end of the buffer
- *
- * Useful for fast quality changes
- */
- resetLoader() {
- this.fetchAtBuffer_ = false;
- this.resyncLoader();
- }
-
- /**
- * Force the SegmentLoader to restart synchronization and make a conservative guess
- * before returning to the simple walk-forward method
- */
- resyncLoader() {
- if (this.transmuxer_) {
- // need to clear out any cached data to prepare for the new segment
- segmentTransmuxer.reset(this.transmuxer_);
- }
- this.mediaIndex = null;
- this.partIndex = null;
- this.syncPoint_ = null;
- this.isPendingTimestampOffset_ = false;
- this.callQueue_ = [];
- this.loadQueue_ = [];
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- this.abort();
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- }
-
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- * @param {Function} [done] - an optional callback to be executed when the remove
- * @param {boolean} force - force all remove operations to happen
- * operation is complete
- */
- remove(start, end, done = () => {}, force = false) {
- // clamp end to duration if we need to remove everything.
- // This is due to a browser bug that causes issues if we remove to Infinity.
- // videojs/videojs-contrib-hls#1225
- if (end === Infinity) {
- end = this.duration_();
- }
-
- // skip removes that would throw an error
- // commonly happens during a rendition switch at the start of a video
- // from start 0 to end 0
- if (end <= start) {
- this.logger_('skipping remove because end ${end} is <= start ${start}');
- return;
- }
-
- if (!this.sourceUpdater_ || !this.startingMediaInfo_) {
- this.logger_('skipping remove because no source updater or starting media info');
- // nothing to remove if we haven't processed any media
- return;
- }
-
- // set it to one to complete this function's removes
- let removesRemaining = 1;
- const removeFinished = () => {
- removesRemaining--;
- if (removesRemaining === 0) {
- done();
- }
- };
-
- if (force || !this.audioDisabled_) {
- removesRemaining++;
- this.sourceUpdater_.removeAudio(start, end, removeFinished);
- }
-
- // While it would be better to only remove video if the main loader has video, this
- // should be safe with audio only as removeVideo will call back even if there's no
- // video buffer.
- //
- // In theory we can check to see if there's video before calling the remove, but in
- // the event that we're switching between renditions and from video to audio only
- // (when we add support for that), we may need to clear the video contents despite
- // what the new media will contain.
- if (force || this.loaderType_ === 'main') {
- this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
- removesRemaining++;
- this.sourceUpdater_.removeVideo(start, end, removeFinished);
- }
-
- // remove any captions and ID3 tags
- for (const track in this.inbandTextTracks_) {
- removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
-
- // finished this function's removes
- removeFinished();
- }
-
- /**
- * (re-)schedule monitorBufferTick_ to run as soon as possible
- *
- * @private
- */
- monitorBuffer_() {
- if (this.checkBufferTimeout_) {
- window.clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
- }
-
- /**
- * As long as the SegmentLoader is in the READY state, periodically
- * invoke fillBuffer_().
- *
- * @private
- */
- monitorBufferTick_() {
- if (this.state === 'READY') {
- this.fillBuffer_();
- }
-
- if (this.checkBufferTimeout_) {
- window.clearTimeout(this.checkBufferTimeout_);
- }
-
- this.checkBufferTimeout_ = window.setTimeout(
- this.monitorBufferTick_.bind(this),
- CHECK_BUFFER_DELAY
- );
- }
-
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- fillBuffer_() {
- // TODO since the source buffer maintains a queue, and we shouldn't call this function
- // except when we're ready for the next segment, this check can most likely be removed
- if (this.sourceUpdater_.updating()) {
- return;
- }
-
- // see if we need to begin loading immediately
- const segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- this.isPendingTimestampOffset_ = false;
- this.timelineChangeController_.pendingTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
-
- this.loadSegment_(segmentInfo);
- }
-
- /**
- * Determines if we should call endOfStream on the media source based
- * on the state of the buffer or if appened segment was the final
- * segment in the playlist.
- *
- * @param {number} [mediaIndex] the media index of segment we last appended
- * @param {Object} [playlist] a media playlist object
- * @return {boolean} do we need to call endOfStream on the MediaSource
- */
- isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
- if (!playlist || !this.mediaSource_) {
- return false;
- }
-
- const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex];
-
- // mediaIndex is zero based but length is 1 based
- const appendedLastSegment = (mediaIndex + 1) === playlist.segments.length;
- // true if there are no parts, or this is the last part.
- const appendedLastPart = !segment || !segment.parts || (partIndex + 1) === segment.parts.length;
-
- // if we've buffered to the end of the video, we need to call endOfStream
- // so that MediaSources can trigger the `ended` event when it runs out of
- // buffered data instead of waiting for me
- return playlist.endList &&
- this.mediaSource_.readyState === 'open' &&
- appendedLastSegment &&
- appendedLastPart;
- }
-
- /**
- * Determines what request should be made given current segment loader state.
- *
- * @return {Object} a request object that describes the segment/part to load
- */
- chooseNextRequest_() {
- const bufferedEnd = lastBufferedEnd(this.buffered_()) || 0;
- const bufferedTime = Math.max(0, bufferedEnd - this.currentTime_());
- const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
- const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
- const segments = this.playlist_.segments;
-
- // return no segment if:
- // 1. we don't have segments
- // 2. The video has not yet played and we already downloaded a segment
- // 3. we already have enough buffered time
- if (!segments.length || preloaded || haveEnoughBuffer) {
- return null;
- }
-
- this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(
- this.playlist_,
- this.duration_(),
- this.currentTimeline_,
- this.currentTime_()
- );
-
- const next = {
- partIndex: null,
- mediaIndex: null,
- startOfSegment: null,
- playlist: this.playlist_,
- isSyncRequest: Boolean(!this.syncPoint_)
- };
-
- if (next.isSyncRequest) {
- next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
- } else if (this.mediaIndex !== null) {
- const segment = segments[this.mediaIndex];
- const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
-
- next.startOfSegment = segment.end ? segment.end : bufferedEnd;
-
- if (segment.parts && segment.parts[partIndex + 1]) {
- next.mediaIndex = this.mediaIndex;
- next.partIndex = partIndex + 1;
- } else {
- next.mediaIndex = this.mediaIndex + 1;
- }
- } else {
- // Find the segment containing the end of the buffer or current time.
- const {segmentIndex, startTime, partIndex} = Playlist.getMediaInfoForTime({
- playlist: this.playlist_,
- currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
- startingPartIndex: this.syncPoint_.partIndex,
- startingSegmentIndex: this.syncPoint_.segmentIndex,
- startTime: this.syncPoint_.time
- });
-
- next.getMediaInfoForTime = this.fetchAtBuffer_ ? 'bufferedEnd' : 'currentTime';
- next.mediaIndex = segmentIndex;
- next.startOfSegment = startTime;
- next.partIndex = partIndex;
- }
-
- const nextSegment = segments[next.mediaIndex];
- const nextPart = nextSegment &&
- typeof next.partIndex === 'number' &&
- nextSegment.parts &&
- nextSegment.parts[next.partIndex];
-
- // if the next segment index is invalid or
- // the next partIndex is invalid do not choose a next segment.
- if (!nextSegment || (typeof next.partIndex === 'number' && !nextPart)) {
- return null;
- }
-
- // if the next segment has parts, and we don't have a partIndex.
- // Set partIndex to 0
- if (typeof next.partIndex !== 'number' && nextSegment.parts) {
- next.partIndex = 0;
- }
-
- const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended';
-
- // do not choose a next segment if all of the following:
- // 1. this is the last segment in the playlist
- // 2. end of stream has been called on the media source already
- // 3. the player is not seeking
- if (next.mediaIndex >= (segments.length - 1) && ended && !this.seeking_()) {
- return null;
- }
-
- return this.generateSegmentInfo_(next);
- }
-
- generateSegmentInfo_(options) {
- const {
- playlist,
- mediaIndex,
- startOfSegment,
- isSyncRequest,
- partIndex,
- forceTimestampOffset,
- getMediaInfoForTime
- } = options;
- const segment = playlist.segments[mediaIndex];
- const part = typeof partIndex === 'number' && segment.parts[partIndex];
- const segmentInfo = {
- requestId: 'segment-loader-' + Math.random(),
- // resolve the segment URL relative to the playlist
- uri: part && part.resolvedUri || segment.resolvedUri,
- // the segment's mediaIndex at the time it was requested
- mediaIndex,
- partIndex: part ? partIndex : null,
- // whether or not to update the SegmentLoader's state with this
- // segment's mediaIndex
- isSyncRequest,
- startOfSegment,
- // the segment's playlist
- playlist,
- // unencrypted bytes of the segment
- bytes: null,
- // when a key is defined for this segment, the encrypted bytes
- encryptedBytes: null,
- // The target timestampOffset for this segment when we append it
- // to the source buffer
- timestampOffset: null,
- // The timeline that the segment is in
- timeline: segment.timeline,
- // The expected duration of the segment in seconds
- duration: part && part.duration || segment.duration,
- // retain the segment in case the playlist updates while doing an async process
- segment,
- part,
- byteLength: 0,
- transmuxer: this.transmuxer_,
- // type of getMediaInfoForTime that was used to get this segment
- getMediaInfoForTime
- };
-
- const overrideCheck =
- typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
-
- segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
- segmentTimeline: segment.timeline,
- currentTimeline: this.currentTimeline_,
- startOfSegment,
- buffered: this.buffered_(),
- overrideCheck
- });
-
- const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
-
- if (typeof audioBufferedEnd === 'number') {
- // since the transmuxer is using the actual timing values, but the buffer is
- // adjusted by the timestamp offset, we must adjust the value here
- segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
- }
-
- if (this.sourceUpdater_.videoBuffered().length) {
- segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(
- this.gopBuffer_,
- // since the transmuxer is using the actual timing values, but the time is
- // adjusted by the timestmap offset, we must adjust the value here
- this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(),
- this.timeMapping_
- );
- }
-
- return segmentInfo;
- }
-
- // get the timestampoffset for a segment,
- // added so that vtt segment loader can override and prevent
- // adding timestamp offsets.
- timestampOffsetForSegment_(options) {
- return timestampOffsetForSegment(options);
- }
- /**
- * Determines if the network has enough bandwidth to complete the current segment
- * request in a timely manner. If not, the request will be aborted early and bandwidth
- * updated to trigger a playlist switch.
- *
- * @param {Object} stats
- * Object containing stats about the request timing and size
- * @private
- */
- earlyAbortWhenNeeded_(stats) {
- if (this.vhs_.tech_.paused() ||
- // Don't abort if the current playlist is on the lowestEnabledRendition
- // TODO: Replace using timeout with a boolean indicating whether this playlist is
- // the lowestEnabledRendition.
- !this.xhrOptions_.timeout ||
- // Don't abort if we have no bandwidth information to estimate segment sizes
- !(this.playlist_.attributes.BANDWIDTH)) {
- return;
- }
-
- // Wait at least 1 second since the first byte of data has been received before
- // using the calculated bandwidth from the progress event to allow the bitrate
- // to stabilize
- if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
- return;
- }
-
- const currentTime = this.currentTime_();
- const measuredBandwidth = stats.bandwidth;
- const segmentDuration = this.pendingSegment_.duration;
-
- const requestTimeRemaining =
- Playlist.estimateSegmentRequestTime(
- segmentDuration,
- measuredBandwidth,
- this.playlist_,
- stats.bytesReceived
- );
-
- // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
- // if we are only left with less than 1 second when the request completes.
- // A negative timeUntilRebuffering indicates we are already rebuffering
- const timeUntilRebuffer = timeUntilRebuffer_(
- this.buffered_(),
- currentTime,
- this.vhs_.tech_.playbackRate()
- ) - 1;
-
- // Only consider aborting early if the estimated time to finish the download
- // is larger than the estimated time until the player runs out of forward buffer
- if (requestTimeRemaining <= timeUntilRebuffer) {
- return;
- }
-
- const switchCandidate = minRebufferMaxBandwidthSelector({
- master: this.vhs_.playlists.master,
- currentTime,
- bandwidth: measuredBandwidth,
- duration: this.duration_(),
- segmentDuration,
- timeUntilRebuffer,
- currentTimeline: this.currentTimeline_,
- syncController: this.syncController_
- });
-
- if (!switchCandidate) {
- return;
- }
-
- const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer;
-
- const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
-
- let minimumTimeSaving = 0.5;
-
- // If we are already rebuffering, increase the amount of variance we add to the
- // potential round trip time of the new request so that we are not too aggressive
- // with switching to a playlist that might save us a fraction of a second.
- if (timeUntilRebuffer <= TIME_FUDGE_FACTOR) {
- minimumTimeSaving = 1;
- }
-
- if (!switchCandidate.playlist ||
- switchCandidate.playlist.uri === this.playlist_.uri ||
- timeSavedBySwitching < minimumTimeSaving) {
- return;
- }
-
- // set the bandwidth to that of the desired playlist being sure to scale by
- // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
- // don't trigger a bandwidthupdate as the bandwidth is artifial
- this.bandwidth =
- switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
- this.trigger('earlyabort');
- }
-
- handleAbort_(segmentInfo) {
- this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
- this.mediaRequestsAborted += 1;
- }
-
- /**
- * XHR `progress` event handler
- *
- * @param {Event}
- * The XHR `progress` event
- * @param {Object} simpleSegment
- * A simplified segment object copy
- * @private
- */
- handleProgress_(event, simpleSegment) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- this.trigger('progress');
- }
-
- handleTrackInfo_(simpleSegment, trackInfo) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- if (this.checkForIllegalMediaSwitch(trackInfo)) {
- return;
- }
-
- trackInfo = trackInfo || {};
-
- // When we have track info, determine what media types this loader is dealing with.
- // Guard against cases where we're not getting track info at all until we are
- // certain that all streams will provide it.
- if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
-
- this.startingMediaInfo_ = trackInfo;
- this.currentMediaInfo_ = trackInfo;
- this.logger_('trackinfo update', trackInfo);
- this.trigger('trackinfo');
- }
-
- // trackinfo may cause an abort if the trackinfo
- // causes a codec change to an unsupported codec.
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- // set trackinfo on the pending segment so that
- // it can append.
- this.pendingSegment_.trackInfo = trackInfo;
-
- // check if any calls were waiting on the track info
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- }
-
- handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- const segmentInfo = this.pendingSegment_;
- const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
-
- segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
- segmentInfo[timingInfoProperty][timeType] = time;
-
- this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`);
-
- // check if any calls were waiting on the timing info
- if (this.hasEnoughInfoToAppend_()) {
- this.processCallQueue_();
- }
- }
-
- handleCaptions_(simpleSegment, captionData) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- // This could only happen with fmp4 segments, but
- // should still not happen in general
- if (captionData.length === 0) {
- this.logger_('SegmentLoader received no captions from a caption event');
- return;
- }
-
- const segmentInfo = this.pendingSegment_;
-
- // Wait until we have some video data so that caption timing
- // can be adjusted by the timestamp offset
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
- return;
- }
-
- const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ?
- this.sourceUpdater_.audioTimestampOffset() :
- this.sourceUpdater_.videoTimestampOffset();
-
- const captionTracks = {};
-
- // get total start/end and captions for each track/stream
- captionData.forEach((caption) => {
- // caption.stream is actually a track name...
- // set to the existing values in tracks or default values
- captionTracks[caption.stream] = captionTracks[caption.stream] || {
- // Infinity, as any other value will be less than this
- startTime: Infinity,
- captions: [],
- // 0 as an other value will be more than this
- endTime: 0
- };
-
- const captionTrack = captionTracks[caption.stream];
-
- captionTrack.startTime = Math.min(captionTrack.startTime, (caption.startTime + timestampOffset));
- captionTrack.endTime = Math.max(captionTrack.endTime, (caption.endTime + timestampOffset));
- captionTrack.captions.push(caption);
- });
-
- Object.keys(captionTracks).forEach((trackName) => {
- const {startTime, endTime, captions} = captionTracks[trackName];
- const inbandTextTracks = this.inbandTextTracks_;
-
- this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
-
- createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName);
- // clear out any cues that start and end at the same time period for the same track.
- // We do this because a rendition change that also changes the timescale for captions
- // will result in captions being re-parsed for certain segments. If we add them again
- // without clearing we will have two of the same captions visible.
- removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
-
- addCaptionData({captionArray: captions, inbandTextTracks, timestampOffset});
- });
-
- // Reset stored captions since we added parsed
- // captions to a text track at this point
-
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearParsedMp4Captions'
- });
- }
- }
-
- handleId3_(simpleSegment, id3Frames, dispatchType) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- const segmentInfo = this.pendingSegment_;
-
- // we need to have appended data in order for the timestamp offset to be set
- if (!segmentInfo.hasAppendedData_) {
- this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
- return;
- }
-
- const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ?
- this.sourceUpdater_.audioTimestampOffset() :
- this.sourceUpdater_.videoTimestampOffset();
-
- // There's potentially an issue where we could double add metadata if there's a muxed
- // audio/video source with a metadata track, and an alt audio with a metadata track.
- // However, this probably won't happen, and if it does it can be handled then.
- createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
- addMetadata({
- inbandTextTracks: this.inbandTextTracks_,
- metadataArray: id3Frames,
- timestampOffset,
- videoDuration: this.duration_()
- });
- }
-
- processMetadataQueue_() {
- this.metadataQueue_.id3.forEach((fn) => fn());
- this.metadataQueue_.caption.forEach((fn) => fn());
-
- this.metadataQueue_.id3 = [];
- this.metadataQueue_.caption = [];
- }
-
- processCallQueue_() {
- const callQueue = this.callQueue_;
-
- // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
- this.callQueue_ = [];
- callQueue.forEach((fun) => fun());
- }
-
- processLoadQueue_() {
- const loadQueue = this.loadQueue_;
-
- // Clear out the queue before the queued functions are run, since some of the
- // functions may check the length of the load queue and default to pushing themselves
- // back onto the queue.
- this.loadQueue_ = [];
- loadQueue.forEach((fun) => fun());
- }
-
- /**
- * Determines whether the loader has enough info to load the next segment.
- *
- * @return {boolean}
- * Whether or not the loader has enough info to load the next segment
- */
- hasEnoughInfoToLoad_() {
- // Since primary timing goes by video, only the audio loader potentially needs to wait
- // to load.
- if (this.loaderType_ !== 'audio') {
- return true;
- }
-
- const segmentInfo = this.pendingSegment_;
-
- // A fill buffer must have already run to establish a pending segment before there's
- // enough info to load.
- if (!segmentInfo) {
- return false;
- }
-
- // The first segment can and should be loaded immediately so that source buffers are
- // created together (before appending). Source buffer creation uses the presence of
- // audio and video data to determine whether to create audio/video source buffers, and
- // uses processed (transmuxed or parsed) media to determine the types required.
- if (!this.currentMediaInfo_) {
- return true;
- }
-
- if (
- // Technically, instead of waiting to load a segment on timeline changes, a segment
- // can be requested and downloaded and only wait before it is transmuxed or parsed.
- // But in practice, there are a few reasons why it is better to wait until a loader
- // is ready to append that segment before requesting and downloading:
- //
- // 1. Because audio and main loaders cross discontinuities together, if this loader
- // is waiting for the other to catch up, then instead of requesting another
- // segment and using up more bandwidth, by not yet loading, more bandwidth is
- // allotted to the loader currently behind.
- // 2. media-segment-request doesn't have to have logic to consider whether a segment
- // is ready to be processed or not, isolating the queueing behavior to the loader.
- // 3. The audio loader bases some of its segment properties on timing information
- // provided by the main loader, meaning that, if the logic for waiting on
- // processing was in media-segment-request, then it would also need to know how
- // to re-generate the segment information after the main loader caught up.
- shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })
- ) {
- return false;
- }
-
- return true;
- }
-
- hasEnoughInfoToAppend_() {
- if (!this.sourceUpdater_.ready()) {
- return false;
- }
-
- // If content needs to be removed or the loader is waiting on an append reattempt,
- // then no additional content should be appended until the prior append is resolved.
- if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
- return false;
- }
-
- const segmentInfo = this.pendingSegment_;
-
- // no segment to append any data for or
- // we do not have information on this specific
- // segment yet
- if (!segmentInfo || !segmentInfo.trackInfo) {
- return false;
- }
-
- const {hasAudio, hasVideo, isMuxed} = this.currentMediaInfo_;
-
- if (hasVideo && !segmentInfo.videoTimingInfo) {
- return false;
- }
-
- // muxed content only relies on video timing information for now.
- if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
- return false;
- }
-
- if (
- shouldWaitForTimelineChange({
- timelineChangeController: this.timelineChangeController_,
- currentTimeline: this.currentTimeline_,
- segmentTimeline: segmentInfo.timeline,
- loaderType: this.loaderType_,
- audioDisabled: this.audioDisabled_
- })
- ) {
- return false;
- }
-
- return true;
- }
-
- handleData_(simpleSegment, result) {
- this.earlyAbortWhenNeeded_(simpleSegment.stats);
-
- if (this.checkForAbort_(simpleSegment.requestId)) {
- return;
- }
-
- // If there's anything in the call queue, then this data came later and should be
- // executed after the calls currently queued.
- if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
- this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
- return;
- }
-
- const segmentInfo = this.pendingSegment_;
-
- // update the time mapping so we can translate from display time to media time
- this.setTimeMapping_(segmentInfo.timeline);
-
- // for tracking overall stats
- this.updateMediaSecondsLoaded_(segmentInfo.segment);
-
- // Note that the state isn't changed from loading to appending. This is because abort
- // logic may change behavior depending on the state, and changing state too early may
- // inflate our estimates of bandwidth. In the future this should be re-examined to
- // note more granular states.
-
- // don't process and append data if the mediaSource is closed
- if (this.mediaSource_.readyState === 'closed') {
- return;
- }
-
- // if this request included an initialization segment, save that data
- // to the initSegment cache
- if (simpleSegment.map) {
- simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true);
- // move over init segment properties to media request
- segmentInfo.segment.map = simpleSegment.map;
- }
-
- // if this request included a segment key, save that data in the cache
- if (simpleSegment.key) {
- this.segmentKey(simpleSegment.key, true);
- }
-
- segmentInfo.isFmp4 = simpleSegment.isFmp4;
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
-
- if (segmentInfo.isFmp4) {
- this.trigger('fmp4');
-
- segmentInfo.timingInfo.start =
- segmentInfo[timingInfoPropertyForMedia(result.type)].start;
- } else {
- const useVideoTimingInfo =
- this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- let firstVideoFrameTimeForData;
-
- if (useVideoTimingInfo) {
- firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
- }
-
- // Segment loader knows more about segment timing than the transmuxer (in certain
- // aspects), so make any changes required for a more accurate start time.
- // Don't set the end time yet, as the segment may not be finished processing.
- segmentInfo.timingInfo.start = this.trueSegmentStart_({
- currentStart: segmentInfo.timingInfo.start,
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex,
- currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
- useVideoTimingInfo,
- firstVideoFrameTimeForData,
- videoTimingInfo: segmentInfo.videoTimingInfo,
- audioTimingInfo: segmentInfo.audioTimingInfo
- });
- }
-
- // Init segments for audio and video only need to be appended in certain cases. Now
- // that data is about to be appended, we can check the final cases to determine
- // whether we should append an init segment.
- this.updateAppendInitSegmentStatus(segmentInfo, result.type);
- // Timestamp offset should be updated once we get new data and have its timing info,
- // as we use the start of the segment to offset the best guess (playlist provided)
- // timestamp offset.
- this.updateSourceBufferTimestampOffset_(segmentInfo);
-
- // if this is a sync request we need to determine whether it should
- // be appended or not.
- if (segmentInfo.isSyncRequest) {
- // first save/update our timing info for this segment.
- // this is what allows us to choose an accurate segment
- // and the main reason we make a sync request.
- this.updateTimingInfoEnd_(segmentInfo);
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
-
- const next = this.chooseNextRequest_();
-
- // If the sync request isn't the segment that would be requested next
- // after taking into account its timing info, do not append it.
- if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
- this.logger_('sync segment was incorrect, not appending');
- return;
- }
- // otherwise append it like any other segment as our guess was correct.
- this.logger_('sync segment was correct, appending');
- }
-
- // Save some state so that in the future anything waiting on first append (and/or
- // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
- // we need some notion of whether the timestamp offset or other relevant information
- // has had a chance to be set.
- segmentInfo.hasAppendedData_ = true;
- // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
- this.processMetadataQueue_();
-
- this.appendData_(segmentInfo, result);
- }
-
- updateAppendInitSegmentStatus(segmentInfo, type) {
- // alt audio doesn't manage timestamp offset
- if (this.loaderType_ === 'main' &&
- typeof segmentInfo.timestampOffset === 'number' &&
- // in the case that we're handling partial data, we don't want to append an init
- // segment for each chunk
- !segmentInfo.changedTimestampOffset) {
- // if the timestamp offset changed, the timeline may have changed, so we have to re-
- // append init segments
- this.appendInitSegment_ = {
- audio: true,
- video: true
- };
- }
-
- if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
- // make sure we append init segment on playlist changes, in case the media config
- // changed
- this.appendInitSegment_[type] = true;
- }
- }
-
- getInitSegmentAndUpdateState_({ type, initSegment, map, playlist }) {
- // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
- // (Section 3) required to parse the applicable Media Segments. It applies to every
- // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
- // or until the end of the playlist."
- // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
- if (map) {
- const id = initSegmentId(map);
-
- if (this.activeInitSegmentId_ === id) {
- // don't need to re-append the init segment if the ID matches
- return null;
- }
-
- // a map-specified init segment takes priority over any transmuxed (or otherwise
- // obtained) init segment
- //
- // this also caches the init segment for later use
- initSegment = this.initSegmentForMap(map, true).bytes;
- this.activeInitSegmentId_ = id;
- }
-
- // We used to always prepend init segments for video, however, that shouldn't be
- // necessary. Instead, we should only append on changes, similar to what we've always
- // done for audio. This is more important (though may not be that important) for
- // frame-by-frame appending for LHLS, simply because of the increased quantity of
- // appends.
- if (initSegment && this.appendInitSegment_[type]) {
- // Make sure we track the playlist that we last used for the init segment, so that
- // we can re-append the init segment in the event that we get data from a new
- // playlist. Discontinuities and track changes are handled in other sections.
- this.playlistOfLastInitSegment_[type] = playlist;
- // Disable future init segment appends for this type. Until a change is necessary.
- this.appendInitSegment_[type] = false;
-
- // we need to clear out the fmp4 active init segment id, since
- // we are appending the muxer init segment
- this.activeInitSegmentId_ = null;
-
- return initSegment;
- }
-
- return null;
- }
-
- handleQuotaExceededError_({segmentInfo, type, bytes}, error) {
- const audioBuffered = this.sourceUpdater_.audioBuffered();
- const videoBuffered = this.sourceUpdater_.videoBuffered();
-
- // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
- // should be cleared out during the buffer removals. However, log in case it helps
- // debug.
- if (audioBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' +
- timeRangesToArray(audioBuffered).join(', '));
- }
- if (videoBuffered.length > 1) {
- this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' +
- timeRangesToArray(videoBuffered).join(', '));
- }
-
- const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
- const audioBufferEnd = audioBuffered.length ?
- audioBuffered.end(audioBuffered.length - 1) : 0;
- const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
- const videoBufferEnd = videoBuffered.length ?
- videoBuffered.end(videoBuffered.length - 1) : 0;
-
- if (
- (audioBufferEnd - audioBufferStart) <= MIN_BACK_BUFFER &&
- (videoBufferEnd - videoBufferStart) <= MIN_BACK_BUFFER
- ) {
- // Can't remove enough buffer to make room for new segment (or the browser doesn't
- // allow for appends of segments this size). In the future, it may be possible to
- // split up the segment and append in pieces, but for now, error out this playlist
- // in an attempt to switch to a more manageable rendition.
- this.logger_('On QUOTA_EXCEEDED_ERR, single segment too large to append to ' +
- 'buffer, triggering an error. ' +
- `Appended byte length: ${bytes.byteLength}, ` +
- `audio buffer: ${timeRangesToArray(audioBuffered).join(', ')}, ` +
- `video buffer: ${timeRangesToArray(videoBuffered).join(', ')}, `);
- this.error({
- message: 'Quota exceeded error with append of a single segment of content',
- excludeUntil: Infinity
- });
- this.trigger('error');
- return;
- }
-
- // To try to resolve the quota exceeded error, clear back buffer and retry. This means
- // that the segment-loader should block on future events until this one is handled, so
- // that it doesn't keep moving onto further segments. Adding the call to the call
- // queue will prevent further appends until waitingOnRemove_ and
- // quotaExceededErrorRetryTimeout_ are cleared.
- //
- // Note that this will only block the current loader. In the case of demuxed content,
- // the other load may keep filling as fast as possible. In practice, this should be
- // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
- // source buffer, or video fills without enough room for audio to append (and without
- // the availability of clearing out seconds of back buffer to make room for audio).
- // But it might still be good to handle this case in the future as a TODO.
- this.waitingOnRemove_ = true;
- this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {segmentInfo, type, bytes}));
-
- const currentTime = this.currentTime_();
- // Try to remove as much audio and video as possible to make room for new content
- // before retrying.
- const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
-
- this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
- this.remove(0, timeToRemoveUntil, () => {
-
- this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
- this.waitingOnRemove_ = false;
- // wait the length of time alotted in the back buffer to prevent wasted
- // attempts (since we can't clear less than the minimum)
- this.quotaExceededErrorRetryTimeout_ = window.setTimeout(() => {
- this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
- this.quotaExceededErrorRetryTimeout_ = null;
- this.processCallQueue_();
- }, MIN_BACK_BUFFER * 1000);
- }, true);
- }
-
- handleAppendError_({segmentInfo, type, bytes}, error) {
- // if there's no error, nothing to do
- if (!error) {
- return;
- }
-
- if (error.code === QUOTA_EXCEEDED_ERR) {
- this.handleQuotaExceededError_({segmentInfo, type, bytes});
- // A quota exceeded error should be recoverable with a future re-append, so no need
- // to trigger an append error.
- return;
- }
-
- this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
- this.error(`${type} append of ${bytes.length}b failed for segment ` +
- `#${segmentInfo.mediaIndex} in playlist ${segmentInfo.playlist.id}`);
-
- // If an append errors, we often can't recover.
- // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
- //
- // Trigger a special error so that it can be handled separately from normal,
- // recoverable errors.
- this.trigger('appenderror');
- }
-
- appendToSourceBuffer_({ segmentInfo, type, initSegment, data, bytes }) {
- // If this is a re-append, bytes were already created and don't need to be recreated
- if (!bytes) {
- const segments = [data];
- let byteLength = data.byteLength;
-
- if (initSegment) {
- // if the media initialization segment is changing, append it before the content
- // segment
- segments.unshift(initSegment);
- byteLength += initSegment.byteLength;
- }
-
- // Technically we should be OK appending the init segment separately, however, we
- // haven't yet tested that, and prepending is how we have always done things.
- bytes = concatSegments({
- bytes: byteLength,
- segments
- });
- }
-
- this.sourceUpdater_.appendBuffer(
- {segmentInfo, type, bytes},
- this.handleAppendError_.bind(this, {segmentInfo, type, bytes})
- );
- }
-
- handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
- if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
- return;
- }
-
- const segment = this.pendingSegment_.segment;
- const timingInfoProperty = `${type}TimingInfo`;
-
- if (!segment[timingInfoProperty]) {
- segment[timingInfoProperty] = {};
- }
-
- segment[timingInfoProperty].transmuxerPrependedSeconds =
- segmentTimingInfo.prependedContentDuration || 0;
- segment[timingInfoProperty].transmuxedPresentationStart =
- segmentTimingInfo.start.presentation;
- segment[timingInfoProperty].transmuxedDecodeStart =
- segmentTimingInfo.start.decode;
- segment[timingInfoProperty].transmuxedPresentationEnd =
- segmentTimingInfo.end.presentation;
- segment[timingInfoProperty].transmuxedDecodeEnd =
- segmentTimingInfo.end.decode;
- // mainly used as a reference for debugging
- segment[timingInfoProperty].baseMediaDecodeTime =
- segmentTimingInfo.baseMediaDecodeTime;
- }
-
- appendData_(segmentInfo, result) {
- const {
- type,
- data
- } = result;
-
- if (!data || !data.byteLength) {
- return;
- }
-
- if (type === 'audio' && this.audioDisabled_) {
- return;
- }
-
- const initSegment = this.getInitSegmentAndUpdateState_({
- type,
- initSegment: result.initSegment,
- playlist: segmentInfo.playlist,
- map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
- });
-
- this.appendToSourceBuffer_({ segmentInfo, type, initSegment, data });
- }
-
- /**
- * load a specific segment from a request into the buffer
- *
- * @private
- */
- loadSegment_(segmentInfo) {
- this.state = 'WAITING';
- this.pendingSegment_ = segmentInfo;
- this.trimBackBuffer_(segmentInfo);
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- if (this.transmuxer_) {
- this.transmuxer_.postMessage({
- action: 'clearAllMp4Captions'
- });
- }
- }
-
- if (!this.hasEnoughInfoToLoad_()) {
- this.loadQueue_.push(() => {
- // regenerate the audioAppendStart, timestampOffset, etc as they
- // may have changed since this function was added to the queue.
- const options = Object.assign(
- {},
- segmentInfo,
- {forceTimestampOffset: true}
- );
-
- Object.assign(segmentInfo, this.generateSegmentInfo_(options));
- this.isPendingTimestampOffset_ = false;
- this.updateTransmuxerAndRequestSegment_(segmentInfo);
- });
- return;
- }
-
- this.updateTransmuxerAndRequestSegment_(segmentInfo);
- }
-
- updateTransmuxerAndRequestSegment_(segmentInfo) {
- // We'll update the source buffer's timestamp offset once we have transmuxed data, but
- // the transmuxer still needs to be updated before then.
- //
- // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
- // offset must be passed to the transmuxer for stream correcting adjustments.
- if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
- this.gopBuffer_.length = 0;
- // gopsToAlignWith was set before the GOP buffer was cleared
- segmentInfo.gopsToAlignWith = [];
- this.timeMapping_ = 0;
- // reset values in the transmuxer since a discontinuity should start fresh
- this.transmuxer_.postMessage({
- action: 'reset'
- });
- this.transmuxer_.postMessage({
- action: 'setTimestampOffset',
- timestampOffset: segmentInfo.timestampOffset
- });
- }
-
- const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
- const isEndOfStream = this.isEndOfStream_(
- segmentInfo.mediaIndex,
- segmentInfo.playlist,
- segmentInfo.partIndex
- );
- const isWalkingForward = this.mediaIndex !== null;
- const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ &&
- // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
- // the first timeline
- segmentInfo.timeline > 0;
- const isEndOfTimeline = isEndOfStream || (isWalkingForward && isDiscontinuity);
-
- this.logger_(`Requesting ${segmentInfoString(segmentInfo)}`);
-
- // If there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),
- // then this init segment has never been seen before and should be appended.
- //
- // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
- // both to true and leave the decision of whether to append the init segment to append time.
- if (simpleSegment.map && !simpleSegment.map.bytes) {
- this.logger_('going to request init segment.');
- this.appendInitSegment_ = {
- video: true,
- audio: true
- };
- }
-
- segmentInfo.abortRequests = mediaSegmentRequest({
- xhr: this.vhs_.xhr,
- xhrOptions: this.xhrOptions_,
- decryptionWorker: this.decrypter_,
- segment: simpleSegment,
- abortFn: this.handleAbort_.bind(this, segmentInfo),
- progressFn: this.handleProgress_.bind(this),
- trackInfoFn: this.handleTrackInfo_.bind(this),
- timingInfoFn: this.handleTimingInfo_.bind(this),
- videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
- audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
- captionsFn: this.handleCaptions_.bind(this),
- isEndOfTimeline,
- endedTimelineFn: () => {
- this.logger_('received endedtimeline callback');
- },
- id3Fn: this.handleId3_.bind(this),
-
- dataFn: this.handleData_.bind(this),
- doneFn: this.segmentRequestFinished_.bind(this)
- });
- }
-
- /**
- * trim the back buffer so that we don't have too much data
- * in the source buffer
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- */
- trimBackBuffer_(segmentInfo) {
- const removeToTime = safeBackBufferTrimTime(
- this.seekable_(),
- this.currentTime_(),
- this.playlist_.targetDuration || 10
- );
-
- // Chrome has a hard limit of 150MB of
- // buffer and a very conservative "garbage collector"
- // We manually clear out the old buffer to ensure
- // we don't trigger the QuotaExceeded error
- // on the source buffer during subsequent appends
-
- if (removeToTime > 0) {
- this.remove(0, removeToTime);
- }
- }
-
- /**
- * created a simplified copy of the segment object with just the
- * information necessary to perform the XHR and decryption
- *
- * @private
- *
- * @param {Object} segmentInfo - the current segment
- * @return {Object} a simplified segment object copy
- */
- createSimplifiedSegmentObj_(segmentInfo) {
- const segment = segmentInfo.segment;
- const part = segmentInfo.part;
-
- const simpleSegment = {
- resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
- byterange: part ? part.byterange : segment.byterange,
- requestId: segmentInfo.requestId,
- transmuxer: segmentInfo.transmuxer,
- audioAppendStart: segmentInfo.audioAppendStart,
- gopsToAlignWith: segmentInfo.gopsToAlignWith,
- part: segmentInfo.part
- };
-
- const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
-
- if (previousSegment && previousSegment.timeline === segment.timeline) {
- // The baseStartTime of a segment is used to handle rollover when probing the TS
- // segment to retrieve timing information. Since the probe only looks at the media's
- // times (e.g., PTS and DTS values of the segment), and doesn't consider the
- // player's time (e.g., player.currentTime()), baseStartTime should reflect the
- // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
- // seconds of media time, so should be used here. The previous segment is used since
- // the end of the previous segment should represent the beginning of the current
- // segment, so long as they are on the same timeline.
- if (previousSegment.videoTimingInfo) {
- simpleSegment.baseStartTime =
- previousSegment.videoTimingInfo.transmuxedDecodeEnd;
- } else if (previousSegment.audioTimingInfo) {
- simpleSegment.baseStartTime =
- previousSegment.audioTimingInfo.transmuxedDecodeEnd;
- }
- }
-
- if (segment.key) {
- // if the media sequence is greater than 2^32, the IV will be incorrect
- // assuming 10s segments, that would be about 1300 years
- const iv = segment.key.iv || new Uint32Array([
- 0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence
- ]);
-
- simpleSegment.key = this.segmentKey(segment.key);
- simpleSegment.key.iv = iv;
- }
-
- if (segment.map) {
- simpleSegment.map = this.initSegmentForMap(segment.map);
- }
-
- return simpleSegment;
- }
-
- saveTransferStats_(stats) {
- // every request counts as a media request even if it has been aborted
- // or canceled due to a timeout
- this.mediaRequests += 1;
-
- if (stats) {
- this.mediaBytesTransferred += stats.bytesReceived;
- this.mediaTransferDuration += stats.roundTripTime;
- }
- }
-
- saveBandwidthRelatedStats_(duration, stats) {
- // byteLength will be used for throughput, and should be based on bytes receieved,
- // which we only know at the end of the request and should reflect total bytes
- // downloaded rather than just bytes processed from components of the segment
- this.pendingSegment_.byteLength = stats.bytesReceived;
-
- if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` +
- ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
- return;
- }
-
- this.bandwidth = stats.bandwidth;
- this.roundTrip = stats.roundTripTime;
- }
-
- handleTimeout_() {
- // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functinality between segment loaders
- this.mediaRequestsTimedout += 1;
- this.bandwidth = 1;
- this.roundTrip = NaN;
- this.trigger('bandwidthupdate');
- }
-
- /**
- * Handle the callback from the segmentRequest function and set the
- * associated SegmentLoader state and errors if necessary
- *
- * @private
- */
- segmentRequestFinished_(error, simpleSegment, result) {
- // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
-
- // check the call queue directly since this function doesn't need to deal with any
- // data, and can continue even if the source buffers are not set up and we didn't get
- // any data from the segment
- if (this.callQueue_.length) {
- this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats);
-
- // The request was aborted and the SegmentLoader has already been reset
- if (!this.pendingSegment_) {
- return;
- }
-
- // the request was aborted and the SegmentLoader has already started
- // another request. this can happen when the timeout for an aborted
- // request triggers due to a limitation in the XHR library
- // do not count this as any sort of request or we risk double-counting
- if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
- return;
- }
-
- // an error occurred from the active pendingSegment_ so reset everything
- if (error) {
- this.pendingSegment_ = null;
- this.state = 'READY';
-
- // aborts are not a true error condition and nothing corrective needs to be done
- if (error.code === REQUEST_ERRORS.ABORTED) {
- return;
- }
-
- this.pause();
-
- // the error is really just that at least one of the requests timed-out
- // set the bandwidth to a very low value and trigger an ABR switch to
- // take emergency action
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- return;
- }
-
- // if control-flow has arrived here, then the error is real
- // emit an error event to blacklist the current playlist
- this.mediaRequestsErrored += 1;
- this.error(error);
- this.trigger('error');
- return;
- }
-
- const segmentInfo = this.pendingSegment_;
-
- // the response was a success so set any bandwidth stats the request
- // generated for ABR purposes
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
-
- segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
-
- if (result.gopInfo) {
- this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
- }
-
- // Although we may have already started appending on progress, we shouldn't switch the
- // state away from loading until we are officially done loading the segment data.
- this.state = 'APPENDING';
-
- // used for testing
- this.trigger('appending');
-
- this.waitForAppendsToComplete_(segmentInfo);
- }
-
- setTimeMapping_(timeline) {
- const timelineMapping = this.syncController_.mappingForTimeline(timeline);
-
- if (timelineMapping !== null) {
- this.timeMapping_ = timelineMapping;
- }
- }
-
- updateMediaSecondsLoaded_(segment) {
- if (typeof segment.start === 'number' && typeof segment.end === 'number') {
- this.mediaSecondsLoaded += segment.end - segment.start;
- } else {
- this.mediaSecondsLoaded += segment.duration;
- }
- }
-
- shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
- if (timestampOffset === null) {
- return false;
- }
-
- // note that we're potentially using the same timestamp offset for both video and
- // audio
-
- if (this.loaderType_ === 'main' &&
- timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- return true;
- }
-
- if (!this.audioDisabled_ &&
- timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- return true;
- }
-
- return false;
- }
-
- trueSegmentStart_({
- currentStart,
- playlist,
- mediaIndex,
- firstVideoFrameTimeForData,
- currentVideoTimestampOffset,
- useVideoTimingInfo,
- videoTimingInfo,
- audioTimingInfo
- }) {
- if (typeof currentStart !== 'undefined') {
- // if start was set once, keep using it
- return currentStart;
- }
-
- if (!useVideoTimingInfo) {
- return audioTimingInfo.start;
- }
-
- const previousSegment = playlist.segments[mediaIndex - 1];
-
- // The start of a segment should be the start of the first full frame contained
- // within that segment. Since the transmuxer maintains a cache of incomplete data
- // from and/or the last frame seen, the start time may reflect a frame that starts
- // in the previous segment. Check for that case and ensure the start time is
- // accurate for the segment.
- if (mediaIndex === 0 ||
- !previousSegment ||
- typeof previousSegment.start === 'undefined' ||
- previousSegment.end !==
- (firstVideoFrameTimeForData + currentVideoTimestampOffset)) {
- return firstVideoFrameTimeForData;
- }
-
- return videoTimingInfo.start;
- }
-
- waitForAppendsToComplete_(segmentInfo) {
- if (!this.currentMediaInfo_) {
- this.error({
- message: 'No starting media returned, likely due to an unsupported media format.',
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return;
- }
- // Although transmuxing is done, appends may not yet be finished. Throw a marker
- // on each queue this loader is responsible for to ensure that the appends are
- // complete.
- const {hasAudio, hasVideo, isMuxed} = this.currentMediaInfo_;
- const waitForVideo = this.loaderType_ === 'main' && hasVideo;
- const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
-
- segmentInfo.waitingOnAppends = 0;
-
- // segments with no data
- if (!segmentInfo.hasAppendedData_) {
- if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
- // When there's no audio or video data in the segment, there's no audio or video
- // timing information.
- //
- // If there's no audio or video timing information, then the timestamp offset
- // can't be adjusted to the appropriate value for the transmuxer and source
- // buffers.
- //
- // Therefore, the next segment should be used to set the timestamp offset.
- this.isPendingTimestampOffset_ = true;
- }
-
- // override settings for metadata only segments
- segmentInfo.timingInfo = {start: 0};
- segmentInfo.waitingOnAppends++;
-
- if (!this.isPendingTimestampOffset_) {
- // update the timestampoffset
- this.updateSourceBufferTimestampOffset_(segmentInfo);
-
- // make sure the metadata queue is processed even though we have
- // no video/audio data.
- this.processMetadataQueue_();
- }
-
- // append is "done" instantly with no data.
- this.checkAppendsDone_(segmentInfo);
- return;
- }
-
- // Since source updater could call back synchronously, do the increments first.
- if (waitForVideo) {
- segmentInfo.waitingOnAppends++;
- }
- if (waitForAudio) {
- segmentInfo.waitingOnAppends++;
- }
-
- if (waitForVideo) {
- this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
- if (waitForAudio) {
- this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
- }
- }
-
- checkAppendsDone_(segmentInfo) {
- if (this.checkForAbort_(segmentInfo.requestId)) {
- return;
- }
-
- segmentInfo.waitingOnAppends--;
-
- if (segmentInfo.waitingOnAppends === 0) {
- this.handleAppendsDone_();
- }
- }
-
- checkForIllegalMediaSwitch(trackInfo) {
- const illegalMediaSwitchError =
- illegalMediaSwitch(this.loaderType_, this.currentMediaInfo_, trackInfo);
-
- if (illegalMediaSwitchError) {
- this.error({
- message: illegalMediaSwitchError,
- blacklistDuration: Infinity
- });
- this.trigger('error');
- return true;
- }
-
- return false;
- }
-
- updateSourceBufferTimestampOffset_(segmentInfo) {
- if (segmentInfo.timestampOffset === null ||
- // we don't yet have the start for whatever media type (video or audio) has
- // priority, timing-wise, so we must wait
- typeof segmentInfo.timingInfo.start !== 'number' ||
- // already updated the timestamp offset for this segment
- segmentInfo.changedTimestampOffset ||
- // the alt audio loader should not be responsible for setting the timestamp offset
- this.loaderType_ !== 'main') {
- return;
- }
-
- let didChange = false;
-
- // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
- // the timing info here comes from video. In the event that the audio is longer than
- // the video, this will trim the start of the audio.
- // This also trims any offset from 0 at the beginning of the media
- segmentInfo.timestampOffset -= segmentInfo.timingInfo.start;
- // In the event that there are part segment downloads, each will try to update the
- // timestamp offset. Retaining this bit of state prevents us from updating in the
- // future (within the same segment), however, there may be a better way to handle it.
- segmentInfo.changedTimestampOffset = true;
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
- this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
- this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
- didChange = true;
- }
-
- if (didChange) {
- this.trigger('timestampoffset');
- }
- }
-
- updateTimingInfoEnd_(segmentInfo) {
- segmentInfo.timingInfo = segmentInfo.timingInfo || {};
- const useVideoTimingInfo =
- this.loaderType_ === 'main' && this.currentMediaInfo_.hasVideo;
- const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ?
- segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
-
- if (!prioritizedTimingInfo) {
- return;
- }
- segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ?
- // End time may not exist in a case where we aren't parsing the full segment (one
- // current example is the case of fmp4), so use the rough duration to calculate an
- // end time.
- prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
- }
-
- /**
- * callback to run when appendBuffer is finished. detects if we are
- * in a good state to do things with the data we got, or if we need
- * to wait for more
- *
- * @private
- */
- handleAppendsDone_() {
- // appendsdone can cause an abort
- if (this.pendingSegment_) {
- this.trigger('appendsdone');
- }
-
- if (!this.pendingSegment_) {
- this.state = 'READY';
- // TODO should this move into this.checkForAbort to speed up requests post abort in
- // all appending cases?
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- return;
- }
-
- const segmentInfo = this.pendingSegment_;
-
- // Now that the end of the segment has been reached, we can set the end time. It's
- // best to wait until all appends are done so we're sure that the primary media is
- // finished (and we have its end time).
- this.updateTimingInfoEnd_(segmentInfo);
- if (this.shouldSaveSegmentTimingInfo_) {
- // Timeline mappings should only be saved for the main loader. This is for multiple
- // reasons:
- //
- // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
- // and the main loader try to save the timeline mapping, whichever comes later
- // will overwrite the first. In theory this is OK, as the mappings should be the
- // same, however, it breaks for (2)
- // 2) In the event of a live stream, the initial live point will make for a somewhat
- // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
- // the mapping will be off for one of the streams, dependent on which one was
- // first saved (see (1)).
- // 3) Primary timing goes by video in VHS, so the mapping should be video.
- //
- // Since the audio loader will wait for the main loader to load the first segment,
- // the main loader will save the first timeline mapping, and ensure that there won't
- // be a case where audio loads two segments without saving a mapping (thus leading
- // to missing segment timing info).
- this.syncController_.saveSegmentTimingInfo({
- segmentInfo,
- shouldSaveTimelineMapping: this.loaderType_ === 'main'
- });
- }
-
- const segmentDurationMessage =
- getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
-
- if (segmentDurationMessage) {
- if (segmentDurationMessage.severity === 'warn') {
- videojs.log.warn(segmentDurationMessage.message);
- } else {
- this.logger_(segmentDurationMessage.message);
- }
- }
-
- this.recordThroughput_(segmentInfo);
- this.pendingSegment_ = null;
- this.state = 'READY';
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate');
- // if the sync request was not appended
- // then it was not the correct segment.
- // throw it away and use the data it gave us
- // to get the correct one.
- if (!segmentInfo.hasAppendedData_) {
- this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
- return;
- }
- }
-
- this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
-
- this.addSegmentMetadataCue_(segmentInfo);
- this.fetchAtBuffer_ = true;
- if (this.currentTimeline_ !== segmentInfo.timeline) {
- this.timelineChangeController_.lastTimelineChange({
- type: this.loaderType_,
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- // If audio is not disabled, the main segment loader is responsible for updating
- // the audio timeline as well. If the content is video only, this won't have any
- // impact.
- if (this.loaderType_ === 'main' && !this.audioDisabled_) {
- this.timelineChangeController_.lastTimelineChange({
- type: 'audio',
- from: this.currentTimeline_,
- to: segmentInfo.timeline
- });
- }
- }
- this.currentTimeline_ = segmentInfo.timeline;
-
- // We must update the syncinfo to recalculate the seekable range before
- // the following conditional otherwise it may consider this a bad "guess"
- // and attempt to resync when the post-update seekable window and live
- // point would mean that this was the perfect segment to fetch
- this.trigger('syncinfoupdate');
-
- const segment = segmentInfo.segment;
-
- // If we previously appended a segment that ends more than 3 targetDurations before
- // the currentTime_ that means that our conservative guess was too conservative.
- // In that case, reset the loader state so that we try to use any information gained
- // from the previous request to create a new, more accurate, sync-point.
- if (segment.end &&
- this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3) {
- this.resetEverything();
- return;
- }
-
- const isWalkingForward = this.mediaIndex !== null;
-
- // Don't do a rendition switch unless we have enough time to get a sync segment
- // and conservatively guess
- if (isWalkingForward) {
- this.trigger('bandwidthupdate');
- }
- this.trigger('progress');
-
- this.mediaIndex = segmentInfo.mediaIndex;
- this.partIndex = segmentInfo.partIndex;
-
- // any time an update finishes and the last segment is in the
- // buffer, end the stream. this ensures the "ended" event will
- // fire if playback reaches that point.
- if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
- this.endOfStream();
- }
-
- // used for testing
- this.trigger('appended');
-
- if (segmentInfo.hasAppendedData_) {
- this.mediaAppends++;
- }
-
- if (!this.paused()) {
- this.monitorBuffer_();
- }
- }
-
- /**
- * Records the current throughput of the decrypt, transmux, and append
- * portion of the semgment pipeline. `throughput.rate` is a the cumulative
- * moving average of the throughput. `throughput.count` is the number of
- * data points in the average.
- *
- * @private
- * @param {Object} segmentInfo the object returned by loadSegment
- */
- recordThroughput_(segmentInfo) {
- if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
- this.logger_(`Ignoring segment's throughput because its duration of ${segmentInfo.duration}` +
- ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
- return;
- }
-
- const rate = this.throughput.rate;
- // Add one to the time to ensure that we don't accidentally attempt to divide
- // by zero in the case where the throughput is ridiculously high
- const segmentProcessingTime =
- Date.now() - segmentInfo.endOfAllRequests + 1;
- // Multiply by 8000 to convert from bytes/millisecond to bits/second
- const segmentProcessingThroughput =
- Math.floor((segmentInfo.byteLength / segmentProcessingTime) * 8 * 1000);
-
- // This is just a cumulative moving average calculation:
- // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
- this.throughput.rate +=
- (segmentProcessingThroughput - rate) / (++this.throughput.count);
- }
-
- /**
- * Adds a cue to the segment-metadata track with some metadata information about the
- * segment
- *
- * @private
- * @param {Object} segmentInfo
- * the object returned by loadSegment
- * @method addSegmentMetadataCue_
- */
- addSegmentMetadataCue_(segmentInfo) {
- if (!this.segmentMetadataTrack_) {
- return;
- }
-
- const segment = segmentInfo.segment;
- const start = segment.start;
- const end = segment.end;
-
- // Do not try adding the cue if the start and end times are invalid.
- if (!finite(start) || !finite(end)) {
- return;
- }
-
- removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
-
- const Cue = window.WebKitDataCue || window.VTTCue;
- const value = {
- custom: segment.custom,
- dateTimeObject: segment.dateTimeObject,
- dateTimeString: segment.dateTimeString,
- bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
- resolution: segmentInfo.playlist.attributes.RESOLUTION,
- codecs: segmentInfo.playlist.attributes.CODECS,
- byteLength: segmentInfo.byteLength,
- uri: segmentInfo.uri,
- timeline: segmentInfo.timeline,
- playlist: segmentInfo.playlist.id,
- start,
- end
- };
- const data = JSON.stringify(value);
- const cue = new Cue(start, end, data);
-
- // Attach the metadata to the value property of the cue to keep consistency between
- // the differences of WebKitDataCue in safari and VTTCue in other browsers
- cue.value = value;
-
- this.segmentMetadataTrack_.addCue(cue);
- }
-}
diff --git a/node_modules/@videojs/http-streaming/src/segment-transmuxer.js b/node_modules/@videojs/http-streaming/src/segment-transmuxer.js
deleted file mode 100644
index d351130..0000000
--- a/node_modules/@videojs/http-streaming/src/segment-transmuxer.js
+++ /dev/null
@@ -1,271 +0,0 @@
-import TransmuxWorker from 'worker!./transmuxer-worker.js';
-
-export const handleData_ = (event, transmuxedData, callback) => {
- const {
- type,
- initSegment,
- captions,
- captionStreams,
- metadata,
- videoFrameDtsTime,
- videoFramePtsTime
- } = event.data.segment;
-
- transmuxedData.buffer.push({
- captions,
- captionStreams,
- metadata
- });
-
- const boxes = event.data.segment.boxes || {
- data: event.data.segment.data
- };
-
- const result = {
- type,
- // cast ArrayBuffer to TypedArray
- data: new Uint8Array(
- boxes.data,
- boxes.data.byteOffset,
- boxes.data.byteLength
- ),
- initSegment: new Uint8Array(
- initSegment.data,
- initSegment.byteOffset,
- initSegment.byteLength
- )
- };
-
- if (typeof videoFrameDtsTime !== 'undefined') {
- result.videoFrameDtsTime = videoFrameDtsTime;
- }
-
- if (typeof videoFramePtsTime !== 'undefined') {
- result.videoFramePtsTime = videoFramePtsTime;
- }
-
- callback(result);
-};
-
-export const handleDone_ = ({
- transmuxedData,
- callback
-}) => {
- // Previously we only returned data on data events,
- // not on done events. Clear out the buffer to keep that consistent.
- transmuxedData.buffer = [];
-
- // all buffers should have been flushed from the muxer, so start processing anything we
- // have received
- callback(transmuxedData);
-};
-
-export const handleGopInfo_ = (event, transmuxedData) => {
- transmuxedData.gopInfo = event.data.gopInfo;
-};
-
-export const processTransmux = (options) => {
- const {
- transmuxer,
- bytes,
- audioAppendStart,
- gopsToAlignWith,
- remux,
- onData,
- onTrackInfo,
- onAudioTimingInfo,
- onVideoTimingInfo,
- onVideoSegmentTimingInfo,
- onAudioSegmentTimingInfo,
- onId3,
- onCaptions,
- onDone,
- onEndedTimeline,
- isEndOfTimeline
- } = options;
- const transmuxedData = {
- buffer: []
- };
- let waitForEndedTimelineEvent = isEndOfTimeline;
-
- const handleMessage = (event) => {
- if (transmuxer.currentTransmux !== options) {
- // disposed
- return;
- }
-
- if (event.data.action === 'data') {
- handleData_(event, transmuxedData, onData);
- }
- if (event.data.action === 'trackinfo') {
- onTrackInfo(event.data.trackInfo);
- }
- if (event.data.action === 'gopInfo') {
- handleGopInfo_(event, transmuxedData);
- }
- if (event.data.action === 'audioTimingInfo') {
- onAudioTimingInfo(event.data.audioTimingInfo);
- }
- if (event.data.action === 'videoTimingInfo') {
- onVideoTimingInfo(event.data.videoTimingInfo);
- }
- if (event.data.action === 'videoSegmentTimingInfo') {
- onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
- }
- if (event.data.action === 'audioSegmentTimingInfo') {
- onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
- }
- if (event.data.action === 'id3Frame') {
- onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
- }
- if (event.data.action === 'caption') {
- onCaptions(event.data.caption);
- }
- if (event.data.action === 'endedtimeline') {
- waitForEndedTimelineEvent = false;
- onEndedTimeline();
- }
-
- // wait for the transmuxed event since we may have audio and video
- if (event.data.type !== 'transmuxed') {
- return;
- }
-
- // If the "endedtimeline" event has not yet fired, and this segment represents the end
- // of a timeline, that means there may still be data events before the segment
- // processing can be considerred complete. In that case, the final event should be
- // an "endedtimeline" event with the type "transmuxed."
- if (waitForEndedTimelineEvent) {
- return;
- }
-
- transmuxer.onmessage = null;
- handleDone_({
- transmuxedData,
- callback: onDone
- });
-
- /* eslint-disable no-use-before-define */
- dequeue(transmuxer);
- /* eslint-enable */
- };
-
- transmuxer.onmessage = handleMessage;
-
- if (audioAppendStart) {
- transmuxer.postMessage({
- action: 'setAudioAppendStart',
- appendStart: audioAppendStart
- });
- }
-
- // allow empty arrays to be passed to clear out GOPs
- if (Array.isArray(gopsToAlignWith)) {
- transmuxer.postMessage({
- action: 'alignGopsWith',
- gopsToAlignWith
- });
- }
-
- if (typeof remux !== 'undefined') {
- transmuxer.postMessage({
- action: 'setRemux',
- remux
- });
- }
-
- if (bytes.byteLength) {
- const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
- const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
-
- transmuxer.postMessage(
- {
- action: 'push',
- // Send the typed-array of data as an ArrayBuffer so that
- // it can be sent as a "Transferable" and avoid the costly
- // memory copy
- data: buffer,
- // To recreate the original typed-array, we need information
- // about what portion of the ArrayBuffer it was a view into
- byteOffset,
- byteLength: bytes.byteLength
- },
- [ buffer ]
- );
- }
-
- if (isEndOfTimeline) {
- transmuxer.postMessage({ action: 'endTimeline' });
- }
- // even if we didn't push any bytes, we have to make sure we flush in case we reached
- // the end of the segment
- transmuxer.postMessage({ action: 'flush' });
-};
-
-export const dequeue = (transmuxer) => {
- transmuxer.currentTransmux = null;
- if (transmuxer.transmuxQueue.length) {
- transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
- if (typeof transmuxer.currentTransmux === 'function') {
- transmuxer.currentTransmux();
- } else {
- processTransmux(transmuxer.currentTransmux);
- }
- }
-};
-
-export const processAction = (transmuxer, action) => {
- transmuxer.postMessage({ action });
- dequeue(transmuxer);
-};
-
-export const enqueueAction = (action, transmuxer) => {
- if (!transmuxer.currentTransmux) {
- transmuxer.currentTransmux = action;
- processAction(transmuxer, action);
- return;
- }
- transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
-};
-
-export const reset = (transmuxer) => {
- enqueueAction('reset', transmuxer);
-};
-
-export const endTimeline = (transmuxer) => {
- enqueueAction('endTimeline', transmuxer);
-};
-
-export const transmux = (options) => {
- if (!options.transmuxer.currentTransmux) {
- options.transmuxer.currentTransmux = options;
- processTransmux(options);
- return;
- }
- options.transmuxer.transmuxQueue.push(options);
-};
-
-export const createTransmuxer = (options) => {
- const transmuxer = new TransmuxWorker();
-
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue = [];
- const term = transmuxer.terminate;
-
- transmuxer.terminate = () => {
- transmuxer.currentTransmux = null;
- transmuxer.transmuxQueue.length = 0;
- return term.call(transmuxer);
- };
-
- transmuxer.postMessage({action: 'init', options});
-
- return transmuxer;
-};
-
-export default {
- reset,
- endTimeline,
- transmux,
- createTransmuxer
-};
diff --git a/node_modules/@videojs/http-streaming/src/source-updater.js b/node_modules/@videojs/http-streaming/src/source-updater.js
deleted file mode 100644
index 8530922..0000000
--- a/node_modules/@videojs/http-streaming/src/source-updater.js
+++ /dev/null
@@ -1,867 +0,0 @@
-/**
- * @file source-updater.js
- */
-import videojs from 'video.js';
-import logger from './util/logger';
-import noop from './util/noop';
-import { bufferIntersection } from './ranges.js';
-import {getMimeForCodec} from '@videojs/vhs-utils/es/codecs.js';
-import window from 'global/window';
-import toTitleCase from './util/to-title-case.js';
-import { QUOTA_EXCEEDED_ERR } from './error-codes';
-
-const bufferTypes = [
- 'video',
- 'audio'
-];
-
-const updating = (type, sourceUpdater) => {
- const sourceBuffer = sourceUpdater[`${type}Buffer`];
-
- return (sourceBuffer && sourceBuffer.updating) || sourceUpdater.queuePending[type];
-};
-
-const nextQueueIndexOfType = (type, queue) => {
- for (let i = 0; i < queue.length; i++) {
- const queueEntry = queue[i];
-
- if (queueEntry.type === 'mediaSource') {
- // If the next entry is a media source entry (uses multiple source buffers), block
- // processing to allow it to go through first.
- return null;
- }
-
- if (queueEntry.type === type) {
- return i;
- }
- }
-
- return null;
-};
-
-const shiftQueue = (type, sourceUpdater) => {
- if (sourceUpdater.queue.length === 0) {
- return;
- }
-
- let queueIndex = 0;
- let queueEntry = sourceUpdater.queue[queueIndex];
-
- if (queueEntry.type === 'mediaSource') {
- if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
- sourceUpdater.queue.shift();
- queueEntry.action(sourceUpdater);
-
- if (queueEntry.doneFn) {
- queueEntry.doneFn();
- }
-
- // Only specific source buffer actions must wait for async updateend events. Media
- // Source actions process synchronously. Therefore, both audio and video source
- // buffers are now clear to process the next queue entries.
- shiftQueue('audio', sourceUpdater);
- shiftQueue('video', sourceUpdater);
- }
-
- // Media Source actions require both source buffers, so if the media source action
- // couldn't process yet (because one or both source buffers are busy), block other
- // queue actions until both are available and the media source action can process.
- return;
- }
-
- if (type === 'mediaSource') {
- // If the queue was shifted by a media source action (this happens when pushing a
- // media source action onto the queue), then it wasn't from an updateend event from an
- // audio or video source buffer, so there's no change from previous state, and no
- // processing should be done.
- return;
- }
-
- // Media source queue entries don't need to consider whether the source updater is
- // started (i.e., source buffers are created) as they don't need the source buffers, but
- // source buffer queue entries do.
- if (
- !sourceUpdater.ready() ||
- sourceUpdater.mediaSource.readyState === 'closed' ||
- updating(type, sourceUpdater)
- ) {
- return;
- }
-
- if (queueEntry.type !== type) {
- queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
-
- if (queueIndex === null) {
- // Either there's no queue entry that uses this source buffer type in the queue, or
- // there's a media source queue entry before the next entry of this type, in which
- // case wait for that action to process first.
- return;
- }
-
- queueEntry = sourceUpdater.queue[queueIndex];
- }
-
- sourceUpdater.queue.splice(queueIndex, 1);
- // Keep a record that this source buffer type is in use.
- //
- // The queue pending operation must be set before the action is performed in the event
- // that the action results in a synchronous event that is acted upon. For instance, if
- // an exception is thrown that can be handled, it's possible that new actions will be
- // appended to an empty queue and immediately executed, but would not have the correct
- // pending information if this property was set after the action was performed.
- sourceUpdater.queuePending[type] = queueEntry;
- queueEntry.action(type, sourceUpdater);
-
- if (!queueEntry.doneFn) {
- // synchronous operation, process next entry
- sourceUpdater.queuePending[type] = null;
- shiftQueue(type, sourceUpdater);
- return;
- }
-};
-
-const cleanupBuffer = (type, sourceUpdater) => {
- const buffer = sourceUpdater[`${type}Buffer`];
- const titleType = toTitleCase(type);
-
- if (!buffer) {
- return;
- }
-
- buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
- buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
-
- sourceUpdater.codecs[type] = null;
- sourceUpdater[`${type}Buffer`] = null;
-};
-
-const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer &&
- Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
-
-const actions = {
- appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
- const sourceBuffer = sourceUpdater[`${type}Buffer`];
-
- // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
-
- try {
- sourceBuffer.appendBuffer(bytes);
- } catch (e) {
- sourceUpdater.logger_(`Error with code ${e.code} ` +
- (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') +
- `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
- sourceUpdater.queuePending[type] = null;
- onError(e);
- }
- },
- remove: (start, end) => (type, sourceUpdater) => {
- const sourceBuffer = sourceUpdater[`${type}Buffer`];
-
- // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
- try {
- sourceBuffer.remove(start, end);
- } catch (e) {
- sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
- }
- },
- timestampOffset: (offset) => (type, sourceUpdater) => {
- const sourceBuffer = sourceUpdater[`${type}Buffer`];
-
- // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
-
- sourceBuffer.timestampOffset = offset;
- },
- callback: (callback) => (type, sourceUpdater) => {
- callback();
- },
- endOfStream: (error) => (sourceUpdater) => {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
- sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
-
- try {
- sourceUpdater.mediaSource.endOfStream(error);
- } catch (e) {
- videojs.log.warn('Failed to call media source endOfStream', e);
- }
- },
- duration: (duration) => (sourceUpdater) => {
- sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
- try {
- sourceUpdater.mediaSource.duration = duration;
- } catch (e) {
- videojs.log.warn('Failed to set media source duration', e);
- }
- },
- abort: () => (type, sourceUpdater) => {
- if (sourceUpdater.mediaSource.readyState !== 'open') {
- return;
- }
- const sourceBuffer = sourceUpdater[`${type}Buffer`];
-
- // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_(`calling abort on ${type}Buffer`);
- try {
- sourceBuffer.abort();
- } catch (e) {
- videojs.log.warn(`Failed to abort on ${type}Buffer`, e);
- }
- },
- addSourceBuffer: (type, codec) => (sourceUpdater) => {
- const titleType = toTitleCase(type);
- const mime = getMimeForCodec(codec);
-
- sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
-
- const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
-
- sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
- sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
- sourceUpdater.codecs[type] = codec;
- sourceUpdater[`${type}Buffer`] = sourceBuffer;
- },
- removeSourceBuffer: (type) => (sourceUpdater) => {
- const sourceBuffer = sourceUpdater[`${type}Buffer`];
-
- cleanupBuffer(type, sourceUpdater);
-
- // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
-
- try {
- sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
- } catch (e) {
- videojs.log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
- }
- },
- changeType: (codec) => (type, sourceUpdater) => {
- const sourceBuffer = sourceUpdater[`${type}Buffer`];
- const mime = getMimeForCodec(codec);
-
- // can't do anything if the media source / source buffer is null
- // or the media source does not contain this source buffer.
- if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
- return;
- }
-
- // do not update codec if we don't need to.
- if (sourceUpdater.codecs[type] === codec) {
- return;
- }
-
- sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);
-
- sourceBuffer.changeType(mime);
- sourceUpdater.codecs[type] = codec;
- }
-};
-
-const pushQueue = ({type, sourceUpdater, action, doneFn, name}) => {
- sourceUpdater.queue.push({
- type,
- action,
- doneFn,
- name
- });
- shiftQueue(type, sourceUpdater);
-};
-
-const onUpdateend = (type, sourceUpdater) => (e) => {
- // Although there should, in theory, be a pending action for any updateend receieved,
- // there are some actions that may trigger updateend events without set definitions in
- // the w3c spec. For instance, setting the duration on the media source may trigger
- // updateend events on source buffers. This does not appear to be in the spec. As such,
- // if we encounter an updateend without a corresponding pending action from our queue
- // for that source buffer type, process the next action.
- if (sourceUpdater.queuePending[type]) {
- const doneFn = sourceUpdater.queuePending[type].doneFn;
-
- sourceUpdater.queuePending[type] = null;
-
- if (doneFn) {
- // if there's an error, report it
- doneFn(sourceUpdater[`${type}Error_`]);
- }
- }
-
- shiftQueue(type, sourceUpdater);
-};
-
-/**
- * A queue of callbacks to be serialized and applied when a
- * MediaSource and its associated SourceBuffers are not in the
- * updating state. It is used by the segment loader to update the
- * underlying SourceBuffers when new data is loaded, for instance.
- *
- * @class SourceUpdater
- * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
- * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
- */
-export default class SourceUpdater extends videojs.EventTarget {
- constructor(mediaSource) {
- super();
- this.mediaSource = mediaSource;
- this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
- this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
- this.logger_ = logger('SourceUpdater');
- // initial timestamp offset is 0
- this.audioTimestampOffset_ = 0;
- this.videoTimestampOffset_ = 0;
- this.queue = [];
- this.queuePending = {
- audio: null,
- video: null
- };
- this.delayedAudioAppendQueue_ = [];
- this.videoAppendQueued_ = false;
- this.codecs = {};
- this.onVideoUpdateEnd_ = onUpdateend('video', this);
- this.onAudioUpdateEnd_ = onUpdateend('audio', this);
- this.onVideoError_ = (e) => {
- // used for debugging
- this.videoError_ = e;
- };
- this.onAudioError_ = (e) => {
- // used for debugging
- this.audioError_ = e;
- };
- this.createdSourceBuffers_ = false;
- this.initializedEme_ = false;
- this.triggeredReady_ = false;
- }
-
- initializedEme() {
- this.initializedEme_ = true;
- this.triggerReady();
- }
-
- hasCreatedSourceBuffers() {
- // if false, likely waiting on one of the segment loaders to get enough data to create
- // source buffers
- return this.createdSourceBuffers_;
- }
-
- hasInitializedAnyEme() {
- return this.initializedEme_;
- }
-
- ready() {
- return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
- }
-
- createSourceBuffers(codecs) {
- if (this.hasCreatedSourceBuffers()) {
- // already created them before
- return;
- }
-
- // the intial addOrChangeSourceBuffers will always be
- // two add buffers.
- this.addOrChangeSourceBuffers(codecs);
- this.createdSourceBuffers_ = true;
- this.trigger('createdsourcebuffers');
- this.triggerReady();
- }
-
- triggerReady() {
- // only allow ready to be triggered once, this prevents the case
- // where:
- // 1. we trigger createdsourcebuffers
- // 2. ie 11 synchronously initializates eme
- // 3. the synchronous initialization causes us to trigger ready
- // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
- if (this.ready() && !this.triggeredReady_) {
- this.triggeredReady_ = true;
- this.trigger('ready');
- }
- }
-
- /**
- * Add a type of source buffer to the media source.
- *
- * @param {string} type
- * The type of source buffer to add.
- *
- * @param {string} codec
- * The codec to add the source buffer with.
- */
- addSourceBuffer(type, codec) {
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.addSourceBuffer(type, codec),
- name: 'addSourceBuffer'
- });
- }
-
- /**
- * call abort on a source buffer.
- *
- * @param {string} type
- * The type of source buffer to call abort on.
- */
- abort(type) {
- pushQueue({
- type,
- sourceUpdater: this,
- action: actions.abort(type),
- name: 'abort'
- });
- }
-
- /**
- * Call removeSourceBuffer and remove a specific type
- * of source buffer on the mediaSource.
- *
- * @param {string} type
- * The type of source buffer to remove.
- */
- removeSourceBuffer(type) {
- if (!this.canRemoveSourceBuffer()) {
- videojs.log.error('removeSourceBuffer is not supported!');
- return;
- }
-
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.removeSourceBuffer(type),
- name: 'removeSourceBuffer'
- });
- }
-
- /**
- * Whether or not the removeSourceBuffer function is supported
- * on the mediaSource.
- *
- * @return {boolean}
- * if removeSourceBuffer can be called.
- */
- canRemoveSourceBuffer() {
- // IE reports that it supports removeSourceBuffer, but often throws
- // errors when attempting to use the function. So we report that it
- // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
- // throws errors, so we report that it does not support this as well.
- return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window.MediaSource &&
- window.MediaSource.prototype &&
- typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
- }
-
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- static canChangeType() {
- return window.SourceBuffer &&
- window.SourceBuffer.prototype &&
- typeof window.SourceBuffer.prototype.changeType === 'function';
- }
-
- /**
- * Whether or not the changeType function is supported
- * on our SourceBuffers.
- *
- * @return {boolean}
- * if changeType can be called.
- */
- canChangeType() {
- return this.constructor.canChangeType();
- }
-
- /**
- * Call the changeType function on a source buffer, given the code and type.
- *
- * @param {string} type
- * The type of source buffer to call changeType on.
- *
- * @param {string} codec
- * The codec string to change type with on the source buffer.
- */
- changeType(type, codec) {
- if (!this.canChangeType()) {
- videojs.log.error('changeType is not supported!');
- return;
- }
-
- pushQueue({
- type,
- sourceUpdater: this,
- action: actions.changeType(codec),
- name: 'changeType'
- });
- }
-
- /**
- * Add source buffers with a codec or, if they are already created,
- * call changeType on source buffers using changeType.
- *
- * @param {Object} codecs
- * Codecs to switch to
- */
- addOrChangeSourceBuffers(codecs) {
- if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
- throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
- }
-
- Object.keys(codecs).forEach((type) => {
- const codec = codecs[type];
-
- if (!this.hasCreatedSourceBuffers()) {
- return this.addSourceBuffer(type, codec);
- }
-
- if (this.canChangeType()) {
- this.changeType(type, codec);
- }
- });
- }
-
- /**
- * Queue an update to append an ArrayBuffer.
- *
- * @param {MediaObject} object containing audioBytes and/or videoBytes
- * @param {Function} done the function to call when done
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
- */
- appendBuffer(options, doneFn) {
- const {segmentInfo, type, bytes} = options;
-
- this.processedAppend_ = true;
- if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
- this.delayedAudioAppendQueue_.push([options, doneFn]);
- this.logger_(`delayed audio append of ${bytes.length} until video append`);
- return;
- }
-
- // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
- // not be fired. This means that the queue will be blocked until the next action
- // taken by the segment-loader. Provide a mechanism for segment-loader to handle
- // these errors by calling the doneFn with the specific error.
- const onError = doneFn;
-
- pushQueue({
- type,
- sourceUpdater: this,
- action: actions.appendBuffer(bytes, segmentInfo || {mediaIndex: -1}, onError),
- doneFn,
- name: 'appendBuffer'
- });
-
- if (type === 'video') {
- this.videoAppendQueued_ = true;
- if (!this.delayedAudioAppendQueue_.length) {
- return;
- }
- const queue = this.delayedAudioAppendQueue_.slice();
-
- this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
-
- this.delayedAudioAppendQueue_.length = 0;
- queue.forEach((que) => {
- this.appendBuffer.apply(this, que);
- });
- }
- }
-
- /**
- * Get the audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The audio buffer's buffered time range
- */
- audioBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
- return videojs.createTimeRange();
- }
-
- return this.audioBuffer.buffered ? this.audioBuffer.buffered :
- videojs.createTimeRange();
- }
-
- /**
- * Get the video buffer's buffered timerange.
- *
- * @return {TimeRange}
- * The video buffer's buffered time range
- */
- videoBuffered() {
- // no media source/source buffer or it isn't in the media sources
- // source buffer list
- if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
- return videojs.createTimeRange();
- }
- return this.videoBuffer.buffered ? this.videoBuffer.buffered :
- videojs.createTimeRange();
- }
-
- /**
- * Get a combined video/audio buffer's buffered timerange.
- *
- * @return {TimeRange}
- * the combined time range
- */
- buffered() {
- const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
- const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
-
- if (audio && !video) {
- return this.audioBuffered();
- }
-
- if (video && !audio) {
- return this.videoBuffered();
- }
-
- return bufferIntersection(this.audioBuffered(), this.videoBuffered());
- }
-
- /**
- * Add a callback to the queue that will set duration on the mediaSource.
- *
- * @param {number} duration
- * The duration to set
- *
- * @param {Function} [doneFn]
- * function to run after duration has been set.
- */
- setDuration(duration, doneFn = noop) {
- // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.duration(duration),
- name: 'duration',
- doneFn
- });
- }
-
- /**
- * Add a mediaSource endOfStream call to the queue
- *
- * @param {Error} [error]
- * Call endOfStream with an error
- *
- * @param {Function} [doneFn]
- * A function that should be called when the
- * endOfStream call has finished.
- */
- endOfStream(error = null, doneFn = noop) {
- if (typeof error !== 'string') {
- error = undefined;
- }
- // In order to set the duration on the media source, it's necessary to wait for all
- // source buffers to no longer be updating. "If the updating attribute equals true on
- // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
- // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
- pushQueue({
- type: 'mediaSource',
- sourceUpdater: this,
- action: actions.endOfStream(error),
- name: 'endOfStream',
- doneFn
- });
- }
-
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- removeAudio(start, end, done = noop) {
- if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
-
- /**
- * Queue an update to remove a time range from the buffer.
- *
- * @param {number} start where to start the removal
- * @param {number} end where to end the removal
- * @param {Function} [done=noop] optional callback to be executed when the remove
- * operation is complete
- * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
- */
- removeVideo(start, end, done = noop) {
- if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
- done();
- return;
- }
-
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.remove(start, end),
- doneFn: done,
- name: 'remove'
- });
- }
-
- /**
- * Whether the underlying sourceBuffer is updating or not
- *
- * @return {boolean} the updating status of the SourceBuffer
- */
- updating() {
- // the audio/video source buffer is updating
- if (updating('audio', this) || updating('video', this)) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Set/get the timestampoffset on the audio SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- audioTimestampOffset(offset) {
- if (typeof offset !== 'undefined' &&
- this.audioBuffer &&
- // no point in updating if it's the same
- this.audioTimestampOffset_ !== offset) {
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.audioTimestampOffset_ = offset;
- }
- return this.audioTimestampOffset_;
- }
-
- /**
- * Set/get the timestampoffset on the video SourceBuffer
- *
- * @return {number} the timestamp offset
- */
- videoTimestampOffset(offset) {
- if (typeof offset !== 'undefined' &&
- this.videoBuffer &&
- // no point in updating if it's the same
- this.videoTimestampOffset !== offset) {
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.timestampOffset(offset),
- name: 'timestampOffset'
- });
- this.videoTimestampOffset_ = offset;
- }
- return this.videoTimestampOffset_;
- }
-
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the audio queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- audioQueueCallback(callback) {
- if (!this.audioBuffer) {
- return;
- }
- pushQueue({
- type: 'audio',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
-
- /**
- * Add a function to the queue that will be called
- * when it is its turn to run in the video queue.
- *
- * @param {Function} callback
- * The callback to queue.
- */
- videoQueueCallback(callback) {
- if (!this.videoBuffer) {
- return;
- }
- pushQueue({
- type: 'video',
- sourceUpdater: this,
- action: actions.callback(callback),
- name: 'callback'
- });
- }
-
- /**
- * dispose of the source updater and the underlying sourceBuffer
- */
- dispose() {
- this.trigger('dispose');
- bufferTypes.forEach((type) => {
- this.abort(type);
- if (this.canRemoveSourceBuffer()) {
- this.removeSourceBuffer(type);
- } else {
- this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
- }
- });
-
- this.videoAppendQueued_ = false;
- this.delayedAudioAppendQueue_.length = 0;
-
- if (this.sourceopenListener_) {
- this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
- }
-
- this.off();
- }
-}
diff --git a/node_modules/@videojs/http-streaming/src/sync-controller.js b/node_modules/@videojs/http-streaming/src/sync-controller.js
deleted file mode 100644
index 51d0740..0000000
--- a/node_modules/@videojs/http-streaming/src/sync-controller.js
+++ /dev/null
@@ -1,588 +0,0 @@
-/**
- * @file sync-controller.js
- */
-
-import {sumDurations, getPartsAndSegments} from './playlist';
-import videojs from 'video.js';
-import logger from './util/logger';
-
-export const syncPointStrategies = [
- // Stategy "VOD": Handle the VOD-case where the sync-point is *always*
- // the equivalence display-time 0 === segment-index 0
- {
- name: 'VOD',
- run: (syncController, playlist, duration, currentTimeline, currentTime) => {
- if (duration !== Infinity) {
- const syncPoint = {
- time: 0,
- segmentIndex: 0,
- partIndex: null
- };
-
- return syncPoint;
- }
- return null;
- }
- },
- // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
- {
- name: 'ProgramDateTime',
- run: (syncController, playlist, duration, currentTimeline, currentTime) => {
- if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
- return null;
- }
-
- let syncPoint = null;
- let lastDistance = null;
- const partsAndSegments = getPartsAndSegments(playlist);
-
- currentTime = currentTime || 0;
- for (let i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- const index = (playlist.endList || currentTime === 0) ? i : partsAndSegments.length - (i + 1);
- const partAndSegment = partsAndSegments[index];
- const segment = partAndSegment.segment;
- const datetimeMapping =
- syncController.timelineToDatetimeMappings[segment.timeline];
-
- if (!datetimeMapping) {
- continue;
- }
-
- if (segment.dateTimeObject) {
- const segmentTime = segment.dateTimeObject.getTime() / 1000;
- let start = segmentTime + datetimeMapping;
-
- // take part duration into account.
- if (segment.parts && typeof partAndSegment.partIndex === 'number') {
- for (let z = 0; z < partAndSegment.partIndex; z++) {
- start += segment.parts[z].duration;
- }
- }
- const distance = Math.abs(currentTime - start);
-
- // Once the distance begins to increase, or if distance is 0, we have passed
- // currentTime and can stop looking for better candidates
- if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
- break;
- }
-
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
- }
- return syncPoint;
- }
- },
- // Stategy "Segment": We have a known time mapping for a timeline and a
- // segment in the current timeline with timing data
- {
- name: 'Segment',
- run: (syncController, playlist, duration, currentTimeline, currentTime) => {
- let syncPoint = null;
- let lastDistance = null;
-
- currentTime = currentTime || 0;
- const partsAndSegments = getPartsAndSegments(playlist);
-
- for (let i = 0; i < partsAndSegments.length; i++) {
- // start from the end and loop backwards for live
- // or start from the front and loop forwards for non-live
- const index = (playlist.endList || currentTime === 0) ? i : partsAndSegments.length - (i + 1);
- const partAndSegment = partsAndSegments[index];
- const segment = partAndSegment.segment;
- const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
-
- if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
- const distance = Math.abs(currentTime - start);
-
- // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: start,
- segmentIndex: partAndSegment.segmentIndex,
- partIndex: partAndSegment.partIndex
- };
- }
-
- }
- }
- return syncPoint;
- }
- },
- // Stategy "Discontinuity": We have a discontinuity with a known
- // display-time
- {
- name: 'Discontinuity',
- run: (syncController, playlist, duration, currentTimeline, currentTime) => {
- let syncPoint = null;
-
- currentTime = currentTime || 0;
-
- if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- let lastDistance = null;
-
- for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
- const segmentIndex = playlist.discontinuityStarts[i];
- const discontinuity = playlist.discontinuitySequence + i + 1;
- const discontinuitySync = syncController.discontinuities[discontinuity];
-
- if (discontinuitySync) {
- const distance = Math.abs(currentTime - discontinuitySync.time);
-
- // Once the distance begins to increase, we have passed
- // currentTime and can stop looking for better candidates
- if (lastDistance !== null && lastDistance < distance) {
- break;
- }
-
- if (!syncPoint || lastDistance === null || lastDistance >= distance) {
- lastDistance = distance;
- syncPoint = {
- time: discontinuitySync.time,
- segmentIndex,
- partIndex: null
- };
- }
- }
- }
- }
- return syncPoint;
- }
- },
- // Stategy "Playlist": We have a playlist with a known mapping of
- // segment index to display time
- {
- name: 'Playlist',
- run: (syncController, playlist, duration, currentTimeline, currentTime) => {
- if (playlist.syncInfo) {
- const syncPoint = {
- time: playlist.syncInfo.time,
- segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
- partIndex: null
- };
-
- return syncPoint;
- }
- return null;
- }
- }
-];
-
-export default class SyncController extends videojs.EventTarget {
- constructor(options = {}) {
- super();
- // ...for synching across variants
- this.timelines = [];
- this.discontinuities = [];
- this.timelineToDatetimeMappings = {};
-
- this.logger_ = logger('SyncController');
- }
-
- /**
- * Find a sync-point for the playlist specified
- *
- * A sync-point is defined as a known mapping from display-time to
- * a segment-index in the current playlist.
- *
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinite if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Object}
- * A sync-point object
- */
- getSyncPoint(playlist, duration, currentTimeline, currentTime) {
- const syncPoints = this.runStrategies_(
- playlist,
- duration,
- currentTimeline,
- currentTime
- );
-
- if (!syncPoints.length) {
- // Signal that we need to attempt to get a sync-point manually
- // by fetching a segment in the playlist and constructing
- // a sync-point from that information
- return null;
- }
-
- // Now find the sync-point that is closest to the currentTime because
- // that should result in the most accurate guess about which segment
- // to fetch
- return this.selectSyncPoint_(syncPoints, { key: 'time', value: currentTime });
- }
-
- /**
- * Calculate the amount of time that has expired off the playlist during playback
- *
- * @param {Playlist} playlist
- * Playlist object to calculate expired from
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playling a live source)
- * @return {number|null}
- * The amount of time that has expired off the playlist during playback. Null
- * if no sync-points for the playlist can be found.
- */
- getExpiredTime(playlist, duration) {
- if (!playlist || !playlist.segments) {
- return null;
- }
-
- const syncPoints = this.runStrategies_(
- playlist,
- duration,
- playlist.discontinuitySequence,
- 0
- );
-
- // Without sync-points, there is not enough information to determine the expired time
- if (!syncPoints.length) {
- return null;
- }
-
- const syncPoint = this.selectSyncPoint_(syncPoints, {
- key: 'segmentIndex',
- value: 0
- });
-
- // If the sync-point is beyond the start of the playlist, we want to subtract the
- // duration from index 0 to syncPoint.segmentIndex instead of adding.
- if (syncPoint.segmentIndex > 0) {
- syncPoint.time *= -1;
- }
-
- return Math.abs(syncPoint.time + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: syncPoint.segmentIndex,
- endIndex: 0
- }));
- }
-
- /**
- * Runs each sync-point strategy and returns a list of sync-points returned by the
- * strategies
- *
- * @private
- * @param {Playlist} playlist
- * The playlist that needs a sync-point
- * @param {number} duration
- * Duration of the MediaSource (Infinity if playing a live source)
- * @param {number} currentTimeline
- * The last timeline from which a segment was loaded
- * @return {Array}
- * A list of sync-point objects
- */
- runStrategies_(playlist, duration, currentTimeline, currentTime) {
- const syncPoints = [];
-
- // Try to find a sync-point in by utilizing various strategies...
- for (let i = 0; i < syncPointStrategies.length; i++) {
- const strategy = syncPointStrategies[i];
- const syncPoint = strategy.run(
- this,
- playlist,
- duration,
- currentTimeline,
- currentTime
- );
-
- if (syncPoint) {
- syncPoint.strategy = strategy.name;
- syncPoints.push({
- strategy: strategy.name,
- syncPoint
- });
- }
- }
-
- return syncPoints;
- }
-
- /**
- * Selects the sync-point nearest the specified target
- *
- * @private
- * @param {Array} syncPoints
- * List of sync-points to select from
- * @param {Object} target
- * Object specifying the property and value we are targeting
- * @param {string} target.key
- * Specifies the property to target. Must be either 'time' or 'segmentIndex'
- * @param {number} target.value
- * The value to target for the specified key.
- * @return {Object}
- * The sync-point nearest the target
- */
- selectSyncPoint_(syncPoints, target) {
- let bestSyncPoint = syncPoints[0].syncPoint;
- let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
- let bestStrategy = syncPoints[0].strategy;
-
- for (let i = 1; i < syncPoints.length; i++) {
- const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
-
- if (newDistance < bestDistance) {
- bestDistance = newDistance;
- bestSyncPoint = syncPoints[i].syncPoint;
- bestStrategy = syncPoints[i].strategy;
- }
- }
-
- this.logger_(`syncPoint for [${target.key}: ${target.value}] chosen with strategy` +
- ` [${bestStrategy}]: [time:${bestSyncPoint.time},` +
- ` segmentIndex:${bestSyncPoint.segmentIndex}` +
- (typeof bestSyncPoint.partIndex === 'number' ? `,partIndex:${bestSyncPoint.partIndex}` : '') +
- ']');
-
- return bestSyncPoint;
- }
-
- /**
- * Save any meta-data present on the segments when segments leave
- * the live window to the playlist to allow for synchronization at the
- * playlist level later.
- *
- * @param {Playlist} oldPlaylist - The previous active playlist
- * @param {Playlist} newPlaylist - The updated and most current playlist
- */
- saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
- const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
-
- // When a segment expires from the playlist and it has a start time
- // save that information as a possible sync-point reference in future
- for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
- const lastRemovedSegment = oldPlaylist.segments[i];
-
- if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
- newPlaylist.syncInfo = {
- mediaSequence: oldPlaylist.mediaSequence + i,
- time: lastRemovedSegment.start
- };
- this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` +
- ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
- this.trigger('syncinfoupdate');
- break;
- }
- }
- }
-
- /**
- * Save the mapping from playlist's ProgramDateTime to display. This should only happen
- * before segments start to load.
- *
- * @param {Playlist} playlist - The currently active playlist
- */
- setDateTimeMappingForStart(playlist) {
- // It's possible for the playlist to be updated before playback starts, meaning time
- // zero is not yet set. If, during these playlist refreshes, a discontinuity is
- // crossed, then the old time zero mapping (for the prior timeline) would be retained
- // unless the mappings are cleared.
- this.timelineToDatetimeMappings = {};
-
- if (playlist.segments &&
- playlist.segments.length &&
- playlist.segments[0].dateTimeObject) {
- const firstSegment = playlist.segments[0];
- const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
-
- this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
- }
- }
-
- /**
- * Calculates and saves timeline mappings, playlist sync info, and segment timing values
- * based on the latest timing information.
- *
- * @param {Object} options
- * Options object
- * @param {SegmentInfo} options.segmentInfo
- * The current active request information
- * @param {boolean} options.shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved for timeline mapping and program date time mappings.
- */
- saveSegmentTimingInfo({ segmentInfo, shouldSaveTimelineMapping }) {
- const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(
- segmentInfo,
- segmentInfo.timingInfo,
- shouldSaveTimelineMapping
- );
- const segment = segmentInfo.segment;
-
- if (didCalculateSegmentTimeMapping) {
- this.saveDiscontinuitySyncInfo_(segmentInfo);
-
- // If the playlist does not have sync information yet, record that information
- // now with segment timing information
- if (!segmentInfo.playlist.syncInfo) {
- segmentInfo.playlist.syncInfo = {
- mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
- time: segment.start
- };
- }
- }
-
- const dateTime = segment.dateTimeObject;
-
- if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
- this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
- }
- }
-
- timestampOffsetForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
- return this.timelines[timeline].time;
- }
-
- mappingForTimeline(timeline) {
- if (typeof this.timelines[timeline] === 'undefined') {
- return null;
- }
- return this.timelines[timeline].mapping;
- }
-
- /**
- * Use the "media time" for a segment to generate a mapping to "display time" and
- * save that display time to the segment.
- *
- * @private
- * @param {SegmentInfo} segmentInfo
- * The current active request information
- * @param {Object} timingInfo
- * The start and end time of the current segment in "media time"
- * @param {boolean} shouldSaveTimelineMapping
- * If there's a timeline change, determines if the timeline mapping should be
- * saved in timelines.
- * @return {boolean}
- * Returns false if segment time mapping could not be calculated
- */
- calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
- // TODO: remove side effects
- const segment = segmentInfo.segment;
- const part = segmentInfo.part;
- let mappingObj = this.timelines[segmentInfo.timeline];
- let start;
- let end;
-
- if (typeof segmentInfo.timestampOffset === 'number') {
- mappingObj = {
- time: segmentInfo.startOfSegment,
- mapping: segmentInfo.startOfSegment - timingInfo.start
- };
- if (shouldSaveTimelineMapping) {
- this.timelines[segmentInfo.timeline] = mappingObj;
- this.trigger('timestampoffset');
-
- this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` +
- `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
- }
-
- start = segmentInfo.startOfSegment;
- end = timingInfo.end + mappingObj.mapping;
-
- } else if (mappingObj) {
- start = timingInfo.start + mappingObj.mapping;
- end = timingInfo.end + mappingObj.mapping;
- } else {
- return false;
- }
-
- if (part) {
- part.start = start;
- part.end = end;
- }
-
- // If we don't have a segment start yet or the start value we got
- // is less than our current segment.start value, save a new start value.
- // We have to do this because parts will have segment timing info saved
- // multiple times and we want segment start to be the earliest part start
- // value for that segment.
- if (!segment.start || start < segment.start) {
- segment.start = start;
- }
- segment.end = end;
-
- return true;
- }
-
- /**
- * Each time we have discontinuity in the playlist, attempt to calculate the location
- * in display of the start of the discontinuity and save that. We also save an accuracy
- * value so that we save values with the most accuracy (closest to 0.)
- *
- * @private
- * @param {SegmentInfo} segmentInfo - The current active request information
- */
- saveDiscontinuitySyncInfo_(segmentInfo) {
- const playlist = segmentInfo.playlist;
- const segment = segmentInfo.segment;
-
- // If the current segment is a discontinuity then we know exactly where
- // the start of the range and it's accuracy is 0 (greater accuracy values
- // mean more approximation)
- if (segment.discontinuity) {
- this.discontinuities[segment.timeline] = {
- time: segment.start,
- accuracy: 0
- };
- } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
- // Search for future discontinuities that we can provide better timing
- // information for and save that information for sync purposes
- for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
- const segmentIndex = playlist.discontinuityStarts[i];
- const discontinuity = playlist.discontinuitySequence + i + 1;
- const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
- const accuracy = Math.abs(mediaIndexDiff);
-
- if (!this.discontinuities[discontinuity] ||
- this.discontinuities[discontinuity].accuracy > accuracy) {
- let time;
-
- if (mediaIndexDiff < 0) {
- time = segment.start - sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex,
- endIndex: segmentIndex
- });
- } else {
- time = segment.end + sumDurations({
- defaultDuration: playlist.targetDuration,
- durationList: playlist.segments,
- startIndex: segmentInfo.mediaIndex + 1,
- endIndex: segmentIndex
- });
- }
-
- this.discontinuities[discontinuity] = {
- time,
- accuracy
- };
- }
- }
- }
- }
-
- dispose() {
- this.trigger('dispose');
- this.off();
- }
-}
diff --git a/node_modules/@videojs/http-streaming/src/timeline-change-controller.js b/node_modules/@videojs/http-streaming/src/timeline-change-controller.js
deleted file mode 100644
index 90cc794..0000000
--- a/node_modules/@videojs/http-streaming/src/timeline-change-controller.js
+++ /dev/null
@@ -1,48 +0,0 @@
-import videojs from 'video.js';
-
-/**
- * The TimelineChangeController acts as a source for segment loaders to listen for and
- * keep track of latest and pending timeline changes. This is useful to ensure proper
- * sync, as each loader may need to make a consideration for what timeline the other
- * loader is on before making changes which could impact the other loader's media.
- *
- * @class TimelineChangeController
- * @extends videojs.EventTarget
- */
-export default class TimelineChangeController extends videojs.EventTarget {
- constructor() {
- super();
-
- this.pendingTimelineChanges_ = {};
- this.lastTimelineChanges_ = {};
- }
-
- clearPendingTimelineChange(type) {
- this.pendingTimelineChanges_[type] = null;
- this.trigger('pendingtimelinechange');
- }
-
- pendingTimelineChange({ type, from, to }) {
- if (typeof from === 'number' && typeof to === 'number') {
- this.pendingTimelineChanges_[type] = { type, from, to };
- this.trigger('pendingtimelinechange');
- }
- return this.pendingTimelineChanges_[type];
- }
-
- lastTimelineChange({ type, from, to }) {
- if (typeof from === 'number' && typeof to === 'number') {
- this.lastTimelineChanges_[type] = { type, from, to };
- delete this.pendingTimelineChanges_[type];
- this.trigger('timelinechange');
- }
- return this.lastTimelineChanges_[type];
- }
-
- dispose() {
- this.trigger('dispose');
- this.pendingTimelineChanges_ = {};
- this.lastTimelineChanges_ = {};
- this.off();
- }
-}
diff --git a/node_modules/@videojs/http-streaming/src/transmuxer-worker.js b/node_modules/@videojs/http-streaming/src/transmuxer-worker.js
deleted file mode 100644
index 7d8e5d7..0000000
--- a/node_modules/@videojs/http-streaming/src/transmuxer-worker.js
+++ /dev/null
@@ -1,373 +0,0 @@
-/* global self */
-/**
- * @file transmuxer-worker.js
- */
-
-/**
- * videojs-contrib-media-sources
- *
- * Copyright (c) 2015 Brightcove
- * All rights reserved.
- *
- * Handles communication between the browser-world and the mux.js
- * transmuxer running inside of a WebWorker by exposing a simple
- * message-based interface to a Transmuxer object.
- */
-
-import {Transmuxer} from 'mux.js/lib/mp4/transmuxer';
-import CaptionParser from 'mux.js/lib/mp4/caption-parser';
-import mp4probe from 'mux.js/lib/mp4/probe';
-import tsInspector from 'mux.js/lib/tools/ts-inspector.js';
-import {
- ONE_SECOND_IN_TS,
- secondsToVideoTs,
- videoTsToSeconds
-} from 'mux.js/lib/utils/clock';
-
-/**
- * Re-emits transmuxer events by converting them into messages to the
- * world outside the worker.
- *
- * @param {Object} transmuxer the transmuxer to wire events on
- * @private
- */
-const wireTransmuxerEvents = function(self, transmuxer) {
- transmuxer.on('data', function(segment) {
- // transfer ownership of the underlying ArrayBuffer
- // instead of doing a copy to save memory
- // ArrayBuffers are transferable but generic TypedArrays are not
- // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
- const initArray = segment.initSegment;
-
- segment.initSegment = {
- data: initArray.buffer,
- byteOffset: initArray.byteOffset,
- byteLength: initArray.byteLength
- };
-
- const typedArray = segment.data;
-
- segment.data = typedArray.buffer;
- self.postMessage({
- action: 'data',
- segment,
- byteOffset: typedArray.byteOffset,
- byteLength: typedArray.byteLength
- }, [segment.data]);
- });
-
- transmuxer.on('done', function(data) {
- self.postMessage({ action: 'done' });
- });
-
- transmuxer.on('gopInfo', function(gopInfo) {
- self.postMessage({
- action: 'gopInfo',
- gopInfo
- });
- });
-
- transmuxer.on('videoSegmentTimingInfo', function(timingInfo) {
- const videoSegmentTimingInfo = {
- start: {
- decode: videoTsToSeconds(timingInfo.start.dts),
- presentation: videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: videoTsToSeconds(timingInfo.end.dts),
- presentation: videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- videoSegmentTimingInfo.prependedContentDuration = videoTsToSeconds(timingInfo.prependedContentDuration);
- }
- self.postMessage({
- action: 'videoSegmentTimingInfo',
- videoSegmentTimingInfo
- });
- });
-
- transmuxer.on('audioSegmentTimingInfo', function(timingInfo) {
- // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
- const audioSegmentTimingInfo = {
- start: {
- decode: videoTsToSeconds(timingInfo.start.dts),
- presentation: videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: videoTsToSeconds(timingInfo.end.dts),
- presentation: videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- audioSegmentTimingInfo.prependedContentDuration =
- videoTsToSeconds(timingInfo.prependedContentDuration);
- }
- self.postMessage({
- action: 'audioSegmentTimingInfo',
- audioSegmentTimingInfo
- });
- });
-
- transmuxer.on('id3Frame', function(id3Frame) {
- self.postMessage({
- action: 'id3Frame',
- id3Frame
- });
- });
-
- transmuxer.on('caption', function(caption) {
- self.postMessage({
- action: 'caption',
- caption
- });
- });
-
- transmuxer.on('trackinfo', function(trackInfo) {
- self.postMessage({
- action: 'trackinfo',
- trackInfo
- });
- });
-
- transmuxer.on('audioTimingInfo', function(audioTimingInfo) {
- // convert to video TS since we prioritize video time over audio
- self.postMessage({
- action: 'audioTimingInfo',
- audioTimingInfo: {
- start: videoTsToSeconds(audioTimingInfo.start),
- end: videoTsToSeconds(audioTimingInfo.end)
- }
- });
- });
-
- transmuxer.on('videoTimingInfo', function(videoTimingInfo) {
- self.postMessage({
- action: 'videoTimingInfo',
- videoTimingInfo: {
- start: videoTsToSeconds(videoTimingInfo.start),
- end: videoTsToSeconds(videoTimingInfo.end)
- }
- });
- });
-
-};
-
-/**
- * All incoming messages route through this hash. If no function exists
- * to handle an incoming message, then we ignore the message.
- *
- * @class MessageHandlers
- * @param {Object} options the options to initialize with
- */
-class MessageHandlers {
- constructor(self, options) {
- this.options = options || {};
- this.self = self;
- this.init();
- }
-
- /**
- * initialize our web worker and wire all the events.
- */
- init() {
- if (this.transmuxer) {
- this.transmuxer.dispose();
- }
- this.transmuxer = new Transmuxer(this.options);
-
- wireTransmuxerEvents(this.self, this.transmuxer);
- }
-
- pushMp4Captions(data) {
- if (!this.captionParser) {
- this.captionParser = new CaptionParser();
- this.captionParser.init();
- }
- const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- const parsed = this.captionParser.parse(
- segment,
- data.trackIds,
- data.timescales
- );
-
- this.self.postMessage({
- action: 'mp4Captions',
- captions: parsed && parsed.captions || [],
- data: segment.buffer
- }, [segment.buffer]);
- }
-
- probeMp4StartTime({timescales, data}) {
- const startTime = mp4probe.startTime(timescales, data);
-
- this.self.postMessage({
- action: 'probeMp4StartTime',
- startTime,
- data
- }, [data.buffer]);
- }
-
- probeMp4Tracks({data}) {
- const tracks = mp4probe.tracks(data);
-
- this.self.postMessage({
- action: 'probeMp4Tracks',
- tracks,
- data
- }, [data.buffer]);
- }
-
- /**
- * Probe an mpeg2-ts segment to determine the start time of the segment in it's
- * internal "media time," as well as whether it contains video and/or audio.
- *
- * @private
- * @param {Uint8Array} bytes - segment bytes
- * @param {number} baseStartTime
- * Relative reference timestamp used when adjusting frame timestamps for rollover.
- * This value should be in seconds, as it's converted to a 90khz clock within the
- * function body.
- * @return {Object} The start time of the current segment in "media time" as well as
- * whether it contains video and/or audio
- */
- probeTs({data, baseStartTime}) {
- const tsStartTime = (typeof baseStartTime === 'number' && !isNaN(baseStartTime)) ?
- (baseStartTime * ONE_SECOND_IN_TS) :
- void 0;
- const timeInfo = tsInspector.inspect(data, tsStartTime);
- let result = null;
-
- if (timeInfo) {
- result = {
- // each type's time info comes back as an array of 2 times, start and end
- hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
- hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
- };
-
- if (result.hasVideo) {
- result.videoStart = timeInfo.video[0].ptsTime;
- }
- if (result.hasAudio) {
- result.audioStart = timeInfo.audio[0].ptsTime;
- }
- }
-
- this.self.postMessage({
- action: 'probeTs',
- result,
- data
- }, [data.buffer]);
- }
-
- clearAllMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearAllCaptions();
- }
- }
-
- clearParsedMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearParsedCaptions();
- }
- }
-
- /**
- * Adds data (a ts segment) to the start of the transmuxer pipeline for
- * processing.
- *
- * @param {ArrayBuffer} data data to push into the muxer
- */
- push(data) {
- // Cast array buffer to correct type for transmuxer
- const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
-
- this.transmuxer.push(segment);
- }
-
- /**
- * Recreate the transmuxer so that the next segment added via `push`
- * start with a fresh transmuxer.
- */
- reset() {
- this.transmuxer.reset();
- }
-
- /**
- * Set the value that will be used as the `baseMediaDecodeTime` time for the
- * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
- * set relative to the first based on the PTS values.
- *
- * @param {Object} data used to set the timestamp offset in the muxer
- */
- setTimestampOffset(data) {
- const timestampOffset = data.timestampOffset || 0;
-
- this.transmuxer.setBaseMediaDecodeTime(Math.round(secondsToVideoTs(timestampOffset)));
- }
-
- setAudioAppendStart(data) {
- this.transmuxer.setAudioAppendStart(Math.ceil(secondsToVideoTs(data.appendStart)));
- }
-
- setRemux(data) {
- this.transmuxer.setRemux(data.remux);
- }
-
- /**
- * Forces the pipeline to finish processing the last segment and emit it's
- * results.
- *
- * @param {Object} data event data, not really used
- */
- flush(data) {
- this.transmuxer.flush();
- // transmuxed done action is fired after both audio/video pipelines are flushed
- self.postMessage({
- action: 'done',
- type: 'transmuxed'
- });
- }
-
- endTimeline() {
- this.transmuxer.endTimeline();
- // transmuxed endedtimeline action is fired after both audio/video pipelines end their
- // timelines
- self.postMessage({
- action: 'endedtimeline',
- type: 'transmuxed'
- });
- }
-
- alignGopsWith(data) {
- this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
- }
-}
-
-/**
- * Our web worker interface so that things can talk to mux.js
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- *
- * @param {Object} self the scope for the web worker
- */
-self.onmessage = function(event) {
- if (event.data.action === 'init' && event.data.options) {
- this.messageHandlers = new MessageHandlers(self, event.data.options);
- return;
- }
-
- if (!this.messageHandlers) {
- this.messageHandlers = new MessageHandlers(self);
- }
-
- if (event.data && event.data.action && event.data.action !== 'init') {
- if (this.messageHandlers[event.data.action]) {
- this.messageHandlers[event.data.action](event.data);
- }
- }
-};
diff --git a/node_modules/@videojs/http-streaming/src/transmuxer-worker.worker.js b/node_modules/@videojs/http-streaming/src/transmuxer-worker.worker.js
deleted file mode 100644
index 7533060..0000000
--- a/node_modules/@videojs/http-streaming/src/transmuxer-worker.worker.js
+++ /dev/null
@@ -1,8110 +0,0 @@
-/*! @name @videojs/http-streaming @version 2.5.0 @license Apache-2.0 */
-var transmuxerWorker = (function () {
- 'use strict';
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * A lightweight readable stream implemention that handles event dispatching.
- * Objects that inherit from streams should call init in their constructors.
- */
-
- var Stream = function Stream() {
- this.init = function () {
- var listeners = {};
- /**
- * Add a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} the callback to be invoked when an event of
- * the specified type occurs
- */
-
- this.on = function (type, listener) {
- if (!listeners[type]) {
- listeners[type] = [];
- }
-
- listeners[type] = listeners[type].concat(listener);
- };
- /**
- * Remove a listener for a specified event type.
- * @param type {string} the event name
- * @param listener {function} a function previously registered for this
- * type of event through `on`
- */
-
-
- this.off = function (type, listener) {
- var index;
-
- if (!listeners[type]) {
- return false;
- }
-
- index = listeners[type].indexOf(listener);
- listeners[type] = listeners[type].slice();
- listeners[type].splice(index, 1);
- return index > -1;
- };
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- * @param type {string} the event name
- */
-
-
- this.trigger = function (type) {
- var callbacks, i, length, args;
- callbacks = listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- args = [];
- i = arguments.length;
-
- for (i = 1; i < arguments.length; ++i) {
- args.push(arguments[i]);
- }
-
- length = callbacks.length;
-
- for (i = 0; i < length; ++i) {
- callbacks[i].apply(this, args);
- }
- }
- };
- /**
- * Destroys the stream and cleans up.
- */
-
-
- this.dispose = function () {
- listeners = {};
- };
- };
- };
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- * @param destination {stream} the stream that will receive all `data` events
- * @param autoFlush {boolean} if false, we will not call `flush` on the destination
- * when the current stream emits a 'done' event
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
-
-
- Stream.prototype.pipe = function (destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- this.on('done', function (flushSource) {
- destination.flush(flushSource);
- });
- this.on('partialdone', function (flushSource) {
- destination.partialFlush(flushSource);
- });
- this.on('endedtimeline', function (flushSource) {
- destination.endTimeline(flushSource);
- });
- this.on('reset', function (flushSource) {
- destination.reset(flushSource);
- });
- return destination;
- }; // Default stream functions that are expected to be overridden to perform
- // actual work. These are provided by the prototype as a sort of no-op
- // implementation so that we don't have to check for their existence in the
- // `pipe` function above.
-
-
- Stream.prototype.push = function (data) {
- this.trigger('data', data);
- };
-
- Stream.prototype.flush = function (flushSource) {
- this.trigger('done', flushSource);
- };
-
- Stream.prototype.partialFlush = function (flushSource) {
- this.trigger('partialdone', flushSource);
- };
-
- Stream.prototype.endTimeline = function (flushSource) {
- this.trigger('endedtimeline', flushSource);
- };
-
- Stream.prototype.reset = function (flushSource) {
- this.trigger('reset', flushSource);
- };
-
- var stream = Stream;
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Functions that generate fragmented MP4s suitable for use with Media
- * Source Extensions.
- */
-
- var UINT32_MAX = Math.pow(2, 32) - 1;
- var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants
-
- (function () {
- var i;
- types = {
- avc1: [],
- // codingname
- avcC: [],
- btrt: [],
- dinf: [],
- dref: [],
- esds: [],
- ftyp: [],
- hdlr: [],
- mdat: [],
- mdhd: [],
- mdia: [],
- mfhd: [],
- minf: [],
- moof: [],
- moov: [],
- mp4a: [],
- // codingname
- mvex: [],
- mvhd: [],
- pasp: [],
- sdtp: [],
- smhd: [],
- stbl: [],
- stco: [],
- stsc: [],
- stsd: [],
- stsz: [],
- stts: [],
- styp: [],
- tfdt: [],
- tfhd: [],
- traf: [],
- trak: [],
- trun: [],
- trex: [],
- tkhd: [],
- vmhd: []
- }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
- // don't throw an error
-
- if (typeof Uint8Array === 'undefined') {
- return;
- }
-
- for (i in types) {
- if (types.hasOwnProperty(i)) {
- types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
- }
- }
-
- MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
- AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
- MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
- VIDEO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
- ]);
- AUDIO_HDLR = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
- ]);
- HDLR_TYPES = {
- video: VIDEO_HDLR,
- audio: AUDIO_HDLR
- };
- DREF = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // entry_count
- 0x00, 0x00, 0x00, 0x0c, // entry_size
- 0x75, 0x72, 0x6c, 0x20, // 'url' type
- 0x00, // version 0
- 0x00, 0x00, 0x01 // entry_flags
- ]);
- SMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, // balance, 0 means centered
- 0x00, 0x00 // reserved
- ]);
- STCO = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00 // entry_count
- ]);
- STSC = STCO;
- STSZ = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x00, // sample_size
- 0x00, 0x00, 0x00, 0x00 // sample_count
- ]);
- STTS = STCO;
- VMHD = new Uint8Array([0x00, // version
- 0x00, 0x00, 0x01, // flags
- 0x00, 0x00, // graphicsmode
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
- ]);
- })();
-
- box = function box(type) {
- var payload = [],
- size = 0,
- i,
- result,
- view;
-
- for (i = 1; i < arguments.length; i++) {
- payload.push(arguments[i]);
- }
-
- i = payload.length; // calculate the total size we need to allocate
-
- while (i--) {
- size += payload[i].byteLength;
- }
-
- result = new Uint8Array(size + 8);
- view = new DataView(result.buffer, result.byteOffset, result.byteLength);
- view.setUint32(0, result.byteLength);
- result.set(type, 4); // copy the payload into the result
-
- for (i = 0, size = 8; i < payload.length; i++) {
- result.set(payload[i], size);
- size += payload[i].byteLength;
- }
-
- return result;
- };
-
- dinf = function dinf() {
- return box(types.dinf, box(types.dref, DREF));
- };
-
- esds = function esds(track) {
- return box(types.esds, new Uint8Array([0x00, // version
- 0x00, 0x00, 0x00, // flags
- // ES_Descriptor
- 0x03, // tag, ES_DescrTag
- 0x19, // length
- 0x00, 0x00, // ES_ID
- 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
- // DecoderConfigDescriptor
- 0x04, // tag, DecoderConfigDescrTag
- 0x11, // length
- 0x40, // object type
- 0x15, // streamType
- 0x00, 0x06, 0x00, // bufferSizeDB
- 0x00, 0x00, 0xda, 0xc0, // maxBitrate
- 0x00, 0x00, 0xda, 0xc0, // avgBitrate
- // DecoderSpecificInfo
- 0x05, // tag, DecoderSpecificInfoTag
- 0x02, // length
- // ISO/IEC 14496-3, AudioSpecificConfig
- // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
- track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
- ]));
- };
-
- ftyp = function ftyp() {
- return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
- };
-
- hdlr = function hdlr(type) {
- return box(types.hdlr, HDLR_TYPES[type]);
- };
-
- mdat = function mdat(data) {
- return box(types.mdat, data);
- };
-
- mdhd = function mdhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x02, // creation_time
- 0x00, 0x00, 0x00, 0x03, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
- 0x55, 0xc4, // 'und' language (undetermined)
- 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
- // defined. The sample rate can be parsed out of an ADTS header, for
- // instance.
-
- if (track.samplerate) {
- result[12] = track.samplerate >>> 24 & 0xFF;
- result[13] = track.samplerate >>> 16 & 0xFF;
- result[14] = track.samplerate >>> 8 & 0xFF;
- result[15] = track.samplerate & 0xFF;
- }
-
- return box(types.mdhd, result);
- };
-
- mdia = function mdia(track) {
- return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
- };
-
- mfhd = function mfhd(sequenceNumber) {
- return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
- (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
- ]));
- };
-
- minf = function minf(track) {
- return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
- };
-
- moof = function moof(sequenceNumber, tracks) {
- var trackFragments = [],
- i = tracks.length; // build traf boxes for each track fragment
-
- while (i--) {
- trackFragments[i] = traf(tracks[i]);
- }
-
- return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
- };
- /**
- * Returns a movie box.
- * @param tracks {array} the tracks associated with this movie
- * @see ISO/IEC 14496-12:2012(E), section 8.2.1
- */
-
-
- moov = function moov(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trak(tracks[i]);
- }
-
- return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
- };
-
- mvex = function mvex(tracks) {
- var i = tracks.length,
- boxes = [];
-
- while (i--) {
- boxes[i] = trex(tracks[i]);
- }
-
- return box.apply(null, [types.mvex].concat(boxes));
- };
-
- mvhd = function mvhd(duration) {
- var bytes = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01, // creation_time
- 0x00, 0x00, 0x00, 0x02, // modification_time
- 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
- (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
- 0x00, 0x01, 0x00, 0x00, // 1.0 rate
- 0x01, 0x00, // 1.0 volume
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- 0xff, 0xff, 0xff, 0xff // next_track_ID
- ]);
- return box(types.mvhd, bytes);
- };
-
- sdtp = function sdtp(track) {
- var samples = track.samples || [],
- bytes = new Uint8Array(4 + samples.length),
- flags,
- i; // leave the full box header (4 bytes) all zero
- // write the sample table
-
- for (i = 0; i < samples.length; i++) {
- flags = samples[i].flags;
- bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
- }
-
- return box(types.sdtp, bytes);
- };
-
- stbl = function stbl(track) {
- return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
- };
-
- (function () {
- var videoSample, audioSample;
-
- stsd = function stsd(track) {
- return box(types.stsd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
- };
-
- videoSample = function videoSample(track) {
- var sps = track.sps || [],
- pps = track.pps || [],
- sequenceParameterSets = [],
- pictureParameterSets = [],
- i,
- avc1Box; // assemble the SPSs
-
- for (i = 0; i < sps.length; i++) {
- sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
- sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
-
- sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
- } // assemble the PPSs
-
-
- for (i = 0; i < pps.length; i++) {
- pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
- pictureParameterSets.push(pps[i].byteLength & 0xFF);
- pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
- }
-
- avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
- (track.width & 0xff00) >> 8, track.width & 0xff, // width
- (track.height & 0xff00) >> 8, track.height & 0xff, // height
- 0x00, 0x48, 0x00, 0x00, // horizresolution
- 0x00, 0x48, 0x00, 0x00, // vertresolution
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // frame_count
- 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
- 0x00, 0x18, // depth = 24
- 0x11, 0x11 // pre_defined = -1
- ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
- track.profileIdc, // AVCProfileIndication
- track.profileCompatibility, // profile_compatibility
- track.levelIdc, // AVCLevelIndication
- 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
- ].concat([sps.length], // numOfSequenceParameterSets
- sequenceParameterSets, // "SPS"
- [pps.length], // numOfPictureParameterSets
- pictureParameterSets // "PPS"
- ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
- 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
- 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
- ]))];
-
- if (track.sarRatio) {
- var hSpacing = track.sarRatio[0],
- vSpacing = track.sarRatio[1];
- avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 0xFF000000) >> 24, (hSpacing & 0xFF0000) >> 16, (hSpacing & 0xFF00) >> 8, hSpacing & 0xFF, (vSpacing & 0xFF000000) >> 24, (vSpacing & 0xFF0000) >> 16, (vSpacing & 0xFF00) >> 8, vSpacing & 0xFF])));
- }
-
- return box.apply(null, avc1Box);
- };
-
- audioSample = function audioSample(track) {
- return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x01, // data_reference_index
- // AudioSampleEntry, ISO/IEC 14496-12
- 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
- (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
- 0x00, 0x00, // pre_defined
- 0x00, 0x00, // reserved
- (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
- // MP4AudioSampleEntry, ISO/IEC 14496-14
- ]), esds(track));
- };
- })();
-
- tkhd = function tkhd(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x07, // flags
- 0x00, 0x00, 0x00, 0x00, // creation_time
- 0x00, 0x00, 0x00, 0x00, // modification_time
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x00, // reserved
- (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
- 0x00, 0x00, // layer
- 0x00, 0x00, // alternate_group
- 0x01, 0x00, // non-audio track volume
- 0x00, 0x00, // reserved
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
- (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
- (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
- ]);
- return box(types.tkhd, result);
- };
- /**
- * Generate a track fragment (traf) box. A traf box collects metadata
- * about tracks in a movie fragment (moof) box.
- */
-
-
- traf = function traf(track) {
- var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
- trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x3a, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x00, 0x00, 0x00 // default_sample_flags
- ]));
- upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
- lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));
- trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
- 0x00, 0x00, 0x00, // flags
- // baseMediaDecodeTime
- upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])); // the data offset specifies the number of bytes from the start of
- // the containing moof to the first payload byte of the associated
- // mdat
-
- dataOffset = 32 + // tfhd
- 20 + // tfdt
- 8 + // traf header
- 16 + // mfhd
- 8 + // moof header
- 8; // mdat header
- // audio tracks require less metadata
-
- if (track.type === 'audio') {
- trackFragmentRun = trun(track, dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
- } // video tracks should contain an independent and disposable samples
- // box (sdtp)
- // generate one and adjust offsets to match
-
-
- sampleDependencyTable = sdtp(track);
- trackFragmentRun = trun(track, sampleDependencyTable.length + dataOffset);
- return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
- };
- /**
- * Generate a track box.
- * @param track {object} a track definition
- * @return {Uint8Array} the track box
- */
-
-
- trak = function trak(track) {
- track.duration = track.duration || 0xffffffff;
- return box(types.trak, tkhd(track), mdia(track));
- };
-
- trex = function trex(track) {
- var result = new Uint8Array([0x00, // version 0
- 0x00, 0x00, 0x00, // flags
- (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
- 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
- 0x00, 0x01, 0x00, 0x01 // default_sample_flags
- ]); // the last two bytes of default_sample_flags is the sample
- // degradation priority, a hint about the importance of this sample
- // relative to others. Lower the degradation priority for all sample
- // types other than video.
-
- if (track.type !== 'video') {
- result[result.length - 1] = 0x00;
- }
-
- return box(types.trex, result);
- };
-
- (function () {
- var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
- // duration is present for the first sample, it will be present for
- // all subsequent samples.
- // see ISO/IEC 14496-12:2012, Section 8.8.8.1
-
- trunHeader = function trunHeader(samples, offset) {
- var durationPresent = 0,
- sizePresent = 0,
- flagsPresent = 0,
- compositionTimeOffset = 0; // trun flag constants
-
- if (samples.length) {
- if (samples[0].duration !== undefined) {
- durationPresent = 0x1;
- }
-
- if (samples[0].size !== undefined) {
- sizePresent = 0x2;
- }
-
- if (samples[0].flags !== undefined) {
- flagsPresent = 0x4;
- }
-
- if (samples[0].compositionTimeOffset !== undefined) {
- compositionTimeOffset = 0x8;
- }
- }
-
- return [0x00, // version 0
- 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
- (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
- (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
- ];
- };
-
- videoTrun = function videoTrun(track, offset) {
- var bytesOffest, bytes, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 16 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 16);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
-
- bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
- bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
- bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
-
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
- }
-
- return box(types.trun, bytes);
- };
-
- audioTrun = function audioTrun(track, offset) {
- var bytes, bytesOffest, header, samples, sample, i;
- samples = track.samples || [];
- offset += 8 + 12 + 8 * samples.length;
- header = trunHeader(samples, offset);
- bytes = new Uint8Array(header.length + samples.length * 8);
- bytes.set(header);
- bytesOffest = header.length;
-
- for (i = 0; i < samples.length; i++) {
- sample = samples[i];
- bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
-
- bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
- bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
- bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
- bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
- }
-
- return box(types.trun, bytes);
- };
-
- trun = function trun(track, offset) {
- if (track.type === 'audio') {
- return audioTrun(track, offset);
- }
-
- return videoTrun(track, offset);
- };
- })();
-
- var mp4Generator = {
- ftyp: ftyp,
- mdat: mdat,
- moof: moof,
- moov: moov,
- initSegment: function initSegment(tracks) {
- var fileType = ftyp(),
- movie = moov(tracks),
- result;
- result = new Uint8Array(fileType.byteLength + movie.byteLength);
- result.set(fileType);
- result.set(movie, fileType.byteLength);
- return result;
- }
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- // Convert an array of nal units into an array of frames with each frame being
- // composed of the nal units that make up that frame
- // Also keep track of cummulative data about the frame from the nal units such
- // as the frame duration, starting pts, etc.
- var groupNalsIntoFrames = function groupNalsIntoFrames(nalUnits) {
- var i,
- currentNal,
- currentFrame = [],
- frames = []; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength = 0;
- frames.nalCount = 0;
- frames.duration = 0;
- currentFrame.byteLength = 0;
-
- for (i = 0; i < nalUnits.length; i++) {
- currentNal = nalUnits[i]; // Split on 'aud'-type nal units
-
- if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
- // Since the very first nal unit is expected to be an AUD
- // only push to the frames array when currentFrame is not empty
- if (currentFrame.length) {
- currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- }
-
- currentFrame = [currentNal];
- currentFrame.byteLength = currentNal.data.byteLength;
- currentFrame.pts = currentNal.pts;
- currentFrame.dts = currentNal.dts;
- } else {
- // Specifically flag key frames for ease of use later
- if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
- currentFrame.keyFrame = true;
- }
-
- currentFrame.duration = currentNal.dts - currentFrame.dts;
- currentFrame.byteLength += currentNal.data.byteLength;
- currentFrame.push(currentNal);
- }
- } // For the last frame, use the duration of the previous frame if we
- // have nothing better to go on
-
-
- if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
- currentFrame.duration = frames[frames.length - 1].duration;
- } // Push the final frame
- // TODO added for LHLS, make sure this is OK
-
-
- frames.byteLength += currentFrame.byteLength;
- frames.nalCount += currentFrame.length;
- frames.duration += currentFrame.duration;
- frames.push(currentFrame);
- return frames;
- }; // Convert an array of frames into an array of Gop with each Gop being composed
- // of the frames that make up that Gop
- // Also keep track of cummulative data about the Gop from the frames such as the
- // Gop duration, starting pts, etc.
-
-
- var groupFramesIntoGops = function groupFramesIntoGops(frames) {
- var i,
- currentFrame,
- currentGop = [],
- gops = []; // We must pre-set some of the values on the Gop since we
- // keep running totals of these values
-
- currentGop.byteLength = 0;
- currentGop.nalCount = 0;
- currentGop.duration = 0;
- currentGop.pts = frames[0].pts;
- currentGop.dts = frames[0].dts; // store some metadata about all the Gops
-
- gops.byteLength = 0;
- gops.nalCount = 0;
- gops.duration = 0;
- gops.pts = frames[0].pts;
- gops.dts = frames[0].dts;
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
-
- if (currentFrame.keyFrame) {
- // Since the very first frame is expected to be an keyframe
- // only push to the gops array when currentGop is not empty
- if (currentGop.length) {
- gops.push(currentGop);
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration;
- }
-
- currentGop = [currentFrame];
- currentGop.nalCount = currentFrame.length;
- currentGop.byteLength = currentFrame.byteLength;
- currentGop.pts = currentFrame.pts;
- currentGop.dts = currentFrame.dts;
- currentGop.duration = currentFrame.duration;
- } else {
- currentGop.duration += currentFrame.duration;
- currentGop.nalCount += currentFrame.length;
- currentGop.byteLength += currentFrame.byteLength;
- currentGop.push(currentFrame);
- }
- }
-
- if (gops.length && currentGop.duration <= 0) {
- currentGop.duration = gops[gops.length - 1].duration;
- }
-
- gops.byteLength += currentGop.byteLength;
- gops.nalCount += currentGop.nalCount;
- gops.duration += currentGop.duration; // push the final Gop
-
- gops.push(currentGop);
- return gops;
- };
- /*
- * Search for the first keyframe in the GOPs and throw away all frames
- * until that keyframe. Then extend the duration of the pulled keyframe
- * and pull the PTS and DTS of the keyframe so that it covers the time
- * range of the frames that were disposed.
- *
- * @param {Array} gops video GOPs
- * @returns {Array} modified video GOPs
- */
-
-
- var extendFirstKeyFrame = function extendFirstKeyFrame(gops) {
- var currentGop;
-
- if (!gops[0][0].keyFrame && gops.length > 1) {
- // Remove the first GOP
- currentGop = gops.shift();
- gops.byteLength -= currentGop.byteLength;
- gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
- // first gop to cover the time period of the
- // frames we just removed
-
- gops[0][0].dts = currentGop.dts;
- gops[0][0].pts = currentGop.pts;
- gops[0][0].duration += currentGop.duration;
- }
-
- return gops;
- };
- /**
- * Default sample object
- * see ISO/IEC 14496-12:2012, section 8.6.4.3
- */
-
-
- var createDefaultSample = function createDefaultSample() {
- return {
- size: 0,
- flags: {
- isLeading: 0,
- dependsOn: 1,
- isDependedOn: 0,
- hasRedundancy: 0,
- degradationPriority: 0,
- isNonSyncSample: 1
- }
- };
- };
- /*
- * Collates information from a video frame into an object for eventual
- * entry into an MP4 sample table.
- *
- * @param {Object} frame the video frame
- * @param {Number} dataOffset the byte offset to position the sample
- * @return {Object} object containing sample table info for a frame
- */
-
-
- var sampleForFrame = function sampleForFrame(frame, dataOffset) {
- var sample = createDefaultSample();
- sample.dataOffset = dataOffset;
- sample.compositionTimeOffset = frame.pts - frame.dts;
- sample.duration = frame.duration;
- sample.size = 4 * frame.length; // Space for nal unit size
-
- sample.size += frame.byteLength;
-
- if (frame.keyFrame) {
- sample.flags.dependsOn = 2;
- sample.flags.isNonSyncSample = 0;
- }
-
- return sample;
- }; // generate the track's sample table from an array of gops
-
-
- var generateSampleTable = function generateSampleTable(gops, baseDataOffset) {
- var h,
- i,
- sample,
- currentGop,
- currentFrame,
- dataOffset = baseDataOffset || 0,
- samples = [];
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h];
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i];
- sample = sampleForFrame(currentFrame, dataOffset);
- dataOffset += sample.size;
- samples.push(sample);
- }
- }
-
- return samples;
- }; // generate the track's raw mdat data from an array of gops
-
-
- var concatenateNalData = function concatenateNalData(gops) {
- var h,
- i,
- j,
- currentGop,
- currentFrame,
- currentNal,
- dataOffset = 0,
- nalsByteLength = gops.byteLength,
- numberOfNals = gops.nalCount,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each Gop..
-
- for (h = 0; h < gops.length; h++) {
- currentGop = gops[h]; // For each Frame..
-
- for (i = 0; i < currentGop.length; i++) {
- currentFrame = currentGop[i]; // For each NAL..
-
- for (j = 0; j < currentFrame.length; j++) {
- currentNal = currentFrame[j];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
- }
- }
-
- return data;
- }; // generate the track's sample table from a frame
-
-
- var generateSampleTableForFrame = function generateSampleTableForFrame(frame, baseDataOffset) {
- var sample,
- dataOffset = baseDataOffset || 0,
- samples = [];
- sample = sampleForFrame(frame, dataOffset);
- samples.push(sample);
- return samples;
- }; // generate the track's raw mdat data from a frame
-
-
- var concatenateNalDataForFrame = function concatenateNalDataForFrame(frame) {
- var i,
- currentNal,
- dataOffset = 0,
- nalsByteLength = frame.byteLength,
- numberOfNals = frame.length,
- totalByteLength = nalsByteLength + 4 * numberOfNals,
- data = new Uint8Array(totalByteLength),
- view = new DataView(data.buffer); // For each NAL..
-
- for (i = 0; i < frame.length; i++) {
- currentNal = frame[i];
- view.setUint32(dataOffset, currentNal.data.byteLength);
- dataOffset += 4;
- data.set(currentNal.data, dataOffset);
- dataOffset += currentNal.data.byteLength;
- }
-
- return data;
- };
-
- var frameUtils = {
- groupNalsIntoFrames: groupNalsIntoFrames,
- groupFramesIntoGops: groupFramesIntoGops,
- extendFirstKeyFrame: extendFirstKeyFrame,
- generateSampleTable: generateSampleTable,
- concatenateNalData: concatenateNalData,
- generateSampleTableForFrame: generateSampleTableForFrame,
- concatenateNalDataForFrame: concatenateNalDataForFrame
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- var highPrefix = [33, 16, 5, 32, 164, 27];
- var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
-
- var zeroFill = function zeroFill(count) {
- var a = [];
-
- while (count--) {
- a.push(0);
- }
-
- return a;
- };
-
- var makeTable = function makeTable(metaTable) {
- return Object.keys(metaTable).reduce(function (obj, key) {
- obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
- return arr.concat(part);
- }, []));
- return obj;
- }, {});
- };
-
- var silence;
-
- var silence_1 = function silence_1() {
- if (!silence) {
- // Frames-of-silence to use for filling in missing AAC frames
- var coneOfSilence = {
- 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
- 88200: [highPrefix, [231], zeroFill(170), [56]],
- 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
- 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
- 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
- 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
- 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
- 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
- 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
- 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
- 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
- };
- silence = makeTable(coneOfSilence);
- }
-
- return silence;
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- var ONE_SECOND_IN_TS = 90000,
- // 90kHz clock
- secondsToVideoTs,
- secondsToAudioTs,
- videoTsToSeconds,
- audioTsToSeconds,
- audioTsToVideoTs,
- videoTsToAudioTs,
- metadataTsToSeconds;
-
- secondsToVideoTs = function secondsToVideoTs(seconds) {
- return seconds * ONE_SECOND_IN_TS;
- };
-
- secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
- return seconds * sampleRate;
- };
-
- videoTsToSeconds = function videoTsToSeconds(timestamp) {
- return timestamp / ONE_SECOND_IN_TS;
- };
-
- audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
- return timestamp / sampleRate;
- };
-
- audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
- return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
- };
-
- videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
- return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
- };
- /**
- * Adjust ID3 tag or caption timing information by the timeline pts values
- * (if keepOriginalTimestamps is false) and convert to seconds
- */
-
-
- metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
- return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
- };
-
- var clock = {
- ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
- secondsToVideoTs: secondsToVideoTs,
- secondsToAudioTs: secondsToAudioTs,
- videoTsToSeconds: videoTsToSeconds,
- audioTsToSeconds: audioTsToSeconds,
- audioTsToVideoTs: audioTsToVideoTs,
- videoTsToAudioTs: videoTsToAudioTs,
- metadataTsToSeconds: metadataTsToSeconds
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- /**
- * Sum the `byteLength` properties of the data in each AAC frame
- */
-
- var sumFrameByteLengths = function sumFrameByteLengths(array) {
- var i,
- currentObj,
- sum = 0; // sum the byteLength's all each nal unit in the frame
-
- for (i = 0; i < array.length; i++) {
- currentObj = array[i];
- sum += currentObj.data.byteLength;
- }
-
- return sum;
- }; // Possibly pad (prefix) the audio track with silence if appending this track
- // would lead to the introduction of a gap in the audio buffer
-
-
- var prefixWithSilence = function prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
- var baseMediaDecodeTimeTs,
- frameDuration = 0,
- audioGapDuration = 0,
- audioFillFrameCount = 0,
- audioFillDuration = 0,
- silentFrame,
- i,
- firstFrame;
-
- if (!frames.length) {
- return;
- }
-
- baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
-
- frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
-
- if (audioAppendStartTs && videoBaseMediaDecodeTime) {
- // insert the shortest possible amount (audio gap or audio to video gap)
- audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
-
- audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
- audioFillDuration = audioFillFrameCount * frameDuration;
- } // don't attempt to fill gaps smaller than a single frame or larger
- // than a half second
-
-
- if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
- return;
- }
-
- silentFrame = silence_1()[track.samplerate];
-
- if (!silentFrame) {
- // we don't have a silent frame pregenerated for the sample rate, so use a frame
- // from the content instead
- silentFrame = frames[0].data;
- }
-
- for (i = 0; i < audioFillFrameCount; i++) {
- firstFrame = frames[0];
- frames.splice(0, 0, {
- data: silentFrame,
- dts: firstFrame.dts - frameDuration,
- pts: firstFrame.pts - frameDuration
- });
- }
-
- track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
- return audioFillDuration;
- }; // If the audio segment extends before the earliest allowed dts
- // value, remove AAC frames until starts at or after the earliest
- // allowed DTS so that we don't end up with a negative baseMedia-
- // DecodeTime for the audio track
-
-
- var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts) {
- if (track.minSegmentDts >= earliestAllowedDts) {
- return adtsFrames;
- } // We will need to recalculate the earliest segment Dts
-
-
- track.minSegmentDts = Infinity;
- return adtsFrames.filter(function (currentFrame) {
- // If this is an allowed frame, keep it and record it's Dts
- if (currentFrame.dts >= earliestAllowedDts) {
- track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
- track.minSegmentPts = track.minSegmentDts;
- return true;
- } // Otherwise, discard it
-
-
- return false;
- });
- }; // generate the track's raw mdat data from an array of frames
-
-
- var generateSampleTable$1 = function generateSampleTable(frames) {
- var i,
- currentFrame,
- samples = [];
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- samples.push({
- size: currentFrame.data.byteLength,
- duration: 1024 // For AAC audio, all samples contain 1024 samples
-
- });
- }
-
- return samples;
- }; // generate the track's sample table from an array of frames
-
-
- var concatenateFrameData = function concatenateFrameData(frames) {
- var i,
- currentFrame,
- dataOffset = 0,
- data = new Uint8Array(sumFrameByteLengths(frames));
-
- for (i = 0; i < frames.length; i++) {
- currentFrame = frames[i];
- data.set(currentFrame.data, dataOffset);
- dataOffset += currentFrame.data.byteLength;
- }
-
- return data;
- };
-
- var audioFrameUtils = {
- prefixWithSilence: prefixWithSilence,
- trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
- generateSampleTable: generateSampleTable$1,
- concatenateFrameData: concatenateFrameData
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS;
- /**
- * Store information about the start and end of the track and the
- * duration for each frame/sample we process in order to calculate
- * the baseMediaDecodeTime
- */
-
- var collectDtsInfo = function collectDtsInfo(track, data) {
- if (typeof data.pts === 'number') {
- if (track.timelineStartInfo.pts === undefined) {
- track.timelineStartInfo.pts = data.pts;
- }
-
- if (track.minSegmentPts === undefined) {
- track.minSegmentPts = data.pts;
- } else {
- track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
- }
-
- if (track.maxSegmentPts === undefined) {
- track.maxSegmentPts = data.pts;
- } else {
- track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
- }
- }
-
- if (typeof data.dts === 'number') {
- if (track.timelineStartInfo.dts === undefined) {
- track.timelineStartInfo.dts = data.dts;
- }
-
- if (track.minSegmentDts === undefined) {
- track.minSegmentDts = data.dts;
- } else {
- track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
- }
-
- if (track.maxSegmentDts === undefined) {
- track.maxSegmentDts = data.dts;
- } else {
- track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
- }
- }
- };
- /**
- * Clear values used to calculate the baseMediaDecodeTime between
- * tracks
- */
-
-
- var clearDtsInfo = function clearDtsInfo(track) {
- delete track.minSegmentDts;
- delete track.maxSegmentDts;
- delete track.minSegmentPts;
- delete track.maxSegmentPts;
- };
- /**
- * Calculate the track's baseMediaDecodeTime based on the earliest
- * DTS the transmuxer has ever seen and the minimum DTS for the
- * current track
- * @param track {object} track metadata configuration
- * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime(track, keepOriginalTimestamps) {
- var baseMediaDecodeTime,
- scale,
- minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
-
- if (!keepOriginalTimestamps) {
- minSegmentDts -= track.timelineStartInfo.dts;
- } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
- // we want the start of the first segment to be placed
-
-
- baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
-
- baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
-
- baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
-
- if (track.type === 'audio') {
- // Audio has a different clock equal to the sampling_rate so we need to
- // scale the PTS values into the clock rate of the track
- scale = track.samplerate / ONE_SECOND_IN_TS$1;
- baseMediaDecodeTime *= scale;
- baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
- }
-
- return baseMediaDecodeTime;
- };
-
- var trackDecodeInfo = {
- clearDtsInfo: clearDtsInfo,
- calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
- collectDtsInfo: collectDtsInfo
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Reads in-band caption information from a video elementary
- * stream. Captions must follow the CEA-708 standard for injection
- * into an MPEG-2 transport streams.
- * @see https://en.wikipedia.org/wiki/CEA-708
- * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
- */
- // payload type field to indicate how they are to be
- // interpreted. CEAS-708 caption content is always transmitted with
- // payload type 0x04.
-
- var USER_DATA_REGISTERED_ITU_T_T35 = 4,
- RBSP_TRAILING_BITS = 128;
- /**
- * Parse a supplemental enhancement information (SEI) NAL unit.
- * Stops parsing once a message of type ITU T T35 has been found.
- *
- * @param bytes {Uint8Array} the bytes of a SEI NAL unit
- * @return {object} the parsed SEI payload
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- */
-
- var parseSei = function parseSei(bytes) {
- var i = 0,
- result = {
- payloadType: -1,
- payloadSize: 0
- },
- payloadType = 0,
- payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
-
- while (i < bytes.byteLength) {
- // stop once we have hit the end of the sei_rbsp
- if (bytes[i] === RBSP_TRAILING_BITS) {
- break;
- } // Parse payload type
-
-
- while (bytes[i] === 0xFF) {
- payloadType += 255;
- i++;
- }
-
- payloadType += bytes[i++]; // Parse payload size
-
- while (bytes[i] === 0xFF) {
- payloadSize += 255;
- i++;
- }
-
- payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
- // there can only ever be one caption message in a frame's sei
-
- if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
- var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
-
- if (userIdentifier === 'GA94') {
- result.payloadType = payloadType;
- result.payloadSize = payloadSize;
- result.payload = bytes.subarray(i, i + payloadSize);
- break;
- } else {
- result.payload = void 0;
- }
- } // skip the payload and parse the next message
-
-
- i += payloadSize;
- payloadType = 0;
- payloadSize = 0;
- }
-
- return result;
- }; // see ANSI/SCTE 128-1 (2013), section 8.1
-
-
- var parseUserData = function parseUserData(sei) {
- // itu_t_t35_contry_code must be 181 (United States) for
- // captions
- if (sei.payload[0] !== 181) {
- return null;
- } // itu_t_t35_provider_code should be 49 (ATSC) for captions
-
-
- if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
- return null;
- } // the user_identifier should be "GA94" to indicate ATSC1 data
-
-
- if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
- return null;
- } // finally, user_data_type_code should be 0x03 for caption data
-
-
- if (sei.payload[7] !== 0x03) {
- return null;
- } // return the user_data_type_structure and strip the trailing
- // marker bits
-
-
- return sei.payload.subarray(8, sei.payload.length - 1);
- }; // see CEA-708-D, section 4.4
-
-
- var parseCaptionPackets = function parseCaptionPackets(pts, userData) {
- var results = [],
- i,
- count,
- offset,
- data; // if this is just filler, return immediately
-
- if (!(userData[0] & 0x40)) {
- return results;
- } // parse out the cc_data_1 and cc_data_2 fields
-
-
- count = userData[0] & 0x1f;
-
- for (i = 0; i < count; i++) {
- offset = i * 3;
- data = {
- type: userData[offset + 2] & 0x03,
- pts: pts
- }; // capture cc data when cc_valid is 1
-
- if (userData[offset + 2] & 0x04) {
- data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
- results.push(data);
- }
- }
-
- return results;
- };
-
- var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- }; // exports
-
-
- var captionPacketParser = {
- parseSei: parseSei,
- parseUserData: parseUserData,
- parseCaptionPackets: parseCaptionPackets,
- discardEmulationPreventionBytes: discardEmulationPreventionBytes,
- USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
- };
-
- // Link To Transport
- // -----------------
-
-
- var CaptionStream = function CaptionStream(options) {
- options = options || {};
- CaptionStream.prototype.init.call(this); // parse708captions flag, default to true
-
- this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
- this.captionPackets_ = [];
- this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
- new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
- ];
-
- if (this.parse708captions_) {
- this.cc708Stream_ = new Cea708Stream(); // eslint-disable-line no-use-before-define
- }
-
- this.reset(); // forward data and done events from CCs to this CaptionStream
-
- this.ccStreams_.forEach(function (cc) {
- cc.on('data', this.trigger.bind(this, 'data'));
- cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
- cc.on('done', this.trigger.bind(this, 'done'));
- }, this);
-
- if (this.parse708captions_) {
- this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
- this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
- this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
- }
- };
-
- CaptionStream.prototype = new stream();
-
- CaptionStream.prototype.push = function (event) {
- var sei, userData, newCaptionPackets; // only examine SEI NALs
-
- if (event.nalUnitType !== 'sei_rbsp') {
- return;
- } // parse the sei
-
-
- sei = captionPacketParser.parseSei(event.escapedRBSP); // no payload data, skip
-
- if (!sei.payload) {
- return;
- } // ignore everything but user_data_registered_itu_t_t35
-
-
- if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
- return;
- } // parse out the user data payload
-
-
- userData = captionPacketParser.parseUserData(sei); // ignore unrecognized userData
-
- if (!userData) {
- return;
- } // Sometimes, the same segment # will be downloaded twice. To stop the
- // caption data from being processed twice, we track the latest dts we've
- // received and ignore everything with a dts before that. However, since
- // data for a specific dts can be split across packets on either side of
- // a segment boundary, we need to make sure we *don't* ignore the packets
- // from the *next* segment that have dts === this.latestDts_. By constantly
- // tracking the number of packets received with dts === this.latestDts_, we
- // know how many should be ignored once we start receiving duplicates.
-
-
- if (event.dts < this.latestDts_) {
- // We've started getting older data, so set the flag.
- this.ignoreNextEqualDts_ = true;
- return;
- } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
- this.numSameDts_--;
-
- if (!this.numSameDts_) {
- // We've received the last duplicate packet, time to start processing again
- this.ignoreNextEqualDts_ = false;
- }
-
- return;
- } // parse out CC data packets and save them for later
-
-
- newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
- this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
-
- if (this.latestDts_ !== event.dts) {
- this.numSameDts_ = 0;
- }
-
- this.numSameDts_++;
- this.latestDts_ = event.dts;
- };
-
- CaptionStream.prototype.flushCCStreams = function (flushType) {
- this.ccStreams_.forEach(function (cc) {
- return flushType === 'flush' ? cc.flush() : cc.partialFlush();
- }, this);
- };
-
- CaptionStream.prototype.flushStream = function (flushType) {
- // make sure we actually parsed captions before proceeding
- if (!this.captionPackets_.length) {
- this.flushCCStreams(flushType);
- return;
- } // In Chrome, the Array#sort function is not stable so add a
- // presortIndex that we can use to ensure we get a stable-sort
-
-
- this.captionPackets_.forEach(function (elem, idx) {
- elem.presortIndex = idx;
- }); // sort caption byte-pairs based on their PTS values
-
- this.captionPackets_.sort(function (a, b) {
- if (a.pts === b.pts) {
- return a.presortIndex - b.presortIndex;
- }
-
- return a.pts - b.pts;
- });
- this.captionPackets_.forEach(function (packet) {
- if (packet.type < 2) {
- // Dispatch packet to the right Cea608Stream
- this.dispatchCea608Packet(packet);
- } else {
- // Dispatch packet to the Cea708Stream
- this.dispatchCea708Packet(packet);
- }
- }, this);
- this.captionPackets_.length = 0;
- this.flushCCStreams(flushType);
- };
-
- CaptionStream.prototype.flush = function () {
- return this.flushStream('flush');
- }; // Only called if handling partial data
-
-
- CaptionStream.prototype.partialFlush = function () {
- return this.flushStream('partialFlush');
- };
-
- CaptionStream.prototype.reset = function () {
- this.latestDts_ = null;
- this.ignoreNextEqualDts_ = false;
- this.numSameDts_ = 0;
- this.activeCea608Channel_ = [null, null];
- this.ccStreams_.forEach(function (ccStream) {
- ccStream.reset();
- });
- }; // From the CEA-608 spec:
-
- /*
- * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
- * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
- * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
- * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
- * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
- * to switch to captioning or Text.
- */
- // With that in mind, we ignore any data between an XDS control code and a
- // subsequent closed-captioning control code.
-
-
- CaptionStream.prototype.dispatchCea608Packet = function (packet) {
- // NOTE: packet.type is the CEA608 field
- if (this.setsTextOrXDSActive(packet)) {
- this.activeCea608Channel_[packet.type] = null;
- } else if (this.setsChannel1Active(packet)) {
- this.activeCea608Channel_[packet.type] = 0;
- } else if (this.setsChannel2Active(packet)) {
- this.activeCea608Channel_[packet.type] = 1;
- }
-
- if (this.activeCea608Channel_[packet.type] === null) {
- // If we haven't received anything to set the active channel, or the
- // packets are Text/XDS data, discard the data; we don't want jumbled
- // captions
- return;
- }
-
- this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
- };
-
- CaptionStream.prototype.setsChannel1Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1000;
- };
-
- CaptionStream.prototype.setsChannel2Active = function (packet) {
- return (packet.ccData & 0x7800) === 0x1800;
- };
-
- CaptionStream.prototype.setsTextOrXDSActive = function (packet) {
- return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
- };
-
- CaptionStream.prototype.dispatchCea708Packet = function (packet) {
- if (this.parse708captions_) {
- this.cc708Stream_.push(packet);
- }
- }; // ----------------------
- // Session to Application
- // ----------------------
- // This hash maps special and extended character codes to their
- // proper Unicode equivalent. The first one-byte key is just a
- // non-standard character code. The two-byte keys that follow are
- // the extended CEA708 character codes, along with the preceding
- // 0x10 extended character byte to distinguish these codes from
- // non-extended character codes. Every CEA708 character code that
- // is not in this object maps directly to a standard unicode
- // character code.
- // The transparent space and non-breaking transparent space are
- // technically not fully supported since there is no code to
- // make them transparent, so they have normal non-transparent
- // stand-ins.
- // The special closed caption (CC) character isn't a standard
- // unicode character, so a fairly similar unicode character was
- // chosen in it's place.
-
-
- var CHARACTER_TRANSLATION_708 = {
- 0x7f: 0x266a,
- // ♪
- 0x1020: 0x20,
- // Transparent Space
- 0x1021: 0xa0,
- // Nob-breaking Transparent Space
- 0x1025: 0x2026,
- // …
- 0x102a: 0x0160,
- // Š
- 0x102c: 0x0152,
- // Œ
- 0x1030: 0x2588,
- // █
- 0x1031: 0x2018,
- // ‘
- 0x1032: 0x2019,
- // ’
- 0x1033: 0x201c,
- // “
- 0x1034: 0x201d,
- // ”
- 0x1035: 0x2022,
- // •
- 0x1039: 0x2122,
- // ™
- 0x103a: 0x0161,
- // š
- 0x103c: 0x0153,
- // œ
- 0x103d: 0x2120,
- // ℠
- 0x103f: 0x0178,
- // Ÿ
- 0x1076: 0x215b,
- // ⅛
- 0x1077: 0x215c,
- // ⅜
- 0x1078: 0x215d,
- // ⅝
- 0x1079: 0x215e,
- // ⅞
- 0x107a: 0x23d0,
- // ⏐
- 0x107b: 0x23a4,
- // ⎤
- 0x107c: 0x23a3,
- // ⎣
- 0x107d: 0x23af,
- // ⎯
- 0x107e: 0x23a6,
- // ⎦
- 0x107f: 0x23a1,
- // ⎡
- 0x10a0: 0x3138 // ㄸ (CC char)
-
- };
-
- var get708CharFromCode = function get708CharFromCode(code) {
- var newCode = CHARACTER_TRANSLATION_708[code] || code;
-
- if (code & 0x1000 && code === newCode) {
- // Invalid extended code
- return '';
- }
-
- return String.fromCharCode(newCode);
- };
-
- var within708TextBlock = function within708TextBlock(b) {
- return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
- };
-
- var Cea708Window = function Cea708Window(windowNum) {
- this.windowNum = windowNum;
- this.reset();
- };
-
- Cea708Window.prototype.reset = function () {
- this.clearText();
- this.pendingNewLine = false;
- this.winAttr = {};
- this.penAttr = {};
- this.penLoc = {};
- this.penColor = {}; // These default values are arbitrary,
- // defineWindow will usually override them
-
- this.visible = 0;
- this.rowLock = 0;
- this.columnLock = 0;
- this.priority = 0;
- this.relativePositioning = 0;
- this.anchorVertical = 0;
- this.anchorHorizontal = 0;
- this.anchorPoint = 0;
- this.rowCount = 1;
- this.virtualRowCount = this.rowCount + 1;
- this.columnCount = 41;
- this.windowStyle = 0;
- this.penStyle = 0;
- };
-
- Cea708Window.prototype.getText = function () {
- return this.rows.join('\n');
- };
-
- Cea708Window.prototype.clearText = function () {
- this.rows = [''];
- this.rowIdx = 0;
- };
-
- Cea708Window.prototype.newLine = function (pts) {
- if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
- this.beforeRowOverflow(pts);
- }
-
- if (this.rows.length > 0) {
- this.rows.push('');
- this.rowIdx++;
- } // Show all virtual rows since there's no visible scrolling
-
-
- while (this.rows.length > this.virtualRowCount) {
- this.rows.shift();
- this.rowIdx--;
- }
- };
-
- Cea708Window.prototype.isEmpty = function () {
- if (this.rows.length === 0) {
- return true;
- } else if (this.rows.length === 1) {
- return this.rows[0] === '';
- }
-
- return false;
- };
-
- Cea708Window.prototype.addText = function (text) {
- this.rows[this.rowIdx] += text;
- };
-
- Cea708Window.prototype.backspace = function () {
- if (!this.isEmpty()) {
- var row = this.rows[this.rowIdx];
- this.rows[this.rowIdx] = row.substr(0, row.length - 1);
- }
- };
-
- var Cea708Service = function Cea708Service(serviceNum) {
- this.serviceNum = serviceNum;
- this.text = '';
- this.currentWindow = new Cea708Window(-1);
- this.windows = [];
- };
- /**
- * Initialize service windows
- * Must be run before service use
- *
- * @param {Integer} pts PTS value
- * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
- */
-
-
- Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
- this.startPts = pts;
-
- for (var win = 0; win < 8; win++) {
- this.windows[win] = new Cea708Window(win);
-
- if (typeof beforeRowOverflow === 'function') {
- this.windows[win].beforeRowOverflow = beforeRowOverflow;
- }
- }
- };
- /**
- * Set current window of service to be affected by commands
- *
- * @param {Integer} windowNum Window number
- */
-
-
- Cea708Service.prototype.setCurrentWindow = function (windowNum) {
- this.currentWindow = this.windows[windowNum];
- };
-
- var Cea708Stream = function Cea708Stream() {
- Cea708Stream.prototype.init.call(this);
- var self = this;
- this.current708Packet = null;
- this.services = {};
-
- this.push = function (packet) {
- if (packet.type === 3) {
- // 708 packet start
- self.new708Packet();
- self.add708Bytes(packet);
- } else {
- if (self.current708Packet === null) {
- // This should only happen at the start of a file if there's no packet start.
- self.new708Packet();
- }
-
- self.add708Bytes(packet);
- }
- };
- };
-
- Cea708Stream.prototype = new stream();
- /**
- * Push current 708 packet, create new 708 packet.
- */
-
- Cea708Stream.prototype.new708Packet = function () {
- if (this.current708Packet !== null) {
- this.push708Packet();
- }
-
- this.current708Packet = {
- data: [],
- ptsVals: []
- };
- };
- /**
- * Add pts and both bytes from packet into current 708 packet.
- */
-
-
- Cea708Stream.prototype.add708Bytes = function (packet) {
- var data = packet.ccData;
- var byte0 = data >>> 8;
- var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
- // that service blocks will always line up with byte pairs.
-
- this.current708Packet.ptsVals.push(packet.pts);
- this.current708Packet.data.push(byte0);
- this.current708Packet.data.push(byte1);
- };
- /**
- * Parse completed 708 packet into service blocks and push each service block.
- */
-
-
- Cea708Stream.prototype.push708Packet = function () {
- var packet708 = this.current708Packet;
- var packetData = packet708.data;
- var serviceNum = null;
- var blockSize = null;
- var i = 0;
- var b = packetData[i++];
- packet708.seq = b >> 6;
- packet708.sizeCode = b & 0x3f; // 0b00111111;
-
- for (; i < packetData.length; i++) {
- b = packetData[i++];
- serviceNum = b >> 5;
- blockSize = b & 0x1f; // 0b00011111
-
- if (serviceNum === 7 && blockSize > 0) {
- // Extended service num
- b = packetData[i++];
- serviceNum = b;
- }
-
- this.pushServiceBlock(serviceNum, i, blockSize);
-
- if (blockSize > 0) {
- i += blockSize - 1;
- }
- }
- };
- /**
- * Parse service block, execute commands, read text.
- *
- * Note: While many of these commands serve important purposes,
- * many others just parse out the parameters or attributes, but
- * nothing is done with them because this is not a full and complete
- * implementation of the entire 708 spec.
- *
- * @param {Integer} serviceNum Service number
- * @param {Integer} start Start index of the 708 packet data
- * @param {Integer} size Block size
- */
-
-
- Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
- var b;
- var i = start;
- var packetData = this.current708Packet.data;
- var service = this.services[serviceNum];
-
- if (!service) {
- service = this.initService(serviceNum, i);
- }
-
- for (; i < start + size && i < packetData.length; i++) {
- b = packetData[i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service);
- } else if (b === 0x10) {
- i = this.extendedCommands(i, service);
- } else if (0x80 <= b && b <= 0x87) {
- i = this.setCurrentWindow(i, service);
- } else if (0x98 <= b && b <= 0x9f) {
- i = this.defineWindow(i, service);
- } else if (b === 0x88) {
- i = this.clearWindows(i, service);
- } else if (b === 0x8c) {
- i = this.deleteWindows(i, service);
- } else if (b === 0x89) {
- i = this.displayWindows(i, service);
- } else if (b === 0x8a) {
- i = this.hideWindows(i, service);
- } else if (b === 0x8b) {
- i = this.toggleWindows(i, service);
- } else if (b === 0x97) {
- i = this.setWindowAttributes(i, service);
- } else if (b === 0x90) {
- i = this.setPenAttributes(i, service);
- } else if (b === 0x91) {
- i = this.setPenColor(i, service);
- } else if (b === 0x92) {
- i = this.setPenLocation(i, service);
- } else if (b === 0x8f) {
- service = this.reset(i, service);
- } else if (b === 0x08) {
- // BS: Backspace
- service.currentWindow.backspace();
- } else if (b === 0x0c) {
- // FF: Form feed
- service.currentWindow.clearText();
- } else if (b === 0x0d) {
- // CR: Carriage return
- service.currentWindow.pendingNewLine = true;
- } else if (b === 0x0e) {
- // HCR: Horizontal carriage return
- service.currentWindow.clearText();
- } else if (b === 0x8d) {
- // DLY: Delay, nothing to do
- i++;
- } else ;
- }
- };
- /**
- * Execute an extended command
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.extendedCommands = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
-
- if (within708TextBlock(b)) {
- i = this.handleText(i, service, true);
- }
-
- return i;
- };
- /**
- * Get PTS value of a given byte index
- *
- * @param {Integer} byteIndex Index of the byte
- * @return {Integer} PTS
- */
-
-
- Cea708Stream.prototype.getPts = function (byteIndex) {
- // There's 1 pts value per 2 bytes
- return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
- };
- /**
- * Initializes a service
- *
- * @param {Integer} serviceNum Service number
- * @return {Service} Initialized service object
- */
-
-
- Cea708Stream.prototype.initService = function (serviceNum, i) {
- var self = this;
- this.services[serviceNum] = new Cea708Service(serviceNum);
- this.services[serviceNum].init(this.getPts(i), function (pts) {
- self.flushDisplayed(pts, self.services[serviceNum]);
- });
- return this.services[serviceNum];
- };
- /**
- * Execute text writing to current window
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.handleText = function (i, service, isExtended) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var extended = isExtended ? 0x1000 : 0x0000;
- var char = get708CharFromCode(extended | b);
- var win = service.currentWindow;
-
- if (win.pendingNewLine && !win.isEmpty()) {
- win.newLine(this.getPts(i));
- }
-
- win.pendingNewLine = false;
- win.addText(char);
- return i;
- };
- /**
- * Parse and execute the CW# command.
- *
- * Set the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setCurrentWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- return i;
- };
- /**
- * Parse and execute the DF# command.
- *
- * Define a window and set it as the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.defineWindow = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var windowNum = b & 0x07;
- service.setCurrentWindow(windowNum);
- var win = service.currentWindow;
- b = packetData[++i];
- win.visible = (b & 0x20) >> 5; // v
-
- win.rowLock = (b & 0x10) >> 4; // rl
-
- win.columnLock = (b & 0x08) >> 3; // cl
-
- win.priority = b & 0x07; // p
-
- b = packetData[++i];
- win.relativePositioning = (b & 0x80) >> 7; // rp
-
- win.anchorVertical = b & 0x7f; // av
-
- b = packetData[++i];
- win.anchorHorizontal = b; // ah
-
- b = packetData[++i];
- win.anchorPoint = (b & 0xf0) >> 4; // ap
-
- win.rowCount = b & 0x0f; // rc
-
- b = packetData[++i];
- win.columnCount = b & 0x3f; // cc
-
- b = packetData[++i];
- win.windowStyle = (b & 0x38) >> 3; // ws
-
- win.penStyle = b & 0x07; // ps
- // The spec says there are (rowCount+1) "virtual rows"
-
- win.virtualRowCount = win.rowCount + 1;
- return i;
- };
- /**
- * Parse and execute the SWA command.
- *
- * Set attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setWindowAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var winAttr = service.currentWindow.winAttr;
- b = packetData[++i];
- winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
-
- winAttr.fillRed = (b & 0x30) >> 4; // fr
-
- winAttr.fillGreen = (b & 0x0c) >> 2; // fg
-
- winAttr.fillBlue = b & 0x03; // fb
-
- b = packetData[++i];
- winAttr.borderType = (b & 0xc0) >> 6; // bt
-
- winAttr.borderRed = (b & 0x30) >> 4; // br
-
- winAttr.borderGreen = (b & 0x0c) >> 2; // bg
-
- winAttr.borderBlue = b & 0x03; // bb
-
- b = packetData[++i];
- winAttr.borderType += (b & 0x80) >> 5; // bt
-
- winAttr.wordWrap = (b & 0x40) >> 6; // ww
-
- winAttr.printDirection = (b & 0x30) >> 4; // pd
-
- winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
-
- winAttr.justify = b & 0x03; // j
-
- b = packetData[++i];
- winAttr.effectSpeed = (b & 0xf0) >> 4; // es
-
- winAttr.effectDirection = (b & 0x0c) >> 2; // ed
-
- winAttr.displayEffect = b & 0x03; // de
-
- return i;
- };
- /**
- * Gather text from all displayed windows and push a caption to output.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.flushDisplayed = function (pts, service) {
- var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
- // display text in the correct order, but sample files so far have not shown any issue.
-
- for (var winId = 0; winId < 8; winId++) {
- if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
- displayedText.push(service.windows[winId].getText());
- }
- }
-
- service.endPts = pts;
- service.text = displayedText.join('\n\n');
- this.pushCaption(service);
- service.startPts = pts;
- };
- /**
- * Push a caption to output if the caption contains text.
- *
- * @param {Service} service The service object to be affected
- */
-
-
- Cea708Stream.prototype.pushCaption = function (service) {
- if (service.text !== '') {
- this.trigger('data', {
- startPts: service.startPts,
- endPts: service.endPts,
- text: service.text,
- stream: 'cc708_' + service.serviceNum
- });
- service.text = '';
- service.startPts = service.endPts;
- }
- };
- /**
- * Parse and execute the DSW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.displayWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the HDW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.hideWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible = 0;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the TGW command.
- *
- * Set visible property of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.toggleWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].visible ^= 1;
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the CLW command.
- *
- * Clear text of windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.clearWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].clearText();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the DLW command.
- *
- * Re-initialize windows based on the parsed bitmask.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.deleteWindows = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[++i];
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
-
- for (var winId = 0; winId < 8; winId++) {
- if (b & 0x01 << winId) {
- service.windows[winId].reset();
- }
- }
-
- return i;
- };
- /**
- * Parse and execute the SPA command.
- *
- * Set pen attributes of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenAttributes = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penAttr = service.currentWindow.penAttr;
- b = packetData[++i];
- penAttr.textTag = (b & 0xf0) >> 4; // tt
-
- penAttr.offset = (b & 0x0c) >> 2; // o
-
- penAttr.penSize = b & 0x03; // s
-
- b = packetData[++i];
- penAttr.italics = (b & 0x80) >> 7; // i
-
- penAttr.underline = (b & 0x40) >> 6; // u
-
- penAttr.edgeType = (b & 0x38) >> 3; // et
-
- penAttr.fontStyle = b & 0x07; // fs
-
- return i;
- };
- /**
- * Parse and execute the SPC command.
- *
- * Set pen color of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenColor = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penColor = service.currentWindow.penColor;
- b = packetData[++i];
- penColor.fgOpacity = (b & 0xc0) >> 6; // fo
-
- penColor.fgRed = (b & 0x30) >> 4; // fr
-
- penColor.fgGreen = (b & 0x0c) >> 2; // fg
-
- penColor.fgBlue = b & 0x03; // fb
-
- b = packetData[++i];
- penColor.bgOpacity = (b & 0xc0) >> 6; // bo
-
- penColor.bgRed = (b & 0x30) >> 4; // br
-
- penColor.bgGreen = (b & 0x0c) >> 2; // bg
-
- penColor.bgBlue = b & 0x03; // bb
-
- b = packetData[++i];
- penColor.edgeRed = (b & 0x30) >> 4; // er
-
- penColor.edgeGreen = (b & 0x0c) >> 2; // eg
-
- penColor.edgeBlue = b & 0x03; // eb
-
- return i;
- };
- /**
- * Parse and execute the SPL command.
- *
- * Set pen location of the current window.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Integer} New index after parsing
- */
-
-
- Cea708Stream.prototype.setPenLocation = function (i, service) {
- var packetData = this.current708Packet.data;
- var b = packetData[i];
- var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
-
- service.currentWindow.pendingNewLine = true;
- b = packetData[++i];
- penLoc.row = b & 0x0f; // r
-
- b = packetData[++i];
- penLoc.column = b & 0x3f; // c
-
- return i;
- };
- /**
- * Execute the RST command.
- *
- * Reset service to a clean slate. Re-initialize.
- *
- * @param {Integer} i Current index in the 708 packet
- * @param {Service} service The service object to be affected
- * @return {Service} Re-initialized service
- */
-
-
- Cea708Stream.prototype.reset = function (i, service) {
- var pts = this.getPts(i);
- this.flushDisplayed(pts, service);
- return this.initService(service.serviceNum, i);
- }; // This hash maps non-ASCII, special, and extended character codes to their
- // proper Unicode equivalent. The first keys that are only a single byte
- // are the non-standard ASCII characters, which simply map the CEA608 byte
- // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
- // character codes, but have their MSB bitmasked with 0x03 so that a lookup
- // can be performed regardless of the field and data channel on which the
- // character code was received.
-
-
- var CHARACTER_TRANSLATION = {
- 0x2a: 0xe1,
- // á
- 0x5c: 0xe9,
- // é
- 0x5e: 0xed,
- // í
- 0x5f: 0xf3,
- // ó
- 0x60: 0xfa,
- // ú
- 0x7b: 0xe7,
- // ç
- 0x7c: 0xf7,
- // ÷
- 0x7d: 0xd1,
- // Ñ
- 0x7e: 0xf1,
- // ñ
- 0x7f: 0x2588,
- // █
- 0x0130: 0xae,
- // ®
- 0x0131: 0xb0,
- // °
- 0x0132: 0xbd,
- // ½
- 0x0133: 0xbf,
- // ¿
- 0x0134: 0x2122,
- // ™
- 0x0135: 0xa2,
- // ¢
- 0x0136: 0xa3,
- // £
- 0x0137: 0x266a,
- // ♪
- 0x0138: 0xe0,
- // à
- 0x0139: 0xa0,
- //
- 0x013a: 0xe8,
- // è
- 0x013b: 0xe2,
- // â
- 0x013c: 0xea,
- // ê
- 0x013d: 0xee,
- // î
- 0x013e: 0xf4,
- // ô
- 0x013f: 0xfb,
- // û
- 0x0220: 0xc1,
- // Á
- 0x0221: 0xc9,
- // É
- 0x0222: 0xd3,
- // Ó
- 0x0223: 0xda,
- // Ú
- 0x0224: 0xdc,
- // Ü
- 0x0225: 0xfc,
- // ü
- 0x0226: 0x2018,
- // ‘
- 0x0227: 0xa1,
- // ¡
- 0x0228: 0x2a,
- // *
- 0x0229: 0x27,
- // '
- 0x022a: 0x2014,
- // —
- 0x022b: 0xa9,
- // ©
- 0x022c: 0x2120,
- // ℠
- 0x022d: 0x2022,
- // •
- 0x022e: 0x201c,
- // “
- 0x022f: 0x201d,
- // ”
- 0x0230: 0xc0,
- // À
- 0x0231: 0xc2,
- // Â
- 0x0232: 0xc7,
- // Ç
- 0x0233: 0xc8,
- // È
- 0x0234: 0xca,
- // Ê
- 0x0235: 0xcb,
- // Ë
- 0x0236: 0xeb,
- // ë
- 0x0237: 0xce,
- // Î
- 0x0238: 0xcf,
- // Ï
- 0x0239: 0xef,
- // ï
- 0x023a: 0xd4,
- // Ô
- 0x023b: 0xd9,
- // Ù
- 0x023c: 0xf9,
- // ù
- 0x023d: 0xdb,
- // Û
- 0x023e: 0xab,
- // «
- 0x023f: 0xbb,
- // »
- 0x0320: 0xc3,
- // Ã
- 0x0321: 0xe3,
- // ã
- 0x0322: 0xcd,
- // Í
- 0x0323: 0xcc,
- // Ì
- 0x0324: 0xec,
- // ì
- 0x0325: 0xd2,
- // Ò
- 0x0326: 0xf2,
- // ò
- 0x0327: 0xd5,
- // Õ
- 0x0328: 0xf5,
- // õ
- 0x0329: 0x7b,
- // {
- 0x032a: 0x7d,
- // }
- 0x032b: 0x5c,
- // \
- 0x032c: 0x5e,
- // ^
- 0x032d: 0x5f,
- // _
- 0x032e: 0x7c,
- // |
- 0x032f: 0x7e,
- // ~
- 0x0330: 0xc4,
- // Ä
- 0x0331: 0xe4,
- // ä
- 0x0332: 0xd6,
- // Ö
- 0x0333: 0xf6,
- // ö
- 0x0334: 0xdf,
- // ß
- 0x0335: 0xa5,
- // ¥
- 0x0336: 0xa4,
- // ¤
- 0x0337: 0x2502,
- // │
- 0x0338: 0xc5,
- // Å
- 0x0339: 0xe5,
- // å
- 0x033a: 0xd8,
- // Ø
- 0x033b: 0xf8,
- // ø
- 0x033c: 0x250c,
- // ┌
- 0x033d: 0x2510,
- // ┐
- 0x033e: 0x2514,
- // └
- 0x033f: 0x2518 // ┘
-
- };
-
- var getCharFromCode = function getCharFromCode(code) {
- if (code === null) {
- return '';
- }
-
- code = CHARACTER_TRANSLATION[code] || code;
- return String.fromCharCode(code);
- }; // the index of the last row in a CEA-608 display buffer
-
-
- var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
- // getting it through bit logic.
-
- var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // CEA-608 captions are rendered onto a 34x15 matrix of character
- // cells. The "bottom" row is the last element in the outer array.
-
- var createDisplayBuffer = function createDisplayBuffer() {
- var result = [],
- i = BOTTOM_ROW + 1;
-
- while (i--) {
- result.push('');
- }
-
- return result;
- };
-
- var Cea608Stream = function Cea608Stream(field, dataChannel) {
- Cea608Stream.prototype.init.call(this);
- this.field_ = field || 0;
- this.dataChannel_ = dataChannel || 0;
- this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
- this.setConstants();
- this.reset();
-
- this.push = function (packet) {
- var data, swap, char0, char1, text; // remove the parity bits
-
- data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
-
- if (data === this.lastControlCode_) {
- this.lastControlCode_ = null;
- return;
- } // Store control codes
-
-
- if ((data & 0xf000) === 0x1000) {
- this.lastControlCode_ = data;
- } else if (data !== this.PADDING_) {
- this.lastControlCode_ = null;
- }
-
- char0 = data >>> 8;
- char1 = data & 0xff;
-
- if (data === this.PADDING_) {
- return;
- } else if (data === this.RESUME_CAPTION_LOADING_) {
- this.mode_ = 'popOn';
- } else if (data === this.END_OF_CAPTION_) {
- // If an EOC is received while in paint-on mode, the displayed caption
- // text should be swapped to non-displayed memory as if it was a pop-on
- // caption. Because of that, we should explicitly switch back to pop-on
- // mode
- this.mode_ = 'popOn';
- this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
-
- this.flushDisplayed(packet.pts); // flip memory
-
- swap = this.displayed_;
- this.displayed_ = this.nonDisplayed_;
- this.nonDisplayed_ = swap; // start measuring the time to display the caption
-
- this.startPts_ = packet.pts;
- } else if (data === this.ROLL_UP_2_ROWS_) {
- this.rollUpRows_ = 2;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_3_ROWS_) {
- this.rollUpRows_ = 3;
- this.setRollUp(packet.pts);
- } else if (data === this.ROLL_UP_4_ROWS_) {
- this.rollUpRows_ = 4;
- this.setRollUp(packet.pts);
- } else if (data === this.CARRIAGE_RETURN_) {
- this.clearFormatting(packet.pts);
- this.flushDisplayed(packet.pts);
- this.shiftRowsUp_();
- this.startPts_ = packet.pts;
- } else if (data === this.BACKSPACE_) {
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- }
- } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
- this.nonDisplayed_ = createDisplayBuffer();
- } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
- if (this.mode_ !== 'paintOn') {
- // NOTE: This should be removed when proper caption positioning is
- // implemented
- this.flushDisplayed(packet.pts);
- this.displayed_ = createDisplayBuffer();
- }
-
- this.mode_ = 'paintOn';
- this.startPts_ = packet.pts; // Append special characters to caption text
- } else if (this.isSpecialCharacter(char0, char1)) {
- // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Append extended characters to caption text
- } else if (this.isExtCharacter(char0, char1)) {
- // Extended characters always follow their "non-extended" equivalents.
- // IE if a "è" is desired, you'll always receive "eè"; non-compliant
- // decoders are supposed to drop the "è", while compliant decoders
- // backspace the "e" and insert "è".
- // Delete the previous character
- if (this.mode_ === 'popOn') {
- this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
- } else {
- this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
- } // Bitmask char0 so that we can apply character transformations
- // regardless of field and data channel.
- // Then byte-shift to the left and OR with char1 so we can pass the
- // entire character code to `getCharFromCode`.
-
-
- char0 = (char0 & 0x03) << 8;
- text = getCharFromCode(char0 | char1);
- this[this.mode_](packet.pts, text);
- this.column_++; // Process mid-row codes
- } else if (this.isMidRowCode(char0, char1)) {
- // Attributes are not additive, so clear all formatting
- this.clearFormatting(packet.pts); // According to the standard, mid-row codes
- // should be replaced with spaces, so add one now
-
- this[this.mode_](packet.pts, ' ');
- this.column_++;
-
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
-
- if ((char1 & 0x1) === 0x1) {
- this.addFormatting(packet.pts, ['u']);
- } // Detect offset control codes and adjust cursor
-
- } else if (this.isOffsetControlCode(char0, char1)) {
- // Cursor position is set by indent PAC (see below) in 4-column
- // increments, with an additional offset code of 1-3 to reach any
- // of the 32 columns specified by CEA-608. So all we need to do
- // here is increment the column cursor by the given offset.
- this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
- } else if (this.isPAC(char0, char1)) {
- // There's no logic for PAC -> row mapping, so we have to just
- // find the row code in an array and use its index :(
- var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
-
- if (this.mode_ === 'rollUp') {
- // This implies that the base row is incorrectly set.
- // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
- // of roll-up rows set.
- if (row - this.rollUpRows_ + 1 < 0) {
- row = this.rollUpRows_ - 1;
- }
-
- this.setRollUp(packet.pts, row);
- }
-
- if (row !== this.row_) {
- // formatting is only persistent for current row
- this.clearFormatting(packet.pts);
- this.row_ = row;
- } // All PACs can apply underline, so detect and apply
- // (All odd-numbered second bytes set underline)
-
-
- if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
- this.addFormatting(packet.pts, ['u']);
- }
-
- if ((data & 0x10) === 0x10) {
- // We've got an indent level code. Each successive even number
- // increments the column cursor by 4, so we can get the desired
- // column position by bit-shifting to the right (to get n/2)
- // and multiplying by 4.
- this.column_ = ((data & 0xe) >> 1) * 4;
- }
-
- if (this.isColorPAC(char1)) {
- // it's a color code, though we only support white, which
- // can be either normal or italicized. white italics can be
- // either 0x4e or 0x6e depending on the row, so we just
- // bitwise-and with 0xe to see if italics should be turned on
- if ((char1 & 0xe) === 0xe) {
- this.addFormatting(packet.pts, ['i']);
- }
- } // We have a normal character in char0, and possibly one in char1
-
- } else if (this.isNormalChar(char0)) {
- if (char1 === 0x00) {
- char1 = null;
- }
-
- text = getCharFromCode(char0);
- text += getCharFromCode(char1);
- this[this.mode_](packet.pts, text);
- this.column_ += text.length;
- } // finish data processing
-
- };
- };
-
- Cea608Stream.prototype = new stream(); // Trigger a cue point that captures the current state of the
- // display buffer
-
- Cea608Stream.prototype.flushDisplayed = function (pts) {
- var content = this.displayed_ // remove spaces from the start and end of the string
- .map(function (row) {
- try {
- return row.trim();
- } catch (e) {
- // Ordinarily, this shouldn't happen. However, caption
- // parsing errors should not throw exceptions and
- // break playback.
- // eslint-disable-next-line no-console
- console.error('Skipping malformed caption.');
- return '';
- }
- }) // combine all text rows to display in one cue
- .join('\n') // and remove blank rows from the start and end, but not the middle
- .replace(/^\n+|\n+$/g, '');
-
- if (content.length) {
- this.trigger('data', {
- startPts: this.startPts_,
- endPts: pts,
- text: content,
- stream: this.name_
- });
- }
- };
- /**
- * Zero out the data, used for startup and on seek
- */
-
-
- Cea608Stream.prototype.reset = function () {
- this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
- // actually display captions. If a caption is shifted to a row
- // with a lower index than this, it is cleared from the display
- // buffer
-
- this.topRow_ = 0;
- this.startPts_ = 0;
- this.displayed_ = createDisplayBuffer();
- this.nonDisplayed_ = createDisplayBuffer();
- this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
-
- this.column_ = 0;
- this.row_ = BOTTOM_ROW;
- this.rollUpRows_ = 2; // This variable holds currently-applied formatting
-
- this.formatting_ = [];
- };
- /**
- * Sets up control code and related constants for this instance
- */
-
-
- Cea608Stream.prototype.setConstants = function () {
- // The following attributes have these uses:
- // ext_ : char0 for mid-row codes, and the base for extended
- // chars (ext_+0, ext_+1, and ext_+2 are char0s for
- // extended codes)
- // control_: char0 for control codes, except byte-shifted to the
- // left so that we can do this.control_ | CONTROL_CODE
- // offset_: char0 for tab offset codes
- //
- // It's also worth noting that control codes, and _only_ control codes,
- // differ between field 1 and field2. Field 2 control codes are always
- // their field 1 value plus 1. That's why there's the "| field" on the
- // control value.
- if (this.dataChannel_ === 0) {
- this.BASE_ = 0x10;
- this.EXT_ = 0x11;
- this.CONTROL_ = (0x14 | this.field_) << 8;
- this.OFFSET_ = 0x17;
- } else if (this.dataChannel_ === 1) {
- this.BASE_ = 0x18;
- this.EXT_ = 0x19;
- this.CONTROL_ = (0x1c | this.field_) << 8;
- this.OFFSET_ = 0x1f;
- } // Constants for the LSByte command codes recognized by Cea608Stream. This
- // list is not exhaustive. For a more comprehensive listing and semantics see
- // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
- // Padding
-
-
- this.PADDING_ = 0x0000; // Pop-on Mode
-
- this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
- this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
-
- this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
- this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
- this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
- this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
-
- this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
-
- this.BACKSPACE_ = this.CONTROL_ | 0x21;
- this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
- this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
- };
- /**
- * Detects if the 2-byte packet data is a special character
- *
- * Special characters have a second byte in the range 0x30 to 0x3f,
- * with the first byte being 0x11 (for data channel 1) or 0x19 (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an special character
- */
-
-
- Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet data is an extended character
- *
- * Extended characters have a second byte in the range 0x20 to 0x3f,
- * with the first byte being 0x12 or 0x13 (for data channel 1) or
- * 0x1a or 0x1b (for data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an extended character
- */
-
-
- Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
- return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
- };
- /**
- * Detects if the 2-byte packet is a mid-row code
- *
- * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
- * the first byte being 0x11 (for data channel 1) or 0x19 (for data
- * channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a mid-row code
- */
-
-
- Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
- return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
- };
- /**
- * Detects if the 2-byte packet is an offset control code
- *
- * Offset control codes have a second byte in the range 0x21 to 0x23,
- * with the first byte being 0x17 (for data channel 1) or 0x1f (for
- * data channel 2).
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are an offset control code
- */
-
-
- Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
- return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
- };
- /**
- * Detects if the 2-byte packet is a Preamble Address Code
- *
- * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
- * or 0x18 to 0x1f (for data channel 2), with the second byte in the
- * range 0x40 to 0x7f.
- *
- * @param {Integer} char0 The first byte
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the 2 bytes are a PAC
- */
-
-
- Cea608Stream.prototype.isPAC = function (char0, char1) {
- return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
- };
- /**
- * Detects if a packet's second byte is in the range of a PAC color code
- *
- * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
- * 0x60 to 0x6f.
- *
- * @param {Integer} char1 The second byte
- * @return {Boolean} Whether the byte is a color PAC
- */
-
-
- Cea608Stream.prototype.isColorPAC = function (char1) {
- return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
- };
- /**
- * Detects if a single byte is in the range of a normal character
- *
- * Normal text bytes are in the range 0x20 to 0x7f.
- *
- * @param {Integer} char The byte
- * @return {Boolean} Whether the byte is a normal character
- */
-
-
- Cea608Stream.prototype.isNormalChar = function (char) {
- return char >= 0x20 && char <= 0x7f;
- };
- /**
- * Configures roll-up
- *
- * @param {Integer} pts Current PTS
- * @param {Integer} newBaseRow Used by PACs to slide the current window to
- * a new position
- */
-
-
- Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
- // Reset the base row to the bottom row when switching modes
- if (this.mode_ !== 'rollUp') {
- this.row_ = BOTTOM_ROW;
- this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
-
- this.flushDisplayed(pts);
- this.nonDisplayed_ = createDisplayBuffer();
- this.displayed_ = createDisplayBuffer();
- }
-
- if (newBaseRow !== undefined && newBaseRow !== this.row_) {
- // move currently displayed captions (up or down) to the new base row
- for (var i = 0; i < this.rollUpRows_; i++) {
- this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
- this.displayed_[this.row_ - i] = '';
- }
- }
-
- if (newBaseRow === undefined) {
- newBaseRow = this.row_;
- }
-
- this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
- }; // Adds the opening HTML tag for the passed character to the caption text,
- // and keeps track of it for later closing
-
-
- Cea608Stream.prototype.addFormatting = function (pts, format) {
- this.formatting_ = this.formatting_.concat(format);
- var text = format.reduce(function (text, format) {
- return text + '<' + format + '>';
- }, '');
- this[this.mode_](pts, text);
- }; // Adds HTML closing tags for current formatting to caption text and
- // clears remembered formatting
-
-
- Cea608Stream.prototype.clearFormatting = function (pts) {
- if (!this.formatting_.length) {
- return;
- }
-
- var text = this.formatting_.reverse().reduce(function (text, format) {
- return text + '' + format + '>';
- }, '');
- this.formatting_ = [];
- this[this.mode_](pts, text);
- }; // Mode Implementations
-
-
- Cea608Stream.prototype.popOn = function (pts, text) {
- var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
-
- baseRow += text;
- this.nonDisplayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.rollUp = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- };
-
- Cea608Stream.prototype.shiftRowsUp_ = function () {
- var i; // clear out inactive rows
-
- for (i = 0; i < this.topRow_; i++) {
- this.displayed_[i] = '';
- }
-
- for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
- this.displayed_[i] = '';
- } // shift displayed rows up
-
-
- for (i = this.topRow_; i < this.row_; i++) {
- this.displayed_[i] = this.displayed_[i + 1];
- } // clear out the bottom row
-
-
- this.displayed_[this.row_] = '';
- };
-
- Cea608Stream.prototype.paintOn = function (pts, text) {
- var baseRow = this.displayed_[this.row_];
- baseRow += text;
- this.displayed_[this.row_] = baseRow;
- }; // exports
-
-
- var captionStream = {
- CaptionStream: CaptionStream,
- Cea608Stream: Cea608Stream,
- Cea708Stream: Cea708Stream
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var streamTypes = {
- H264_STREAM_TYPE: 0x1B,
- ADTS_STREAM_TYPE: 0x0F,
- METADATA_STREAM_TYPE: 0x15
- };
-
- var MAX_TS = 8589934592;
- var RO_THRESH = 4294967296;
- var TYPE_SHARED = 'shared';
-
- var handleRollover = function handleRollover(value, reference) {
- var direction = 1;
-
- if (value > reference) {
- // If the current timestamp value is greater than our reference timestamp and we detect a
- // timestamp rollover, this means the roll over is happening in the opposite direction.
- // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
- // point will be set to a small number, e.g. 1. The user then seeks backwards over the
- // rollover point. In loading this segment, the timestamp values will be very large,
- // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
- // the time stamp to be `value - 2^33`.
- direction = -1;
- } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
- // cause an incorrect adjustment.
-
-
- while (Math.abs(reference - value) > RO_THRESH) {
- value += direction * MAX_TS;
- }
-
- return value;
- };
-
- var TimestampRolloverStream = function TimestampRolloverStream(type) {
- var lastDTS, referenceDTS;
- TimestampRolloverStream.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
- // video and audio. We could use `undefined` here, but having a string
- // makes debugging a little clearer.
-
- this.type_ = type || TYPE_SHARED;
-
- this.push = function (data) {
- // Any "shared" rollover streams will accept _all_ data. Otherwise,
- // streams will only accept data that matches their type.
- if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
- return;
- }
-
- if (referenceDTS === undefined) {
- referenceDTS = data.dts;
- }
-
- data.dts = handleRollover(data.dts, referenceDTS);
- data.pts = handleRollover(data.pts, referenceDTS);
- lastDTS = data.dts;
- this.trigger('data', data);
- };
-
- this.flush = function () {
- referenceDTS = lastDTS;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.discontinuity = function () {
- referenceDTS = void 0;
- lastDTS = void 0;
- };
-
- this.reset = function () {
- this.discontinuity();
- this.trigger('reset');
- };
- };
-
- TimestampRolloverStream.prototype = new stream();
- var timestampRolloverStream = {
- TimestampRolloverStream: TimestampRolloverStream,
- handleRollover: handleRollover
- };
-
- var percentEncode = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- },
- // return the string representation of the specified byte range,
- // interpreted as UTf-8.
- parseUtf8 = function parseUtf8(bytes, start, end) {
- return decodeURIComponent(percentEncode(bytes, start, end));
- },
- // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
- parseIso88591 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
- },
- parseSyncSafeInteger = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- },
- tagParsers = {
- TXXX: function TXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the text fields
- tag.description = parseUtf8(tag.data, 1, i); // do not include the null terminator in the tag value
-
- tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
- break;
- }
- }
-
- tag.data = tag.value;
- },
- WXXX: function WXXX(tag) {
- var i;
-
- if (tag.data[0] !== 3) {
- // ignore frames with unrecognized character encodings
- return;
- }
-
- for (i = 1; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.description = parseUtf8(tag.data, 1, i);
- tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
- break;
- }
- }
- },
- PRIV: function PRIV(tag) {
- var i;
-
- for (i = 0; i < tag.data.length; i++) {
- if (tag.data[i] === 0) {
- // parse the description and URL fields
- tag.owner = parseIso88591(tag.data, 0, i);
- break;
- }
- }
-
- tag.privateData = tag.data.subarray(i + 1);
- tag.data = tag.privateData;
- }
- },
- _MetadataStream;
-
- _MetadataStream = function MetadataStream(options) {
- var settings = {
- debug: !!(options && options.debug),
- // the bytes of the program-level descriptor field in MP2T
- // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
- // program element descriptors"
- descriptor: options && options.descriptor
- },
- // the total size in bytes of the ID3 tag being parsed
- tagSize = 0,
- // tag data that is not complete enough to be parsed
- buffer = [],
- // the total number of bytes currently in the buffer
- bufferSize = 0,
- i;
-
- _MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
- // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
-
-
- this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
-
- if (settings.descriptor) {
- for (i = 0; i < settings.descriptor.length; i++) {
- this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
- }
- }
-
- this.push = function (chunk) {
- var tag, frameStart, frameSize, frame, i, frameHeader;
-
- if (chunk.type !== 'timed-metadata') {
- return;
- } // if data_alignment_indicator is set in the PES header,
- // we must have the start of a new ID3 tag. Assume anything
- // remaining in the buffer was malformed and throw it out
-
-
- if (chunk.dataAlignmentIndicator) {
- bufferSize = 0;
- buffer.length = 0;
- } // ignore events that don't look like ID3 data
-
-
- if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) {
- if (settings.debug) {
- // eslint-disable-next-line no-console
- console.log('Skipping unrecognized metadata packet');
- }
-
- return;
- } // add this chunk to the data we've collected so far
-
-
- buffer.push(chunk);
- bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
-
- if (buffer.length === 1) {
- // the frame size is transmitted as a 28-bit integer in the
- // last four bytes of the ID3 header.
- // The most significant bit of each byte is dropped and the
- // results concatenated to recover the actual value.
- tagSize = parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
- // convenient for our comparisons to include it
-
- tagSize += 10;
- } // if the entire frame has not arrived, wait for more data
-
-
- if (bufferSize < tagSize) {
- return;
- } // collect the entire frame so it can be parsed
-
-
- tag = {
- data: new Uint8Array(tagSize),
- frames: [],
- pts: buffer[0].pts,
- dts: buffer[0].dts
- };
-
- for (i = 0; i < tagSize;) {
- tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
- i += buffer[0].data.byteLength;
- bufferSize -= buffer[0].data.byteLength;
- buffer.shift();
- } // find the start of the first frame and the end of the tag
-
-
- frameStart = 10;
-
- if (tag.data[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
-
- tagSize -= parseSyncSafeInteger(tag.data.subarray(16, 20));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- // eslint-disable-next-line no-console
- return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
- }
-
- frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
- frame = {
- id: frameHeader,
- data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
- };
- frame.key = frame.id;
-
- if (tagParsers[frame.id]) {
- tagParsers[frame.id](frame); // handle the special PRIV frame used to indicate the start
- // time for raw AAC data
-
- if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.data,
- size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
- // on the value of this frame
- // we couldn't have known the appropriate pts and dts before
- // parsing this ID3 tag so set those values now
-
- if (tag.pts === undefined && tag.dts === undefined) {
- tag.pts = frame.timeStamp;
- tag.dts = frame.timeStamp;
- }
-
- this.trigger('timestamp', frame);
- }
- }
-
- tag.frames.push(frame);
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < tagSize);
-
- this.trigger('data', tag);
- };
- };
-
- _MetadataStream.prototype = new stream();
- var metadataStream = _MetadataStream;
-
- var TimestampRolloverStream$1 = timestampRolloverStream.TimestampRolloverStream; // object types
-
- var _TransportPacketStream, _TransportParseStream, _ElementaryStream; // constants
-
-
- var MP2T_PACKET_LENGTH = 188,
- // bytes
- SYNC_BYTE = 0x47;
- /**
- * Splits an incoming stream of binary data into MPEG-2 Transport
- * Stream packets.
- */
-
- _TransportPacketStream = function TransportPacketStream() {
- var buffer = new Uint8Array(MP2T_PACKET_LENGTH),
- bytesInBuffer = 0;
-
- _TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
-
- /**
- * Split a stream of data into M2TS packets
- **/
-
-
- this.push = function (bytes) {
- var startIndex = 0,
- endIndex = MP2T_PACKET_LENGTH,
- everything; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (bytesInBuffer) {
- everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
- everything.set(buffer.subarray(0, bytesInBuffer));
- everything.set(bytes, bytesInBuffer);
- bytesInBuffer = 0;
- } else {
- everything = bytes;
- } // While we have enough data for a packet
-
-
- while (endIndex < everything.byteLength) {
- // Look for a pair of start and end sync bytes in the data..
- if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) {
- // We found a packet so emit it and jump one whole packet forward in
- // the stream
- this.trigger('data', everything.subarray(startIndex, endIndex));
- startIndex += MP2T_PACKET_LENGTH;
- endIndex += MP2T_PACKET_LENGTH;
- continue;
- } // If we get here, we have somehow become de-synchronized and we need to step
- // forward one byte at a time until we find a pair of sync bytes that denote
- // a packet
-
-
- startIndex++;
- endIndex++;
- } // If there was some data left over at the end of the segment that couldn't
- // possibly be a whole packet, keep it because it might be the start of a packet
- // that continues in the next segment
-
-
- if (startIndex < everything.byteLength) {
- buffer.set(everything.subarray(startIndex), 0);
- bytesInBuffer = everything.byteLength - startIndex;
- }
- };
- /**
- * Passes identified M2TS packets to the TransportParseStream to be parsed
- **/
-
-
- this.flush = function () {
- // If the buffer contains a whole packet when we are being flushed, emit it
- // and empty the buffer. Otherwise hold onto the data because it may be
- // important for decoding the next segment
- if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) {
- this.trigger('data', buffer);
- bytesInBuffer = 0;
- }
-
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
-
- this.reset = function () {
- bytesInBuffer = 0;
- this.trigger('reset');
- };
- };
-
- _TransportPacketStream.prototype = new stream();
- /**
- * Accepts an MP2T TransportPacketStream and emits data events with parsed
- * forms of the individual transport stream packets.
- */
-
- _TransportParseStream = function TransportParseStream() {
- var parsePsi, parsePat, parsePmt, self;
-
- _TransportParseStream.prototype.init.call(this);
-
- self = this;
- this.packetsWaitingForPmt = [];
- this.programMapTable = undefined;
-
- parsePsi = function parsePsi(payload, psi) {
- var offset = 0; // PSI packets may be split into multiple sections and those
- // sections may be split into multiple packets. If a PSI
- // section starts in this packet, the payload_unit_start_indicator
- // will be true and the first byte of the payload will indicate
- // the offset from the current position to the start of the
- // section.
-
- if (psi.payloadUnitStartIndicator) {
- offset += payload[offset] + 1;
- }
-
- if (psi.type === 'pat') {
- parsePat(payload.subarray(offset), psi);
- } else {
- parsePmt(payload.subarray(offset), psi);
- }
- };
-
- parsePat = function parsePat(payload, pat) {
- pat.section_number = payload[7]; // eslint-disable-line camelcase
-
- pat.last_section_number = payload[8]; // eslint-disable-line camelcase
- // skip the PSI header and parse the first PMT entry
-
- self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
- pat.pmtPid = self.pmtPid;
- };
- /**
- * Parse out the relevant fields of a Program Map Table (PMT).
- * @param payload {Uint8Array} the PMT-specific portion of an MP2T
- * packet. The first byte in this array should be the table_id
- * field.
- * @param pmt {object} the object that should be decorated with
- * fields parsed from the PMT.
- */
-
-
- parsePmt = function parsePmt(payload, pmt) {
- var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
- // take effect. We don't believe this should ever be the case
- // for HLS but we'll ignore "forward" PMT declarations if we see
- // them. Future PMT declarations have the current_next_indicator
- // set to zero.
-
- if (!(payload[5] & 0x01)) {
- return;
- } // overwrite any existing program map table
-
-
- self.programMapTable = {
- video: null,
- audio: null,
- 'timed-metadata': {}
- }; // the mapping table ends at the end of the current section
-
- sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
- tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
- // long the program info descriptors are
-
- programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
-
- offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- var streamType = payload[offset];
- var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
- // TODO: should this be done for metadata too? for now maintain behavior of
- // multiple metadata streams
-
- if (streamType === streamTypes.H264_STREAM_TYPE && self.programMapTable.video === null) {
- self.programMapTable.video = pid;
- } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
- self.programMapTable.audio = pid;
- } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
- // map pid to stream type for metadata streams
- self.programMapTable['timed-metadata'][pid] = streamType;
- } // move to the next table entry
- // skip past the elementary stream descriptors, if present
-
-
- offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
- } // record the map on the packet as well
-
-
- pmt.programMapTable = self.programMapTable;
- };
- /**
- * Deliver a new MP2T packet to the next stream in the pipeline.
- */
-
-
- this.push = function (packet) {
- var result = {},
- offset = 4;
- result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
-
- result.pid = packet[1] & 0x1f;
- result.pid <<= 8;
- result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
- // fifth byte of the TS packet header. The adaptation field is
- // used to add stuffing to PES packets that don't fill a complete
- // TS packet, and to specify some forms of timing and control data
- // that we do not currently use.
-
- if ((packet[3] & 0x30) >>> 4 > 0x01) {
- offset += packet[offset] + 1;
- } // parse the rest of the packet based on the type
-
-
- if (result.pid === 0) {
- result.type = 'pat';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result);
- } else if (result.pid === this.pmtPid) {
- result.type = 'pmt';
- parsePsi(packet.subarray(offset), result);
- this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
-
- while (this.packetsWaitingForPmt.length) {
- this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
- }
- } else if (this.programMapTable === undefined) {
- // When we have not seen a PMT yet, defer further processing of
- // PES packets until one has been parsed
- this.packetsWaitingForPmt.push([packet, offset, result]);
- } else {
- this.processPes_(packet, offset, result);
- }
- };
-
- this.processPes_ = function (packet, offset, result) {
- // set the appropriate stream type
- if (result.pid === this.programMapTable.video) {
- result.streamType = streamTypes.H264_STREAM_TYPE;
- } else if (result.pid === this.programMapTable.audio) {
- result.streamType = streamTypes.ADTS_STREAM_TYPE;
- } else {
- // if not video or audio, it is timed-metadata or unknown
- // if unknown, streamType will be undefined
- result.streamType = this.programMapTable['timed-metadata'][result.pid];
- }
-
- result.type = 'pes';
- result.data = packet.subarray(offset);
- this.trigger('data', result);
- };
- };
-
- _TransportParseStream.prototype = new stream();
- _TransportParseStream.STREAM_TYPES = {
- h264: 0x1b,
- adts: 0x0f
- };
- /**
- * Reconsistutes program elementary stream (PES) packets from parsed
- * transport stream packets. That is, if you pipe an
- * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
- * events will be events which capture the bytes for individual PES
- * packets plus relevant metadata that has been extracted from the
- * container.
- */
-
- _ElementaryStream = function ElementaryStream() {
- var self = this,
- // PES packet fragments
- video = {
- data: [],
- size: 0
- },
- audio = {
- data: [],
- size: 0
- },
- timedMetadata = {
- data: [],
- size: 0
- },
- programMapTable,
- parsePes = function parsePes(payload, pes) {
- var ptsDtsFlags; // get the packet length, this will be 0 for video
-
- pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
-
- pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
- // and a DTS value. Determine what combination of values is
- // available to work with.
-
- ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
- // performs all bitwise operations on 32-bit integers but javascript
- // supports a much greater range (52-bits) of integer using standard
- // mathematical operations.
- // We construct a 31-bit value using bitwise operators over the 31
- // most significant bits and then multiply by 4 (equal to a left-shift
- // of 2) before we add the final 2 least significant bits of the
- // timestamp (equal to an OR.)
-
- if (ptsDtsFlags & 0xC0) {
- // the PTS and DTS are not written out directly. For information
- // on how they are encoded, see
- // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
- pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
- pes.pts *= 4; // Left shift by 2
-
- pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
-
- pes.dts = pes.pts;
-
- if (ptsDtsFlags & 0x40) {
- pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
- pes.dts *= 4; // Left shift by 2
-
- pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
- }
- } // the data section starts immediately after the PES header.
- // pes_header_data_length specifies the number of header bytes
- // that follow the last byte of the field.
-
-
- pes.data = payload.subarray(9 + payload[8]);
- },
-
- /**
- * Pass completely parsed PES packets to the next stream in the pipeline
- **/
- flushStream = function flushStream(stream, type, forceFlush) {
- var packetData = new Uint8Array(stream.size),
- event = {
- type: type
- },
- i = 0,
- offset = 0,
- packetFlushable = false,
- fragment; // do nothing if there is not enough buffered data for a complete
- // PES header
-
- if (!stream.data.length || stream.size < 9) {
- return;
- }
-
- event.trackId = stream.data[0].pid; // reassemble the packet
-
- for (i = 0; i < stream.data.length; i++) {
- fragment = stream.data[i];
- packetData.set(fragment.data, offset);
- offset += fragment.data.byteLength;
- } // parse assembled packet's PES header
-
-
- parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
- // check that there is enough stream data to fill the packet
-
- packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
-
- if (forceFlush || packetFlushable) {
- stream.size = 0;
- stream.data.length = 0;
- } // only emit packets that are complete. this is to avoid assembling
- // incomplete PES packets due to poor segmentation
-
-
- if (packetFlushable) {
- self.trigger('data', event);
- }
- };
-
- _ElementaryStream.prototype.init.call(this);
- /**
- * Identifies M2TS packet types and parses PES packets using metadata
- * parsed from the PMT
- **/
-
-
- this.push = function (data) {
- ({
- pat: function pat() {// we have to wait for the PMT to arrive as well before we
- // have any meaningful metadata
- },
- pes: function pes() {
- var stream, streamType;
-
- switch (data.streamType) {
- case streamTypes.H264_STREAM_TYPE:
- stream = video;
- streamType = 'video';
- break;
-
- case streamTypes.ADTS_STREAM_TYPE:
- stream = audio;
- streamType = 'audio';
- break;
-
- case streamTypes.METADATA_STREAM_TYPE:
- stream = timedMetadata;
- streamType = 'timed-metadata';
- break;
-
- default:
- // ignore unknown stream types
- return;
- } // if a new packet is starting, we can flush the completed
- // packet
-
-
- if (data.payloadUnitStartIndicator) {
- flushStream(stream, streamType, true);
- } // buffer this fragment until we are sure we've received the
- // complete payload
-
-
- stream.data.push(data);
- stream.size += data.data.byteLength;
- },
- pmt: function pmt() {
- var event = {
- type: 'metadata',
- tracks: []
- };
- programMapTable = data.programMapTable; // translate audio and video streams to tracks
-
- if (programMapTable.video !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.video,
- codec: 'avc',
- type: 'video'
- });
- }
-
- if (programMapTable.audio !== null) {
- event.tracks.push({
- timelineStartInfo: {
- baseMediaDecodeTime: 0
- },
- id: +programMapTable.audio,
- codec: 'adts',
- type: 'audio'
- });
- }
-
- self.trigger('data', event);
- }
- })[data.type]();
- };
-
- this.reset = function () {
- video.size = 0;
- video.data.length = 0;
- audio.size = 0;
- audio.data.length = 0;
- this.trigger('reset');
- };
- /**
- * Flush any remaining input. Video PES packets may be of variable
- * length. Normally, the start of a new video packet can trigger the
- * finalization of the previous packet. That is not possible if no
- * more video is forthcoming, however. In that case, some other
- * mechanism (like the end of the file) has to be employed. When it is
- * clear that no additional data is forthcoming, calling this method
- * will flush the buffered packets.
- */
-
-
- this.flushStreams_ = function () {
- // !!THIS ORDER IS IMPORTANT!!
- // video first then audio
- flushStream(video, 'video');
- flushStream(audio, 'audio');
- flushStream(timedMetadata, 'timed-metadata');
- };
-
- this.flush = function () {
- this.flushStreams_();
- this.trigger('done');
- };
- };
-
- _ElementaryStream.prototype = new stream();
- var m2ts = {
- PAT_PID: 0x0000,
- MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH,
- TransportPacketStream: _TransportPacketStream,
- TransportParseStream: _TransportParseStream,
- ElementaryStream: _ElementaryStream,
- TimestampRolloverStream: TimestampRolloverStream$1,
- CaptionStream: captionStream.CaptionStream,
- Cea608Stream: captionStream.Cea608Stream,
- Cea708Stream: captionStream.Cea708Stream,
- MetadataStream: metadataStream
- };
-
- for (var type in streamTypes) {
- if (streamTypes.hasOwnProperty(type)) {
- m2ts[type] = streamTypes[type];
- }
- }
-
- var m2ts_1 = m2ts;
-
- var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
-
- var _AdtsStream;
-
- var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
- /*
- * Accepts a ElementaryStream and emits data events with parsed
- * AAC Audio Frames of the individual packets. Input audio in ADTS
- * format is unpacked and re-emitted as AAC frames.
- *
- * @see http://wiki.multimedia.cx/index.php?title=ADTS
- * @see http://wiki.multimedia.cx/?title=Understanding_AAC
- */
-
- _AdtsStream = function AdtsStream(handlePartialSegments) {
- var buffer,
- frameNum = 0;
-
- _AdtsStream.prototype.init.call(this);
-
- this.push = function (packet) {
- var i = 0,
- frameLength,
- protectionSkipBytes,
- frameEnd,
- oldBuffer,
- sampleCount,
- adtsFrameDuration;
-
- if (!handlePartialSegments) {
- frameNum = 0;
- }
-
- if (packet.type !== 'audio') {
- // ignore non-audio data
- return;
- } // Prepend any data in the buffer to the input data so that we can parse
- // aac frames the cross a PES packet boundary
-
-
- if (buffer) {
- oldBuffer = buffer;
- buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
- buffer.set(oldBuffer);
- buffer.set(packet.data, oldBuffer.byteLength);
- } else {
- buffer = packet.data;
- } // unpack any ADTS frames which have been fully received
- // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
-
-
- while (i + 5 < buffer.length) {
- // Look for the start of an ADTS header..
- if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- } // The protection skip bit tells us if we have 2 bytes of CRC data at the
- // end of the ADTS header
-
-
- protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
- // end of the sync sequence
-
- frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
- sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
- adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2];
- frameEnd = i + frameLength; // If we don't have enough data to actually finish this ADTS frame, return
- // and wait for more data
-
- if (buffer.byteLength < frameEnd) {
- return;
- } // Otherwise, deliver the complete AAC frame
-
-
- this.trigger('data', {
- pts: packet.pts + frameNum * adtsFrameDuration,
- dts: packet.dts + frameNum * adtsFrameDuration,
- sampleCount: sampleCount,
- audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
- channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
- samplerate: ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2],
- samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
- // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
- samplesize: 16,
- data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
- });
- frameNum++; // If the buffer is empty, clear it and return
-
- if (buffer.byteLength === frameEnd) {
- buffer = undefined;
- return;
- } // Remove the finished frame from the buffer and start the process again
-
-
- buffer = buffer.subarray(frameEnd);
- }
- };
-
- this.flush = function () {
- frameNum = 0;
- this.trigger('done');
- };
-
- this.reset = function () {
- buffer = void 0;
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- buffer = void 0;
- this.trigger('endedtimeline');
- };
- };
-
- _AdtsStream.prototype = new stream();
- var adts = _AdtsStream;
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var ExpGolomb;
- /**
- * Parser for exponential Golomb codes, a variable-bitwidth number encoding
- * scheme used by h264.
- */
-
- ExpGolomb = function ExpGolomb(workingData) {
- var // the number of bytes left to examine in workingData
- workingBytesAvailable = workingData.byteLength,
- // the current word being examined
- workingWord = 0,
- // :uint
- // the number of bits left to examine in the current word
- workingBitsAvailable = 0; // :uint;
- // ():uint
-
- this.length = function () {
- return 8 * workingBytesAvailable;
- }; // ():uint
-
-
- this.bitsAvailable = function () {
- return 8 * workingBytesAvailable + workingBitsAvailable;
- }; // ():void
-
-
- this.loadWord = function () {
- var position = workingData.byteLength - workingBytesAvailable,
- workingBytes = new Uint8Array(4),
- availableBytes = Math.min(4, workingBytesAvailable);
-
- if (availableBytes === 0) {
- throw new Error('no bytes available');
- }
-
- workingBytes.set(workingData.subarray(position, position + availableBytes));
- workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
-
- workingBitsAvailable = availableBytes * 8;
- workingBytesAvailable -= availableBytes;
- }; // (count:int):void
-
-
- this.skipBits = function (count) {
- var skipBytes; // :int
-
- if (workingBitsAvailable > count) {
- workingWord <<= count;
- workingBitsAvailable -= count;
- } else {
- count -= workingBitsAvailable;
- skipBytes = Math.floor(count / 8);
- count -= skipBytes * 8;
- workingBytesAvailable -= skipBytes;
- this.loadWord();
- workingWord <<= count;
- workingBitsAvailable -= count;
- }
- }; // (size:int):uint
-
-
- this.readBits = function (size) {
- var bits = Math.min(workingBitsAvailable, size),
- // :uint
- valu = workingWord >>> 32 - bits; // :uint
- // if size > 31, handle error
-
- workingBitsAvailable -= bits;
-
- if (workingBitsAvailable > 0) {
- workingWord <<= bits;
- } else if (workingBytesAvailable > 0) {
- this.loadWord();
- }
-
- bits = size - bits;
-
- if (bits > 0) {
- return valu << bits | this.readBits(bits);
- }
-
- return valu;
- }; // ():uint
-
-
- this.skipLeadingZeros = function () {
- var leadingZeroCount; // :uint
-
- for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
- if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
- // the first bit of working word is 1
- workingWord <<= leadingZeroCount;
- workingBitsAvailable -= leadingZeroCount;
- return leadingZeroCount;
- }
- } // we exhausted workingWord and still have not found a 1
-
-
- this.loadWord();
- return leadingZeroCount + this.skipLeadingZeros();
- }; // ():void
-
-
- this.skipUnsignedExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():void
-
-
- this.skipExpGolomb = function () {
- this.skipBits(1 + this.skipLeadingZeros());
- }; // ():uint
-
-
- this.readUnsignedExpGolomb = function () {
- var clz = this.skipLeadingZeros(); // :uint
-
- return this.readBits(clz + 1) - 1;
- }; // ():int
-
-
- this.readExpGolomb = function () {
- var valu = this.readUnsignedExpGolomb(); // :int
-
- if (0x01 & valu) {
- // the number is odd if the low order bit is set
- return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
- }
-
- return -1 * (valu >>> 1); // divide by two then make it negative
- }; // Some convenience functions
- // :Boolean
-
-
- this.readBoolean = function () {
- return this.readBits(1) === 1;
- }; // ():int
-
-
- this.readUnsignedByte = function () {
- return this.readBits(8);
- };
-
- this.loadWord();
- };
-
- var expGolomb = ExpGolomb;
-
- var _H264Stream, _NalByteStream;
-
- var PROFILES_WITH_OPTIONAL_SPS_DATA;
- /**
- * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
- */
-
- _NalByteStream = function NalByteStream() {
- var syncPoint = 0,
- i,
- buffer;
-
- _NalByteStream.prototype.init.call(this);
- /*
- * Scans a byte stream and triggers a data event with the NAL units found.
- * @param {Object} data Event received from H264Stream
- * @param {Uint8Array} data.data The h264 byte stream to be scanned
- *
- * @see H264Stream.push
- */
-
-
- this.push = function (data) {
- var swapBuffer;
-
- if (!buffer) {
- buffer = data.data;
- } else {
- swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
- swapBuffer.set(buffer);
- swapBuffer.set(data.data, buffer.byteLength);
- buffer = swapBuffer;
- }
-
- var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
- // scan for NAL unit boundaries
- // a match looks like this:
- // 0 0 1 .. NAL .. 0 0 1
- // ^ sync point ^ i
- // or this:
- // 0 0 1 .. NAL .. 0 0 0
- // ^ sync point ^ i
- // advance the sync point to a NAL start, if necessary
-
- for (; syncPoint < len - 3; syncPoint++) {
- if (buffer[syncPoint + 2] === 1) {
- // the sync point is properly aligned
- i = syncPoint + 5;
- break;
- }
- }
-
- while (i < len) {
- // look at the current byte to determine if we've hit the end of
- // a NAL unit boundary
- switch (buffer[i]) {
- case 0:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0) {
- i += 2;
- break;
- } else if (buffer[i - 2] !== 0) {
- i++;
- break;
- } // deliver the NAL unit if it isn't empty
-
-
- if (syncPoint + 3 !== i - 2) {
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- } // drop trailing zeroes
-
-
- do {
- i++;
- } while (buffer[i] !== 1 && i < len);
-
- syncPoint = i - 2;
- i += 3;
- break;
-
- case 1:
- // skip past non-sync sequences
- if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
- i += 3;
- break;
- } // deliver the NAL unit
-
-
- this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
- syncPoint = i - 2;
- i += 3;
- break;
-
- default:
- // the current byte isn't a one or zero, so it cannot be part
- // of a sync sequence
- i += 3;
- break;
- }
- } // filter out the NAL units that were delivered
-
-
- buffer = buffer.subarray(syncPoint);
- i -= syncPoint;
- syncPoint = 0;
- };
-
- this.reset = function () {
- buffer = null;
- syncPoint = 0;
- this.trigger('reset');
- };
-
- this.flush = function () {
- // deliver the last buffered NAL unit
- if (buffer && buffer.byteLength > 3) {
- this.trigger('data', buffer.subarray(syncPoint + 3));
- } // reset the stream state
-
-
- buffer = null;
- syncPoint = 0;
- this.trigger('done');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline');
- };
- };
-
- _NalByteStream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the SPS
- // see Recommendation ITU-T H.264 (4/2013),
- // 7.3.2.1.1 Sequence parameter set data syntax
-
- PROFILES_WITH_OPTIONAL_SPS_DATA = {
- 100: true,
- 110: true,
- 122: true,
- 244: true,
- 44: true,
- 83: true,
- 86: true,
- 118: true,
- 128: true,
- 138: true,
- 139: true,
- 134: true
- };
- /**
- * Accepts input from a ElementaryStream and produces H.264 NAL unit data
- * events.
- */
-
- _H264Stream = function H264Stream() {
- var nalByteStream = new _NalByteStream(),
- self,
- trackId,
- currentPts,
- currentDts,
- discardEmulationPreventionBytes,
- readSequenceParameterSet,
- skipScalingList;
-
- _H264Stream.prototype.init.call(this);
-
- self = this;
- /*
- * Pushes a packet from a stream onto the NalByteStream
- *
- * @param {Object} packet - A packet received from a stream
- * @param {Uint8Array} packet.data - The raw bytes of the packet
- * @param {Number} packet.dts - Decode timestamp of the packet
- * @param {Number} packet.pts - Presentation timestamp of the packet
- * @param {Number} packet.trackId - The id of the h264 track this packet came from
- * @param {('video'|'audio')} packet.type - The type of packet
- *
- */
-
- this.push = function (packet) {
- if (packet.type !== 'video') {
- return;
- }
-
- trackId = packet.trackId;
- currentPts = packet.pts;
- currentDts = packet.dts;
- nalByteStream.push(packet);
- };
- /*
- * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
- * for the NALUs to the next stream component.
- * Also, preprocess caption and sequence parameter NALUs.
- *
- * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
- * @see NalByteStream.push
- */
-
-
- nalByteStream.on('data', function (data) {
- var event = {
- trackId: trackId,
- pts: currentPts,
- dts: currentDts,
- data: data
- };
-
- switch (data[0] & 0x1f) {
- case 0x05:
- event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
- break;
-
- case 0x06:
- event.nalUnitType = 'sei_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- break;
-
- case 0x07:
- event.nalUnitType = 'seq_parameter_set_rbsp';
- event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
- event.config = readSequenceParameterSet(event.escapedRBSP);
- break;
-
- case 0x08:
- event.nalUnitType = 'pic_parameter_set_rbsp';
- break;
-
- case 0x09:
- event.nalUnitType = 'access_unit_delimiter_rbsp';
- break;
- } // This triggers data on the H264Stream
-
-
- self.trigger('data', event);
- });
- nalByteStream.on('done', function () {
- self.trigger('done');
- });
- nalByteStream.on('partialdone', function () {
- self.trigger('partialdone');
- });
- nalByteStream.on('reset', function () {
- self.trigger('reset');
- });
- nalByteStream.on('endedtimeline', function () {
- self.trigger('endedtimeline');
- });
-
- this.flush = function () {
- nalByteStream.flush();
- };
-
- this.partialFlush = function () {
- nalByteStream.partialFlush();
- };
-
- this.reset = function () {
- nalByteStream.reset();
- };
-
- this.endTimeline = function () {
- nalByteStream.endTimeline();
- };
- /**
- * Advance the ExpGolomb decoder past a scaling list. The scaling
- * list is optionally transmitted as part of a sequence parameter
- * set and is not relevant to transmuxing.
- * @param count {number} the number of entries in this scaling list
- * @param expGolombDecoder {object} an ExpGolomb pointed to the
- * start of a scaling list
- * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
- */
-
-
- skipScalingList = function skipScalingList(count, expGolombDecoder) {
- var lastScale = 8,
- nextScale = 8,
- j,
- deltaScale;
-
- for (j = 0; j < count; j++) {
- if (nextScale !== 0) {
- deltaScale = expGolombDecoder.readExpGolomb();
- nextScale = (lastScale + deltaScale + 256) % 256;
- }
-
- lastScale = nextScale === 0 ? lastScale : nextScale;
- }
- };
- /**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
-
- discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
- var length = data.byteLength,
- emulationPreventionBytesPositions = [],
- i = 1,
- newLength,
- newData; // Find all `Emulation Prevention Bytes`
-
- while (i < length - 2) {
- if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
- emulationPreventionBytesPositions.push(i + 2);
- i += 2;
- } else {
- i++;
- }
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (emulationPreventionBytesPositions.length === 0) {
- return data;
- } // Create a new array to hold the NAL unit data
-
-
- newLength = length - emulationPreventionBytesPositions.length;
- newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === emulationPreventionBytesPositions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- emulationPreventionBytesPositions.shift();
- }
-
- newData[i] = data[sourceIndex];
- }
-
- return newData;
- };
- /**
- * Read a sequence parameter set and return some interesting video
- * properties. A sequence parameter set is the H264 metadata that
- * describes the properties of upcoming video frames.
- * @param data {Uint8Array} the bytes of a sequence parameter set
- * @return {object} an object with configuration parsed from the
- * sequence parameter set, including the dimensions of the
- * associated video frames.
- */
-
-
- readSequenceParameterSet = function readSequenceParameterSet(data) {
- var frameCropLeftOffset = 0,
- frameCropRightOffset = 0,
- frameCropTopOffset = 0,
- frameCropBottomOffset = 0,
- sarScale = 1,
- expGolombDecoder,
- profileIdc,
- levelIdc,
- profileCompatibility,
- chromaFormatIdc,
- picOrderCntType,
- numRefFramesInPicOrderCntCycle,
- picWidthInMbsMinus1,
- picHeightInMapUnitsMinus1,
- frameMbsOnlyFlag,
- scalingListCount,
- sarRatio,
- aspectRatioIdc,
- i;
- expGolombDecoder = new expGolomb(data);
- profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
-
- profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
-
- levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
-
- expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
- // some profiles have more optional data we don't need
-
- if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
- chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
-
- if (chromaFormatIdc === 3) {
- expGolombDecoder.skipBits(1); // separate_colour_plane_flag
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
-
- expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
-
- expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
-
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_matrix_present_flag
- scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
-
- for (i = 0; i < scalingListCount; i++) {
- if (expGolombDecoder.readBoolean()) {
- // seq_scaling_list_present_flag[ i ]
- if (i < 6) {
- skipScalingList(16, expGolombDecoder);
- } else {
- skipScalingList(64, expGolombDecoder);
- }
- }
- }
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
-
- picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
-
- if (picOrderCntType === 0) {
- expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
- } else if (picOrderCntType === 1) {
- expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
-
- expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
-
- expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
-
- numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
-
- for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
- expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
- }
- }
-
- expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
-
- expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
-
- picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
- frameMbsOnlyFlag = expGolombDecoder.readBits(1);
-
- if (frameMbsOnlyFlag === 0) {
- expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
- }
-
- expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
-
- if (expGolombDecoder.readBoolean()) {
- // frame_cropping_flag
- frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
- frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
- }
-
- if (expGolombDecoder.readBoolean()) {
- // vui_parameters_present_flag
- if (expGolombDecoder.readBoolean()) {
- // aspect_ratio_info_present_flag
- aspectRatioIdc = expGolombDecoder.readUnsignedByte();
-
- switch (aspectRatioIdc) {
- case 1:
- sarRatio = [1, 1];
- break;
-
- case 2:
- sarRatio = [12, 11];
- break;
-
- case 3:
- sarRatio = [10, 11];
- break;
-
- case 4:
- sarRatio = [16, 11];
- break;
-
- case 5:
- sarRatio = [40, 33];
- break;
-
- case 6:
- sarRatio = [24, 11];
- break;
-
- case 7:
- sarRatio = [20, 11];
- break;
-
- case 8:
- sarRatio = [32, 11];
- break;
-
- case 9:
- sarRatio = [80, 33];
- break;
-
- case 10:
- sarRatio = [18, 11];
- break;
-
- case 11:
- sarRatio = [15, 11];
- break;
-
- case 12:
- sarRatio = [64, 33];
- break;
-
- case 13:
- sarRatio = [160, 99];
- break;
-
- case 14:
- sarRatio = [4, 3];
- break;
-
- case 15:
- sarRatio = [3, 2];
- break;
-
- case 16:
- sarRatio = [2, 1];
- break;
-
- case 255:
- {
- sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
- break;
- }
- }
-
- if (sarRatio) {
- sarScale = sarRatio[0] / sarRatio[1];
- }
- }
- }
-
- return {
- profileIdc: profileIdc,
- levelIdc: levelIdc,
- profileCompatibility: profileCompatibility,
- width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
- height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
- sarRatio: sarRatio
- };
- };
- };
-
- _H264Stream.prototype = new stream();
- var h264 = {
- H264Stream: _H264Stream,
- NalByteStream: _NalByteStream
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- *
- * Utilities to detect basic properties and metadata about Aac data.
- */
-
- var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
-
- var parseId3TagSize = function parseId3TagSize(header, byteIndex) {
- var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
- flags = header[byteIndex + 5],
- footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
-
- returnSize = returnSize >= 0 ? returnSize : 0;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
- };
-
- var getId3Offset = function getId3Offset(data, offset) {
- if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
- return offset;
- }
-
- offset += parseId3TagSize(data, offset);
- return getId3Offset(data, offset);
- }; // TODO: use vhs-utils
-
-
- var isLikelyAacData = function isLikelyAacData(data) {
- var offset = getId3Offset(data, 0);
- return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
- // is not mp3 data but aac data.
- (data[offset + 1] & 0x16) === 0x10;
- };
-
- var parseSyncSafeInteger$1 = function parseSyncSafeInteger(data) {
- return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
- }; // return a percent-encoded representation of the specified byte range
- // @see http://en.wikipedia.org/wiki/Percent-encoding
-
-
- var percentEncode$1 = function percentEncode(bytes, start, end) {
- var i,
- result = '';
-
- for (i = start; i < end; i++) {
- result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
- }
-
- return result;
- }; // return the string representation of the specified byte range,
- // interpreted as ISO-8859-1.
-
-
- var parseIso88591$1 = function parseIso88591(bytes, start, end) {
- return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
- };
-
- var parseAdtsSize = function parseAdtsSize(header, byteIndex) {
- var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
- middle = header[byteIndex + 4] << 3,
- highTwo = header[byteIndex + 3] & 0x3 << 11;
- return highTwo | middle | lowThree;
- };
-
- var parseType = function parseType(header, byteIndex) {
- if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
- return 'timed-metadata';
- } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
- return 'audio';
- }
-
- return null;
- };
-
- var parseSampleRate = function parseSampleRate(packet) {
- var i = 0;
-
- while (i + 5 < packet.length) {
- if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
- // If a valid header was not found, jump one forward and attempt to
- // find a valid ADTS header starting at the next byte
- i++;
- continue;
- }
-
- return ADTS_SAMPLING_FREQUENCIES$1[(packet[i + 2] & 0x3c) >>> 2];
- }
-
- return null;
- };
-
- var parseAacTimestamp = function parseAacTimestamp(packet) {
- var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
-
- frameStart = 10;
-
- if (packet[5] & 0x40) {
- // advance the frame start past the extended header
- frameStart += 4; // header size field
-
- frameStart += parseSyncSafeInteger$1(packet.subarray(10, 14));
- } // parse one or more ID3 frames
- // http://id3.org/id3v2.3.0#ID3v2_frame_overview
-
-
- do {
- // determine the number of bytes in this frame
- frameSize = parseSyncSafeInteger$1(packet.subarray(frameStart + 4, frameStart + 8));
-
- if (frameSize < 1) {
- return null;
- }
-
- frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
-
- if (frameHeader === 'PRIV') {
- frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
-
- for (var i = 0; i < frame.byteLength; i++) {
- if (frame[i] === 0) {
- var owner = parseIso88591$1(frame, 0, i);
-
- if (owner === 'com.apple.streaming.transportStreamTimestamp') {
- var d = frame.subarray(i + 1);
- var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
- size *= 4;
- size += d[7] & 0x03;
- return size;
- }
-
- break;
- }
- }
- }
-
- frameStart += 10; // advance past the frame header
-
- frameStart += frameSize; // advance past the frame body
- } while (frameStart < packet.byteLength);
-
- return null;
- };
-
- var utils = {
- isLikelyAacData: isLikelyAacData,
- parseId3TagSize: parseId3TagSize,
- parseAdtsSize: parseAdtsSize,
- parseType: parseType,
- parseSampleRate: parseSampleRate,
- parseAacTimestamp: parseAacTimestamp
- };
-
- var _AacStream;
- /**
- * Splits an incoming stream of binary data into ADTS and ID3 Frames.
- */
-
-
- _AacStream = function AacStream() {
- var everything = new Uint8Array(),
- timeStamp = 0;
-
- _AacStream.prototype.init.call(this);
-
- this.setTimestamp = function (timestamp) {
- timeStamp = timestamp;
- };
-
- this.push = function (bytes) {
- var frameSize = 0,
- byteIndex = 0,
- bytesLeft,
- chunk,
- packet,
- tempLength; // If there are bytes remaining from the last segment, prepend them to the
- // bytes that were pushed in
-
- if (everything.length) {
- tempLength = everything.length;
- everything = new Uint8Array(bytes.byteLength + tempLength);
- everything.set(everything.subarray(0, tempLength));
- everything.set(bytes, tempLength);
- } else {
- everything = bytes;
- }
-
- while (everything.length - byteIndex >= 3) {
- if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
- // Exit early because we don't have enough to parse
- // the ID3 tag header
- if (everything.length - byteIndex < 10) {
- break;
- } // check framesize
-
-
- frameSize = utils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
- // Add to byteIndex to support multiple ID3 tags in sequence
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- chunk = {
- type: 'timed-metadata',
- data: everything.subarray(byteIndex, byteIndex + frameSize)
- };
- this.trigger('data', chunk);
- byteIndex += frameSize;
- continue;
- } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
- // Exit early because we don't have enough to parse
- // the ADTS frame header
- if (everything.length - byteIndex < 7) {
- break;
- }
-
- frameSize = utils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
- // to emit a full packet
-
- if (byteIndex + frameSize > everything.length) {
- break;
- }
-
- packet = {
- type: 'audio',
- data: everything.subarray(byteIndex, byteIndex + frameSize),
- pts: timeStamp,
- dts: timeStamp
- };
- this.trigger('data', packet);
- byteIndex += frameSize;
- continue;
- }
-
- byteIndex++;
- }
-
- bytesLeft = everything.length - byteIndex;
-
- if (bytesLeft > 0) {
- everything = everything.subarray(byteIndex);
- } else {
- everything = new Uint8Array();
- }
- };
-
- this.reset = function () {
- everything = new Uint8Array();
- this.trigger('reset');
- };
-
- this.endTimeline = function () {
- everything = new Uint8Array();
- this.trigger('endedtimeline');
- };
- };
-
- _AacStream.prototype = new stream();
- var aac = _AacStream;
-
- // constants
- var AUDIO_PROPERTIES = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
- var audioProperties = AUDIO_PROPERTIES;
-
- var VIDEO_PROPERTIES = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
- var videoProperties = VIDEO_PROPERTIES;
-
- var H264Stream = h264.H264Stream;
- var isLikelyAacData$1 = utils.isLikelyAacData;
- var ONE_SECOND_IN_TS$3 = clock.ONE_SECOND_IN_TS; // object types
-
- var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
- /**
- * Compare two arrays (even typed) for same-ness
- */
-
-
- var arrayEquals = function arrayEquals(a, b) {
- var i;
-
- if (a.length !== b.length) {
- return false;
- } // compare the value of each element in the array
-
-
- for (i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) {
- return false;
- }
- }
-
- return true;
- };
-
- var generateSegmentTimingInfo = function generateSegmentTimingInfo(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
- var ptsOffsetFromDts = startPts - startDts,
- decodeDuration = endDts - startDts,
- presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
- // however, the player time values will reflect a start from the baseMediaDecodeTime.
- // In order to provide relevant values for the player times, base timing info on the
- // baseMediaDecodeTime and the DTS and PTS durations of the segment.
-
- return {
- start: {
- dts: baseMediaDecodeTime,
- pts: baseMediaDecodeTime + ptsOffsetFromDts
- },
- end: {
- dts: baseMediaDecodeTime + decodeDuration,
- pts: baseMediaDecodeTime + presentationDuration
- },
- prependedContentDuration: prependedContentDuration,
- baseMediaDecodeTime: baseMediaDecodeTime
- };
- };
- /**
- * Constructs a single-track, ISO BMFF media segment from AAC data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
-
- _AudioSegmentStream = function AudioSegmentStream(track, options) {
- var adtsFrames = [],
- sequenceNumber = 0,
- earliestAllowedDts = 0,
- audioAppendStartTs = 0,
- videoBaseMediaDecodeTime = Infinity;
- options = options || {};
-
- _AudioSegmentStream.prototype.init.call(this);
-
- this.push = function (data) {
- trackDecodeInfo.collectDtsInfo(track, data);
-
- if (track) {
- audioProperties.forEach(function (prop) {
- track[prop] = data[prop];
- });
- } // buffer audio data until end() is called
-
-
- adtsFrames.push(data);
- };
-
- this.setEarliestDts = function (earliestDts) {
- earliestAllowedDts = earliestDts;
- };
-
- this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- videoBaseMediaDecodeTime = baseMediaDecodeTime;
- };
-
- this.setAudioAppendStart = function (timestamp) {
- audioAppendStartTs = timestamp;
- };
-
- this.flush = function () {
- var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
-
- if (adtsFrames.length === 0) {
- this.trigger('done', 'AudioSegmentStream');
- return;
- }
-
- frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
-
- videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
- // samples (that is, adts frames) in the audio data
-
- track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
-
- mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
- adtsFrames = [];
- moof = mp4Generator.moof(sequenceNumber, [track]);
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- trackDecodeInfo.clearDtsInfo(track);
- frameDuration = Math.ceil(ONE_SECOND_IN_TS$3 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
- // tests) on adding the timingInfo event. However, it seems unlikely that there's a
- // valid use-case where an init segment/data should be triggered without associated
- // frames. Leaving for now, but should be looked into.
-
- if (frames.length) {
- segmentDuration = frames.length * frameDuration;
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
- // frame info is in video clock cycles. Convert to match expectation of
- // listeners (that all timestamps will be based on video clock cycles).
- clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
- frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
- this.trigger('timingInfo', {
- start: frames[0].pts,
- end: frames[0].pts + segmentDuration
- });
- }
-
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.trigger('done', 'AudioSegmentStream');
- };
-
- this.reset = function () {
- trackDecodeInfo.clearDtsInfo(track);
- adtsFrames = [];
- this.trigger('reset');
- };
- };
-
- _AudioSegmentStream.prototype = new stream();
- /**
- * Constructs a single-track, ISO BMFF media segment from H264 data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- * @param track {object} track metadata configuration
- * @param options {object} transmuxer options object
- * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
- * gopsToAlignWith list when attempting to align gop pts
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at 0.
- */
-
- _VideoSegmentStream = function VideoSegmentStream(track, options) {
- var sequenceNumber = 0,
- nalUnits = [],
- gopsToAlignWith = [],
- config,
- pps;
- options = options || {};
-
- _VideoSegmentStream.prototype.init.call(this);
-
- delete track.minPTS;
- this.gopCache_ = [];
- /**
- * Constructs a ISO BMFF segment given H264 nalUnits
- * @param {Object} nalUnit A data event representing a nalUnit
- * @param {String} nalUnit.nalUnitType
- * @param {Object} nalUnit.config Properties for a mp4 track
- * @param {Uint8Array} nalUnit.data The nalUnit bytes
- * @see lib/codecs/h264.js
- **/
-
- this.push = function (nalUnit) {
- trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
-
- if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
- config = nalUnit.config;
- track.sps = [nalUnit.data];
- videoProperties.forEach(function (prop) {
- track[prop] = config[prop];
- }, this);
- }
-
- if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
- pps = nalUnit.data;
- track.pps = [nalUnit.data];
- } // buffer video until flush() is called
-
-
- nalUnits.push(nalUnit);
- };
- /**
- * Pass constructed ISO BMFF track and boxes on to the
- * next stream in the pipeline
- **/
-
-
- this.flush = function () {
- var frames,
- gopForFusion,
- gops,
- moof,
- mdat,
- boxes,
- prependedContentDuration = 0,
- firstGop,
- lastGop; // Throw away nalUnits at the start of the byte stream until
- // we find the first AUD
-
- while (nalUnits.length) {
- if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
- break;
- }
-
- nalUnits.shift();
- } // Return early if no video data has been observed
-
-
- if (nalUnits.length === 0) {
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Organize the raw nal-units into arrays that represent
- // higher-level constructs such as frames and gops
- // (group-of-pictures)
-
-
- frames = frameUtils.groupNalsIntoFrames(nalUnits);
- gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
- // a problem since MSE (on Chrome) requires a leading keyframe.
- //
- // We have two approaches to repairing this situation:
- // 1) GOP-FUSION:
- // This is where we keep track of the GOPS (group-of-pictures)
- // from previous fragments and attempt to find one that we can
- // prepend to the current fragment in order to create a valid
- // fragment.
- // 2) KEYFRAME-PULLING:
- // Here we search for the first keyframe in the fragment and
- // throw away all the frames between the start of the fragment
- // and that keyframe. We then extend the duration and pull the
- // PTS of the keyframe forward so that it covers the time range
- // of the frames that were disposed of.
- //
- // #1 is far prefereable over #2 which can cause "stuttering" but
- // requires more things to be just right.
-
- if (!gops[0][0].keyFrame) {
- // Search for a gop for fusion from our gopCache
- gopForFusion = this.getGopForFusion_(nalUnits[0], track);
-
- if (gopForFusion) {
- // in order to provide more accurate timing information about the segment, save
- // the number of seconds prepended to the original segment due to GOP fusion
- prependedContentDuration = gopForFusion.duration;
- gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
- // new gop at the beginning
-
- gops.byteLength += gopForFusion.byteLength;
- gops.nalCount += gopForFusion.nalCount;
- gops.pts = gopForFusion.pts;
- gops.dts = gopForFusion.dts;
- gops.duration += gopForFusion.duration;
- } else {
- // If we didn't find a candidate gop fall back to keyframe-pulling
- gops = frameUtils.extendFirstKeyFrame(gops);
- }
- } // Trim gops to align with gopsToAlignWith
-
-
- if (gopsToAlignWith.length) {
- var alignedGops;
-
- if (options.alignGopsAtEnd) {
- alignedGops = this.alignGopsAtEnd_(gops);
- } else {
- alignedGops = this.alignGopsAtStart_(gops);
- }
-
- if (!alignedGops) {
- // save all the nals in the last GOP into the gop cache
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
-
- this.resetStream_();
- this.trigger('done', 'VideoSegmentStream');
- return;
- } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
- // when recalculated before sending off to CoalesceStream
-
-
- trackDecodeInfo.clearDtsInfo(track);
- gops = alignedGops;
- }
-
- trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
- // samples (that is, frames) in the video data
-
- track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
-
- mdat = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
- this.trigger('processedGopsInfo', gops.map(function (gop) {
- return {
- pts: gop.pts,
- dts: gop.dts,
- byteLength: gop.byteLength
- };
- }));
- firstGop = gops[0];
- lastGop = gops[gops.length - 1];
- this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
- this.trigger('timingInfo', {
- start: gops[0].pts,
- end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
- }); // save all the nals in the last GOP into the gop cache
-
- this.gopCache_.unshift({
- gop: gops.pop(),
- pps: track.pps,
- sps: track.sps
- }); // Keep a maximum of 6 GOPs in the cache
-
- this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
-
- nalUnits = [];
- this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
- this.trigger('timelineStartInfo', track.timelineStartInfo);
- moof = mp4Generator.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
- // throwing away hundreds of media segment fragments
-
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
-
- sequenceNumber++;
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- this.resetStream_(); // Continue with the flush process now
-
- this.trigger('done', 'VideoSegmentStream');
- };
-
- this.reset = function () {
- this.resetStream_();
- nalUnits = [];
- this.gopCache_.length = 0;
- gopsToAlignWith.length = 0;
- this.trigger('reset');
- };
-
- this.resetStream_ = function () {
- trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
- // for instance, when we are rendition switching
-
- config = undefined;
- pps = undefined;
- }; // Search for a candidate Gop for gop-fusion from the gop cache and
- // return it or return null if no good candidate was found
-
-
- this.getGopForFusion_ = function (nalUnit) {
- var halfSecond = 45000,
- // Half-a-second in a 90khz clock
- allowableOverlap = 10000,
- // About 3 frames @ 30fps
- nearestDistance = Infinity,
- dtsDistance,
- nearestGopObj,
- currentGop,
- currentGopObj,
- i; // Search for the GOP nearest to the beginning of this nal unit
-
- for (i = 0; i < this.gopCache_.length; i++) {
- currentGopObj = this.gopCache_[i];
- currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
-
- if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
- continue;
- } // Reject Gops that would require a negative baseMediaDecodeTime
-
-
- if (currentGop.dts < track.timelineStartInfo.dts) {
- continue;
- } // The distance between the end of the gop and the start of the nalUnit
-
-
- dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
- // a half-second of the nal unit
-
- if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
- // Always use the closest GOP we found if there is more than
- // one candidate
- if (!nearestGopObj || nearestDistance > dtsDistance) {
- nearestGopObj = currentGopObj;
- nearestDistance = dtsDistance;
- }
- }
- }
-
- if (nearestGopObj) {
- return nearestGopObj.gop;
- }
-
- return null;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the START of the list
-
-
- this.alignGopsAtStart_ = function (gops) {
- var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
- byteLength = gops.byteLength;
- nalCount = gops.nalCount;
- duration = gops.duration;
- alignIndex = gopIndex = 0;
-
- while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- break;
- }
-
- if (gop.pts > align.pts) {
- // this current gop starts after the current gop we want to align on, so increment
- // align index
- alignIndex++;
- continue;
- } // current gop starts before the current gop we want to align on. so increment gop
- // index
-
-
- gopIndex++;
- byteLength -= gop.byteLength;
- nalCount -= gop.nalCount;
- duration -= gop.duration;
- }
-
- if (gopIndex === 0) {
- // no gops to trim
- return gops;
- }
-
- if (gopIndex === gops.length) {
- // all gops trimmed, skip appending all gops
- return null;
- }
-
- alignedGops = gops.slice(gopIndex);
- alignedGops.byteLength = byteLength;
- alignedGops.duration = duration;
- alignedGops.nalCount = nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- }; // trim gop list to the first gop found that has a matching pts with a gop in the list
- // of gopsToAlignWith starting from the END of the list
-
-
- this.alignGopsAtEnd_ = function (gops) {
- var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
- alignIndex = gopsToAlignWith.length - 1;
- gopIndex = gops.length - 1;
- alignEndIndex = null;
- matchFound = false;
-
- while (alignIndex >= 0 && gopIndex >= 0) {
- align = gopsToAlignWith[alignIndex];
- gop = gops[gopIndex];
-
- if (align.pts === gop.pts) {
- matchFound = true;
- break;
- }
-
- if (align.pts > gop.pts) {
- alignIndex--;
- continue;
- }
-
- if (alignIndex === gopsToAlignWith.length - 1) {
- // gop.pts is greater than the last alignment candidate. If no match is found
- // by the end of this loop, we still want to append gops that come after this
- // point
- alignEndIndex = gopIndex;
- }
-
- gopIndex--;
- }
-
- if (!matchFound && alignEndIndex === null) {
- return null;
- }
-
- var trimIndex;
-
- if (matchFound) {
- trimIndex = gopIndex;
- } else {
- trimIndex = alignEndIndex;
- }
-
- if (trimIndex === 0) {
- return gops;
- }
-
- var alignedGops = gops.slice(trimIndex);
- var metadata = alignedGops.reduce(function (total, gop) {
- total.byteLength += gop.byteLength;
- total.duration += gop.duration;
- total.nalCount += gop.nalCount;
- return total;
- }, {
- byteLength: 0,
- duration: 0,
- nalCount: 0
- });
- alignedGops.byteLength = metadata.byteLength;
- alignedGops.duration = metadata.duration;
- alignedGops.nalCount = metadata.nalCount;
- alignedGops.pts = alignedGops[0].pts;
- alignedGops.dts = alignedGops[0].dts;
- return alignedGops;
- };
-
- this.alignGopsWith = function (newGopsToAlignWith) {
- gopsToAlignWith = newGopsToAlignWith;
- };
- };
-
- _VideoSegmentStream.prototype = new stream();
- /**
- * A Stream that can combine multiple streams (ie. audio & video)
- * into a single output segment for MSE. Also supports audio-only
- * and video-only streams.
- * @param options {object} transmuxer options object
- * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
- * in the source; false to adjust the first segment to start at media timeline start.
- */
-
- _CoalesceStream = function CoalesceStream(options, metadataStream) {
- // Number of Tracks per output segment
- // If greater than 1, we combine multiple
- // tracks into a single segment
- this.numberOfTracks = 0;
- this.metadataStream = metadataStream;
- options = options || {};
-
- if (typeof options.remux !== 'undefined') {
- this.remuxTracks = !!options.remux;
- } else {
- this.remuxTracks = true;
- }
-
- if (typeof options.keepOriginalTimestamps === 'boolean') {
- this.keepOriginalTimestamps = options.keepOriginalTimestamps;
- } else {
- this.keepOriginalTimestamps = false;
- }
-
- this.pendingTracks = [];
- this.videoTrack = null;
- this.pendingBoxes = [];
- this.pendingCaptions = [];
- this.pendingMetadata = [];
- this.pendingBytes = 0;
- this.emittedTracks = 0;
-
- _CoalesceStream.prototype.init.call(this); // Take output from multiple
-
-
- this.push = function (output) {
- // buffer incoming captions until the associated video segment
- // finishes
- if (output.text) {
- return this.pendingCaptions.push(output);
- } // buffer incoming id3 tags until the final flush
-
-
- if (output.frames) {
- return this.pendingMetadata.push(output);
- } // Add this track to the list of pending tracks and store
- // important information required for the construction of
- // the final segment
-
-
- this.pendingTracks.push(output.track);
- this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
- // We unshift audio and push video because
- // as of Chrome 75 when switching from
- // one init segment to another if the video
- // mdat does not appear after the audio mdat
- // only audio will play for the duration of our transmux.
-
- if (output.track.type === 'video') {
- this.videoTrack = output.track;
- this.pendingBoxes.push(output.boxes);
- }
-
- if (output.track.type === 'audio') {
- this.audioTrack = output.track;
- this.pendingBoxes.unshift(output.boxes);
- }
- };
- };
-
- _CoalesceStream.prototype = new stream();
-
- _CoalesceStream.prototype.flush = function (flushSource) {
- var offset = 0,
- event = {
- captions: [],
- captionStreams: {},
- metadata: [],
- info: {}
- },
- caption,
- id3,
- initSegment,
- timelineStartPts = 0,
- i;
-
- if (this.pendingTracks.length < this.numberOfTracks) {
- if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
- // Return because we haven't received a flush from a data-generating
- // portion of the segment (meaning that we have only recieved meta-data
- // or captions.)
- return;
- } else if (this.remuxTracks) {
- // Return until we have enough tracks from the pipeline to remux (if we
- // are remuxing audio and video into a single MP4)
- return;
- } else if (this.pendingTracks.length === 0) {
- // In the case where we receive a flush without any data having been
- // received we consider it an emitted track for the purposes of coalescing
- // `done` events.
- // We do this for the case where there is an audio and video track in the
- // segment but no audio data. (seen in several playlists with alternate
- // audio tracks and no audio present in the main TS segments.)
- this.emittedTracks++;
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
-
- return;
- }
- }
-
- if (this.videoTrack) {
- timelineStartPts = this.videoTrack.timelineStartInfo.pts;
- videoProperties.forEach(function (prop) {
- event.info[prop] = this.videoTrack[prop];
- }, this);
- } else if (this.audioTrack) {
- timelineStartPts = this.audioTrack.timelineStartInfo.pts;
- audioProperties.forEach(function (prop) {
- event.info[prop] = this.audioTrack[prop];
- }, this);
- }
-
- if (this.videoTrack || this.audioTrack) {
- if (this.pendingTracks.length === 1) {
- event.type = this.pendingTracks[0].type;
- } else {
- event.type = 'combined';
- }
-
- this.emittedTracks += this.pendingTracks.length;
- initSegment = mp4Generator.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
-
- event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
- // and track definitions
-
- event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
-
- event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
-
- for (i = 0; i < this.pendingBoxes.length; i++) {
- event.data.set(this.pendingBoxes[i], offset);
- offset += this.pendingBoxes[i].byteLength;
- } // Translate caption PTS times into second offsets to match the
- // video timeline for the segment, and add track info
-
-
- for (i = 0; i < this.pendingCaptions.length; i++) {
- caption = this.pendingCaptions[i];
- caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
- caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
- event.captionStreams[caption.stream] = true;
- event.captions.push(caption);
- } // Translate ID3 frame PTS times into second offsets to match the
- // video timeline for the segment
-
-
- for (i = 0; i < this.pendingMetadata.length; i++) {
- id3 = this.pendingMetadata[i];
- id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
- event.metadata.push(id3);
- } // We add this to every single emitted segment even though we only need
- // it for the first
-
-
- event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
-
- this.pendingTracks.length = 0;
- this.videoTrack = null;
- this.pendingBoxes.length = 0;
- this.pendingCaptions.length = 0;
- this.pendingBytes = 0;
- this.pendingMetadata.length = 0; // Emit the built segment
- // We include captions and ID3 tags for backwards compatibility,
- // ideally we should send only video and audio in the data event
-
- this.trigger('data', event); // Emit each caption to the outside world
- // Ideally, this would happen immediately on parsing captions,
- // but we need to ensure that video data is sent back first
- // so that caption timing can be adjusted to match video timing
-
- for (i = 0; i < event.captions.length; i++) {
- caption = event.captions[i];
- this.trigger('caption', caption);
- } // Emit each id3 tag to the outside world
- // Ideally, this would happen immediately on parsing the tag,
- // but we need to ensure that video data is sent back first
- // so that ID3 frame timing can be adjusted to match video timing
-
-
- for (i = 0; i < event.metadata.length; i++) {
- id3 = event.metadata[i];
- this.trigger('id3Frame', id3);
- }
- } // Only emit `done` if all tracks have been flushed and emitted
-
-
- if (this.emittedTracks >= this.numberOfTracks) {
- this.trigger('done');
- this.emittedTracks = 0;
- }
- };
-
- _CoalesceStream.prototype.setRemux = function (val) {
- this.remuxTracks = val;
- };
- /**
- * A Stream that expects MP2T binary data as input and produces
- * corresponding media segments, suitable for use with Media Source
- * Extension (MSE) implementations that support the ISO BMFF byte
- * stream format, like Chrome.
- */
-
-
- _Transmuxer = function Transmuxer(options) {
- var self = this,
- hasFlushed = true,
- videoTrack,
- audioTrack;
-
- _Transmuxer.prototype.init.call(this);
-
- options = options || {};
- this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
- this.transmuxPipeline_ = {};
-
- this.setupAacPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'aac';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.aacStream = new aac();
- pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('audio');
- pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('timed-metadata');
- pipeline.adtsStream = new adts();
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.aacStream;
- pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
- pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
- pipeline.metadataStream.on('timestamp', function (frame) {
- pipeline.aacStream.setTimestamp(frame.timeStamp);
- });
- pipeline.aacStream.on('data', function (data) {
- if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
- return;
- }
-
- audioTrack = audioTrack || {
- timelineStartInfo: {
- baseMediaDecodeTime: self.baseMediaDecodeTime
- },
- codec: 'adts',
- type: 'audio'
- }; // hook up the audio segment stream to the first track with aac data
-
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- };
-
- this.setupTsPipeline = function () {
- var pipeline = {};
- this.transmuxPipeline_ = pipeline;
- pipeline.type = 'ts';
- pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
-
- pipeline.packetStream = new m2ts_1.TransportPacketStream();
- pipeline.parseStream = new m2ts_1.TransportParseStream();
- pipeline.elementaryStream = new m2ts_1.ElementaryStream();
- pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
- pipeline.adtsStream = new adts();
- pipeline.h264Stream = new H264Stream();
- pipeline.captionStream = new m2ts_1.CaptionStream(options);
- pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
- pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
-
- pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
- // demux the streams
-
- pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
- pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
- pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
-
- pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
- pipeline.elementaryStream.on('data', function (data) {
- var i;
-
- if (data.type === 'metadata') {
- i = data.tracks.length; // scan the tracks listed in the metadata
-
- while (i--) {
- if (!videoTrack && data.tracks[i].type === 'video') {
- videoTrack = data.tracks[i];
- videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- } else if (!audioTrack && data.tracks[i].type === 'audio') {
- audioTrack = data.tracks[i];
- audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
- }
- } // hook up the video segment stream to the first track with h264 data
-
-
- if (videoTrack && !pipeline.videoSegmentStream) {
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
- pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
- // When video emits timelineStartInfo data after a flush, we forward that
- // info to the AudioSegmentStream, if it exists, because video timeline
- // data takes precedence. Do not do this if keepOriginalTimestamps is set,
- // because this is a particularly subtle form of timestamp alteration.
- if (audioTrack && !options.keepOriginalTimestamps) {
- audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
- // very earliest DTS we have seen in video because Chrome will
- // interpret any video track with a baseMediaDecodeTime that is
- // non-zero as a gap.
-
- pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
- pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
- pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
- if (audioTrack) {
- pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
-
- pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
- }
-
- if (audioTrack && !pipeline.audioSegmentStream) {
- // hook up the audio segment stream to the first track with aac data
- pipeline.coalesceStream.numberOfTracks++;
- pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
- pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
- pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
- } // emit pmt info
-
-
- self.trigger('trackinfo', {
- hasAudio: !!audioTrack,
- hasVideo: !!videoTrack
- });
- }
- }); // Re-emit any data coming from the coalesce stream to the outside world
-
- pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
- pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
- id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
- self.trigger('id3Frame', id3Frame);
- });
- pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
-
- pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
- }; // hook up the segment streams once track metadata is delivered
-
-
- this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- var pipeline = this.transmuxPipeline_;
-
- if (!options.keepOriginalTimestamps) {
- this.baseMediaDecodeTime = baseMediaDecodeTime;
- }
-
- if (audioTrack) {
- audioTrack.timelineStartInfo.dts = undefined;
- audioTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(audioTrack);
-
- if (pipeline.audioTimestampRolloverStream) {
- pipeline.audioTimestampRolloverStream.discontinuity();
- }
- }
-
- if (videoTrack) {
- if (pipeline.videoSegmentStream) {
- pipeline.videoSegmentStream.gopCache_ = [];
- }
-
- videoTrack.timelineStartInfo.dts = undefined;
- videoTrack.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(videoTrack);
- pipeline.captionStream.reset();
- }
-
- if (pipeline.timestampRolloverStream) {
- pipeline.timestampRolloverStream.discontinuity();
- }
- };
-
- this.setAudioAppendStart = function (timestamp) {
- if (audioTrack) {
- this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
- }
- };
-
- this.setRemux = function (val) {
- var pipeline = this.transmuxPipeline_;
- options.remux = val;
-
- if (pipeline && pipeline.coalesceStream) {
- pipeline.coalesceStream.setRemux(val);
- }
- };
-
- this.alignGopsWith = function (gopsToAlignWith) {
- if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
- this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
- }
- }; // feed incoming data to the front of the parsing pipeline
-
-
- this.push = function (data) {
- if (hasFlushed) {
- var isAac = isLikelyAacData$1(data);
-
- if (isAac && this.transmuxPipeline_.type !== 'aac') {
- this.setupAacPipeline();
- } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
- this.setupTsPipeline();
- }
-
- hasFlushed = false;
- }
-
- this.transmuxPipeline_.headOfPipeline.push(data);
- }; // flush any buffered data
-
-
- this.flush = function () {
- hasFlushed = true; // Start at the top of the pipeline and flush all pending work
-
- this.transmuxPipeline_.headOfPipeline.flush();
- };
-
- this.endTimeline = function () {
- this.transmuxPipeline_.headOfPipeline.endTimeline();
- };
-
- this.reset = function () {
- if (this.transmuxPipeline_.headOfPipeline) {
- this.transmuxPipeline_.headOfPipeline.reset();
- }
- }; // Caption data has to be reset when seeking outside buffered range
-
-
- this.resetCaptions = function () {
- if (this.transmuxPipeline_.captionStream) {
- this.transmuxPipeline_.captionStream.reset();
- }
- };
- };
-
- _Transmuxer.prototype = new stream();
- var transmuxer = {
- Transmuxer: _Transmuxer,
- VideoSegmentStream: _VideoSegmentStream,
- AudioSegmentStream: _AudioSegmentStream,
- AUDIO_PROPERTIES: audioProperties,
- VIDEO_PROPERTIES: videoProperties,
- // exported for testing
- generateSegmentTimingInfo: generateSegmentTimingInfo
- };
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
-
- var codecs = {
- Adts: adts,
- h264: h264
- };
-
- var ONE_SECOND_IN_TS$4 = clock.ONE_SECOND_IN_TS;
- /**
- * Constructs a single-track, ISO BMFF media segment from AAC data
- * events. The output of this stream can be fed to a SourceBuffer
- * configured with a suitable initialization segment.
- */
-
- var AudioSegmentStream = function AudioSegmentStream(track, options) {
- var adtsFrames = [],
- sequenceNumber = 0,
- earliestAllowedDts = 0,
- audioAppendStartTs = 0,
- videoBaseMediaDecodeTime = Infinity,
- segmentStartPts = null,
- segmentEndPts = null;
- options = options || {};
- AudioSegmentStream.prototype.init.call(this);
-
- this.push = function (data) {
- trackDecodeInfo.collectDtsInfo(track, data);
-
- if (track) {
- audioProperties.forEach(function (prop) {
- track[prop] = data[prop];
- });
- } // buffer audio data until end() is called
-
-
- adtsFrames.push(data);
- };
-
- this.setEarliestDts = function (earliestDts) {
- earliestAllowedDts = earliestDts;
- };
-
- this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- videoBaseMediaDecodeTime = baseMediaDecodeTime;
- };
-
- this.setAudioAppendStart = function (timestamp) {
- audioAppendStartTs = timestamp;
- };
-
- this.processFrames_ = function () {
- var frames, moof, mdat, boxes, timingInfo; // return early if no audio data has been observed
-
- if (adtsFrames.length === 0) {
- return;
- }
-
- frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
-
- if (frames.length === 0) {
- // return early if the frames are all after the earliest allowed DTS
- // TODO should we clear the adtsFrames?
- return;
- }
-
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
- audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
- // samples (that is, adts frames) in the audio data
-
- track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
-
- mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
- adtsFrames = [];
- moof = mp4Generator.moof(sequenceNumber, [track]); // bump the sequence number for next time
-
- sequenceNumber++;
- track.initSegment = mp4Generator.initSegment([track]); // it would be great to allocate this array up front instead of
- // throwing away hundreds of media segment fragments
-
- boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- trackDecodeInfo.clearDtsInfo(track);
-
- if (segmentStartPts === null) {
- segmentEndPts = segmentStartPts = frames[0].pts;
- }
-
- segmentEndPts += frames.length * (ONE_SECOND_IN_TS$4 * 1024 / track.samplerate);
- timingInfo = {
- start: segmentStartPts
- };
- this.trigger('timingInfo', timingInfo);
- this.trigger('data', {
- track: track,
- boxes: boxes
- });
- };
-
- this.flush = function () {
- this.processFrames_(); // trigger final timing info
-
- this.trigger('timingInfo', {
- start: segmentStartPts,
- end: segmentEndPts
- });
- this.resetTiming_();
- this.trigger('done', 'AudioSegmentStream');
- };
-
- this.partialFlush = function () {
- this.processFrames_();
- this.trigger('partialdone', 'AudioSegmentStream');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline', 'AudioSegmentStream');
- };
-
- this.resetTiming_ = function () {
- trackDecodeInfo.clearDtsInfo(track);
- segmentStartPts = null;
- segmentEndPts = null;
- };
-
- this.reset = function () {
- this.resetTiming_();
- adtsFrames = [];
- this.trigger('reset');
- };
- };
-
- AudioSegmentStream.prototype = new stream();
- var audioSegmentStream = AudioSegmentStream;
-
- var VideoSegmentStream = function VideoSegmentStream(track, options) {
- var sequenceNumber = 0,
- nalUnits = [],
- frameCache = [],
- // gopsToAlignWith = [],
- config,
- pps,
- segmentStartPts = null,
- segmentEndPts = null,
- gops,
- ensureNextFrameIsKeyFrame = true;
- options = options || {};
- VideoSegmentStream.prototype.init.call(this);
-
- this.push = function (nalUnit) {
- trackDecodeInfo.collectDtsInfo(track, nalUnit);
-
- if (typeof track.timelineStartInfo.dts === 'undefined') {
- track.timelineStartInfo.dts = nalUnit.dts;
- } // record the track config
-
-
- if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
- config = nalUnit.config;
- track.sps = [nalUnit.data];
- videoProperties.forEach(function (prop) {
- track[prop] = config[prop];
- }, this);
- }
-
- if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
- pps = nalUnit.data;
- track.pps = [nalUnit.data];
- } // buffer video until flush() is called
-
-
- nalUnits.push(nalUnit);
- };
-
- this.processNals_ = function (cacheLastFrame) {
- var i;
- nalUnits = frameCache.concat(nalUnits); // Throw away nalUnits at the start of the byte stream until
- // we find the first AUD
-
- while (nalUnits.length) {
- if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
- break;
- }
-
- nalUnits.shift();
- } // Return early if no video data has been observed
-
-
- if (nalUnits.length === 0) {
- return;
- }
-
- var frames = frameUtils.groupNalsIntoFrames(nalUnits);
-
- if (!frames.length) {
- return;
- } // note that the frame cache may also protect us from cases where we haven't
- // pushed data for the entire first or last frame yet
-
-
- frameCache = frames[frames.length - 1];
-
- if (cacheLastFrame) {
- frames.pop();
- frames.duration -= frameCache.duration;
- frames.nalCount -= frameCache.length;
- frames.byteLength -= frameCache.byteLength;
- }
-
- if (!frames.length) {
- nalUnits = [];
- return;
- }
-
- this.trigger('timelineStartInfo', track.timelineStartInfo);
-
- if (ensureNextFrameIsKeyFrame) {
- gops = frameUtils.groupFramesIntoGops(frames);
-
- if (!gops[0][0].keyFrame) {
- gops = frameUtils.extendFirstKeyFrame(gops);
-
- if (!gops[0][0].keyFrame) {
- // we haven't yet gotten a key frame, so reset nal units to wait for more nal
- // units
- nalUnits = [].concat.apply([], frames).concat(frameCache);
- frameCache = [];
- return;
- }
-
- frames = [].concat.apply([], gops);
- frames.duration = gops.duration;
- }
-
- ensureNextFrameIsKeyFrame = false;
- }
-
- if (segmentStartPts === null) {
- segmentStartPts = frames[0].pts;
- segmentEndPts = segmentStartPts;
- }
-
- segmentEndPts += frames.duration;
- this.trigger('timingInfo', {
- start: segmentStartPts,
- end: segmentEndPts
- });
-
- for (i = 0; i < frames.length; i++) {
- var frame = frames[i];
- track.samples = frameUtils.generateSampleTableForFrame(frame);
- var mdat = mp4Generator.mdat(frameUtils.concatenateNalDataForFrame(frame));
- trackDecodeInfo.clearDtsInfo(track);
- trackDecodeInfo.collectDtsInfo(track, frame);
- track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
- var moof = mp4Generator.moof(sequenceNumber, [track]);
- sequenceNumber++;
- track.initSegment = mp4Generator.initSegment([track]);
- var boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
- boxes.set(moof);
- boxes.set(mdat, moof.byteLength);
- this.trigger('data', {
- track: track,
- boxes: boxes,
- sequence: sequenceNumber,
- videoFrameDts: frame.dts,
- videoFramePts: frame.pts
- });
- }
-
- nalUnits = [];
- };
-
- this.resetTimingAndConfig_ = function () {
- config = undefined;
- pps = undefined;
- segmentStartPts = null;
- segmentEndPts = null;
- };
-
- this.partialFlush = function () {
- this.processNals_(true);
- this.trigger('partialdone', 'VideoSegmentStream');
- };
-
- this.flush = function () {
- this.processNals_(false); // reset config and pps because they may differ across segments
- // for instance, when we are rendition switching
-
- this.resetTimingAndConfig_();
- this.trigger('done', 'VideoSegmentStream');
- };
-
- this.endTimeline = function () {
- this.flush();
- this.trigger('endedtimeline', 'VideoSegmentStream');
- };
-
- this.reset = function () {
- this.resetTimingAndConfig_();
- frameCache = [];
- nalUnits = [];
- ensureNextFrameIsKeyFrame = true;
- this.trigger('reset');
- };
- };
-
- VideoSegmentStream.prototype = new stream();
- var videoSegmentStream = VideoSegmentStream;
-
- var isLikelyAacData$2 = utils.isLikelyAacData;
-
- var createPipeline = function createPipeline(object) {
- object.prototype = new stream();
- object.prototype.init.call(object);
- return object;
- };
-
- var tsPipeline = function tsPipeline(options) {
- var pipeline = {
- type: 'ts',
- tracks: {
- audio: null,
- video: null
- },
- packet: new m2ts_1.TransportPacketStream(),
- parse: new m2ts_1.TransportParseStream(),
- elementary: new m2ts_1.ElementaryStream(),
- timestampRollover: new m2ts_1.TimestampRolloverStream(),
- adts: new codecs.Adts(),
- h264: new codecs.h264.H264Stream(),
- captionStream: new m2ts_1.CaptionStream(options),
- metadataStream: new m2ts_1.MetadataStream()
- };
- pipeline.headOfPipeline = pipeline.packet; // Transport Stream
-
- pipeline.packet.pipe(pipeline.parse).pipe(pipeline.elementary).pipe(pipeline.timestampRollover); // H264
-
- pipeline.timestampRollover.pipe(pipeline.h264); // Hook up CEA-608/708 caption stream
-
- pipeline.h264.pipe(pipeline.captionStream);
- pipeline.timestampRollover.pipe(pipeline.metadataStream); // ADTS
-
- pipeline.timestampRollover.pipe(pipeline.adts);
- pipeline.elementary.on('data', function (data) {
- if (data.type !== 'metadata') {
- return;
- }
-
- for (var i = 0; i < data.tracks.length; i++) {
- if (!pipeline.tracks[data.tracks[i].type]) {
- pipeline.tracks[data.tracks[i].type] = data.tracks[i];
- pipeline.tracks[data.tracks[i].type].timelineStartInfo.baseMediaDecodeTime = options.baseMediaDecodeTime;
- }
- }
-
- if (pipeline.tracks.video && !pipeline.videoSegmentStream) {
- pipeline.videoSegmentStream = new videoSegmentStream(pipeline.tracks.video, options);
- pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
- if (pipeline.tracks.audio && !options.keepOriginalTimestamps) {
- pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - options.baseMediaDecodeTime);
- }
- });
- pipeline.videoSegmentStream.on('timingInfo', pipeline.trigger.bind(pipeline, 'videoTimingInfo'));
- pipeline.videoSegmentStream.on('data', function (data) {
- pipeline.trigger('data', {
- type: 'video',
- data: data
- });
- });
- pipeline.videoSegmentStream.on('done', pipeline.trigger.bind(pipeline, 'done'));
- pipeline.videoSegmentStream.on('partialdone', pipeline.trigger.bind(pipeline, 'partialdone'));
- pipeline.videoSegmentStream.on('endedtimeline', pipeline.trigger.bind(pipeline, 'endedtimeline'));
- pipeline.h264.pipe(pipeline.videoSegmentStream);
- }
-
- if (pipeline.tracks.audio && !pipeline.audioSegmentStream) {
- pipeline.audioSegmentStream = new audioSegmentStream(pipeline.tracks.audio, options);
- pipeline.audioSegmentStream.on('data', function (data) {
- pipeline.trigger('data', {
- type: 'audio',
- data: data
- });
- });
- pipeline.audioSegmentStream.on('done', pipeline.trigger.bind(pipeline, 'done'));
- pipeline.audioSegmentStream.on('partialdone', pipeline.trigger.bind(pipeline, 'partialdone'));
- pipeline.audioSegmentStream.on('endedtimeline', pipeline.trigger.bind(pipeline, 'endedtimeline'));
- pipeline.audioSegmentStream.on('timingInfo', pipeline.trigger.bind(pipeline, 'audioTimingInfo'));
- pipeline.adts.pipe(pipeline.audioSegmentStream);
- } // emit pmt info
-
-
- pipeline.trigger('trackinfo', {
- hasAudio: !!pipeline.tracks.audio,
- hasVideo: !!pipeline.tracks.video
- });
- });
- pipeline.captionStream.on('data', function (caption) {
- var timelineStartPts;
-
- if (pipeline.tracks.video) {
- timelineStartPts = pipeline.tracks.video.timelineStartInfo.pts || 0;
- } else {
- // This will only happen if we encounter caption packets before
- // video data in a segment. This is an unusual/unlikely scenario,
- // so we assume the timeline starts at zero for now.
- timelineStartPts = 0;
- } // Translate caption PTS times into second offsets into the
- // video timeline for the segment
-
-
- caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, options.keepOriginalTimestamps);
- caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, options.keepOriginalTimestamps);
- pipeline.trigger('caption', caption);
- });
- pipeline = createPipeline(pipeline);
- pipeline.metadataStream.on('data', pipeline.trigger.bind(pipeline, 'id3Frame'));
- return pipeline;
- };
-
- var aacPipeline = function aacPipeline(options) {
- var pipeline = {
- type: 'aac',
- tracks: {
- audio: null
- },
- metadataStream: new m2ts_1.MetadataStream(),
- aacStream: new aac(),
- audioRollover: new m2ts_1.TimestampRolloverStream('audio'),
- timedMetadataRollover: new m2ts_1.TimestampRolloverStream('timed-metadata'),
- adtsStream: new adts(true)
- }; // set up the parsing pipeline
-
- pipeline.headOfPipeline = pipeline.aacStream;
- pipeline.aacStream.pipe(pipeline.audioRollover).pipe(pipeline.adtsStream);
- pipeline.aacStream.pipe(pipeline.timedMetadataRollover).pipe(pipeline.metadataStream);
- pipeline.metadataStream.on('timestamp', function (frame) {
- pipeline.aacStream.setTimestamp(frame.timeStamp);
- });
- pipeline.aacStream.on('data', function (data) {
- if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
- return;
- }
-
- pipeline.tracks.audio = pipeline.tracks.audio || {
- timelineStartInfo: {
- baseMediaDecodeTime: options.baseMediaDecodeTime
- },
- codec: 'adts',
- type: 'audio'
- }; // hook up the audio segment stream to the first track with aac data
-
- pipeline.audioSegmentStream = new audioSegmentStream(pipeline.tracks.audio, options);
- pipeline.audioSegmentStream.on('data', function (data) {
- pipeline.trigger('data', {
- type: 'audio',
- data: data
- });
- });
- pipeline.audioSegmentStream.on('partialdone', pipeline.trigger.bind(pipeline, 'partialdone'));
- pipeline.audioSegmentStream.on('done', pipeline.trigger.bind(pipeline, 'done'));
- pipeline.audioSegmentStream.on('endedtimeline', pipeline.trigger.bind(pipeline, 'endedtimeline'));
- pipeline.audioSegmentStream.on('timingInfo', pipeline.trigger.bind(pipeline, 'audioTimingInfo')); // Set up the final part of the audio pipeline
-
- pipeline.adtsStream.pipe(pipeline.audioSegmentStream);
- pipeline.trigger('trackinfo', {
- hasAudio: !!pipeline.tracks.audio,
- hasVideo: !!pipeline.tracks.video
- });
- }); // set the pipeline up as a stream before binding to get access to the trigger function
-
- pipeline = createPipeline(pipeline);
- pipeline.metadataStream.on('data', pipeline.trigger.bind(pipeline, 'id3Frame'));
- return pipeline;
- };
-
- var setupPipelineListeners = function setupPipelineListeners(pipeline, transmuxer) {
- pipeline.on('data', transmuxer.trigger.bind(transmuxer, 'data'));
- pipeline.on('done', transmuxer.trigger.bind(transmuxer, 'done'));
- pipeline.on('partialdone', transmuxer.trigger.bind(transmuxer, 'partialdone'));
- pipeline.on('endedtimeline', transmuxer.trigger.bind(transmuxer, 'endedtimeline'));
- pipeline.on('audioTimingInfo', transmuxer.trigger.bind(transmuxer, 'audioTimingInfo'));
- pipeline.on('videoTimingInfo', transmuxer.trigger.bind(transmuxer, 'videoTimingInfo'));
- pipeline.on('trackinfo', transmuxer.trigger.bind(transmuxer, 'trackinfo'));
- pipeline.on('id3Frame', function (event) {
- // add this to every single emitted segment even though it's only needed for the first
- event.dispatchType = pipeline.metadataStream.dispatchType; // keep original time, can be adjusted if needed at a higher level
-
- event.cueTime = clock.videoTsToSeconds(event.pts);
- transmuxer.trigger('id3Frame', event);
- });
- pipeline.on('caption', function (event) {
- transmuxer.trigger('caption', event);
- });
- };
-
- var Transmuxer = function Transmuxer(options) {
- var pipeline = null,
- hasFlushed = true;
- options = options || {};
- Transmuxer.prototype.init.call(this);
- options.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
-
- this.push = function (bytes) {
- if (hasFlushed) {
- var isAac = isLikelyAacData$2(bytes);
-
- if (isAac && (!pipeline || pipeline.type !== 'aac')) {
- pipeline = aacPipeline(options);
- setupPipelineListeners(pipeline, this);
- } else if (!isAac && (!pipeline || pipeline.type !== 'ts')) {
- pipeline = tsPipeline(options);
- setupPipelineListeners(pipeline, this);
- }
-
- hasFlushed = false;
- }
-
- pipeline.headOfPipeline.push(bytes);
- };
-
- this.flush = function () {
- if (!pipeline) {
- return;
- }
-
- hasFlushed = true;
- pipeline.headOfPipeline.flush();
- };
-
- this.partialFlush = function () {
- if (!pipeline) {
- return;
- }
-
- pipeline.headOfPipeline.partialFlush();
- };
-
- this.endTimeline = function () {
- if (!pipeline) {
- return;
- }
-
- pipeline.headOfPipeline.endTimeline();
- };
-
- this.reset = function () {
- if (!pipeline) {
- return;
- }
-
- pipeline.headOfPipeline.reset();
- };
-
- this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
- if (!options.keepOriginalTimestamps) {
- options.baseMediaDecodeTime = baseMediaDecodeTime;
- }
-
- if (!pipeline) {
- return;
- }
-
- if (pipeline.tracks.audio) {
- pipeline.tracks.audio.timelineStartInfo.dts = undefined;
- pipeline.tracks.audio.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(pipeline.tracks.audio);
-
- if (pipeline.audioRollover) {
- pipeline.audioRollover.discontinuity();
- }
- }
-
- if (pipeline.tracks.video) {
- if (pipeline.videoSegmentStream) {
- pipeline.videoSegmentStream.gopCache_ = [];
- }
-
- pipeline.tracks.video.timelineStartInfo.dts = undefined;
- pipeline.tracks.video.timelineStartInfo.pts = undefined;
- trackDecodeInfo.clearDtsInfo(pipeline.tracks.video); // pipeline.captionStream.reset();
- }
-
- if (pipeline.timestampRollover) {
- pipeline.timestampRollover.discontinuity();
- }
- };
-
- this.setRemux = function (val) {
- options.remux = val;
-
- if (pipeline && pipeline.coalesceStream) {
- pipeline.coalesceStream.setRemux(val);
- }
- };
-
- this.setAudioAppendStart = function (audioAppendStart) {
- if (!pipeline || !pipeline.tracks.audio || !pipeline.audioSegmentStream) {
- return;
- }
-
- pipeline.audioSegmentStream.setAudioAppendStart(audioAppendStart);
- }; // TODO GOP alignment support
- // Support may be a bit trickier than with full segment appends, as GOPs may be split
- // and processed in a more granular fashion
-
-
- this.alignGopsWith = function (gopsToAlignWith) {
- return;
- };
- };
-
- Transmuxer.prototype = new stream();
- var transmuxer$1 = Transmuxer;
-
- /**
- * mux.js
- *
- * Copyright (c) Brightcove
- * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
- */
- var toUnsigned = function toUnsigned(value) {
- return value >>> 0;
- };
-
- var toHexString = function toHexString(value) {
- return ('00' + value.toString(16)).slice(-2);
- };
-
- var bin = {
- toUnsigned: toUnsigned,
- toHexString: toHexString
- };
-
- var parseType$1 = function parseType(buffer) {
- var result = '';
- result += String.fromCharCode(buffer[0]);
- result += String.fromCharCode(buffer[1]);
- result += String.fromCharCode(buffer[2]);
- result += String.fromCharCode(buffer[3]);
- return result;
- };
-
- var parseType_1 = parseType$1;
-
- var toUnsigned$1 = bin.toUnsigned;
-
- var findBox = function findBox(data, path) {
- var results = [],
- i,
- size,
- type,
- end,
- subresults;
-
- if (!path.length) {
- // short-circuit the search for empty paths
- return null;
- }
-
- for (i = 0; i < data.byteLength;) {
- size = toUnsigned$1(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
- type = parseType_1(data.subarray(i + 4, i + 8));
- end = size > 1 ? i + size : data.byteLength;
-
- if (type === path[0]) {
- if (path.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data.subarray(i + 8, end));
- } else {
- // recursively search for the next box along the path
- subresults = findBox(data.subarray(i + 8, end), path.slice(1));
-
- if (subresults.length) {
- results = results.concat(subresults);
- }
- }
- }
-
- i = end;
- } // we've finished searching all of data
-
-
- return results;
- };
-
- var findBox_1 = findBox;
-
- var toUnsigned$2 = bin.toUnsigned;
-
- var tfdt = function tfdt(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- baseMediaDecodeTime: toUnsigned$2(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7])
- };
-
- if (result.version === 1) {
- result.baseMediaDecodeTime *= Math.pow(2, 32);
- result.baseMediaDecodeTime += toUnsigned$2(data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11]);
- }
-
- return result;
- };
-
- var parseTfdt = tfdt;
-
- var parseSampleFlags = function parseSampleFlags(flags) {
- return {
- isLeading: (flags[0] & 0x0c) >>> 2,
- dependsOn: flags[0] & 0x03,
- isDependedOn: (flags[1] & 0xc0) >>> 6,
- hasRedundancy: (flags[1] & 0x30) >>> 4,
- paddingValue: (flags[1] & 0x0e) >>> 1,
- isNonSyncSample: flags[1] & 0x01,
- degradationPriority: flags[2] << 8 | flags[3]
- };
- };
-
- var parseSampleFlags_1 = parseSampleFlags;
-
- var trun$1 = function trun(data) {
- var result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- samples: []
- },
- view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- // Flag interpretation
- dataOffsetPresent = result.flags[2] & 0x01,
- // compare with 2nd byte of 0x1
- firstSampleFlagsPresent = result.flags[2] & 0x04,
- // compare with 2nd byte of 0x4
- sampleDurationPresent = result.flags[1] & 0x01,
- // compare with 2nd byte of 0x100
- sampleSizePresent = result.flags[1] & 0x02,
- // compare with 2nd byte of 0x200
- sampleFlagsPresent = result.flags[1] & 0x04,
- // compare with 2nd byte of 0x400
- sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
- // compare with 2nd byte of 0x800
- sampleCount = view.getUint32(4),
- offset = 8,
- sample;
-
- if (dataOffsetPresent) {
- // 32 bit signed integer
- result.dataOffset = view.getInt32(offset);
- offset += 4;
- } // Overrides the flags for the first sample only. The order of
- // optional values will be: duration, size, compositionTimeOffset
-
-
- if (firstSampleFlagsPresent && sampleCount) {
- sample = {
- flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
- };
- offset += 4;
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- sampleCount--;
- }
-
- while (sampleCount--) {
- sample = {};
-
- if (sampleDurationPresent) {
- sample.duration = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleSizePresent) {
- sample.size = view.getUint32(offset);
- offset += 4;
- }
-
- if (sampleFlagsPresent) {
- sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
- offset += 4;
- }
-
- if (sampleCompositionTimeOffsetPresent) {
- if (result.version === 1) {
- sample.compositionTimeOffset = view.getInt32(offset);
- } else {
- sample.compositionTimeOffset = view.getUint32(offset);
- }
-
- offset += 4;
- }
-
- result.samples.push(sample);
- }
-
- return result;
- };
-
- var parseTrun = trun$1;
-
- var tfhd = function tfhd(data) {
- var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
- result = {
- version: data[0],
- flags: new Uint8Array(data.subarray(1, 4)),
- trackId: view.getUint32(4)
- },
- baseDataOffsetPresent = result.flags[2] & 0x01,
- sampleDescriptionIndexPresent = result.flags[2] & 0x02,
- defaultSampleDurationPresent = result.flags[2] & 0x08,
- defaultSampleSizePresent = result.flags[2] & 0x10,
- defaultSampleFlagsPresent = result.flags[2] & 0x20,
- durationIsEmpty = result.flags[0] & 0x010000,
- defaultBaseIsMoof = result.flags[0] & 0x020000,
- i;
- i = 8;
-
- if (baseDataOffsetPresent) {
- i += 4; // truncate top 4 bytes
- // FIXME: should we read the full 64 bits?
-
- result.baseDataOffset = view.getUint32(12);
- i += 4;
- }
-
- if (sampleDescriptionIndexPresent) {
- result.sampleDescriptionIndex = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleDurationPresent) {
- result.defaultSampleDuration = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleSizePresent) {
- result.defaultSampleSize = view.getUint32(i);
- i += 4;
- }
-
- if (defaultSampleFlagsPresent) {
- result.defaultSampleFlags = view.getUint32(i);
- }
-
- if (durationIsEmpty) {
- result.durationIsEmpty = true;
- }
-
- if (!baseDataOffsetPresent && defaultBaseIsMoof) {
- result.baseDataOffsetIsMoof = true;
- }
-
- return result;
- };
-
- var parseTfhd = tfhd;
-
- var discardEmulationPreventionBytes$1 = captionPacketParser.discardEmulationPreventionBytes;
- var CaptionStream$1 = captionStream.CaptionStream;
- /**
- * Maps an offset in the mdat to a sample based on the the size of the samples.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Number} offset - The offset into the mdat
- * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
- * @return {?Object} The matching sample, or null if no match was found.
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
- var mapToSample = function mapToSample(offset, samples) {
- var approximateOffset = offset;
-
- for (var i = 0; i < samples.length; i++) {
- var sample = samples[i];
-
- if (approximateOffset < sample.size) {
- return sample;
- }
-
- approximateOffset -= sample.size;
- }
-
- return null;
- };
- /**
- * Finds SEI nal units contained in a Media Data Box.
- * Assumes that `parseSamples` has been called first.
- *
- * @param {Uint8Array} avcStream - The bytes of the mdat
- * @param {Object[]} samples - The samples parsed out by `parseSamples`
- * @param {Number} trackId - The trackId of this video track
- * @return {Object[]} seiNals - the parsed SEI NALUs found.
- * The contents of the seiNal should match what is expected by
- * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
- *
- * @see ISO-BMFF-12/2015, Section 8.1.1
- * @see Rec. ITU-T H.264, 7.3.2.3.1
- **/
-
-
- var findSeiNals = function findSeiNals(avcStream, samples, trackId) {
- var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
- result = [],
- seiNal,
- i,
- length,
- lastMatchedSample;
-
- for (i = 0; i + 4 < avcStream.length; i += length) {
- length = avcView.getUint32(i);
- i += 4; // Bail if this doesn't appear to be an H264 stream
-
- if (length <= 0) {
- continue;
- }
-
- switch (avcStream[i] & 0x1F) {
- case 0x06:
- var data = avcStream.subarray(i + 1, i + 1 + length);
- var matchingSample = mapToSample(i, samples);
- seiNal = {
- nalUnitType: 'sei_rbsp',
- size: length,
- data: data,
- escapedRBSP: discardEmulationPreventionBytes$1(data),
- trackId: trackId
- };
-
- if (matchingSample) {
- seiNal.pts = matchingSample.pts;
- seiNal.dts = matchingSample.dts;
- lastMatchedSample = matchingSample;
- } else if (lastMatchedSample) {
- // If a matching sample cannot be found, use the last
- // sample's values as they should be as close as possible
- seiNal.pts = lastMatchedSample.pts;
- seiNal.dts = lastMatchedSample.dts;
- } else {
- // eslint-disable-next-line no-console
- console.log("We've encountered a nal unit without data. See mux.js#233.");
- break;
- }
-
- result.push(seiNal);
- break;
- }
- }
-
- return result;
- };
- /**
- * Parses sample information out of Track Run Boxes and calculates
- * the absolute presentation and decode timestamps of each sample.
- *
- * @param {Array} truns - The Trun Run boxes to be parsed
- * @param {Number} baseMediaDecodeTime - base media decode time from tfdt
- @see ISO-BMFF-12/2015, Section 8.8.12
- * @param {Object} tfhd - The parsed Track Fragment Header
- * @see inspect.parseTfhd
- * @return {Object[]} the parsed samples
- *
- * @see ISO-BMFF-12/2015, Section 8.8.8
- **/
-
-
- var parseSamples = function parseSamples(truns, baseMediaDecodeTime, tfhd) {
- var currentDts = baseMediaDecodeTime;
- var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
- var defaultSampleSize = tfhd.defaultSampleSize || 0;
- var trackId = tfhd.trackId;
- var allSamples = [];
- truns.forEach(function (trun) {
- // Note: We currently do not parse the sample table as well
- // as the trun. It's possible some sources will require this.
- // moov > trak > mdia > minf > stbl
- var trackRun = parseTrun(trun);
- var samples = trackRun.samples;
- samples.forEach(function (sample) {
- if (sample.duration === undefined) {
- sample.duration = defaultSampleDuration;
- }
-
- if (sample.size === undefined) {
- sample.size = defaultSampleSize;
- }
-
- sample.trackId = trackId;
- sample.dts = currentDts;
-
- if (sample.compositionTimeOffset === undefined) {
- sample.compositionTimeOffset = 0;
- }
-
- sample.pts = currentDts + sample.compositionTimeOffset;
- currentDts += sample.duration;
- });
- allSamples = allSamples.concat(samples);
- });
- return allSamples;
- };
- /**
- * Parses out caption nals from an FMP4 segment's video tracks.
- *
- * @param {Uint8Array} segment - The bytes of a single segment
- * @param {Number} videoTrackId - The trackId of a video track in the segment
- * @return {Object.} A mapping of video trackId to
- * a list of seiNals found in that track
- **/
-
-
- var parseCaptionNals = function parseCaptionNals(segment, videoTrackId) {
- // To get the samples
- var trafs = findBox_1(segment, ['moof', 'traf']); // To get SEI NAL units
-
- var mdats = findBox_1(segment, ['mdat']);
- var captionNals = {};
- var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
-
- mdats.forEach(function (mdat, index) {
- var matchingTraf = trafs[index];
- mdatTrafPairs.push({
- mdat: mdat,
- traf: matchingTraf
- });
- });
- mdatTrafPairs.forEach(function (pair) {
- var mdat = pair.mdat;
- var traf = pair.traf;
- var tfhd = findBox_1(traf, ['tfhd']); // Exactly 1 tfhd per traf
-
- var headerInfo = parseTfhd(tfhd[0]);
- var trackId = headerInfo.trackId;
- var tfdt = findBox_1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
-
- var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
- var truns = findBox_1(traf, ['trun']);
- var samples;
- var seiNals; // Only parse video data for the chosen video track
-
- if (videoTrackId === trackId && truns.length > 0) {
- samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
- seiNals = findSeiNals(mdat, samples, trackId);
-
- if (!captionNals[trackId]) {
- captionNals[trackId] = [];
- }
-
- captionNals[trackId] = captionNals[trackId].concat(seiNals);
- }
- });
- return captionNals;
- };
- /**
- * Parses out inband captions from an MP4 container and returns
- * caption objects that can be used by WebVTT and the TextTrack API.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
- * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
- * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number} trackId - The id of the video track to parse
- * @param {Number} timescale - The timescale for the video track from the init segment
- *
- * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
- * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
- * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
- * @return {String} parsedCaptions[].text - The visible content of the caption
- **/
-
-
- var parseEmbeddedCaptions = function parseEmbeddedCaptions(segment, trackId, timescale) {
- var seiNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
-
- if (trackId === null) {
- return null;
- }
-
- seiNals = parseCaptionNals(segment, trackId);
- return {
- seiNals: seiNals[trackId],
- timescale: timescale
- };
- };
- /**
- * Converts SEI NALUs into captions that can be used by video.js
- **/
-
-
- var CaptionParser = function CaptionParser() {
- var isInitialized = false;
- var captionStream; // Stores segments seen before trackId and timescale are set
-
- var segmentCache; // Stores video track ID of the track being parsed
-
- var trackId; // Stores the timescale of the track being parsed
-
- var timescale; // Stores captions parsed so far
-
- var parsedCaptions; // Stores whether we are receiving partial data or not
-
- var parsingPartial;
- /**
- * A method to indicate whether a CaptionParser has been initalized
- * @returns {Boolean}
- **/
-
- this.isInitialized = function () {
- return isInitialized;
- };
- /**
- * Initializes the underlying CaptionStream, SEI NAL parsing
- * and management, and caption collection
- **/
-
-
- this.init = function (options) {
- captionStream = new CaptionStream$1();
- isInitialized = true;
- parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
-
- captionStream.on('data', function (event) {
- // Convert to seconds in the source's timescale
- event.startTime = event.startPts / timescale;
- event.endTime = event.endPts / timescale;
- parsedCaptions.captions.push(event);
- parsedCaptions.captionStreams[event.stream] = true;
- });
- };
- /**
- * Determines if a new video track will be selected
- * or if the timescale changed
- * @return {Boolean}
- **/
-
-
- this.isNewInit = function (videoTrackIds, timescales) {
- if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
- return false;
- }
-
- return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
- };
- /**
- * Parses out SEI captions and interacts with underlying
- * CaptionStream to return dispatched captions
- *
- * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
- * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
- * @param {Object.} timescales - The timescales found in the init segment
- * @see parseEmbeddedCaptions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.parse = function (segment, videoTrackIds, timescales) {
- var parsedData;
-
- if (!this.isInitialized()) {
- return null; // This is not likely to be a video segment
- } else if (!videoTrackIds || !timescales) {
- return null;
- } else if (this.isNewInit(videoTrackIds, timescales)) {
- // Use the first video track only as there is no
- // mechanism to switch to other video tracks
- trackId = videoTrackIds[0];
- timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
- // data until we have one.
- // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
- } else if (trackId === null || !timescale) {
- segmentCache.push(segment);
- return null;
- } // Now that a timescale and trackId is set, parse cached segments
-
-
- while (segmentCache.length > 0) {
- var cachedSegment = segmentCache.shift();
- this.parse(cachedSegment, videoTrackIds, timescales);
- }
-
- parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
-
- if (parsedData === null || !parsedData.seiNals) {
- return null;
- }
-
- this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
-
- this.flushStream();
- return parsedCaptions;
- };
- /**
- * Pushes SEI NALUs onto CaptionStream
- * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
- * Assumes that `parseCaptionNals` has been called first
- * @see m2ts/caption-stream.js
- **/
-
-
- this.pushNals = function (nals) {
- if (!this.isInitialized() || !nals || nals.length === 0) {
- return null;
- }
-
- nals.forEach(function (nal) {
- captionStream.push(nal);
- });
- };
- /**
- * Flushes underlying CaptionStream to dispatch processed, displayable captions
- * @see m2ts/caption-stream.js
- **/
-
-
- this.flushStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- if (!parsingPartial) {
- captionStream.flush();
- } else {
- captionStream.partialFlush();
- }
- };
- /**
- * Reset caption buckets for new data
- **/
-
-
- this.clearParsedCaptions = function () {
- parsedCaptions.captions = [];
- parsedCaptions.captionStreams = {};
- };
- /**
- * Resets underlying CaptionStream
- * @see m2ts/caption-stream.js
- **/
-
-
- this.resetCaptionStream = function () {
- if (!this.isInitialized()) {
- return null;
- }
-
- captionStream.reset();
- };
- /**
- * Convenience method to clear all captions flushed from the
- * CaptionStream and still being parsed
- * @see m2ts/caption-stream.js
- **/
-
-
- this.clearAllCaptions = function () {
- this.clearParsedCaptions();
- this.resetCaptionStream();
- };
- /**
- * Reset caption parser
- **/
-
-
- this.reset = function () {
- segmentCache = [];
- trackId = null;
- timescale = null;
-
- if (!parsedCaptions) {
- parsedCaptions = {
- captions: [],
- // CC1, CC2, CC3, CC4
- captionStreams: {}
- };
- } else {
- this.clearParsedCaptions();
- }
-
- this.resetCaptionStream();
- };
-
- this.reset();
- };
-
- var captionParser = CaptionParser;
-
- /* global self */
-
- var typeFromStreamString = function typeFromStreamString(streamString) {
- if (streamString === 'AudioSegmentStream') {
- return 'audio';
- }
-
- return streamString === 'VideoSegmentStream' ? 'video' : '';
- };
- /**
- * Re-emits transmuxer events by converting them into messages to the
- * world outside the worker.
- *
- * @param {Object} transmuxer the transmuxer to wire events on
- * @private
- */
-
-
- var wireFullTransmuxerEvents = function wireFullTransmuxerEvents(self, transmuxer) {
- transmuxer.on('data', function (segment) {
- // transfer ownership of the underlying ArrayBuffer
- // instead of doing a copy to save memory
- // ArrayBuffers are transferable but generic TypedArrays are not
- // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
- var initArray = segment.initSegment;
- segment.initSegment = {
- data: initArray.buffer,
- byteOffset: initArray.byteOffset,
- byteLength: initArray.byteLength
- };
- var typedArray = segment.data;
- segment.data = typedArray.buffer;
- self.postMessage({
- action: 'data',
- segment: segment,
- byteOffset: typedArray.byteOffset,
- byteLength: typedArray.byteLength
- }, [segment.data]);
- });
- transmuxer.on('done', function (data) {
- self.postMessage({
- action: 'done'
- });
- });
- transmuxer.on('gopInfo', function (gopInfo) {
- self.postMessage({
- action: 'gopInfo',
- gopInfo: gopInfo
- });
- });
- transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
- var videoSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- videoSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'videoSegmentTimingInfo',
- videoSegmentTimingInfo: videoSegmentTimingInfo
- });
- });
- transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
- // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
- var audioSegmentTimingInfo = {
- start: {
- decode: clock.videoTsToSeconds(timingInfo.start.dts),
- presentation: clock.videoTsToSeconds(timingInfo.start.pts)
- },
- end: {
- decode: clock.videoTsToSeconds(timingInfo.end.dts),
- presentation: clock.videoTsToSeconds(timingInfo.end.pts)
- },
- baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
- };
-
- if (timingInfo.prependedContentDuration) {
- audioSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
- }
-
- self.postMessage({
- action: 'audioSegmentTimingInfo',
- audioSegmentTimingInfo: audioSegmentTimingInfo
- });
- });
- transmuxer.on('id3Frame', function (id3Frame) {
- self.postMessage({
- action: 'id3Frame',
- id3Frame: id3Frame
- });
- });
- transmuxer.on('caption', function (caption) {
- self.postMessage({
- action: 'caption',
- caption: caption
- });
- });
- transmuxer.on('trackinfo', function (trackInfo) {
- self.postMessage({
- action: 'trackinfo',
- trackInfo: trackInfo
- });
- });
- transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
- // convert to video TS since we prioritize video time over audio
- self.postMessage({
- action: 'audioTimingInfo',
- audioTimingInfo: {
- start: clock.videoTsToSeconds(audioTimingInfo.start),
- end: clock.videoTsToSeconds(audioTimingInfo.end)
- }
- });
- });
- transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
- self.postMessage({
- action: 'videoTimingInfo',
- videoTimingInfo: {
- start: clock.videoTsToSeconds(videoTimingInfo.start),
- end: clock.videoTsToSeconds(videoTimingInfo.end)
- }
- });
- });
- };
-
- var wirePartialTransmuxerEvents = function wirePartialTransmuxerEvents(self, transmuxer) {
- transmuxer.on('data', function (event) {
- // transfer ownership of the underlying ArrayBuffer
- // instead of doing a copy to save memory
- // ArrayBuffers are transferable but generic TypedArrays are not
- // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
- var initSegment = {
- data: event.data.track.initSegment.buffer,
- byteOffset: event.data.track.initSegment.byteOffset,
- byteLength: event.data.track.initSegment.byteLength
- };
- var boxes = {
- data: event.data.boxes.buffer,
- byteOffset: event.data.boxes.byteOffset,
- byteLength: event.data.boxes.byteLength
- };
- var segment = {
- boxes: boxes,
- initSegment: initSegment,
- type: event.type,
- sequence: event.data.sequence
- };
-
- if (typeof event.data.videoFrameDts !== 'undefined') {
- segment.videoFrameDtsTime = clock.videoTsToSeconds(event.data.videoFrameDts);
- }
-
- if (typeof event.data.videoFramePts !== 'undefined') {
- segment.videoFramePtsTime = clock.videoTsToSeconds(event.data.videoFramePts);
- }
-
- self.postMessage({
- action: 'data',
- segment: segment
- }, [segment.boxes.data, segment.initSegment.data]);
- });
- transmuxer.on('id3Frame', function (id3Frame) {
- self.postMessage({
- action: 'id3Frame',
- id3Frame: id3Frame
- });
- });
- transmuxer.on('caption', function (caption) {
- self.postMessage({
- action: 'caption',
- caption: caption
- });
- });
- transmuxer.on('done', function (data) {
- self.postMessage({
- action: 'done',
- type: typeFromStreamString(data)
- });
- });
- transmuxer.on('partialdone', function (data) {
- self.postMessage({
- action: 'partialdone',
- type: typeFromStreamString(data)
- });
- });
- transmuxer.on('endedsegment', function (data) {
- self.postMessage({
- action: 'endedSegment',
- type: typeFromStreamString(data)
- });
- });
- transmuxer.on('trackinfo', function (trackInfo) {
- self.postMessage({
- action: 'trackinfo',
- trackInfo: trackInfo
- });
- });
- transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
- // This can happen if flush is called when no
- // audio has been processed. This should be an
- // unusual case, but if it does occur should not
- // result in valid data being returned
- if (audioTimingInfo.start === null) {
- self.postMessage({
- action: 'audioTimingInfo',
- audioTimingInfo: audioTimingInfo
- });
- return;
- } // convert to video TS since we prioritize video time over audio
-
-
- var timingInfoInSeconds = {
- start: clock.videoTsToSeconds(audioTimingInfo.start)
- };
-
- if (audioTimingInfo.end) {
- timingInfoInSeconds.end = clock.videoTsToSeconds(audioTimingInfo.end);
- }
-
- self.postMessage({
- action: 'audioTimingInfo',
- audioTimingInfo: timingInfoInSeconds
- });
- });
- transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
- var timingInfoInSeconds = {
- start: clock.videoTsToSeconds(videoTimingInfo.start)
- };
-
- if (videoTimingInfo.end) {
- timingInfoInSeconds.end = clock.videoTsToSeconds(videoTimingInfo.end);
- }
-
- self.postMessage({
- action: 'videoTimingInfo',
- videoTimingInfo: timingInfoInSeconds
- });
- });
- };
- /**
- * All incoming messages route through this hash. If no function exists
- * to handle an incoming message, then we ignore the message.
- *
- * @class MessageHandlers
- * @param {Object} options the options to initialize with
- */
-
-
- var MessageHandlers = /*#__PURE__*/function () {
- function MessageHandlers(self, options) {
- this.options = options || {};
- this.self = self;
- this.init();
- }
- /**
- * initialize our web worker and wire all the events.
- */
-
-
- var _proto = MessageHandlers.prototype;
-
- _proto.init = function init() {
- if (this.transmuxer) {
- this.transmuxer.dispose();
- }
-
- this.transmuxer = this.options.handlePartialData ? new transmuxer$1(this.options) : new transmuxer.Transmuxer(this.options);
-
- if (this.options.handlePartialData) {
- wirePartialTransmuxerEvents(this.self, this.transmuxer);
- } else {
- wireFullTransmuxerEvents(this.self, this.transmuxer);
- }
- };
-
- _proto.pushMp4Captions = function pushMp4Captions(data) {
- if (!this.captionParser) {
- this.captionParser = new captionParser();
- this.captionParser.init();
- }
-
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- var parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
- this.self.postMessage({
- action: 'mp4Captions',
- captions: parsed && parsed.captions || [],
- data: segment.buffer
- }, [segment.buffer]);
- };
-
- _proto.clearAllMp4Captions = function clearAllMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearAllCaptions();
- }
- };
-
- _proto.clearParsedMp4Captions = function clearParsedMp4Captions() {
- if (this.captionParser) {
- this.captionParser.clearParsedCaptions();
- }
- }
- /**
- * Adds data (a ts segment) to the start of the transmuxer pipeline for
- * processing.
- *
- * @param {ArrayBuffer} data data to push into the muxer
- */
- ;
-
- _proto.push = function push(data) {
- // Cast array buffer to correct type for transmuxer
- var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
- this.transmuxer.push(segment);
- }
- /**
- * Recreate the transmuxer so that the next segment added via `push`
- * start with a fresh transmuxer.
- */
- ;
-
- _proto.reset = function reset() {
- this.transmuxer.reset();
- }
- /**
- * Set the value that will be used as the `baseMediaDecodeTime` time for the
- * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
- * set relative to the first based on the PTS values.
- *
- * @param {Object} data used to set the timestamp offset in the muxer
- */
- ;
-
- _proto.setTimestampOffset = function setTimestampOffset(data) {
- var timestampOffset = data.timestampOffset || 0;
- this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset)));
- };
-
- _proto.setAudioAppendStart = function setAudioAppendStart(data) {
- this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));
- };
-
- _proto.setRemux = function setRemux(data) {
- this.transmuxer.setRemux(data.remux);
- }
- /**
- * Forces the pipeline to finish processing the last segment and emit it's
- * results.
- *
- * @param {Object} data event data, not really used
- */
- ;
-
- _proto.flush = function flush(data) {
- this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
-
- self.postMessage({
- action: 'done',
- type: 'transmuxed'
- });
- };
-
- _proto.partialFlush = function partialFlush(data) {
- this.transmuxer.partialFlush(); // transmuxed partialdone action is fired after both audio/video pipelines are flushed
-
- self.postMessage({
- action: 'partialdone',
- type: 'transmuxed'
- });
- };
-
- _proto.endTimeline = function endTimeline() {
- this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
- // timelines
-
- self.postMessage({
- action: 'endedtimeline',
- type: 'transmuxed'
- });
- };
-
- _proto.alignGopsWith = function alignGopsWith(data) {
- this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
- };
-
- return MessageHandlers;
- }();
- /**
- * Our web worker interface so that things can talk to mux.js
- * that will be running in a web worker. the scope is passed to this by
- * webworkify.
- *
- * @param {Object} self the scope for the web worker
- */
-
-
- var TransmuxerWorker = function TransmuxerWorker(self) {
- self.onmessage = function (event) {
- if (event.data.action === 'init' && event.data.options) {
- this.messageHandlers = new MessageHandlers(self, event.data.options);
- return;
- }
-
- if (!this.messageHandlers) {
- this.messageHandlers = new MessageHandlers(self);
- }
-
- if (event.data && event.data.action && event.data.action !== 'init') {
- if (this.messageHandlers[event.data.action]) {
- this.messageHandlers[event.data.action](event.data);
- }
- }
- };
- };
-
- var transmuxerWorker = new TransmuxerWorker(self);
-
- return transmuxerWorker;
-
-}());
diff --git a/node_modules/@videojs/http-streaming/src/util/codecs.js b/node_modules/@videojs/http-streaming/src/util/codecs.js
deleted file mode 100644
index 103d3e2..0000000
--- a/node_modules/@videojs/http-streaming/src/util/codecs.js
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
- * codec strings, or translating codec strings into objects that can be examined.
- */
-
-import {
- translateLegacyCodec,
- parseCodecs,
- codecsFromDefault
-} from '@videojs/vhs-utils/es/codecs.js';
-import logger from './logger.js';
-
-const logFn = logger('CodecUtils');
-
-/**
- * Returns a set of codec strings parsed from the playlist or the default
- * codec strings if no codecs were specified in the playlist
- *
- * @param {Playlist} media the current media playlist
- * @return {Object} an object with the video and audio codecs
- */
-const getCodecs = function(media) {
- // if the codecs were explicitly specified, use them instead of the
- // defaults
- const mediaAttributes = media.attributes || {};
-
- if (mediaAttributes.CODECS) {
- return parseCodecs(mediaAttributes.CODECS);
- }
-};
-
-export const isMaat = (master, media) => {
- const mediaAttributes = media.attributes || {};
-
- return master && master.mediaGroups && master.mediaGroups.AUDIO &&
- mediaAttributes.AUDIO &&
- master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
-};
-
-export const isMuxed = (master, media) => {
- if (!isMaat(master, media)) {
- return true;
- }
-
- const mediaAttributes = media.attributes || {};
- const audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
-
- for (const groupId in audioGroup) {
- // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
- // or there are listed playlists (the case for DASH, as the manifest will have already
- // provided all of the details necessary to generate the audio playlist, as opposed to
- // HLS' externally requested playlists), then the content is demuxed.
- if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
- return true;
- }
- }
-
- return false;
-};
-
-export const unwrapCodecList = function(codecList) {
- const codecs = {};
-
- codecList.forEach(({mediaType, type, details}) => {
- codecs[mediaType] = codecs[mediaType] || [];
- codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));
- });
-
- Object.keys(codecs).forEach(function(mediaType) {
- if (codecs[mediaType].length > 1) {
- logFn(`multiple ${mediaType} codecs found as attributes: ${codecs[mediaType].join(', ')}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`);
- codecs[mediaType] = null;
- return;
- }
-
- codecs[mediaType] = codecs[mediaType][0];
- });
-
- return codecs;
-};
-
-export const codecCount = function(codecObj) {
- let count = 0;
-
- if (codecObj.audio) {
- count++;
- }
-
- if (codecObj.video) {
- count++;
- }
-
- return count;
-};
-
-/**
- * Calculates the codec strings for a working configuration of
- * SourceBuffers to play variant streams in a master playlist. If
- * there is no possible working configuration, an empty object will be
- * returned.
- *
- * @param master {Object} the m3u8 object for the master playlist
- * @param media {Object} the m3u8 object for the variant playlist
- * @return {Object} the codec strings.
- *
- * @private
- */
-export const codecsForPlaylist = function(master, media) {
- const mediaAttributes = media.attributes || {};
- const codecInfo = unwrapCodecList(getCodecs(media) || []);
-
- // HLS with multiple-audio tracks must always get an audio codec.
- // Put another way, there is no way to have a video-only multiple-audio HLS!
- if (isMaat(master, media) && !codecInfo.audio) {
- if (!isMuxed(master, media)) {
- // It is possible for codecs to be specified on the audio media group playlist but
- // not on the rendition playlist. This is mostly the case for DASH, where audio and
- // video are always separate (and separately specified).
- const defaultCodecs = unwrapCodecList(codecsFromDefault(master, mediaAttributes.AUDIO) || []);
-
- if (defaultCodecs.audio) {
- codecInfo.audio = defaultCodecs.audio;
- }
- }
- }
-
- return codecInfo;
-};
diff --git a/node_modules/@videojs/http-streaming/src/util/container-request.js b/node_modules/@videojs/http-streaming/src/util/container-request.js
deleted file mode 100644
index 8bd5719..0000000
--- a/node_modules/@videojs/http-streaming/src/util/container-request.js
+++ /dev/null
@@ -1,86 +0,0 @@
-import {getId3Offset} from '@videojs/vhs-utils/es/id3-helpers';
-import {detectContainerForBytes} from '@videojs/vhs-utils/es/containers';
-import {stringToBytes, concatTypedArrays} from '@videojs/vhs-utils/es/byte-helpers';
-import {callbackWrapper} from '../xhr';
-
-// calls back if the request is readyState DONE
-// which will only happen if the request is complete.
-const callbackOnCompleted = (request, cb) => {
- if (request.readyState === 4) {
- return cb();
- }
- return;
-};
-
-const containerRequest = (uri, xhr, cb) => {
- let bytes = [];
- let id3Offset;
- let finished = false;
-
- const endRequestAndCallback = function(err, req, type, _bytes) {
- req.abort();
- finished = true;
- return cb(err, req, type, _bytes);
- };
-
- const progressListener = function(error, request) {
- if (finished) {
- return;
- }
- if (error) {
- return endRequestAndCallback(error, request, '', bytes);
- }
-
- // grap the new part of content that was just downloaded
- const newPart = request.responseText.substring(
- bytes && bytes.byteLength || 0,
- request.responseText.length
- );
-
- // add that onto bytes
- bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
- id3Offset = id3Offset || getId3Offset(bytes);
-
- // we need at least 10 bytes to determine a type
- // or we need at least two bytes after an id3Offset
- if (bytes.length < 10 || (id3Offset && bytes.length < id3Offset + 2)) {
- return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
- }
-
- const type = detectContainerForBytes(bytes);
-
- // if this looks like a ts segment but we don't have enough data
- // to see the second sync byte, wait until we have enough data
- // before declaring it ts
- if (type === 'ts' && bytes.length < 188) {
- return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
- }
-
- // this may be an unsynced ts segment
- // wait for 376 bytes before detecting no container
- if (!type && bytes.length < 376) {
- return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
- }
-
- return endRequestAndCallback(null, request, type, bytes);
- };
-
- const options = {
- uri,
- beforeSend(request) {
- // this forces the browser to pass the bytes to us unprocessed
- request.overrideMimeType('text/plain; charset=x-user-defined');
- request.addEventListener('progress', function({total, loaded}) {
- return callbackWrapper(request, null, {statusCode: request.status}, progressListener);
- });
- }
- };
-
- const request = xhr(options, function(error, response) {
- return callbackWrapper(request, error, response, progressListener);
- });
-
- return request;
-};
-
-export default containerRequest;
diff --git a/node_modules/@videojs/http-streaming/src/util/gops.js b/node_modules/@videojs/http-streaming/src/util/gops.js
deleted file mode 100644
index d951127..0000000
--- a/node_modules/@videojs/http-streaming/src/util/gops.js
+++ /dev/null
@@ -1,119 +0,0 @@
-import { ONE_SECOND_IN_TS } from 'mux.js/lib/utils/clock';
-
-/**
- * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
- * front of current time.
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {number} currentTime
- * The current time
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- * @return {Array}
- * List of gops considered safe to append over
- */
-export const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
- if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
- return [];
- }
-
- // pts value for current time + 3 seconds to give a bit more wiggle room
- const currentTimePts = Math.ceil((currentTime - mapping + 3) * ONE_SECOND_IN_TS);
-
- let i;
-
- for (i = 0; i < buffer.length; i++) {
- if (buffer[i].pts > currentTimePts) {
- break;
- }
- }
-
- return buffer.slice(i);
-};
-
-/**
- * Appends gop information (timing and byteLength) received by the transmuxer for the
- * gops appended in the last call to appendBuffer
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Array} gops
- * List of new gop information
- * @param {boolean} replace
- * If true, replace the buffer with the new gop information. If false, append the
- * new gop information to the buffer in the right location of time.
- * @return {Array}
- * Updated list of gop information
- */
-export const updateGopBuffer = (buffer, gops, replace) => {
- if (!gops.length) {
- return buffer;
- }
-
- if (replace) {
- // If we are in safe append mode, then completely overwrite the gop buffer
- // with the most recent appeneded data. This will make sure that when appending
- // future segments, we only try to align with gops that are both ahead of current
- // time and in the last segment appended.
- return gops.slice();
- }
-
- const start = gops[0].pts;
-
- let i = 0;
-
- for (i; i < buffer.length; i++) {
- if (buffer[i].pts >= start) {
- break;
- }
- }
-
- return buffer.slice(0, i).concat(gops);
-};
-
-/**
- * Removes gop information in buffer that overlaps with provided start and end
- *
- * @param {Array} buffer
- * The current buffer of gop information
- * @param {Double} start
- * position to start the remove at
- * @param {Double} end
- * position to end the remove at
- * @param {Double} mapping
- * Offset to map display time to stream presentation time
- */
-export const removeGopBuffer = (buffer, start, end, mapping) => {
- const startPts = Math.ceil((start - mapping) * ONE_SECOND_IN_TS);
- const endPts = Math.ceil((end - mapping) * ONE_SECOND_IN_TS);
- const updatedBuffer = buffer.slice();
-
- let i = buffer.length;
-
- while (i--) {
- if (buffer[i].pts <= endPts) {
- break;
- }
- }
-
- if (i === -1) {
- // no removal because end of remove range is before start of buffer
- return updatedBuffer;
- }
-
- let j = i + 1;
-
- while (j--) {
- if (buffer[j].pts <= startPts) {
- break;
- }
- }
-
- // clamp remove range start to 0 index
- j = Math.max(j, 0);
-
- updatedBuffer.splice(j, i - j + 1);
-
- return updatedBuffer;
-};
diff --git a/node_modules/@videojs/http-streaming/src/util/logger.js b/node_modules/@videojs/http-streaming/src/util/logger.js
deleted file mode 100644
index b5a6d86..0000000
--- a/node_modules/@videojs/http-streaming/src/util/logger.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import videojs from 'video.js';
-
-const logger = (source) => {
- if (videojs.log.debug) {
- return videojs.log.debug.bind(videojs, 'VHS:', `${source} >`);
- }
-
- return function() {};
-};
-
-export default logger;
diff --git a/node_modules/@videojs/http-streaming/src/util/noop.js b/node_modules/@videojs/http-streaming/src/util/noop.js
deleted file mode 100644
index ca6a744..0000000
--- a/node_modules/@videojs/http-streaming/src/util/noop.js
+++ /dev/null
@@ -1 +0,0 @@
-export default function noop() {}
diff --git a/node_modules/@videojs/http-streaming/src/util/segment.js b/node_modules/@videojs/http-streaming/src/util/segment.js
deleted file mode 100644
index c9adbe9..0000000
--- a/node_modules/@videojs/http-streaming/src/util/segment.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * Combine all segments into a single Uint8Array
- *
- * @param {Object} segmentObj
- * @return {Uint8Array} concatenated bytes
- * @private
- */
-export const concatSegments = (segmentObj) => {
- let offset = 0;
- let tempBuffer;
-
- if (segmentObj.bytes) {
- tempBuffer = new Uint8Array(segmentObj.bytes);
-
- // combine the individual segments into one large typed-array
- segmentObj.segments.forEach((segment) => {
- tempBuffer.set(segment, offset);
- offset += segment.byteLength;
- });
- }
-
- return tempBuffer;
-};
diff --git a/node_modules/@videojs/http-streaming/src/util/shallow-equal.js b/node_modules/@videojs/http-streaming/src/util/shallow-equal.js
deleted file mode 100644
index e4b13bb..0000000
--- a/node_modules/@videojs/http-streaming/src/util/shallow-equal.js
+++ /dev/null
@@ -1,41 +0,0 @@
-const shallowEqual = function(a, b) {
- // if both are undefined
- // or one or the other is undefined
- // they are not equal
- if ((!a && !b) || (!a && b) || (a && !b)) {
- return false;
- }
-
- // they are the same object and thus, equal
- if (a === b) {
- return true;
- }
-
- // sort keys so we can make sure they have
- // all the same keys later.
- const akeys = Object.keys(a).sort();
- const bkeys = Object.keys(b).sort();
-
- // different number of keys, not equal
- if (akeys.length !== bkeys.length) {
- return false;
- }
-
- for (let i = 0; i < akeys.length; i++) {
- const key = akeys[i];
-
- // different sorted keys, not equal
- if (key !== bkeys[i]) {
- return false;
- }
-
- // different values, not equal
- if (a[key] !== b[key]) {
- return false;
- }
- }
-
- return true;
-};
-
-export default shallowEqual;
diff --git a/node_modules/@videojs/http-streaming/src/util/string-to-array-buffer.js b/node_modules/@videojs/http-streaming/src/util/string-to-array-buffer.js
deleted file mode 100644
index 92c09ac..0000000
--- a/node_modules/@videojs/http-streaming/src/util/string-to-array-buffer.js
+++ /dev/null
@@ -1,9 +0,0 @@
-export const stringToArrayBuffer = (string) => {
- const view = new Uint8Array(new ArrayBuffer(string.length));
-
- for (let i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view.buffer;
-};
diff --git a/node_modules/@videojs/http-streaming/src/util/string.js b/node_modules/@videojs/http-streaming/src/util/string.js
deleted file mode 100644
index abec959..0000000
--- a/node_modules/@videojs/http-streaming/src/util/string.js
+++ /dev/null
@@ -1,2 +0,0 @@
-export const uint8ToUtf8 = (uintArray) =>
- decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
diff --git a/node_modules/@videojs/http-streaming/src/util/text-tracks.js b/node_modules/@videojs/http-streaming/src/util/text-tracks.js
deleted file mode 100644
index cc95a31..0000000
--- a/node_modules/@videojs/http-streaming/src/util/text-tracks.js
+++ /dev/null
@@ -1,311 +0,0 @@
-/**
- * @file text-tracks.js
- */
-import window from 'global/window';
-import videojs from 'video.js';
-
-/**
- * Create captions text tracks on video.js if they do not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {Object} tech the video.js tech
- * @param {Object} captionStream the caption stream to create
- * @private
- */
-export const createCaptionsTrackIfNotExists = function(inbandTextTracks, tech, captionStream) {
- if (!inbandTextTracks[captionStream]) {
- tech.trigger({type: 'usage', name: 'vhs-608'});
- tech.trigger({type: 'usage', name: 'hls-608'});
-
- let instreamId = captionStream;
-
- // we need to translate SERVICEn for 708 to how mux.js currently labels them
- if (/^cc708_/.test(captionStream)) {
- instreamId = 'SERVICE' + captionStream.split('_')[1];
- }
-
- const track = tech.textTracks().getTrackById(instreamId);
-
- if (track) {
- // Resuse an existing track with a CC# id because this was
- // very likely created by videojs-contrib-hls from information
- // in the m3u8 for us to use
- inbandTextTracks[captionStream] = track;
- } else {
- // This section gets called when we have caption services that aren't specified in the manifest.
- // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
- const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
- let label = captionStream;
- let language = captionStream;
- let def = false;
- const captionService = captionServices[instreamId];
-
- if (captionService) {
- label = captionService.label;
- language = captionService.language;
- def = captionService.default;
- }
-
- // Otherwise, create a track with the default `CC#` label and
- // without a language
- inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
- kind: 'captions',
- id: instreamId,
- // TODO: investigate why this doesn't seem to turn the caption on by default
- default: def,
- label,
- language
- }, false).track;
- }
- }
-};
-
-/**
- * Add caption text track data to a source handler given an array of captions
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {Array} captionArray an array of caption data
- * @private
- */
-export const addCaptionData = function({
- inbandTextTracks,
- captionArray,
- timestampOffset
-}) {
- if (!captionArray) {
- return;
- }
-
- const Cue = window.WebKitDataCue || window.VTTCue;
-
- captionArray.forEach((caption) => {
- const track = caption.stream;
-
- inbandTextTracks[track].addCue(new Cue(
- caption.startTime + timestampOffset,
- caption.endTime + timestampOffset,
- caption.text
- ));
- });
-};
-
-/**
- * Define properties on a cue for backwards compatability,
- * but warn the user that the way that they are using it
- * is depricated and will be removed at a later date.
- *
- * @param {Cue} cue the cue to add the properties on
- * @private
- */
-const deprecateOldCue = function(cue) {
- Object.defineProperties(cue.frame, {
- id: {
- get() {
- videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
- return cue.value.key;
- }
- },
- value: {
- get() {
- videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- },
- privateData: {
- get() {
- videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
- return cue.value.data;
- }
- }
- });
-};
-
-/**
- * Add metadata text track data to a source handler given an array of metadata
- *
- * @param {Object}
- * @param {Object} inbandTextTracks the inband text tracks
- * @param {Array} metadataArray an array of meta data
- * @param {number} timestampOffset the timestamp offset of the source buffer
- * @param {number} videoDuration the duration of the video
- * @private
- */
-export const addMetadata = ({
- inbandTextTracks,
- metadataArray,
- timestampOffset,
- videoDuration
-}) => {
- if (!metadataArray) {
- return;
- }
-
- const Cue = window.WebKitDataCue || window.VTTCue;
- const metadataTrack = inbandTextTracks.metadataTrack_;
-
- if (!metadataTrack) {
- return;
- }
-
- metadataArray.forEach((metadata) => {
- const time = metadata.cueTime + timestampOffset;
-
- // if time isn't a finite number between 0 and Infinity, like NaN,
- // ignore this bit of metadata.
- // This likely occurs when you have an non-timed ID3 tag like TIT2,
- // which is the "Title/Songname/Content description" frame
- if (typeof time !== 'number' || window.isNaN(time) || time < 0 || !(time < Infinity)) {
- return;
- }
-
- metadata.frames.forEach((frame) => {
- const cue = new Cue(
- time,
- time,
- frame.value || frame.url || frame.data || ''
- );
-
- cue.frame = frame;
- cue.value = frame;
- deprecateOldCue(cue);
-
- metadataTrack.addCue(cue);
- });
- });
-
- if (!metadataTrack.cues || !metadataTrack.cues.length) {
- return;
- }
-
- // Updating the metadeta cues so that
- // the endTime of each cue is the startTime of the next cue
- // the endTime of last cue is the duration of the video
- const cues = metadataTrack.cues;
- const cuesArray = [];
-
- // Create a copy of the TextTrackCueList...
- // ...disregarding cues with a falsey value
- for (let i = 0; i < cues.length; i++) {
- if (cues[i]) {
- cuesArray.push(cues[i]);
- }
- }
-
- // Group cues by their startTime value
- const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
- const timeSlot = obj[cue.startTime] || [];
-
- timeSlot.push(cue);
- obj[cue.startTime] = timeSlot;
-
- return obj;
- }, {});
-
- // Sort startTimes by ascending order
- const sortedStartTimes = Object.keys(cuesGroupedByStartTime)
- .sort((a, b) => Number(a) - Number(b));
-
- // Map each cue group's endTime to the next group's startTime
- sortedStartTimes.forEach((startTime, idx) => {
- const cueGroup = cuesGroupedByStartTime[startTime];
- const nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration;
-
- // Map each cue's endTime the next group's startTime
- cueGroup.forEach((cue) => {
- cue.endTime = nextTime;
- });
- });
-};
-
-/**
- * Create metadata text track on video.js if it does not exist
- *
- * @param {Object} inbandTextTracks a reference to current inbandTextTracks
- * @param {string} dispatchType the inband metadata track dispatch type
- * @param {Object} tech the video.js tech
- * @private
- */
-export const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
- if (inbandTextTracks.metadataTrack_) {
- return;
- }
-
- inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
- kind: 'metadata',
- label: 'Timed Metadata'
- }, false).track;
-
- inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
-};
-
-/**
- * Remove cues from a track on video.js.
- *
- * @param {Double} start start of where we should remove the cue
- * @param {Double} end end of where the we should remove the cue
- * @param {Object} track the text track to remove the cues from
- * @private
- */
-export const removeCuesFromTrack = function(start, end, track) {
- let i;
- let cue;
-
- if (!track) {
- return;
- }
-
- if (!track.cues) {
- return;
- }
-
- i = track.cues.length;
-
- while (i--) {
- cue = track.cues[i];
-
- // Remove any cue within the provided start and end time
- if (cue.startTime >= start && cue.endTime <= end) {
- track.removeCue(cue);
- }
- }
-};
-
-/**
- * Remove duplicate cues from a track on video.js (a cue is considered a
- * duplicate if it has the same time interval and text as another)
- *
- * @param {Object} track the text track to remove the duplicate cues from
- * @private
- */
-export const removeDuplicateCuesFromTrack = function(track) {
- const cues = track.cues;
-
- if (!cues) {
- return;
- }
-
- for (let i = 0; i < cues.length; i++) {
- const duplicates = [];
- let occurrences = 0;
-
- for (let j = 0; j < cues.length; j++) {
- if (
- cues[i].startTime === cues[j].startTime &&
- cues[i].endTime === cues[j].endTime &&
- cues[i].text === cues[j].text
- ) {
- occurrences++;
-
- if (occurrences > 1) {
- duplicates.push(cues[j]);
- }
- }
- }
-
- if (duplicates.length) {
- duplicates.forEach(dupe => track.removeCue(dupe));
- }
- }
-};
diff --git a/node_modules/@videojs/http-streaming/src/util/time.js b/node_modules/@videojs/http-streaming/src/util/time.js
deleted file mode 100644
index 3edf48f..0000000
--- a/node_modules/@videojs/http-streaming/src/util/time.js
+++ /dev/null
@@ -1,402 +0,0 @@
-// TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
-
-/**
- * @file time.js
- */
-
-import Playlist from '../playlist';
-
-// Add 25% to the segment duration to account for small discrepencies in segment timing.
-// 25% was arbitrarily chosen, and may need to be refined over time.
-const SEGMENT_END_FUDGE_PERCENT = 0.25;
-
-/**
- * Converts a player time (any time that can be gotten/set from player.currentTime(),
- * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
- * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
- *
- * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
- * point" (a point where we have a mapping from program time to player time, with player
- * time being the post transmux start of the segment).
- *
- * For more details, see [this doc](../../docs/program-time-from-player-time.md).
- *
- * @param {number} playerTime the player time
- * @param {Object} segment the segment which contains the player time
- * @return {Date} program time
- */
-export const playerTimeToProgramTime = (playerTime, segment) => {
- if (!segment.dateTimeObject) {
- // Can't convert without an "anchor point" for the program time (i.e., a time that can
- // be used to map the start of a segment with a real world time).
- return null;
- }
-
- const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
- const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart;
-
- // get the start of the content from before old content is prepended
- const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
- const offsetFromSegmentStart = playerTime - startOfSegment;
-
- return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
-};
-
-export const originalSegmentVideoDuration = (videoTimingInfo) => {
- return videoTimingInfo.transmuxedPresentationEnd -
- videoTimingInfo.transmuxedPresentationStart -
- videoTimingInfo.transmuxerPrependedSeconds;
-};
-
-/**
- * Finds a segment that contains the time requested given as an ISO-8601 string. The
- * returned segment might be an estimate or an accurate match.
- *
- * @param {string} programTime The ISO-8601 programTime to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-export const findSegmentForProgramTime = (programTime, playlist) => {
- // Assumptions:
- // - verifyProgramDateTimeTags has already been run
- // - live streams have been started
-
- let dateTimeObject;
-
- try {
- dateTimeObject = new Date(programTime);
- } catch (e) {
- return null;
- }
-
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- let segment = playlist.segments[0];
-
- if (dateTimeObject < segment.dateTimeObject) {
- // Requested time is before stream start.
- return null;
- }
-
- for (let i = 0; i < playlist.segments.length - 1; i++) {
- segment = playlist.segments[i];
-
- const nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
-
- if (dateTimeObject < nextSegmentStart) {
- break;
- }
- }
-
- const lastSegment = playlist.segments[playlist.segments.length - 1];
- const lastSegmentStart = lastSegment.dateTimeObject;
- const lastSegmentDuration = lastSegment.videoTimingInfo ?
- originalSegmentVideoDuration(lastSegment.videoTimingInfo) :
- lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
- const lastSegmentEnd =
- new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
-
- if (dateTimeObject > lastSegmentEnd) {
- // Beyond the end of the stream, or our best guess of the end of the stream.
- return null;
- }
-
- if (dateTimeObject > lastSegmentStart) {
- segment = lastSegment;
- }
-
- return {
- segment,
- estimatedStart: segment.videoTimingInfo ?
- segment.videoTimingInfo.transmuxedPresentationStart :
- Playlist.duration(
- playlist,
- playlist.mediaSequence + playlist.segments.indexOf(segment)
- ),
- // Although, given that all segments have accurate date time objects, the segment
- // selected should be accurate, unless the video has been transmuxed at some point
- // (determined by the presence of the videoTimingInfo object), the segment's "player
- // time" (the start time in the player) can't be considered accurate.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
-};
-
-/**
- * Finds a segment that contains the given player time(in seconds).
- *
- * @param {number} time The player time to find a match for
- * @param {Object} playlist A playlist object to search within
- */
-export const findSegmentForPlayerTime = (time, playlist) => {
- // Assumptions:
- // - there will always be a segment.duration
- // - we can start from zero
- // - segments are in time order
-
- if (!playlist || !playlist.segments || playlist.segments.length === 0) {
- return null;
- }
-
- let segmentEnd = 0;
- let segment;
-
- for (let i = 0; i < playlist.segments.length; i++) {
- segment = playlist.segments[i];
-
- // videoTimingInfo is set after the segment is downloaded and transmuxed, and
- // should contain the most accurate values we have for the segment's player times.
- //
- // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
- // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
- // calculate an end value.
- segmentEnd = segment.videoTimingInfo ?
- segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
-
- if (time <= segmentEnd) {
- break;
- }
- }
-
- const lastSegment = playlist.segments[playlist.segments.length - 1];
-
- if (lastSegment.videoTimingInfo &&
- lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
- // The time requested is beyond the stream end.
- return null;
- }
-
- if (time > segmentEnd) {
- // The time is within or beyond the last segment.
- //
- // Check to see if the time is beyond a reasonable guess of the end of the stream.
- if (time > segmentEnd + (lastSegment.duration * SEGMENT_END_FUDGE_PERCENT)) {
- // Technically, because the duration value is only an estimate, the time may still
- // exist in the last segment, however, there isn't enough information to make even
- // a reasonable estimate.
- return null;
- }
-
- segment = lastSegment;
- }
-
- return {
- segment,
- estimatedStart: segment.videoTimingInfo ?
- segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
- // Because videoTimingInfo is only set after transmux, it is the only way to get
- // accurate timing values.
- type: segment.videoTimingInfo ? 'accurate' : 'estimate'
- };
-};
-
-/**
- * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
- * If the offset returned is positive, the programTime occurs after the
- * comparisonTimestamp.
- * If the offset is negative, the programTime occurs before the comparisonTimestamp.
- *
- * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
- * @param {string} programTime The programTime as an ISO-8601 string
- * @return {number} offset
- */
-export const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
- let segmentDateTime;
- let programDateTime;
-
- try {
- segmentDateTime = new Date(comparisonTimeStamp);
- programDateTime = new Date(programTime);
- } catch (e) {
- // TODO handle error
- }
-
- const segmentTimeEpoch = segmentDateTime.getTime();
- const programTimeEpoch = programDateTime.getTime();
-
- return (programTimeEpoch - segmentTimeEpoch) / 1000;
-};
-
-/**
- * Checks that all segments in this playlist have programDateTime tags.
- *
- * @param {Object} playlist A playlist object
- */
-export const verifyProgramDateTimeTags = (playlist) => {
- if (!playlist.segments || playlist.segments.length === 0) {
- return false;
- }
-
- for (let i = 0; i < playlist.segments.length; i++) {
- const segment = playlist.segments[i];
-
- if (!segment.dateTimeObject) {
- return false;
- }
- }
-
- return true;
-};
-
-/**
- * Returns the programTime of the media given a playlist and a playerTime.
- * The playlist must have programDateTime tags for a programDateTime tag to be returned.
- * If the segments containing the time requested have not been buffered yet, an estimate
- * may be returned to the callback.
- *
- * @param {Object} args
- * @param {Object} args.playlist A playlist object to search within
- * @param {number} time A playerTime in seconds
- * @param {Function} callback(err, programTime)
- * @return {string} err.message A detailed error message
- * @return {Object} programTime
- * @return {number} programTime.mediaSeconds The streamTime in seconds
- * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
- */
-export const getProgramTime = ({
- playlist,
- time = undefined,
- callback
-}) => {
-
- if (!callback) {
- throw new Error('getProgramTime: callback must be provided');
- }
-
- if (!playlist || time === undefined) {
- return callback({
- message: 'getProgramTime: playlist and time must be provided'
- });
- }
-
- const matchedSegment = findSegmentForPlayerTime(time, playlist);
-
- if (!matchedSegment) {
- return callback({
- message: 'valid programTime was not found'
- });
- }
-
- if (matchedSegment.type === 'estimate') {
- return callback({
- message:
- 'Accurate programTime could not be determined.' +
- ' Please seek to e.seekTime and try again',
- seekTime: matchedSegment.estimatedStart
- });
- }
-
- const programTimeObject = {
- mediaSeconds: time
- };
- const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
-
- if (programTime) {
- programTimeObject.programDateTime = programTime.toISOString();
- }
-
- return callback(null, programTimeObject);
-};
-
-/**
- * Seeks in the player to a time that matches the given programTime ISO-8601 string.
- *
- * @param {Object} args
- * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
- * @param {Object} args.playlist A playlist to look within
- * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
- * @param {Function} args.seekTo A method to perform a seek
- * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
- * @param {Object} args.tech The tech to seek on
- * @param {Function} args.callback(err, newTime) A callback to return the new time to
- * @return {string} err.message A detailed error message
- * @return {number} newTime The exact time that was seeked to in seconds
- */
-export const seekToProgramTime = ({
- programTime,
- playlist,
- retryCount = 2,
- seekTo,
- pauseAfterSeek = true,
- tech,
- callback
-}) => {
-
- if (!callback) {
- throw new Error('seekToProgramTime: callback must be provided');
- }
-
- if (typeof programTime === 'undefined' || !playlist || !seekTo) {
- return callback({
- message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
- });
- }
-
- if (!playlist.endList && !tech.hasStarted_) {
- return callback({
- message: 'player must be playing a live stream to start buffering'
- });
- }
-
- if (!verifyProgramDateTimeTags(playlist)) {
- return callback({
- message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
- });
- }
-
- const matchedSegment = findSegmentForProgramTime(programTime, playlist);
-
- // no match
- if (!matchedSegment) {
- return callback({
- message: `${programTime} was not found in the stream`
- });
- }
-
- const segment = matchedSegment.segment;
- const mediaOffset = getOffsetFromTimestamp(
- segment.dateTimeObject,
- programTime
- );
-
- if (matchedSegment.type === 'estimate') {
- // we've run out of retries
- if (retryCount === 0) {
- return callback({
- message: `${programTime} is not buffered yet. Try again`
- });
- }
-
- seekTo(matchedSegment.estimatedStart + mediaOffset);
-
- tech.one('seeked', () => {
- seekToProgramTime({
- programTime,
- playlist,
- retryCount: retryCount - 1,
- seekTo,
- pauseAfterSeek,
- tech,
- callback
- });
- });
-
- return;
- }
-
- // Since the segment.start value is determined from the buffered end or ending time
- // of the prior segment, the seekToTime doesn't need to account for any transmuxer
- // modifications.
- const seekToTime = segment.start + mediaOffset;
- const seekedCallback = () => {
- return callback(null, tech.currentTime());
- };
-
- // listen for seeked event
- tech.one('seeked', seekedCallback);
- // pause before seeking as video.js will restore this state
- if (pauseAfterSeek) {
- tech.pause();
- }
- seekTo(seekToTime);
-};
diff --git a/node_modules/@videojs/http-streaming/src/util/to-title-case.js b/node_modules/@videojs/http-streaming/src/util/to-title-case.js
deleted file mode 100644
index 48856ac..0000000
--- a/node_modules/@videojs/http-streaming/src/util/to-title-case.js
+++ /dev/null
@@ -1,9 +0,0 @@
-const toTitleCase = function(string) {
- if (typeof string !== 'string') {
- return string;
- }
-
- return string.replace(/./, (w) => w.toUpperCase());
-};
-
-export default toTitleCase;
diff --git a/node_modules/@videojs/http-streaming/src/util/worker-callback.js b/node_modules/@videojs/http-streaming/src/util/worker-callback.js
deleted file mode 100644
index 9747547..0000000
--- a/node_modules/@videojs/http-streaming/src/util/worker-callback.js
+++ /dev/null
@@ -1,42 +0,0 @@
-export const workerCallback = function(options) {
- const transmuxer = options.transmuxer;
- const endAction = options.endAction || options.action;
- const callback = options.callback;
- const message = Object.assign({}, options, {endAction: null, transmuxer: null, callback: null});
-
- const listenForEndEvent = (event) => {
- if (event.data.action !== endAction) {
- return;
- }
- transmuxer.removeEventListener('message', listenForEndEvent);
-
- // transfer ownership of bytes back to us.
- if (event.data.data) {
- event.data.data = new Uint8Array(
- event.data.data,
- options.byteOffset || 0,
- options.byteLength || event.data.data.byteLength
- );
- if (options.data) {
- options.data = event.data.data;
- }
- }
-
- callback(event.data);
- };
-
- transmuxer.addEventListener('message', listenForEndEvent);
-
- if (options.data) {
- const isArrayBuffer = options.data instanceof ArrayBuffer;
-
- message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
- message.byteLength = options.data.byteLength;
-
- const transfers = [isArrayBuffer ? options.data : options.data.buffer];
-
- transmuxer.postMessage(message, transfers);
- } else {
- transmuxer.postMessage(message);
- }
-};
diff --git a/node_modules/@videojs/http-streaming/src/videojs-http-streaming.js b/node_modules/@videojs/http-streaming/src/videojs-http-streaming.js
deleted file mode 100644
index db21548..0000000
--- a/node_modules/@videojs/http-streaming/src/videojs-http-streaming.js
+++ /dev/null
@@ -1,1270 +0,0 @@
-/**
- * @file videojs-http-streaming.js
- *
- * The main file for the HLS project.
- * License: https://github.com/videojs/videojs-http-streaming/blob/master/LICENSE
- */
-import document from 'global/document';
-import window from 'global/window';
-import PlaylistLoader from './playlist-loader';
-import Playlist from './playlist';
-import xhrFactory from './xhr';
-import { simpleTypeFromSourceType } from '@videojs/vhs-utils/es/media-types.js';
-import * as utils from './bin-utils';
-import {
- getProgramTime,
- seekToProgramTime
-} from './util/time';
-import { timeRangesToArray } from './ranges';
-import videojs from 'video.js';
-import { MasterPlaylistController } from './master-playlist-controller';
-import Config from './config';
-import renditionSelectionMixin from './rendition-mixin';
-import PlaybackWatcher from './playback-watcher';
-import SourceUpdater from './source-updater';
-import reloadSourceOnError from './reload-source-on-error';
-import {
- lastBandwidthSelector,
- lowestBitrateCompatibleVariantSelector,
- movingAverageBandwidthSelector,
- comparePlaylistBandwidth,
- comparePlaylistResolution
-} from './playlist-selectors.js';
-import {
- browserSupportsCodec,
- getMimeForCodec,
- parseCodecs
-} from '@videojs/vhs-utils/es/codecs.js';
-import { unwrapCodecList } from './util/codecs.js';
-import logger from './util/logger';
-import {SAFE_TIME_DELTA} from './ranges';
-
-// IMPORTANT:
-// keep these at the bottom they are replaced at build time
-// because webpack and rollup without plugins do not support json
-// and we do not want to break our users
-import {version as vhsVersion} from '../package.json';
-import {version as muxVersion} from 'mux.js/package.json';
-import {version as mpdVersion} from 'mpd-parser/package.json';
-import {version as m3u8Version} from 'm3u8-parser/package.json';
-import {version as aesVersion} from 'aes-decrypter/package.json';
-
-const Vhs = {
- PlaylistLoader,
- Playlist,
- utils,
-
- STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
- INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
- lastBandwidthSelector,
- movingAverageBandwidthSelector,
- comparePlaylistBandwidth,
- comparePlaylistResolution,
-
- xhr: xhrFactory()
-};
-
-// Define getter/setters for config properties
-Object.keys(Config).forEach((prop) => {
- Object.defineProperty(Vhs, prop, {
- get() {
- videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
- return Config[prop];
- },
- set(value) {
- videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
-
- if (typeof value !== 'number' || value < 0) {
- videojs.log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
- return;
- }
-
- Config[prop] = value;
- }
- });
-});
-
-export const LOCAL_STORAGE_KEY = 'videojs-vhs';
-
-/**
- * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
- * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
- * @function handleVhsMediaChange
- */
-const handleVhsMediaChange = function(qualityLevels, playlistLoader) {
- const newPlaylist = playlistLoader.media();
- let selectedIndex = -1;
-
- for (let i = 0; i < qualityLevels.length; i++) {
- if (qualityLevels[i].id === newPlaylist.id) {
- selectedIndex = i;
- break;
- }
- }
-
- qualityLevels.selectedIndex_ = selectedIndex;
- qualityLevels.trigger({
- selectedIndex,
- type: 'change'
- });
-};
-
-/**
- * Adds quality levels to list once playlist metadata is available
- *
- * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
- * @param {Object} vhs Vhs object to listen to for media events.
- * @function handleVhsLoadedMetadata
- */
-const handleVhsLoadedMetadata = function(qualityLevels, vhs) {
- vhs.representations().forEach((rep) => {
- qualityLevels.addQualityLevel(rep);
- });
- handleVhsMediaChange(qualityLevels, vhs.playlists);
-};
-
-// HLS is a source handler, not a tech. Make sure attempts to use it
-// as one do not cause exceptions.
-Vhs.canPlaySource = function() {
- return videojs.log.warn('HLS is no longer a tech. Please remove it from ' +
- 'your player\'s techOrder.');
-};
-
-const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
- if (!keySystemOptions) {
- return keySystemOptions;
- }
-
- let codecs = {};
-
- if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
- codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
- }
-
- if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
- codecs.audio = audioPlaylist.attributes.CODECS;
- }
-
- const videoContentType = getMimeForCodec(codecs.video);
- const audioContentType = getMimeForCodec(codecs.audio);
-
- // upsert the content types based on the selected playlist
- const keySystemContentTypes = {};
-
- for (const keySystem in keySystemOptions) {
- keySystemContentTypes[keySystem] = {};
-
- if (audioContentType) {
- keySystemContentTypes[keySystem].audioContentType = audioContentType;
- }
- if (videoContentType) {
- keySystemContentTypes[keySystem].videoContentType = videoContentType;
- }
-
- // Default to using the video playlist's PSSH even though they may be different, as
- // videojs-contrib-eme will only accept one in the options.
- //
- // This shouldn't be an issue for most cases as early intialization will handle all
- // unique PSSH values, and if they aren't, then encrypted events should have the
- // specific information needed for the unique license.
- if (mainPlaylist.contentProtection &&
- mainPlaylist.contentProtection[keySystem] &&
- mainPlaylist.contentProtection[keySystem].pssh) {
- keySystemContentTypes[keySystem].pssh =
- mainPlaylist.contentProtection[keySystem].pssh;
- }
-
- // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
- // so we need to prevent overwriting the URL entirely
- if (typeof keySystemOptions[keySystem] === 'string') {
- keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
- }
- }
-
- return videojs.mergeOptions(keySystemOptions, keySystemContentTypes);
-};
-
-/**
- * @typedef {Object} KeySystems
- *
- * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
- * Note: not all options are listed here.
- *
- * @property {Uint8Array} [pssh]
- * Protection System Specific Header
- */
-
-/**
- * Goes through all the playlists and collects an array of KeySystems options objects
- * containing each playlist's keySystems and their pssh values, if available.
- *
- * @param {Object[]} playlists
- * The playlists to look through
- * @param {string[]} keySystems
- * The keySystems to collect pssh values for
- *
- * @return {KeySystems[]}
- * An array of KeySystems objects containing available key systems and their
- * pssh values
- */
-const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
- return playlists.reduce((keySystemsArr, playlist) => {
- if (!playlist.contentProtection) {
- return keySystemsArr;
- }
-
- const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
- const keySystemOptions = playlist.contentProtection[keySystem];
-
- if (keySystemOptions && keySystemOptions.pssh) {
- keySystemsObj[keySystem] = { pssh: keySystemOptions.pssh };
- }
-
- return keySystemsObj;
- }, {});
-
- if (Object.keys(keySystemsOptions).length) {
- keySystemsArr.push(keySystemsOptions);
- }
-
- return keySystemsArr;
- }, []);
-};
-
-/**
- * Returns a promise that waits for the
- * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
- *
- * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
- * browsers.
- *
- * As per the above ticket, this is particularly important for Chrome, where, if
- * unencrypted content is appended before encrypted content and the key session has not
- * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
- * during playback.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- * @param {Object[]} mainPlaylists
- * The playlists found on the master playlist object
- *
- * @return {Object}
- * Promise that resolves when the key session has been created
- */
-export const waitForKeySessionCreation = ({
- player,
- sourceKeySystems,
- audioMedia,
- mainPlaylists
-}) => {
- if (!player.eme.initializeMediaKeys) {
- return Promise.resolve();
- }
-
- // TODO should all audio PSSH values be initialized for DRM?
- //
- // All unique video rendition pssh values are initialized for DRM, but here only
- // the initial audio playlist license is initialized. In theory, an encrypted
- // event should be fired if the user switches to an alternative audio playlist
- // where a license is required, but this case hasn't yet been tested. In addition, there
- // may be many alternate audio playlists unlikely to be used (e.g., multiple different
- // languages).
- const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
-
- const keySystemsOptionsArr = getAllPsshKeySystemsOptions(
- playlists,
- Object.keys(sourceKeySystems)
- );
-
- const initializationFinishedPromises = [];
- const keySessionCreatedPromises = [];
-
- // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
- // only place where it should not be deduped is for ms-prefixed APIs, but the early
- // return for IE11 above, and the existence of modern EME APIs in addition to
- // ms-prefixed APIs on Edge should prevent this from being a concern.
- // initializeMediaKeys also won't use the webkit-prefixed APIs.
- keySystemsOptionsArr.forEach((keySystemsOptions) => {
- keySessionCreatedPromises.push(new Promise((resolve, reject) => {
- player.tech_.one('keysessioncreated', resolve);
- }));
-
- initializationFinishedPromises.push(new Promise((resolve, reject) => {
- player.eme.initializeMediaKeys({
- keySystems: keySystemsOptions
- }, (err) => {
- if (err) {
- reject(err);
- return;
- }
- resolve();
- });
- }));
- });
-
- // The reasons Promise.race is chosen over Promise.any:
- //
- // * Promise.any is only available in Safari 14+.
- // * None of these promises are expected to reject. If they do reject, it might be
- // better here for the race to surface the rejection, rather than mask it by using
- // Promise.any.
- return Promise.race([
- // If a session was previously created, these will all finish resolving without
- // creating a new session, otherwise it will take until the end of all license
- // requests, which is why the key session check is used (to make setup much faster).
- Promise.all(initializationFinishedPromises),
- // Once a single session is created, the browser knows DRM will be used.
- Promise.race(keySessionCreatedPromises)
- ]);
-};
-
-/**
- * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
- * there are keySystems on the source, sets up source options to prepare the source for
- * eme.
- *
- * @param {Object} player
- * The player instance
- * @param {Object[]} sourceKeySystems
- * The key systems options from the player source
- * @param {Object} media
- * The active media playlist
- * @param {Object} [audioMedia]
- * The active audio media playlist (optional)
- *
- * @return {boolean}
- * Whether or not options were configured and EME is available
- */
-const setupEmeOptions = ({
- player,
- sourceKeySystems,
- media,
- audioMedia
-}) => {
- const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
-
- if (!sourceOptions) {
- return false;
- }
-
- player.currentSource().keySystems = sourceOptions;
-
- // eme handles the rest of the setup, so if it is missing
- // do nothing.
- if (sourceOptions && !player.eme) {
- videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
- return false;
- }
-
- return true;
-};
-
-const getVhsLocalStorage = () => {
- if (!window.localStorage) {
- return null;
- }
-
- const storedObject = window.localStorage.getItem(LOCAL_STORAGE_KEY);
-
- if (!storedObject) {
- return null;
- }
-
- try {
- return JSON.parse(storedObject);
- } catch (e) {
- // someone may have tampered with the value
- return null;
- }
-};
-
-const updateVhsLocalStorage = (options) => {
- if (!window.localStorage) {
- return false;
- }
-
- let objectToStore = getVhsLocalStorage();
-
- objectToStore = objectToStore ? videojs.mergeOptions(objectToStore, options) : options;
-
- try {
- window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
- } catch (e) {
- // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
- // storage is set to 0).
- // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
- // No need to perform any operation.
- return false;
- }
-
- return objectToStore;
-};
-
-/**
- * Parses VHS-supported media types from data URIs. See
- * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
- * for information on data URIs.
- *
- * @param {string} dataUri
- * The data URI
- *
- * @return {string|Object}
- * The parsed object/string, or the original string if no supported media type
- * was found
- */
-const expandDataUri = (dataUri) => {
- if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
- return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
- }
- // no known case for this data URI, return the string as-is
- return dataUri;
-};
-
-/**
- * Whether the browser has built-in HLS support.
- */
-Vhs.supportsNativeHls = (function() {
- if (!document || !document.createElement) {
- return false;
- }
-
- const video = document.createElement('video');
-
- // native HLS is definitely not supported if HTML5 video isn't
- if (!videojs.getTech('Html5').isSupported()) {
- return false;
- }
-
- // HLS manifests can go by many mime-types
- const canPlay = [
- // Apple santioned
- 'application/vnd.apple.mpegurl',
- // Apple sanctioned for backwards compatibility
- 'audio/mpegurl',
- // Very common
- 'audio/x-mpegurl',
- // Very common
- 'application/x-mpegurl',
- // Included for completeness
- 'video/x-mpegurl',
- 'video/mpegurl',
- 'application/mpegurl'
- ];
-
- return canPlay.some(function(canItPlay) {
- return (/maybe|probably/i).test(video.canPlayType(canItPlay));
- });
-}());
-
-Vhs.supportsNativeDash = (function() {
- if (!document || !document.createElement || !videojs.getTech('Html5').isSupported()) {
- return false;
- }
-
- return (/maybe|probably/i).test(document.createElement('video').canPlayType('application/dash+xml'));
-}());
-
-Vhs.supportsTypeNatively = (type) => {
- if (type === 'hls') {
- return Vhs.supportsNativeHls;
- }
-
- if (type === 'dash') {
- return Vhs.supportsNativeDash;
- }
-
- return false;
-};
-
-/**
- * HLS is a source handler, not a tech. Make sure attempts to use it
- * as one do not cause exceptions.
- */
-Vhs.isSupported = function() {
- return videojs.log.warn('HLS is no longer a tech. Please remove it from ' +
- 'your player\'s techOrder.');
-};
-
-const Component = videojs.getComponent('Component');
-
-/**
- * The Vhs Handler object, where we orchestrate all of the parts
- * of HLS to interact with video.js
- *
- * @class VhsHandler
- * @extends videojs.Component
- * @param {Object} source the soruce object
- * @param {Tech} tech the parent tech object
- * @param {Object} options optional and required options
- */
-class VhsHandler extends Component {
- constructor(source, tech, options) {
- super(tech, videojs.mergeOptions(options.hls, options.vhs));
-
- if (options.hls && Object.keys(options.hls).length) {
- videojs.log.warn('Using hls options is deprecated. Use vhs instead.');
- }
-
- // if a tech level `initialBandwidth` option was passed
- // use that over the VHS level `bandwidth` option
- if (typeof options.initialBandwidth === 'number') {
- this.options_.bandwidth = options.initialBandwidth;
- }
-
- this.logger_ = logger('VhsHandler');
-
- // tech.player() is deprecated but setup a reference to HLS for
- // backwards-compatibility
- if (tech.options_ && tech.options_.playerId) {
- const _player = videojs(tech.options_.playerId);
-
- if (!_player.hasOwnProperty('hls')) {
- Object.defineProperty(_player, 'hls', {
- get: () => {
- videojs.log.warn('player.hls is deprecated. Use player.tech().vhs instead.');
- tech.trigger({ type: 'usage', name: 'hls-player-access' });
- return this;
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('vhs')) {
- Object.defineProperty(_player, 'vhs', {
- get: () => {
- videojs.log.warn('player.vhs is deprecated. Use player.tech().vhs instead.');
- tech.trigger({ type: 'usage', name: 'vhs-player-access' });
- return this;
- },
- configurable: true
- });
- }
-
- if (!_player.hasOwnProperty('dash')) {
- Object.defineProperty(_player, 'dash', {
- get: () => {
- videojs.log.warn('player.dash is deprecated. Use player.tech().vhs instead.');
- return this;
- },
- configurable: true
- });
- }
-
- this.player_ = _player;
- }
-
- this.tech_ = tech;
- this.source_ = source;
- this.stats = {};
- this.ignoreNextSeekingEvent_ = false;
- this.setOptions_();
-
- if (this.options_.overrideNative &&
- tech.overrideNativeAudioTracks &&
- tech.overrideNativeVideoTracks) {
- tech.overrideNativeAudioTracks(true);
- tech.overrideNativeVideoTracks(true);
- } else if (this.options_.overrideNative &&
- (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
- // overriding native HLS only works if audio tracks have been emulated
- // error early if we're misconfigured
- throw new Error('Overriding native HLS requires emulated tracks. ' +
- 'See https://git.io/vMpjB');
- }
-
- // listen for fullscreenchange events for this player so that we
- // can adjust our quality selection quickly
- this.on(document, [
- 'fullscreenchange', 'webkitfullscreenchange',
- 'mozfullscreenchange', 'MSFullscreenChange'
- ], (event) => {
- const fullscreenElement = document.fullscreenElement ||
- document.webkitFullscreenElement ||
- document.mozFullScreenElement ||
- document.msFullscreenElement;
-
- if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
- this.masterPlaylistController_.fastQualityChange_();
- } else {
- // When leaving fullscreen, since the in page pixel dimensions should be smaller
- // than full screen, see if there should be a rendition switch down to preserve
- // bandwidth.
- this.masterPlaylistController_.checkABR_();
- }
- });
-
- this.on(this.tech_, 'seeking', function() {
- if (this.ignoreNextSeekingEvent_) {
- this.ignoreNextSeekingEvent_ = false;
- return;
- }
-
- this.setCurrentTime(this.tech_.currentTime());
- });
-
- this.on(this.tech_, 'error', function() {
- // verify that the error was real and we are loaded
- // enough to have mpc loaded.
- if (this.tech_.error() && this.masterPlaylistController_) {
- this.masterPlaylistController_.pauseLoading();
- }
- });
-
- this.on(this.tech_, 'play', this.play);
- }
-
- setOptions_() {
- // defaults
- this.options_.withCredentials = this.options_.withCredentials || false;
- this.options_.handleManifestRedirects = this.options_.handleManifestRedirects === false ? false : true;
- this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
- this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
- this.options_.smoothQualityChange = this.options_.smoothQualityChange || false;
- this.options_.useBandwidthFromLocalStorage =
- typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ?
- this.source_.useBandwidthFromLocalStorage :
- this.options_.useBandwidthFromLocalStorage || false;
- this.options_.customTagParsers = this.options_.customTagParsers || [];
- this.options_.customTagMappers = this.options_.customTagMappers || [];
- this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
-
- if (typeof this.options_.blacklistDuration !== 'number') {
- this.options_.blacklistDuration = 5 * 60;
- }
-
- if (typeof this.options_.bandwidth !== 'number') {
- if (this.options_.useBandwidthFromLocalStorage) {
- const storedObject = getVhsLocalStorage();
-
- if (storedObject && storedObject.bandwidth) {
- this.options_.bandwidth = storedObject.bandwidth;
- this.tech_.trigger({type: 'usage', name: 'vhs-bandwidth-from-local-storage'});
- this.tech_.trigger({type: 'usage', name: 'hls-bandwidth-from-local-storage'});
- }
- if (storedObject && storedObject.throughput) {
- this.options_.throughput = storedObject.throughput;
- this.tech_.trigger({type: 'usage', name: 'vhs-throughput-from-local-storage'});
- this.tech_.trigger({type: 'usage', name: 'hls-throughput-from-local-storage'});
- }
- }
- }
- // if bandwidth was not set by options or pulled from local storage, start playlist
- // selection at a reasonable bandwidth
- if (typeof this.options_.bandwidth !== 'number') {
- this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
- }
-
- // If the bandwidth number is unchanged from the initial setting
- // then this takes precedence over the enableLowInitialPlaylist option
- this.options_.enableLowInitialPlaylist =
- this.options_.enableLowInitialPlaylist &&
- this.options_.bandwidth === Config.INITIAL_BANDWIDTH;
-
- // grab options passed to player.src
- [
- 'withCredentials',
- 'useDevicePixelRatio',
- 'limitRenditionByPlayerDimensions',
- 'bandwidth',
- 'smoothQualityChange',
- 'customTagParsers',
- 'customTagMappers',
- 'handleManifestRedirects',
- 'cacheEncryptionKeys',
- 'playlistSelector',
- 'initialPlaylistSelector',
- 'experimentalBufferBasedABR',
- 'liveRangeSafeTimeDelta',
- 'experimentalLLHLS'
- ].forEach((option) => {
- if (typeof this.source_[option] !== 'undefined') {
- this.options_[option] = this.source_[option];
- }
- });
-
- this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
- this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
- }
- /**
- * called when player.src gets called, handle a new source
- *
- * @param {Object} src the source object to handle
- */
- src(src, type) {
- // do nothing if the src is falsey
- if (!src) {
- return;
- }
- this.setOptions_();
- // add master playlist controller options
- this.options_.src = expandDataUri(this.source_.src);
- this.options_.tech = this.tech_;
- this.options_.externVhs = Vhs;
- this.options_.sourceType = simpleTypeFromSourceType(type);
-
- // Whenever we seek internally, we should update the tech
- this.options_.seekTo = (time) => {
- this.tech_.setCurrentTime(time);
- };
-
- if (this.options_.smoothQualityChange) {
- videojs.log.warn('smoothQualityChange is deprecated and will be removed in the next major version');
- }
-
- this.masterPlaylistController_ = new MasterPlaylistController(this.options_);
-
- const playbackWatcherOptions = videojs.mergeOptions(
- {
- liveRangeSafeTimeDelta: SAFE_TIME_DELTA
- },
- this.options_,
- {
- seekable: () => this.seekable(),
- media: () => this.masterPlaylistController_.media(),
- masterPlaylistController: this.masterPlaylistController_
- }
- );
-
- this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
-
- this.masterPlaylistController_.on('error', () => {
- const player = videojs.players[this.tech_.options_.playerId];
- let error = this.masterPlaylistController_.error;
-
- if (typeof error === 'object' && !error.code) {
- error.code = 3;
- } else if (typeof error === 'string') {
- error = {message: error, code: 3};
- }
-
- player.error(error);
- });
-
- const defaultSelector = this.options_.experimentalBufferBasedABR ?
- Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR;
-
- // `this` in selectPlaylist should be the VhsHandler for backwards
- // compatibility with < v2
- this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ?
- this.selectPlaylist.bind(this) :
- defaultSelector.bind(this);
-
- this.masterPlaylistController_.selectInitialPlaylist =
- Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this);
-
- // re-expose some internal objects for backwards compatibility with < v2
- this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
- this.mediaSource = this.masterPlaylistController_.mediaSource;
-
- // Proxy assignment of some properties to the master playlist
- // controller. Using a custom property for backwards compatibility
- // with < v2
- Object.defineProperties(this, {
- selectPlaylist: {
- get() {
- return this.masterPlaylistController_.selectPlaylist;
- },
- set(selectPlaylist) {
- this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
- }
- },
- throughput: {
- get() {
- return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
- },
- set(throughput) {
- this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput;
- // By setting `count` to 1 the throughput value becomes the starting value
- // for the cumulative average
- this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
- }
- },
- bandwidth: {
- get() {
- return this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
- },
- set(bandwidth) {
- this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth;
- // setting the bandwidth manually resets the throughput counter
- // `count` is set to zero that current value of `rate` isn't included
- // in the cumulative average
- this.masterPlaylistController_.mainSegmentLoader_.throughput = {
- rate: 0,
- count: 0
- };
- }
- },
- /**
- * `systemBandwidth` is a combination of two serial processes bit-rates. The first
- * is the network bitrate provided by `bandwidth` and the second is the bitrate of
- * the entire process after that - decryption, transmuxing, and appending - provided
- * by `throughput`.
- *
- * Since the two process are serial, the overall system bandwidth is given by:
- * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
- */
- systemBandwidth: {
- get() {
- const invBandwidth = 1 / (this.bandwidth || 1);
- let invThroughput;
-
- if (this.throughput > 0) {
- invThroughput = 1 / this.throughput;
- } else {
- invThroughput = 0;
- }
-
- const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
-
- return systemBitrate;
- },
- set() {
- videojs.log.error('The "systemBandwidth" property is read-only');
- }
- }
- });
-
- if (this.options_.bandwidth) {
- this.bandwidth = this.options_.bandwidth;
- }
- if (this.options_.throughput) {
- this.throughput = this.options_.throughput;
- }
-
- Object.defineProperties(this.stats, {
- bandwidth: {
- get: () => this.bandwidth || 0,
- enumerable: true
- },
- mediaRequests: {
- get: () => this.masterPlaylistController_.mediaRequests_() || 0,
- enumerable: true
- },
- mediaRequestsAborted: {
- get: () => this.masterPlaylistController_.mediaRequestsAborted_() || 0,
- enumerable: true
- },
- mediaRequestsTimedout: {
- get: () => this.masterPlaylistController_.mediaRequestsTimedout_() || 0,
- enumerable: true
- },
- mediaRequestsErrored: {
- get: () => this.masterPlaylistController_.mediaRequestsErrored_() || 0,
- enumerable: true
- },
- mediaTransferDuration: {
- get: () => this.masterPlaylistController_.mediaTransferDuration_() || 0,
- enumerable: true
- },
- mediaBytesTransferred: {
- get: () => this.masterPlaylistController_.mediaBytesTransferred_() || 0,
- enumerable: true
- },
- mediaSecondsLoaded: {
- get: () => this.masterPlaylistController_.mediaSecondsLoaded_() || 0,
- enumerable: true
- },
- mediaAppends: {
- get: () => this.masterPlaylistController_.mediaAppends_() || 0,
- enumerable: true
- },
- mainAppendsToLoadedData: {
- get: () => this.masterPlaylistController_.mainAppendsToLoadedData_() || 0,
- enumerable: true
- },
- audioAppendsToLoadedData: {
- get: () => this.masterPlaylistController_.audioAppendsToLoadedData_() || 0,
- enumerable: true
- },
- appendsToLoadedData: {
- get: () => this.masterPlaylistController_.appendsToLoadedData_() || 0,
- enumerable: true
- },
- timeToLoadedData: {
- get: () => this.masterPlaylistController_.timeToLoadedData_() || 0,
- enumerable: true
- },
- buffered: {
- get: () => timeRangesToArray(this.tech_.buffered()),
- enumerable: true
- },
- currentTime: {
- get: () => this.tech_.currentTime(),
- enumerable: true
- },
- currentSource: {
- get: () => this.tech_.currentSource_,
- enumerable: true
- },
- currentTech: {
- get: () => this.tech_.name_,
- enumerable: true
- },
- duration: {
- get: () => this.tech_.duration(),
- enumerable: true
- },
- master: {
- get: () => this.playlists.master,
- enumerable: true
- },
- playerDimensions: {
- get: () => this.tech_.currentDimensions(),
- enumerable: true
- },
- seekable: {
- get: () => timeRangesToArray(this.tech_.seekable()),
- enumerable: true
- },
- timestamp: {
- get: () => Date.now(),
- enumerable: true
- },
- videoPlaybackQuality: {
- get: () => this.tech_.getVideoPlaybackQuality(),
- enumerable: true
- }
- });
-
- this.tech_.one(
- 'canplay',
- this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_)
- );
-
- this.tech_.on('bandwidthupdate', () => {
- if (this.options_.useBandwidthFromLocalStorage) {
- updateVhsLocalStorage({
- bandwidth: this.bandwidth,
- throughput: Math.round(this.throughput)
- });
- }
- });
-
- this.masterPlaylistController_.on('selectedinitialmedia', () => {
- // Add the manual rendition mix-in to VhsHandler
- renditionSelectionMixin(this);
- });
-
- this.masterPlaylistController_.sourceUpdater_.on('createdsourcebuffers', () => {
- this.setupEme_();
- });
-
- // the bandwidth of the primary segment loader is our best
- // estimate of overall bandwidth
- this.on(this.masterPlaylistController_, 'progress', function() {
- this.tech_.trigger('progress');
- });
-
- // In the live case, we need to ignore the very first `seeking` event since
- // that will be the result of the seek-to-live behavior
- this.on(this.masterPlaylistController_, 'firstplay', function() {
- this.ignoreNextSeekingEvent_ = true;
- });
-
- this.setupQualityLevels_();
-
- // do nothing if the tech has been disposed already
- // this can occur if someone sets the src in player.ready(), for instance
- if (!this.tech_.el()) {
- return;
- }
-
- this.mediaSourceUrl_ = window.URL.createObjectURL(this.masterPlaylistController_.mediaSource);
-
- this.tech_.src(this.mediaSourceUrl_);
- }
-
- /**
- * If necessary and EME is available, sets up EME options and waits for key session
- * creation.
- *
- * This function also updates the source updater so taht it can be used, as for some
- * browsers, EME must be configured before content is appended (if appending unencrypted
- * content before encrypted content).
- */
- setupEme_() {
- const audioPlaylistLoader =
- this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
-
- const didSetupEmeOptions = setupEmeOptions({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- media: this.playlists.media(),
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
- });
-
- // In IE11 this is too early to initialize media keys, and IE11 does not support
- // promises.
- if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
- // If EME options were not set up, we've done all we could to initialize EME.
- this.masterPlaylistController_.sourceUpdater_.initializedEme();
- return;
- }
-
- this.logger_('waiting for EME key session creation');
- waitForKeySessionCreation({
- player: this.player_,
- sourceKeySystems: this.source_.keySystems,
- audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
- mainPlaylists: this.playlists.master.playlists
- }).then(() => {
- this.logger_('created EME key session');
- this.masterPlaylistController_.sourceUpdater_.initializedEme();
- }).catch((err) => {
- this.logger_('error while creating EME key session', err);
- this.player_.error({
- message: 'Failed to initialize media keys for EME',
- code: 3
- });
- });
- }
-
- /**
- * Initializes the quality levels and sets listeners to update them.
- *
- * @method setupQualityLevels_
- * @private
- */
- setupQualityLevels_() {
- const player = videojs.players[this.tech_.options_.playerId];
-
- // if there isn't a player or there isn't a qualityLevels plugin
- // or qualityLevels_ listeners have already been setup, do nothing.
- if (!player || !player.qualityLevels || this.qualityLevels_) {
- return;
- }
-
- this.qualityLevels_ = player.qualityLevels();
-
- this.masterPlaylistController_.on('selectedinitialmedia', () => {
- handleVhsLoadedMetadata(this.qualityLevels_, this);
- });
-
- this.playlists.on('mediachange', () => {
- handleVhsMediaChange(this.qualityLevels_, this.playlists);
- });
- }
-
- /**
- * return the version
- */
- static version() {
- return {
- '@videojs/http-streaming': vhsVersion,
- 'mux.js': muxVersion,
- 'mpd-parser': mpdVersion,
- 'm3u8-parser': m3u8Version,
- 'aes-decrypter': aesVersion
- };
- }
-
- /**
- * return the version
- */
- version() {
- return this.constructor.version();
- }
-
- canChangeType() {
- return SourceUpdater.canChangeType();
- }
-
- /**
- * Begin playing the video.
- */
- play() {
- this.masterPlaylistController_.play();
- }
-
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- setCurrentTime(currentTime) {
- this.masterPlaylistController_.setCurrentTime(currentTime);
- }
-
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- duration() {
- return this.masterPlaylistController_.duration();
- }
-
- /**
- * a wrapper around the function in MasterPlaylistController
- */
- seekable() {
- return this.masterPlaylistController_.seekable();
- }
-
- /**
- * Abort all outstanding work and cleanup.
- */
- dispose() {
- if (this.playbackWatcher_) {
- this.playbackWatcher_.dispose();
- }
- if (this.masterPlaylistController_) {
- this.masterPlaylistController_.dispose();
- }
- if (this.qualityLevels_) {
- this.qualityLevels_.dispose();
- }
-
- if (this.player_) {
- delete this.player_.vhs;
- delete this.player_.dash;
- delete this.player_.hls;
- }
-
- if (this.tech_ && this.tech_.vhs) {
- delete this.tech_.vhs;
- }
-
- // don't check this.tech_.hls as it will log a deprecated warning
- if (this.tech_) {
- delete this.tech_.hls;
- }
-
- if (this.mediaSourceUrl_ && window.URL.revokeObjectURL) {
- window.URL.revokeObjectURL(this.mediaSourceUrl_);
- this.mediaSourceUrl_ = null;
- }
-
- super.dispose();
- }
-
- convertToProgramTime(time, callback) {
- return getProgramTime({
- playlist: this.masterPlaylistController_.media(),
- time,
- callback
- });
- }
-
- // the player must be playing before calling this
- seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
- return seekToProgramTime({
- programTime,
- playlist: this.masterPlaylistController_.media(),
- retryCount,
- pauseAfterSeek,
- seekTo: this.options_.seekTo,
- tech: this.options_.tech,
- callback
- });
- }
-}
-
-/**
- * The Source Handler object, which informs video.js what additional
- * MIME types are supported and sets up playback. It is registered
- * automatically to the appropriate tech based on the capabilities of
- * the browser it is running in. It is not necessary to use or modify
- * this object in normal usage.
- */
-const VhsSourceHandler = {
- name: 'videojs-http-streaming',
- VERSION: vhsVersion,
- canHandleSource(srcObj, options = {}) {
- const localOptions = videojs.mergeOptions(videojs.options, options);
-
- return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
- },
- handleSource(source, tech, options = {}) {
- const localOptions = videojs.mergeOptions(videojs.options, options);
-
- tech.vhs = new VhsHandler(source, tech, localOptions);
- if (!videojs.hasOwnProperty('hls')) {
- Object.defineProperty(tech, 'hls', {
- get: () => {
- videojs.log.warn('player.tech().hls is deprecated. Use player.tech().vhs instead.');
- return tech.vhs;
- },
- configurable: true
- });
- }
- tech.vhs.xhr = xhrFactory();
-
- tech.vhs.src(source.src, source.type);
- return tech.vhs;
- },
- canPlayType(type, options = {}) {
- const { vhs: { overrideNative = !videojs.browser.IS_ANY_SAFARI } } = videojs.mergeOptions(videojs.options, options);
- const supportedType = simpleTypeFromSourceType(type);
- const canUseMsePlayback = supportedType &&
- (!Vhs.supportsTypeNatively(supportedType) || overrideNative);
-
- return canUseMsePlayback ? 'maybe' : '';
- }
-};
-
-/**
- * Check to see if the native MediaSource object exists and supports
- * an MP4 container with both H.264 video and AAC-LC audio.
- *
- * @return {boolean} if native media sources are supported
- */
-const supportsNativeMediaSources = () => {
- return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
-};
-
-// register source handlers with the appropriate techs
-if (supportsNativeMediaSources()) {
- videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
-}
-
-videojs.VhsHandler = VhsHandler;
-Object.defineProperty(videojs, 'HlsHandler', {
- get: () => {
- videojs.log.warn('videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.');
- return VhsHandler;
- },
- configurable: true
-});
-videojs.VhsSourceHandler = VhsSourceHandler;
-Object.defineProperty(videojs, 'HlsSourceHandler', {
- get: () => {
- videojs.log.warn('videojs.HlsSourceHandler is deprecated. ' +
- 'Use videojs.VhsSourceHandler instead.');
- return VhsSourceHandler;
- },
- configurable: true
-});
-videojs.Vhs = Vhs;
-Object.defineProperty(videojs, 'Hls', {
- get: () => {
- videojs.log.warn('videojs.Hls is deprecated. Use videojs.Vhs instead.');
- return Vhs;
- },
- configurable: true
-});
-if (!videojs.use) {
- videojs.registerComponent('Hls', Vhs);
- videojs.registerComponent('Vhs', Vhs);
-}
-videojs.options.vhs = videojs.options.vhs || {};
-videojs.options.hls = videojs.options.hls || {};
-
-if (videojs.registerPlugin) {
- videojs.registerPlugin('reloadSourceOnError', reloadSourceOnError);
-} else {
- videojs.plugin('reloadSourceOnError', reloadSourceOnError);
-}
-
-export {
- Vhs,
- VhsHandler,
- VhsSourceHandler,
- emeKeySystems,
- simpleTypeFromSourceType,
- expandDataUri,
- setupEmeOptions,
- getAllPsshKeySystemsOptions
-};
diff --git a/node_modules/@videojs/http-streaming/src/vtt-segment-loader.js b/node_modules/@videojs/http-streaming/src/vtt-segment-loader.js
deleted file mode 100644
index a8df841..0000000
--- a/node_modules/@videojs/http-streaming/src/vtt-segment-loader.js
+++ /dev/null
@@ -1,491 +0,0 @@
-/**
- * @file vtt-segment-loader.js
- */
-import SegmentLoader from './segment-loader';
-import videojs from 'video.js';
-import window from 'global/window';
-import { removeCuesFromTrack, removeDuplicateCuesFromTrack } from './util/text-tracks';
-import { initSegmentId } from './bin-utils';
-import { uint8ToUtf8 } from './util/string';
-import { REQUEST_ERRORS } from './media-segment-request';
-import { ONE_SECOND_IN_TS } from 'mux.js/lib/utils/clock';
-
-const VTT_LINE_TERMINATORS =
- new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
-
-/**
- * An object that manages segment loading and appending.
- *
- * @class VTTSegmentLoader
- * @param {Object} options required and optional options
- * @extends videojs.EventTarget
- */
-export default class VTTSegmentLoader extends SegmentLoader {
- constructor(settings, options = {}) {
- super(settings, options);
-
- // SegmentLoader requires a MediaSource be specified or it will throw an error;
- // however, VTTSegmentLoader has no need of a media source, so delete the reference
- this.mediaSource_ = null;
-
- this.subtitlesTrack_ = null;
-
- this.loaderType_ = 'subtitle';
-
- this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
-
- // The VTT segment will have its own time mappings. Saving VTT segment timing info in
- // the sync controller leads to improper behavior.
- this.shouldSaveSegmentTimingInfo_ = false;
- }
-
- createTransmuxer_() {
- // don't need to transmux any subtitles
- return null;
- }
-
- /**
- * Indicates which time ranges are buffered
- *
- * @return {TimeRange}
- * TimeRange object representing the current buffered ranges
- */
- buffered_() {
- if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
- return videojs.createTimeRanges();
- }
-
- const cues = this.subtitlesTrack_.cues;
- const start = cues[0].startTime;
- const end = cues[cues.length - 1].startTime;
-
- return videojs.createTimeRanges([[start, end]]);
- }
-
- /**
- * Gets and sets init segment for the provided map
- *
- * @param {Object} map
- * The map object representing the init segment to get or set
- * @param {boolean=} set
- * If true, the init segment for the provided map should be saved
- * @return {Object}
- * map object for desired init segment
- */
- initSegmentForMap(map, set = false) {
- if (!map) {
- return null;
- }
-
- const id = initSegmentId(map);
- let storedMap = this.initSegments_[id];
-
- if (set && !storedMap && map.bytes) {
- // append WebVTT line terminators to the media initialization segment if it exists
- // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
- // requires two or more WebVTT line terminators between the WebVTT header and the
- // rest of the file
- const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
- const combinedSegment = new Uint8Array(combinedByteLength);
-
- combinedSegment.set(map.bytes);
- combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
-
- this.initSegments_[id] = storedMap = {
- resolvedUri: map.resolvedUri,
- byterange: map.byterange,
- bytes: combinedSegment
- };
- }
-
- return storedMap || map;
- }
-
- /**
- * Returns true if all configuration required for loading is present, otherwise false.
- *
- * @return {boolean} True if the all configuration is ready for loading
- * @private
- */
- couldBeginLoading_() {
- return this.playlist_ &&
- this.subtitlesTrack_ &&
- !this.paused();
- }
-
- /**
- * Once all the starting parameters have been specified, begin
- * operation. This method should only be invoked from the INIT
- * state.
- *
- * @private
- */
- init_() {
- this.state = 'READY';
- this.resetEverything();
- return this.monitorBuffer_();
- }
-
- /**
- * Set a subtitle track on the segment loader to add subtitles to
- *
- * @param {TextTrack=} track
- * The text track to add loaded subtitles to
- * @return {TextTrack}
- * Returns the subtitles track
- */
- track(track) {
- if (typeof track === 'undefined') {
- return this.subtitlesTrack_;
- }
-
- this.subtitlesTrack_ = track;
-
- // if we were unpaused but waiting for a sourceUpdater, start
- // buffering now
- if (this.state === 'INIT' && this.couldBeginLoading_()) {
- this.init_();
- }
-
- return this.subtitlesTrack_;
- }
-
- /**
- * Remove any data in the source buffer between start and end times
- *
- * @param {number} start - the start time of the region to remove from the buffer
- * @param {number} end - the end time of the region to remove from the buffer
- */
- remove(start, end) {
- removeCuesFromTrack(start, end, this.subtitlesTrack_);
- }
-
- /**
- * fill the buffer with segements unless the sourceBuffers are
- * currently updating
- *
- * Note: this function should only ever be called by monitorBuffer_
- * and never directly
- *
- * @private
- */
- fillBuffer_() {
- // see if we need to begin loading immediately
- const segmentInfo = this.chooseNextRequest_();
-
- if (!segmentInfo) {
- return;
- }
-
- if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
- // We don't have the timestamp offset that we need to sync subtitles.
- // Rerun on a timestamp offset or user interaction.
- const checkTimestampOffset = () => {
- this.state = 'READY';
- if (!this.paused()) {
- // if not paused, queue a buffer check as soon as possible
- this.monitorBuffer_();
- }
- };
-
- this.syncController_.one('timestampoffset', checkTimestampOffset);
- this.state = 'WAITING_ON_TIMELINE';
- return;
- }
-
- this.loadSegment_(segmentInfo);
- }
-
- // never set a timestamp offset for vtt segments.
- timestampOffsetForSegment_() {
- return null;
- }
-
- chooseNextRequest_() {
- return this.skipEmptySegments_(super.chooseNextRequest_());
- }
-
- /**
- * Prevents the segment loader from requesting segments we know contain no subtitles
- * by walking forward until we find the next segment that we don't know whether it is
- * empty or not.
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @return {Object}
- * a segment info object that describes the current segment
- */
- skipEmptySegments_(segmentInfo) {
- while (segmentInfo && segmentInfo.segment.empty) {
- // stop at the last possible segmentInfo
- if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
- segmentInfo = null;
- break;
- }
- segmentInfo = this.generateSegmentInfo_({
- playlist: segmentInfo.playlist,
- mediaIndex: segmentInfo.mediaIndex + 1,
- startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
- isSyncRequest: segmentInfo.isSyncRequest
- });
- }
- return segmentInfo;
- }
-
- stopForError(error) {
- this.error(error);
- this.state = 'READY';
- this.pause();
- this.trigger('error');
- }
-
- /**
- * append a decrypted segement to the SourceBuffer through a SourceUpdater
- *
- * @private
- */
- segmentRequestFinished_(error, simpleSegment, result) {
- if (!this.subtitlesTrack_) {
- this.state = 'READY';
- return;
- }
-
- this.saveTransferStats_(simpleSegment.stats);
-
- // the request was aborted
- if (!this.pendingSegment_) {
- this.state = 'READY';
- this.mediaRequestsAborted += 1;
- return;
- }
-
- if (error) {
- if (error.code === REQUEST_ERRORS.TIMEOUT) {
- this.handleTimeout_();
- }
-
- if (error.code === REQUEST_ERRORS.ABORTED) {
- this.mediaRequestsAborted += 1;
- } else {
- this.mediaRequestsErrored += 1;
- }
-
- this.stopForError(error);
- return;
- }
-
- const segmentInfo = this.pendingSegment_;
-
- // although the VTT segment loader bandwidth isn't really used, it's good to
- // maintain functionality between segment loaders
- this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
-
- this.state = 'APPENDING';
-
- // used for tests
- this.trigger('appending');
-
- const segment = segmentInfo.segment;
-
- if (segment.map) {
- segment.map.bytes = simpleSegment.map.bytes;
- }
- segmentInfo.bytes = simpleSegment.bytes;
-
- // Make sure that vttjs has loaded, otherwise, wait till it finished loading
- if (typeof window.WebVTT !== 'function' &&
- this.subtitlesTrack_ &&
- this.subtitlesTrack_.tech_) {
-
- let loadHandler;
- const errorHandler = () => {
- this.subtitlesTrack_.tech_.off('vttjsloaded', loadHandler);
- this.stopForError({
- message: 'Error loading vtt.js'
- });
- return;
- };
-
- loadHandler = () => {
- this.subtitlesTrack_.tech_.off('vttjserror', errorHandler);
- this.segmentRequestFinished_(error, simpleSegment, result);
- };
-
- this.state = 'WAITING_ON_VTTJS';
- this.subtitlesTrack_.tech_.one('vttjsloaded', loadHandler);
- this.subtitlesTrack_.tech_.one('vttjserror', errorHandler);
-
- return;
- }
-
- segment.requested = true;
-
- try {
- this.parseVTTCues_(segmentInfo);
- } catch (e) {
- this.stopForError({
- message: e.message
- });
- return;
- }
-
- this.updateTimeMapping_(
- segmentInfo,
- this.syncController_.timelines[segmentInfo.timeline],
- this.playlist_
- );
-
- if (segmentInfo.cues.length) {
- segmentInfo.timingInfo = {
- start: segmentInfo.cues[0].startTime,
- end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
- };
- } else {
- segmentInfo.timingInfo = {
- start: segmentInfo.startOfSegment,
- end: segmentInfo.startOfSegment + segmentInfo.duration
- };
- }
-
- if (segmentInfo.isSyncRequest) {
- this.trigger('syncinfoupdate');
- this.pendingSegment_ = null;
- this.state = 'READY';
- return;
- }
-
- segmentInfo.byteLength = segmentInfo.bytes.byteLength;
-
- this.mediaSecondsLoaded += segment.duration;
-
- // Create VTTCue instances for each cue in the new segment and add them to
- // the subtitle track
- segmentInfo.cues.forEach((cue) => {
- this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ?
- new window.VTTCue(cue.startTime, cue.endTime, cue.text) :
- cue);
- });
-
- // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
- // cues to have identical time-intervals, but if the text is also identical
- // we can safely assume it is a duplicate that can be removed (ex. when a cue
- // "overlaps" VTT segments)
- removeDuplicateCuesFromTrack(this.subtitlesTrack_);
-
- this.handleAppendsDone_();
- }
-
- handleData_() {
- // noop as we shouldn't be getting video/audio data captions
- // that we do not support here.
- }
- updateTimingInfoEnd_() {
- // noop
- }
-
- /**
- * Uses the WebVTT parser to parse the segment response
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @private
- */
- parseVTTCues_(segmentInfo) {
- let decoder;
- let decodeBytesToString = false;
-
- if (typeof window.TextDecoder === 'function') {
- decoder = new window.TextDecoder('utf8');
- } else {
- decoder = window.WebVTT.StringDecoder();
- decodeBytesToString = true;
- }
-
- const parser = new window.WebVTT.Parser(
- window,
- window.vttjs,
- decoder
- );
-
- segmentInfo.cues = [];
- segmentInfo.timestampmap = { MPEGTS: 0, LOCAL: 0 };
-
- parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
- parser.ontimestampmap = (map) => {
- segmentInfo.timestampmap = map;
- };
- parser.onparsingerror = (error) => {
- videojs.log.warn('Error encountered when parsing cues: ' + error.message);
- };
-
- if (segmentInfo.segment.map) {
- let mapData = segmentInfo.segment.map.bytes;
-
- if (decodeBytesToString) {
- mapData = uint8ToUtf8(mapData);
- }
-
- parser.parse(mapData);
- }
-
- let segmentData = segmentInfo.bytes;
-
- if (decodeBytesToString) {
- segmentData = uint8ToUtf8(segmentData);
- }
-
- parser.parse(segmentData);
- parser.flush();
- }
-
- /**
- * Updates the start and end times of any cues parsed by the WebVTT parser using
- * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
- * from the SyncController
- *
- * @param {Object} segmentInfo
- * a segment info object that describes the current segment
- * @param {Object} mappingObj
- * object containing a mapping from TS to media time
- * @param {Object} playlist
- * the playlist object containing the segment
- * @private
- */
- updateTimeMapping_(segmentInfo, mappingObj, playlist) {
- const segment = segmentInfo.segment;
-
- if (!mappingObj) {
- // If the sync controller does not have a mapping of TS to Media Time for the
- // timeline, then we don't have enough information to update the cue
- // start/end times
- return;
- }
-
- if (!segmentInfo.cues.length) {
- // If there are no cues, we also do not have enough information to figure out
- // segment timing. Mark that the segment contains no cues so we don't re-request
- // an empty segment.
- segment.empty = true;
- return;
- }
-
- const timestampmap = segmentInfo.timestampmap;
- const diff = (timestampmap.MPEGTS / ONE_SECOND_IN_TS) - timestampmap.LOCAL + mappingObj.mapping;
-
- segmentInfo.cues.forEach((cue) => {
- // First convert cue time to TS time using the timestamp-map provided within the vtt
- cue.startTime += diff;
- cue.endTime += diff;
- });
-
- if (!playlist.syncInfo) {
- const firstStart = segmentInfo.cues[0].startTime;
- const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
-
- playlist.syncInfo = {
- mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
- time: Math.min(firstStart, lastStart - segment.duration)
- };
- }
- }
-}
diff --git a/node_modules/@videojs/http-streaming/src/xhr.js b/node_modules/@videojs/http-streaming/src/xhr.js
deleted file mode 100644
index bb59230..0000000
--- a/node_modules/@videojs/http-streaming/src/xhr.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/**
- * @file xhr.js
- */
-
-/**
- * A wrapper for videojs.xhr that tracks bandwidth.
- *
- * @param {Object} options options for the XHR
- * @param {Function} callback the callback to call when done
- * @return {Request} the xhr request that is going to be made
- */
-import videojs from 'video.js';
-
-const {
- xhr: videojsXHR,
- mergeOptions
-} = videojs;
-
-const callbackWrapper = function(request, error, response, callback) {
- const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
-
- if (!error && reqResponse) {
- request.responseTime = Date.now();
- request.roundTripTime = request.responseTime - request.requestTime;
- request.bytesReceived = reqResponse.byteLength || reqResponse.length;
- if (!request.bandwidth) {
- request.bandwidth =
- Math.floor((request.bytesReceived / request.roundTripTime) * 8 * 1000);
- }
- }
-
- if (response.headers) {
- request.responseHeaders = response.headers;
- }
-
- // videojs.xhr now uses a specific code on the error
- // object to signal that a request has timed out instead
- // of setting a boolean on the request object
- if (error && error.code === 'ETIMEDOUT') {
- request.timedout = true;
- }
-
- // videojs.xhr no longer considers status codes outside of 200 and 0
- // (for file uris) to be errors, but the old XHR did, so emulate that
- // behavior. Status 206 may be used in response to byterange requests.
- if (!error &&
- !request.aborted &&
- response.statusCode !== 200 &&
- response.statusCode !== 206 &&
- response.statusCode !== 0) {
- error = new Error('XHR Failed with a response of: ' +
- (request && (reqResponse || request.responseText)));
- }
-
- callback(error, request);
-};
-
-const xhrFactory = function() {
- const xhr = function XhrFunction(options, callback) {
- // Add a default timeout
- options = mergeOptions({
- timeout: 45e3
- }, options);
-
- // Allow an optional user-specified function to modify the option
- // object before we construct the xhr request
- const beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
-
- if (beforeRequest && typeof beforeRequest === 'function') {
- const newOptions = beforeRequest(options);
-
- if (newOptions) {
- options = newOptions;
- }
- }
-
- // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
- // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
- const xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
-
- const request = xhrMethod(options, function(error, response) {
- return callbackWrapper(request, error, response, callback);
- });
- const originalAbort = request.abort;
-
- request.abort = function() {
- request.aborted = true;
- return originalAbort.apply(request, arguments);
- };
- request.uri = options.uri;
- request.requestTime = Date.now();
- return request;
- };
-
- xhr.original = true;
-
- return xhr;
-};
-
-/**
- * Turns segment byterange into a string suitable for use in
- * HTTP Range requests
- *
- * @param {Object} byterange - an object with two values defining the start and end
- * of a byte-range
- */
-const byterangeStr = function(byterange) {
- // `byterangeEnd` is one less than `offset + length` because the HTTP range
- // header uses inclusive ranges
- const byterangeEnd = byterange.offset + byterange.length - 1;
- const byterangeStart = byterange.offset;
-
- return 'bytes=' + byterangeStart + '-' + byterangeEnd;
-};
-
-/**
- * Defines headers for use in the xhr request for a particular segment.
- *
- * @param {Object} segment - a simplified copy of the segmentInfo object
- * from SegmentLoader
- */
-const segmentXhrHeaders = function(segment) {
- const headers = {};
-
- if (segment.byterange) {
- headers.Range = byterangeStr(segment.byterange);
- }
- return headers;
-};
-
-export {segmentXhrHeaders, callbackWrapper, xhrFactory};
-
-export default xhrFactory;
diff --git a/node_modules/@videojs/vhs-utils/CHANGELOG.md b/node_modules/@videojs/vhs-utils/CHANGELOG.md
deleted file mode 100644
index e8408ad..0000000
--- a/node_modules/@videojs/vhs-utils/CHANGELOG.md
+++ /dev/null
@@ -1,142 +0,0 @@
-
-## [3.0.2](https://github.com/videojs/vhs-utils/compare/v3.0.1...v3.0.2) (2021-05-20)
-
-### Bug Fixes
-
-* properly handle data URIs ([#27](https://github.com/videojs/vhs-utils/issues/27)) ([9b10245](https://github.com/videojs/vhs-utils/commit/9b10245)), closes [videojs/video.js#7240](https://github.com/videojs/video.js/issues/7240)
-
-
-## [3.0.1](https://github.com/videojs/vhs-utils/compare/v3.0.0...v3.0.1) (2021-04-29)
-
-### Bug Fixes
-
-* binary issues ([e9f5079](https://github.com/videojs/vhs-utils/commit/e9f5079))
-
-### Chores
-
-* update vjsverify ([105c26a](https://github.com/videojs/vhs-utils/commit/105c26a))
-
-### Performance Improvements
-
-* use native URL when available ([#26](https://github.com/videojs/vhs-utils/issues/26)) ([e7eaab9](https://github.com/videojs/vhs-utils/commit/e7eaab9))
-
-
-# [3.0.0](https://github.com/videojs/vhs-utils/compare/v2.3.0...v3.0.0) (2020-12-18)
-
-### Features
-
-* Extend our current container parsing logic and add logic for parsing codecs from files ([#14](https://github.com/videojs/vhs-utils/issues/14)) ([d425956](https://github.com/videojs/vhs-utils/commit/d425956))
-* parse any number of codecs rather than just the last audio or the last video codec. ([#23](https://github.com/videojs/vhs-utils/issues/23)) ([33ec9f5](https://github.com/videojs/vhs-utils/commit/33ec9f5))
-* use [@videojs](https://github.com/videojs)/babel-config to transpile code to cjs/es for node ([#20](https://github.com/videojs/vhs-utils/issues/20)) ([c6dbd0b](https://github.com/videojs/vhs-utils/commit/c6dbd0b))
-
-### Chores
-
-* switch from travis to github ci ([#24](https://github.com/videojs/vhs-utils/issues/24)) ([cfee30b](https://github.com/videojs/vhs-utils/commit/cfee30b))
-
-
-### BREAKING CHANGES
-
-* cjs dist files changed from './dist' to './cjs'
-* parseCodecs now returns an array of codecs that where parsed so that we can support any number of codecs instead of just two.
-* toUint8 in byte-helpers functions slightly differently
-* getId3Offset is exported from id3-helpers rather than containers
-
-We can now parse the container for and many of the codecs within (where applicable) for mp4, avi, ts, mkv, webm, ogg, wav, aac, ac3 (and ec3 which is contained in ac3 files), mp3, flac, raw h265, and raw h264.
-
-Codec parsing has also been extended to parse codec details in a file for vp09, avc (h264), hevc (h265), av1, and opus
-
-Finally we have the following additional features to our parsing of codec/container information:
-* skipping multiple id3 tags at the start of a file for flac, mp3, and aac
-* discarding emulation prevention bits (in h264, h265)
-* parsing raw h264/h265 to get codec params for ts, avi, and even raw h264/h265 files
-
-
-# [2.3.0](https://github.com/videojs/vhs-utils/compare/v2.2.1...v2.3.0) (2020-12-03)
-
-### Features
-
-* parse unknown and text codecs ([#19](https://github.com/videojs/vhs-utils/issues/19)) ([9c90076](https://github.com/videojs/vhs-utils/commit/9c90076))
-
-### Chores
-
-* Add repository info to package.json ([#22](https://github.com/videojs/vhs-utils/issues/22)) ([a22ae78](https://github.com/videojs/vhs-utils/commit/a22ae78))
-
-
-## [2.2.1](https://github.com/videojs/stream/compare/v2.2.0...v2.2.1) (2020-10-06)
-
-### Bug Fixes
-
-* check for multiple id3 sections in a file (#21) ([759a039](https://github.com/videojs/stream/commit/759a039)), closes [#21](https://github.com/videojs/stream/issues/21)
-* parse unknown codecs as audio or video (#15) ([cd2c9bb](https://github.com/videojs/stream/commit/cd2c9bb)), closes [#15](https://github.com/videojs/stream/issues/15)
-
-### Reverts
-
-* "fix: parse unknown codecs as audio or video (#15)" (#18) ([9983be8](https://github.com/videojs/stream/commit/9983be8)), closes [#15](https://github.com/videojs/stream/issues/15) [#18](https://github.com/videojs/stream/issues/18)
-
-
-# [2.2.0](https://github.com/videojs/stream/compare/v2.1.0...v2.2.0) (2020-05-01)
-
-### Features
-
-* Add a function to concat typed arrays into one Uint8Array (#13) ([e733509](https://github.com/videojs/stream/commit/e733509)), closes [#13](https://github.com/videojs/stream/issues/13)
-
-
-# [2.1.0](https://github.com/videojs/stream/compare/v2.0.0...v2.1.0) (2020-04-27)
-
-### Features
-
-* Add functions for byte manipulation and segment container detection (#12) ([325f677](https://github.com/videojs/stream/commit/325f677)), closes [#12](https://github.com/videojs/stream/issues/12)
-
-
-# [2.0.0](https://github.com/videojs/stream/compare/v1.3.0...v2.0.0) (2020-04-07)
-
-### Features
-
-* **codec:** changes to handle muxer/browser/video/audio support separately (#10) ([1f92865](https://github.com/videojs/stream/commit/1f92865)), closes [#10](https://github.com/videojs/stream/issues/10)
-
-### Bug Fixes
-
-* Allow VP9 and AV1 codecs through in VHS ([b32e35b](https://github.com/videojs/stream/commit/b32e35b))
-
-
-### BREAKING CHANGES
-
-* **codec:** parseCodecs output has been changed. It now returns an object that can have an audio or video property, depending on the codecs found. Those properties are object that contain type. and details. Type being the codec name and details being codec specific information usually with a leading period.
-* **codec:** `audioProfileFromDefault` has been renamed to `codecsFromDefault` and now returns all output from `parseCodecs` not just audio or audio profile.
-
-
-# [1.3.0](https://github.com/videojs/vhs-utils/compare/v1.2.1...v1.3.0) (2020-02-05)
-
-### Features
-
-* add forEachMediaGroup in media-groups module (#8) ([a1eacf4](https://github.com/videojs/vhs-utils/commit/a1eacf4)), closes [#8](https://github.com/videojs/vhs-utils/issues/8)
-
-
-## [1.2.1](https://github.com/videojs/vhs-utils/compare/v1.2.0...v1.2.1) (2020-01-15)
-
-### Bug Fixes
-
-* include videojs in VHS JSON media type (#7) ([da072f0](https://github.com/videojs/vhs-utils/commit/da072f0)), closes [#7](https://github.com/videojs/vhs-utils/issues/7)
-
-
-# [1.2.0](https://github.com/videojs/vhs-utils/compare/v1.1.0...v1.2.0) (2019-12-06)
-
-### Features
-
-* add media-types module with simpleTypeFromSourceType function (#4) ([d3ebd3f](https://github.com/videojs/vhs-utils/commit/d3ebd3f)), closes [#4](https://github.com/videojs/vhs-utils/issues/4)
-* add VHS codec parsing and translation functions (#5) ([4fe0e22](https://github.com/videojs/vhs-utils/commit/4fe0e22)), closes [#5](https://github.com/videojs/vhs-utils/issues/5)
-
-
-# [1.1.0](https://github.com/videojs/stream/compare/v1.0.0...v1.1.0) (2019-08-30)
-
-### Features
-
-* node support and more stream tests ([315ab8d](https://github.com/videojs/stream/commit/315ab8d))
-
-
-# 1.0.0 (2019-08-21)
-
-### Features
-
-* clones from mpd-parser, m3u8-parser, mux.js, aes-decrypter, and vhs ([5e89042](https://github.com/videojs/stream/commit/5e89042))
-
diff --git a/node_modules/@videojs/vhs-utils/CONTRIBUTING.md b/node_modules/@videojs/vhs-utils/CONTRIBUTING.md
deleted file mode 100644
index 175d976..0000000
--- a/node_modules/@videojs/vhs-utils/CONTRIBUTING.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# CONTRIBUTING
-
-We welcome contributions from everyone!
-
-## Getting Started
-
-Make sure you have Node.js 8 or higher and npm installed.
-
-1. Fork this repository and clone your fork
-1. Install dependencies: `npm install`
-1. Run a development server: `npm start`
-
-### Making Changes
-
-Refer to the [video.js plugin conventions][conventions] for more detail on best practices and tooling for video.js plugin authorship.
-
-When you've made your changes, push your commit(s) to your fork and issue a pull request against the original repository.
-
-### Running Tests
-
-Testing is a crucial part of any software project. For all but the most trivial changes (typos, etc) test cases are expected. Tests are run in actual browsers using [Karma][karma].
-
-- In all available and supported browsers: `npm test`
-- In a specific browser: `npm run test:chrome`, `npm run test:firefox`, etc.
-- While development server is running (`npm start`), navigate to [`http://localhost:9999/test/`][local]
-
-
-[karma]: http://karma-runner.github.io/
-[local]: http://localhost:9999/test/
-[conventions]: https://github.com/videojs/generator-videojs-plugin/blob/master/docs/conventions.md
diff --git a/node_modules/@videojs/vhs-utils/LICENSE b/node_modules/@videojs/vhs-utils/LICENSE
deleted file mode 100644
index f49cb37..0000000
--- a/node_modules/@videojs/vhs-utils/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) brandonocasey
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/node_modules/@videojs/vhs-utils/README.md b/node_modules/@videojs/vhs-utils/README.md
deleted file mode 100644
index 1854821..0000000
--- a/node_modules/@videojs/vhs-utils/README.md
+++ /dev/null
@@ -1,41 +0,0 @@
-
-
-
-
-- [@videojs/vhs-utils](#videojsvhs-utils)
- - [Installation](#installation)
- - [Usage](#usage)
-
-
-
-# @videojs/vhs-utils
-
-vhs-utils serves two purposes:
-
-1. It extracts objects and functions shared throughout @videojs/http-streaming code to save on package size. See [the original @videojs/http-streaming PR](https://github.com/videojs/http-streaming/pull/637) for details.
-2. It exports generic functions from VHS that may be useful to plugin authors.
-
-## Installation
-
-```sh
-npm install --save @videojs/vhs-utils
-```
-
-## Usage
-
-All utility functions are published under dist and can be required/imported like so:
-
-> es import using es dist
-```js
-import resolveUrl from '@videojs/vhs-utils/es/resolve-url';
-```
-
-> cjs import using cjs dist
-```js
-const resolveUrl = require('@videojs/vhs-utils/cjs/resolve-url');
-```
-
-> depricated cjs dist
-```js
-const resolveUrl = require('@videojs/vhs-utils/dist/resolve-url');
-```
diff --git a/node_modules/@videojs/vhs-utils/cjs/byte-helpers.js b/node_modules/@videojs/vhs-utils/cjs/byte-helpers.js
deleted file mode 100644
index 0bdb519..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/byte-helpers.js
+++ /dev/null
@@ -1,323 +0,0 @@
-"use strict";
-
-var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.reverseBytes = exports.sliceBytes = exports.bytesMatch = exports.concatTypedArrays = exports.stringToBytes = exports.bytesToString = exports.numberToBytes = exports.bytesToNumber = exports.IS_LITTLE_ENDIAN = exports.IS_BIG_ENDIAN = exports.ENDIANNESS = exports.toBinaryString = exports.toHexString = exports.toUint8 = exports.isTypedArray = exports.padStart = exports.countBytes = exports.countBits = void 0;
-
-var _window = _interopRequireDefault(require("global/window"));
-
-// const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
-var repeat = function repeat(str, len) {
- var acc = '';
-
- while (len--) {
- acc += str;
- }
-
- return acc;
-}; // count the number of bits it would take to represent a number
-// we used to do this with log2 but BigInt does not support builtin math
-// Math.ceil(log2(x));
-
-
-var countBits = function countBits(x) {
- return x.toString(2).length;
-}; // count the number of whole bytes it would take to represent a number
-
-
-exports.countBits = countBits;
-
-var countBytes = function countBytes(x) {
- return Math.ceil(countBits(x) / 8);
-};
-
-exports.countBytes = countBytes;
-
-var padStart = function padStart(b, len, str) {
- if (str === void 0) {
- str = ' ';
- }
-
- return (repeat(str, len) + b.toString()).slice(-len);
-};
-
-exports.padStart = padStart;
-
-var isTypedArray = function isTypedArray(obj) {
- return ArrayBuffer.isView(obj);
-};
-
-exports.isTypedArray = isTypedArray;
-
-var toUint8 = function toUint8(bytes) {
- if (bytes instanceof Uint8Array) {
- return bytes;
- }
-
- if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
- // any non-number or NaN leads to empty uint8array
- // eslint-disable-next-line
- if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
- bytes = 0;
- } else {
- bytes = [bytes];
- }
- }
-
- return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
-};
-
-exports.toUint8 = toUint8;
-
-var toHexString = function toHexString(bytes) {
- bytes = toUint8(bytes);
- var str = '';
-
- for (var i = 0; i < bytes.length; i++) {
- str += padStart(bytes[i].toString(16), 2, '0');
- }
-
- return str;
-};
-
-exports.toHexString = toHexString;
-
-var toBinaryString = function toBinaryString(bytes) {
- bytes = toUint8(bytes);
- var str = '';
-
- for (var i = 0; i < bytes.length; i++) {
- str += padStart(bytes[i].toString(2), 8, '0');
- }
-
- return str;
-};
-
-exports.toBinaryString = toBinaryString;
-var BigInt = _window.default.BigInt || Number;
-var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
-
-var ENDIANNESS = function () {
- var a = new Uint16Array([0xFFCC]);
- var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
-
- if (b[0] === 0xFF) {
- return 'big';
- }
-
- if (b[0] === 0xCC) {
- return 'little';
- }
-
- return 'unknown';
-}();
-
-exports.ENDIANNESS = ENDIANNESS;
-var IS_BIG_ENDIAN = ENDIANNESS === 'big';
-exports.IS_BIG_ENDIAN = IS_BIG_ENDIAN;
-var IS_LITTLE_ENDIAN = ENDIANNESS === 'little';
-exports.IS_LITTLE_ENDIAN = IS_LITTLE_ENDIAN;
-
-var bytesToNumber = function bytesToNumber(bytes, _temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- _ref$signed = _ref.signed,
- signed = _ref$signed === void 0 ? false : _ref$signed,
- _ref$le = _ref.le,
- le = _ref$le === void 0 ? false : _ref$le;
-
- bytes = toUint8(bytes);
- var fn = le ? 'reduce' : 'reduceRight';
- var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
- var number = obj.call(bytes, function (total, byte, i) {
- var exponent = le ? i : Math.abs(i + 1 - bytes.length);
- return total + BigInt(byte) * BYTE_TABLE[exponent];
- }, BigInt(0));
-
- if (signed) {
- var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
- number = BigInt(number);
-
- if (number > max) {
- number -= max;
- number -= max;
- number -= BigInt(2);
- }
- }
-
- return Number(number);
-};
-
-exports.bytesToNumber = bytesToNumber;
-
-var numberToBytes = function numberToBytes(number, _temp2) {
- var _ref2 = _temp2 === void 0 ? {} : _temp2,
- _ref2$le = _ref2.le,
- le = _ref2$le === void 0 ? false : _ref2$le;
-
- // eslint-disable-next-line
- if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
- number = 0;
- }
-
- number = BigInt(number);
- var byteCount = countBytes(number);
- var bytes = new Uint8Array(new ArrayBuffer(byteCount));
-
- for (var i = 0; i < byteCount; i++) {
- var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
- bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
-
- if (number < 0) {
- bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
- bytes[byteIndex] -= i === 0 ? 1 : 2;
- }
- }
-
- return bytes;
-};
-
-exports.numberToBytes = numberToBytes;
-
-var bytesToString = function bytesToString(bytes) {
- if (!bytes) {
- return '';
- } // TODO: should toUint8 handle cases where we only have 8 bytes
- // but report more since this is a Uint16+ Array?
-
-
- bytes = Array.prototype.slice.call(bytes);
- var string = String.fromCharCode.apply(null, toUint8(bytes));
-
- try {
- return decodeURIComponent(escape(string));
- } catch (e) {// if decodeURIComponent/escape fails, we are dealing with partial
- // or full non string data. Just return the potentially garbled string.
- }
-
- return string;
-};
-
-exports.bytesToString = bytesToString;
-
-var stringToBytes = function stringToBytes(string, stringIsBytes) {
- if (typeof string !== 'string' && string && typeof string.toString === 'function') {
- string = string.toString();
- }
-
- if (typeof string !== 'string') {
- return new Uint8Array();
- } // If the string already is bytes, we don't have to do this
- // otherwise we do this so that we split multi length characters
- // into individual bytes
-
-
- if (!stringIsBytes) {
- string = unescape(encodeURIComponent(string));
- }
-
- var view = new Uint8Array(string.length);
-
- for (var i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view;
-};
-
-exports.stringToBytes = stringToBytes;
-
-var concatTypedArrays = function concatTypedArrays() {
- for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
- buffers[_key] = arguments[_key];
- }
-
- buffers = buffers.filter(function (b) {
- return b && (b.byteLength || b.length) && typeof b !== 'string';
- });
-
- if (buffers.length <= 1) {
- // for 0 length we will return empty uint8
- // for 1 length we return the first uint8
- return toUint8(buffers[0]);
- }
-
- var totalLen = buffers.reduce(function (total, buf, i) {
- return total + (buf.byteLength || buf.length);
- }, 0);
- var tempBuffer = new Uint8Array(totalLen);
- var offset = 0;
- buffers.forEach(function (buf) {
- buf = toUint8(buf);
- tempBuffer.set(buf, offset);
- offset += buf.byteLength;
- });
- return tempBuffer;
-};
-/**
- * Check if the bytes "b" are contained within bytes "a".
- *
- * @param {Uint8Array|Array} a
- * Bytes to check in
- *
- * @param {Uint8Array|Array} b
- * Bytes to check for
- *
- * @param {Object} options
- * options
- *
- * @param {Array|Uint8Array} [offset=0]
- * offset to use when looking at bytes in a
- *
- * @param {Array|Uint8Array} [mask=[]]
- * mask to use on bytes before comparison.
- *
- * @return {boolean}
- * If all bytes in b are inside of a, taking into account
- * bit masks.
- */
-
-
-exports.concatTypedArrays = concatTypedArrays;
-
-var bytesMatch = function bytesMatch(a, b, _temp3) {
- var _ref3 = _temp3 === void 0 ? {} : _temp3,
- _ref3$offset = _ref3.offset,
- offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
- _ref3$mask = _ref3.mask,
- mask = _ref3$mask === void 0 ? [] : _ref3$mask;
-
- a = toUint8(a);
- b = toUint8(b); // ie 11 does not support uint8 every
-
- var fn = b.every ? b.every : Array.prototype.every;
- return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
- fn.call(b, function (bByte, i) {
- var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
- return bByte === aByte;
- });
-};
-
-exports.bytesMatch = bytesMatch;
-
-var sliceBytes = function sliceBytes(src, start, end) {
- if (Uint8Array.prototype.slice) {
- return Uint8Array.prototype.slice.call(src, start, end);
- }
-
- return new Uint8Array(Array.prototype.slice.call(src, start, end));
-};
-
-exports.sliceBytes = sliceBytes;
-
-var reverseBytes = function reverseBytes(src) {
- if (src.reverse) {
- return src.reverse();
- }
-
- return Array.prototype.reverse.call(src);
-};
-
-exports.reverseBytes = reverseBytes;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/codec-helpers.js b/node_modules/@videojs/vhs-utils/cjs/codec-helpers.js
deleted file mode 100644
index 3c85adc..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/codec-helpers.js
+++ /dev/null
@@ -1,112 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.getHvcCodec = exports.getAvcCodec = exports.getAv1Codec = void 0;
-
-var _byteHelpers = require("./byte-helpers.js");
-
-// https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
-// https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter#AV1
-var getAv1Codec = function getAv1Codec(bytes) {
- var codec = '';
- var profile = bytes[1] >>> 3;
- var level = bytes[1] & 0x1F;
- var tier = bytes[2] >>> 7;
- var highBitDepth = (bytes[2] & 0x40) >> 6;
- var twelveBit = (bytes[2] & 0x20) >> 5;
- var monochrome = (bytes[2] & 0x10) >> 4;
- var chromaSubsamplingX = (bytes[2] & 0x08) >> 3;
- var chromaSubsamplingY = (bytes[2] & 0x04) >> 2;
- var chromaSamplePosition = bytes[2] & 0x03;
- codec += profile + "." + (0, _byteHelpers.padStart)(level, 2, '0');
-
- if (tier === 0) {
- codec += 'M';
- } else if (tier === 1) {
- codec += 'H';
- }
-
- var bitDepth;
-
- if (profile === 2 && highBitDepth) {
- bitDepth = twelveBit ? 12 : 10;
- } else {
- bitDepth = highBitDepth ? 10 : 8;
- }
-
- codec += "." + (0, _byteHelpers.padStart)(bitDepth, 2, '0'); // TODO: can we parse color range??
-
- codec += "." + monochrome;
- codec += "." + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition;
- return codec;
-};
-
-exports.getAv1Codec = getAv1Codec;
-
-var getAvcCodec = function getAvcCodec(bytes) {
- var profileId = (0, _byteHelpers.toHexString)(bytes[1]);
- var constraintFlags = (0, _byteHelpers.toHexString)(bytes[2] & 0xFC);
- var levelId = (0, _byteHelpers.toHexString)(bytes[3]);
- return "" + profileId + constraintFlags + levelId;
-};
-
-exports.getAvcCodec = getAvcCodec;
-
-var getHvcCodec = function getHvcCodec(bytes) {
- var codec = '';
- var profileSpace = bytes[1] >> 6;
- var profileId = bytes[1] & 0x1F;
- var tierFlag = (bytes[1] & 0x20) >> 5;
- var profileCompat = bytes.subarray(2, 6);
- var constraintIds = bytes.subarray(6, 12);
- var levelId = bytes[12];
-
- if (profileSpace === 1) {
- codec += 'A';
- } else if (profileSpace === 2) {
- codec += 'B';
- } else if (profileSpace === 3) {
- codec += 'C';
- }
-
- codec += profileId + "."; // ffmpeg does this in big endian
-
- var profileCompatVal = parseInt((0, _byteHelpers.toBinaryString)(profileCompat).split('').reverse().join(''), 2); // apple does this in little endian...
-
- if (profileCompatVal > 255) {
- profileCompatVal = parseInt((0, _byteHelpers.toBinaryString)(profileCompat), 2);
- }
-
- codec += profileCompatVal.toString(16) + ".";
-
- if (tierFlag === 0) {
- codec += 'L';
- } else {
- codec += 'H';
- }
-
- codec += levelId;
- var constraints = '';
-
- for (var i = 0; i < constraintIds.length; i++) {
- var v = constraintIds[i];
-
- if (v) {
- if (constraints) {
- constraints += '.';
- }
-
- constraints += v.toString(16);
- }
- }
-
- if (constraints) {
- codec += "." + constraints;
- }
-
- return codec;
-};
-
-exports.getHvcCodec = getHvcCodec;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/codecs.js b/node_modules/@videojs/vhs-utils/cjs/codecs.js
deleted file mode 100644
index a6251c5..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/codecs.js
+++ /dev/null
@@ -1,297 +0,0 @@
-"use strict";
-
-var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.DEFAULT_VIDEO_CODEC = exports.DEFAULT_AUDIO_CODEC = exports.muxerSupportsCodec = exports.browserSupportsCodec = exports.getMimeForCodec = exports.isTextCodec = exports.isAudioCodec = exports.isVideoCodec = exports.codecsFromDefault = exports.parseCodecs = exports.mapLegacyAvcCodecs = exports.translateLegacyCodecs = exports.translateLegacyCodec = void 0;
-
-var _window = _interopRequireDefault(require("global/window"));
-
-var regexs = {
- // to determine mime types
- mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
- webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
- ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
- // to determine if a codec is audio or video
- video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
- audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
- text: /^(stpp.ttml.im1t)/,
- // mux.js support regex
- muxerVideo: /^(avc0?1)/,
- muxerAudio: /^(mp4a)/,
- // match nothing as muxer does not support text right now.
- // there cannot never be a character before the start of a string
- // so this matches nothing.
- muxerText: /a^/
-};
-var mediaTypes = ['video', 'audio', 'text'];
-var upperMediaTypes = ['Video', 'Audio', 'Text'];
-/**
- * Replace the old apple-style `avc1..` codec string with the standard
- * `avc1.`
- *
- * @param {string} codec
- * Codec string to translate
- * @return {string}
- * The translated codec string
- */
-
-var translateLegacyCodec = function translateLegacyCodec(codec) {
- if (!codec) {
- return codec;
- }
-
- return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
- var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
- var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
- return 'avc1.' + profileHex + '00' + avcLevelHex;
- });
-};
-/**
- * Replace the old apple-style `avc1..` codec strings with the standard
- * `avc1.`
- *
- * @param {string[]} codecs
- * An array of codec strings to translate
- * @return {string[]}
- * The translated array of codec strings
- */
-
-
-exports.translateLegacyCodec = translateLegacyCodec;
-
-var translateLegacyCodecs = function translateLegacyCodecs(codecs) {
- return codecs.map(translateLegacyCodec);
-};
-/**
- * Replace codecs in the codec string with the old apple-style `avc1..` to the
- * standard `avc1.`.
- *
- * @param {string} codecString
- * The codec string
- * @return {string}
- * The codec string with old apple-style codecs replaced
- *
- * @private
- */
-
-
-exports.translateLegacyCodecs = translateLegacyCodecs;
-
-var mapLegacyAvcCodecs = function mapLegacyAvcCodecs(codecString) {
- return codecString.replace(/avc1\.(\d+)\.(\d+)/i, function (match) {
- return translateLegacyCodecs([match])[0];
- });
-};
-/**
- * @typedef {Object} ParsedCodecInfo
- * @property {number} codecCount
- * Number of codecs parsed
- * @property {string} [videoCodec]
- * Parsed video codec (if found)
- * @property {string} [videoObjectTypeIndicator]
- * Video object type indicator (if found)
- * @property {string|null} audioProfile
- * Audio profile
- */
-
-/**
- * Parses a codec string to retrieve the number of codecs specified, the video codec and
- * object type indicator, and the audio profile.
- *
- * @param {string} [codecString]
- * The codec string to parse
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
-
-exports.mapLegacyAvcCodecs = mapLegacyAvcCodecs;
-
-var parseCodecs = function parseCodecs(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- var codecs = codecString.split(',');
- var result = [];
- codecs.forEach(function (codec) {
- codec = codec.trim();
- var codecType;
- mediaTypes.forEach(function (name) {
- var match = regexs[name].exec(codec.toLowerCase());
-
- if (!match || match.length <= 1) {
- return;
- }
-
- codecType = name; // maintain codec case
-
- var type = codec.substring(0, match[1].length);
- var details = codec.replace(type, '');
- result.push({
- type: type,
- details: details,
- mediaType: name
- });
- });
-
- if (!codecType) {
- result.push({
- type: codec,
- details: '',
- mediaType: 'unknown'
- });
- }
- });
- return result;
-};
-/**
- * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
- * a default alternate audio playlist for the provided audio group.
- *
- * @param {Object} master
- * The master playlist
- * @param {string} audioGroupId
- * ID of the audio group for which to find the default codec info
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
-
-exports.parseCodecs = parseCodecs;
-
-var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
- if (!master.mediaGroups.AUDIO || !audioGroupId) {
- return null;
- }
-
- var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
-
- if (!audioGroup) {
- return null;
- }
-
- for (var name in audioGroup) {
- var audioType = audioGroup[name];
-
- if (audioType.default && audioType.playlists) {
- // codec should be the same for all playlists within the audio type
- return parseCodecs(audioType.playlists[0].attributes.CODECS);
- }
- }
-
- return null;
-};
-
-exports.codecsFromDefault = codecsFromDefault;
-
-var isVideoCodec = function isVideoCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.video.test(codec.trim().toLowerCase());
-};
-
-exports.isVideoCodec = isVideoCodec;
-
-var isAudioCodec = function isAudioCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.audio.test(codec.trim().toLowerCase());
-};
-
-exports.isAudioCodec = isAudioCodec;
-
-var isTextCodec = function isTextCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.text.test(codec.trim().toLowerCase());
-};
-
-exports.isTextCodec = isTextCodec;
-
-var getMimeForCodec = function getMimeForCodec(codecString) {
- if (!codecString || typeof codecString !== 'string') {
- return;
- }
-
- var codecs = codecString.toLowerCase().split(',').map(function (c) {
- return translateLegacyCodec(c.trim());
- }); // default to video type
-
- var type = 'video'; // only change to audio type if the only codec we have is
- // audio
-
- if (codecs.length === 1 && isAudioCodec(codecs[0])) {
- type = 'audio';
- } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
- // text uses application/ for now
- type = 'application';
- } // default the container to mp4
-
-
- var container = 'mp4'; // every codec must be able to go into the container
- // for that container to be the correct one
-
- if (codecs.every(function (c) {
- return regexs.mp4.test(c);
- })) {
- container = 'mp4';
- } else if (codecs.every(function (c) {
- return regexs.webm.test(c);
- })) {
- container = 'webm';
- } else if (codecs.every(function (c) {
- return regexs.ogg.test(c);
- })) {
- container = 'ogg';
- }
-
- return type + "/" + container + ";codecs=\"" + codecString + "\"";
-};
-
-exports.getMimeForCodec = getMimeForCodec;
-
-var browserSupportsCodec = function browserSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return _window.default.MediaSource && _window.default.MediaSource.isTypeSupported && _window.default.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
-};
-
-exports.browserSupportsCodec = browserSupportsCodec;
-
-var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return codecString.toLowerCase().split(',').every(function (codec) {
- codec = codec.trim(); // any match is supported.
-
- for (var i = 0; i < upperMediaTypes.length; i++) {
- var type = upperMediaTypes[i];
-
- if (regexs["muxer" + type].test(codec)) {
- return true;
- }
- }
-
- return false;
- });
-};
-
-exports.muxerSupportsCodec = muxerSupportsCodec;
-var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
-exports.DEFAULT_AUDIO_CODEC = DEFAULT_AUDIO_CODEC;
-var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
-exports.DEFAULT_VIDEO_CODEC = DEFAULT_VIDEO_CODEC;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/containers.js b/node_modules/@videojs/vhs-utils/cjs/containers.js
deleted file mode 100644
index 5c079cf..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/containers.js
+++ /dev/null
@@ -1,181 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.isLikelyFmp4MediaSegment = exports.detectContainerForBytes = exports.isLikely = void 0;
-
-var _byteHelpers = require("./byte-helpers.js");
-
-var _mp4Helpers = require("./mp4-helpers.js");
-
-var _ebmlHelpers = require("./ebml-helpers.js");
-
-var _id3Helpers = require("./id3-helpers.js");
-
-var _nalHelpers = require("./nal-helpers.js");
-
-var CONSTANTS = {
- // "webm" string literal in hex
- 'webm': (0, _byteHelpers.toUint8)([0x77, 0x65, 0x62, 0x6d]),
- // "matroska" string literal in hex
- 'matroska': (0, _byteHelpers.toUint8)([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
- // "fLaC" string literal in hex
- 'flac': (0, _byteHelpers.toUint8)([0x66, 0x4c, 0x61, 0x43]),
- // "OggS" string literal in hex
- 'ogg': (0, _byteHelpers.toUint8)([0x4f, 0x67, 0x67, 0x53]),
- // ac-3 sync byte, also works for ec-3 as that is simply a codec
- // of ac-3
- 'ac3': (0, _byteHelpers.toUint8)([0x0b, 0x77]),
- // "RIFF" string literal in hex used for wav and avi
- 'riff': (0, _byteHelpers.toUint8)([0x52, 0x49, 0x46, 0x46]),
- // "AVI" string literal in hex
- 'avi': (0, _byteHelpers.toUint8)([0x41, 0x56, 0x49]),
- // "WAVE" string literal in hex
- 'wav': (0, _byteHelpers.toUint8)([0x57, 0x41, 0x56, 0x45]),
- // "ftyp3g" string literal in hex
- '3gp': (0, _byteHelpers.toUint8)([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
- // "ftyp" string literal in hex
- 'mp4': (0, _byteHelpers.toUint8)([0x66, 0x74, 0x79, 0x70]),
- // "styp" string literal in hex
- 'fmp4': (0, _byteHelpers.toUint8)([0x73, 0x74, 0x79, 0x70]),
- // "ftyp" string literal in hex
- 'mov': (0, _byteHelpers.toUint8)([0x66, 0x74, 0x79, 0x70, 0x71, 0x74])
-};
-var _isLikely = {
- aac: function aac(bytes) {
- var offset = (0, _id3Helpers.getId3Offset)(bytes);
- return (0, _byteHelpers.bytesMatch)(bytes, [0xFF, 0x10], {
- offset: offset,
- mask: [0xFF, 0x16]
- });
- },
- mp3: function mp3(bytes) {
- var offset = (0, _id3Helpers.getId3Offset)(bytes);
- return (0, _byteHelpers.bytesMatch)(bytes, [0xFF, 0x02], {
- offset: offset,
- mask: [0xFF, 0x06]
- });
- },
- webm: function webm(bytes) {
- var docType = (0, _ebmlHelpers.findEbml)(bytes, [_ebmlHelpers.EBML_TAGS.EBML, _ebmlHelpers.EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
-
- return (0, _byteHelpers.bytesMatch)(docType, CONSTANTS.webm);
- },
- mkv: function mkv(bytes) {
- var docType = (0, _ebmlHelpers.findEbml)(bytes, [_ebmlHelpers.EBML_TAGS.EBML, _ebmlHelpers.EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
-
- return (0, _byteHelpers.bytesMatch)(docType, CONSTANTS.matroska);
- },
- mp4: function mp4(bytes) {
- return !_isLikely['3gp'](bytes) && !_isLikely.mov(bytes) && ((0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.mp4, {
- offset: 4
- }) || (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.fmp4, {
- offset: 4
- }));
- },
- mov: function mov(bytes) {
- return (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.mov, {
- offset: 4
- });
- },
- '3gp': function gp(bytes) {
- return (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS['3gp'], {
- offset: 4
- });
- },
- ac3: function ac3(bytes) {
- var offset = (0, _id3Helpers.getId3Offset)(bytes);
- return (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.ac3, {
- offset: offset
- });
- },
- ts: function ts(bytes) {
- if (bytes.length < 189 && bytes.length >= 1) {
- return bytes[0] === 0x47;
- }
-
- var i = 0; // check the first 376 bytes for two matching sync bytes
-
- while (i + 188 < bytes.length && i < 188) {
- if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
- return true;
- }
-
- i += 1;
- }
-
- return false;
- },
- flac: function flac(bytes) {
- var offset = (0, _id3Helpers.getId3Offset)(bytes);
- return (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.flac, {
- offset: offset
- });
- },
- ogg: function ogg(bytes) {
- return (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.ogg);
- },
- avi: function avi(bytes) {
- return (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.riff) && (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.avi, {
- offset: 8
- });
- },
- wav: function wav(bytes) {
- return (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.riff) && (0, _byteHelpers.bytesMatch)(bytes, CONSTANTS.wav, {
- offset: 8
- });
- },
- 'h264': function h264(bytes) {
- // find seq_parameter_set_rbsp
- return (0, _nalHelpers.findH264Nal)(bytes, 7, 3).length;
- },
- 'h265': function h265(bytes) {
- // find video_parameter_set_rbsp or seq_parameter_set_rbsp
- return (0, _nalHelpers.findH265Nal)(bytes, [32, 33], 3).length;
- }
-}; // get all the isLikely functions
-// but make sure 'ts' is above h264 and h265
-// but below everything else as it is the least specific
-
-var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
-.filter(function (t) {
- return t !== 'ts' && t !== 'h264' && t !== 'h265';
-}) // add it back to the bottom
-.concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
-
-isLikelyTypes.forEach(function (type) {
- var isLikelyFn = _isLikely[type];
-
- _isLikely[type] = function (bytes) {
- return isLikelyFn((0, _byteHelpers.toUint8)(bytes));
- };
-}); // export after wrapping
-
-var isLikely = _isLikely; // A useful list of file signatures can be found here
-// https://en.wikipedia.org/wiki/List_of_file_signatures
-
-exports.isLikely = isLikely;
-
-var detectContainerForBytes = function detectContainerForBytes(bytes) {
- bytes = (0, _byteHelpers.toUint8)(bytes);
-
- for (var i = 0; i < isLikelyTypes.length; i++) {
- var type = isLikelyTypes[i];
-
- if (isLikely[type](bytes)) {
- return type;
- }
- }
-
- return '';
-}; // fmp4 is not a container
-
-
-exports.detectContainerForBytes = detectContainerForBytes;
-
-var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
- return (0, _mp4Helpers.findBox)(bytes, ['moof']).length > 0;
-};
-
-exports.isLikelyFmp4MediaSegment = isLikelyFmp4MediaSegment;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/decode-b64-to-uint8-array.js b/node_modules/@videojs/vhs-utils/cjs/decode-b64-to-uint8-array.js
deleted file mode 100644
index d0c5a2f..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/decode-b64-to-uint8-array.js
+++ /dev/null
@@ -1,27 +0,0 @@
-"use strict";
-
-var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = decodeB64ToUint8Array;
-
-var _window = _interopRequireDefault(require("global/window"));
-
-var atob = function atob(s) {
- return _window.default.atob ? _window.default.atob(s) : Buffer.from(s, 'base64').toString('binary');
-};
-
-function decodeB64ToUint8Array(b64Text) {
- var decodedString = atob(b64Text);
- var array = new Uint8Array(decodedString.length);
-
- for (var i = 0; i < decodedString.length; i++) {
- array[i] = decodedString.charCodeAt(i);
- }
-
- return array;
-}
-
-module.exports = exports.default;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/ebml-helpers.js b/node_modules/@videojs/vhs-utils/cjs/ebml-helpers.js
deleted file mode 100644
index 3beb936..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/ebml-helpers.js
+++ /dev/null
@@ -1,518 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.parseData = exports.parseTracks = exports.decodeBlock = exports.findEbml = exports.EBML_TAGS = void 0;
-
-var _byteHelpers = require("./byte-helpers");
-
-var _codecHelpers = require("./codec-helpers.js");
-
-// relevant specs for this parser:
-// https://matroska-org.github.io/libebml/specs.html
-// https://www.matroska.org/technical/elements.html
-// https://www.webmproject.org/docs/container/
-var EBML_TAGS = {
- EBML: (0, _byteHelpers.toUint8)([0x1A, 0x45, 0xDF, 0xA3]),
- DocType: (0, _byteHelpers.toUint8)([0x42, 0x82]),
- Segment: (0, _byteHelpers.toUint8)([0x18, 0x53, 0x80, 0x67]),
- SegmentInfo: (0, _byteHelpers.toUint8)([0x15, 0x49, 0xA9, 0x66]),
- Tracks: (0, _byteHelpers.toUint8)([0x16, 0x54, 0xAE, 0x6B]),
- Track: (0, _byteHelpers.toUint8)([0xAE]),
- TrackNumber: (0, _byteHelpers.toUint8)([0xd7]),
- DefaultDuration: (0, _byteHelpers.toUint8)([0x23, 0xe3, 0x83]),
- TrackEntry: (0, _byteHelpers.toUint8)([0xAE]),
- TrackType: (0, _byteHelpers.toUint8)([0x83]),
- FlagDefault: (0, _byteHelpers.toUint8)([0x88]),
- CodecID: (0, _byteHelpers.toUint8)([0x86]),
- CodecPrivate: (0, _byteHelpers.toUint8)([0x63, 0xA2]),
- VideoTrack: (0, _byteHelpers.toUint8)([0xe0]),
- AudioTrack: (0, _byteHelpers.toUint8)([0xe1]),
- // Not used yet, but will be used for live webm/mkv
- // see https://www.matroska.org/technical/basics.html#block-structure
- // see https://www.matroska.org/technical/basics.html#simpleblock-structure
- Cluster: (0, _byteHelpers.toUint8)([0x1F, 0x43, 0xB6, 0x75]),
- Timestamp: (0, _byteHelpers.toUint8)([0xE7]),
- TimestampScale: (0, _byteHelpers.toUint8)([0x2A, 0xD7, 0xB1]),
- BlockGroup: (0, _byteHelpers.toUint8)([0xA0]),
- BlockDuration: (0, _byteHelpers.toUint8)([0x9B]),
- Block: (0, _byteHelpers.toUint8)([0xA1]),
- SimpleBlock: (0, _byteHelpers.toUint8)([0xA3])
-};
-/**
- * This is a simple table to determine the length
- * of things in ebml. The length is one based (starts at 1,
- * rather than zero) and for every zero bit before a one bit
- * we add one to length. We also need this table because in some
- * case we have to xor all the length bits from another value.
- */
-
-exports.EBML_TAGS = EBML_TAGS;
-var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
-
-var getLength = function getLength(byte) {
- var len = 1;
-
- for (var i = 0; i < LENGTH_TABLE.length; i++) {
- if (byte & LENGTH_TABLE[i]) {
- break;
- }
-
- len++;
- }
-
- return len;
-}; // length in ebml is stored in the first 4 to 8 bits
-// of the first byte. 4 for the id length and 8 for the
-// data size length. Length is measured by converting the number to binary
-// then 1 + the number of zeros before a 1 is encountered starting
-// from the left.
-
-
-var getvint = function getvint(bytes, offset, removeLength, signed) {
- if (removeLength === void 0) {
- removeLength = true;
- }
-
- if (signed === void 0) {
- signed = false;
- }
-
- var length = getLength(bytes[offset]);
- var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
- // as they will be modified below to remove the dataSizeLen bits and we do not
- // want to modify the original data. normally we could just call slice on
- // uint8array but ie 11 does not support that...
-
- if (removeLength) {
- valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
- valueBytes[0] ^= LENGTH_TABLE[length - 1];
- }
-
- return {
- length: length,
- value: (0, _byteHelpers.bytesToNumber)(valueBytes, {
- signed: signed
- }),
- bytes: valueBytes
- };
-};
-
-var normalizePath = function normalizePath(path) {
- if (typeof path === 'string') {
- return path.match(/.{1,2}/g).map(function (p) {
- return normalizePath(p);
- });
- }
-
- if (typeof path === 'number') {
- return (0, _byteHelpers.numberToBytes)(path);
- }
-
- return path;
-};
-
-var normalizePaths = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath(p);
- });
-};
-
-var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
- if (offset >= bytes.length) {
- return bytes.length;
- }
-
- var innerid = getvint(bytes, offset, false);
-
- if ((0, _byteHelpers.bytesMatch)(id.bytes, innerid.bytes)) {
- return offset;
- }
-
- var dataHeader = getvint(bytes, offset + innerid.length);
- return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
-};
-/**
- * Notes on the EBLM format.
- *
- * EBLM uses "vints" tags. Every vint tag contains
- * two parts
- *
- * 1. The length from the first byte. You get this by
- * converting the byte to binary and counting the zeros
- * before a 1. Then you add 1 to that. Examples
- * 00011111 = length 4 because there are 3 zeros before a 1.
- * 00100000 = length 3 because there are 2 zeros before a 1.
- * 00000011 = length 7 because there are 6 zeros before a 1.
- *
- * 2. The bits used for length are removed from the first byte
- * Then all the bytes are merged into a value. NOTE: this
- * is not the case for id ebml tags as there id includes
- * length bits.
- *
- */
-
-
-var findEbml = function findEbml(bytes, paths) {
- paths = normalizePaths(paths);
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var results = [];
-
- if (!paths.length) {
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var id = getvint(bytes, i, false);
- var dataHeader = getvint(bytes, i + id.length);
- var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
-
- if (dataHeader.value === 0x7f) {
- dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
-
- if (dataHeader.value !== bytes.length) {
- dataHeader.value -= dataStart;
- }
- }
-
- var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
- var data = bytes.subarray(dataStart, dataEnd);
-
- if ((0, _byteHelpers.bytesMatch)(paths[0], id.bytes)) {
- if (paths.length === 1) {
- // this is the end of the paths and we've found the tag we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next tag inside of the data
- // of this one
- results = results.concat(findEbml(data, paths.slice(1)));
- }
- }
-
- var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
-
- i += totalLength;
- }
-
- return results;
-}; // see https://www.matroska.org/technical/basics.html#block-structure
-
-
-exports.findEbml = findEbml;
-
-var decodeBlock = function decodeBlock(block, type, timestampScale, clusterTimestamp) {
- var duration;
-
- if (type === 'group') {
- duration = findEbml(block, [EBML_TAGS.BlockDuration])[0];
-
- if (duration) {
- duration = (0, _byteHelpers.bytesToNumber)(duration);
- duration = 1 / timestampScale * duration * timestampScale / 1000;
- }
-
- block = findEbml(block, [EBML_TAGS.Block])[0];
- type = 'block'; // treat data as a block after this point
- }
-
- var dv = new DataView(block.buffer, block.byteOffset, block.byteLength);
- var trackNumber = getvint(block, 0);
- var timestamp = dv.getInt16(trackNumber.length, false);
- var flags = block[trackNumber.length + 2];
- var data = block.subarray(trackNumber.length + 3); // pts/dts in seconds
-
- var ptsdts = 1 / timestampScale * (clusterTimestamp + timestamp) * timestampScale / 1000; // return the frame
-
- var parsed = {
- duration: duration,
- trackNumber: trackNumber.value,
- keyframe: type === 'simple' && flags >> 7 === 1,
- invisible: (flags & 0x08) >> 3 === 1,
- lacing: (flags & 0x06) >> 1,
- discardable: type === 'simple' && (flags & 0x01) === 1,
- frames: [],
- pts: ptsdts,
- dts: ptsdts,
- timestamp: timestamp
- };
-
- if (!parsed.lacing) {
- parsed.frames.push(data);
- return parsed;
- }
-
- var numberOfFrames = data[0] + 1;
- var frameSizes = [];
- var offset = 1; // Fixed
-
- if (parsed.lacing === 2) {
- var sizeOfFrame = (data.length - offset) / numberOfFrames;
-
- for (var i = 0; i < numberOfFrames; i++) {
- frameSizes.push(sizeOfFrame);
- }
- } // xiph
-
-
- if (parsed.lacing === 1) {
- for (var _i = 0; _i < numberOfFrames - 1; _i++) {
- var size = 0;
-
- do {
- size += data[offset];
- offset++;
- } while (data[offset - 1] === 0xFF);
-
- frameSizes.push(size);
- }
- } // ebml
-
-
- if (parsed.lacing === 3) {
- // first vint is unsinged
- // after that vints are singed and
- // based on a compounding size
- var _size = 0;
-
- for (var _i2 = 0; _i2 < numberOfFrames - 1; _i2++) {
- var vint = _i2 === 0 ? getvint(data, offset) : getvint(data, offset, true, true);
- _size += vint.value;
- frameSizes.push(_size);
- offset += vint.length;
- }
- }
-
- frameSizes.forEach(function (size) {
- parsed.frames.push(data.subarray(offset, offset + size));
- offset += size;
- });
- return parsed;
-}; // VP9 Codec Feature Metadata (CodecPrivate)
-// https://www.webmproject.org/docs/container/
-
-
-exports.decodeBlock = decodeBlock;
-
-var parseVp9Private = function parseVp9Private(bytes) {
- var i = 0;
- var params = {};
-
- while (i < bytes.length) {
- var id = bytes[i] & 0x7f;
- var len = bytes[i + 1];
- var val = void 0;
-
- if (len === 1) {
- val = bytes[i + 2];
- } else {
- val = bytes.subarray(i + 2, i + 2 + len);
- }
-
- if (id === 1) {
- params.profile = val;
- } else if (id === 2) {
- params.level = val;
- } else if (id === 3) {
- params.bitDepth = val;
- } else if (id === 4) {
- params.chromaSubsampling = val;
- } else {
- params[id] = val;
- }
-
- i += 2 + len;
- }
-
- return params;
-};
-
-var parseTracks = function parseTracks(bytes) {
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var decodedTracks = [];
- var tracks = findEbml(bytes, [EBML_TAGS.Segment, EBML_TAGS.Tracks, EBML_TAGS.Track]);
-
- if (!tracks.length) {
- tracks = findEbml(bytes, [EBML_TAGS.Tracks, EBML_TAGS.Track]);
- }
-
- if (!tracks.length) {
- tracks = findEbml(bytes, [EBML_TAGS.Track]);
- }
-
- if (!tracks.length) {
- return decodedTracks;
- }
-
- tracks.forEach(function (track) {
- var trackType = findEbml(track, EBML_TAGS.TrackType)[0];
-
- if (!trackType || !trackType.length) {
- return;
- } // 1 is video, 2 is audio, 17 is subtitle
- // other values are unimportant in this context
-
-
- if (trackType[0] === 1) {
- trackType = 'video';
- } else if (trackType[0] === 2) {
- trackType = 'audio';
- } else if (trackType[0] === 17) {
- trackType = 'subtitle';
- } else {
- return;
- } // todo parse language
-
-
- var decodedTrack = {
- rawCodec: (0, _byteHelpers.bytesToString)(findEbml(track, [EBML_TAGS.CodecID])[0]),
- type: trackType,
- codecPrivate: findEbml(track, [EBML_TAGS.CodecPrivate])[0],
- number: (0, _byteHelpers.bytesToNumber)(findEbml(track, [EBML_TAGS.TrackNumber])[0]),
- defaultDuration: (0, _byteHelpers.bytesToNumber)(findEbml(track, [EBML_TAGS.DefaultDuration])[0]),
- default: findEbml(track, [EBML_TAGS.FlagDefault])[0],
- rawData: track
- };
- var codec = '';
-
- if (/V_MPEG4\/ISO\/AVC/.test(decodedTrack.rawCodec)) {
- codec = "avc1." + (0, _codecHelpers.getAvcCodec)(decodedTrack.codecPrivate);
- } else if (/V_MPEGH\/ISO\/HEVC/.test(decodedTrack.rawCodec)) {
- codec = "hev1." + (0, _codecHelpers.getHvcCodec)(decodedTrack.codecPrivate);
- } else if (/V_MPEG4\/ISO\/ASP/.test(decodedTrack.rawCodec)) {
- if (decodedTrack.codecPrivate) {
- codec = 'mp4v.20.' + decodedTrack.codecPrivate[4].toString();
- } else {
- codec = 'mp4v.20.9';
- }
- } else if (/^V_THEORA/.test(decodedTrack.rawCodec)) {
- codec = 'theora';
- } else if (/^V_VP8/.test(decodedTrack.rawCodec)) {
- codec = 'vp8';
- } else if (/^V_VP9/.test(decodedTrack.rawCodec)) {
- if (decodedTrack.codecPrivate) {
- var _parseVp9Private = parseVp9Private(decodedTrack.codecPrivate),
- profile = _parseVp9Private.profile,
- level = _parseVp9Private.level,
- bitDepth = _parseVp9Private.bitDepth,
- chromaSubsampling = _parseVp9Private.chromaSubsampling;
-
- codec = 'vp09.';
- codec += (0, _byteHelpers.padStart)(profile, 2, '0') + ".";
- codec += (0, _byteHelpers.padStart)(level, 2, '0') + ".";
- codec += (0, _byteHelpers.padStart)(bitDepth, 2, '0') + ".";
- codec += "" + (0, _byteHelpers.padStart)(chromaSubsampling, 2, '0'); // Video -> Colour -> Ebml name
-
- var matrixCoefficients = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xB1]])[0] || [];
- var videoFullRangeFlag = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xB9]])[0] || [];
- var transferCharacteristics = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xBA]])[0] || [];
- var colourPrimaries = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xBB]])[0] || []; // if we find any optional codec parameter specify them all.
-
- if (matrixCoefficients.length || videoFullRangeFlag.length || transferCharacteristics.length || colourPrimaries.length) {
- codec += "." + (0, _byteHelpers.padStart)(colourPrimaries[0], 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(transferCharacteristics[0], 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(matrixCoefficients[0], 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(videoFullRangeFlag[0], 2, '0');
- }
- } else {
- codec = 'vp9';
- }
- } else if (/^V_AV1/.test(decodedTrack.rawCodec)) {
- codec = "av01." + (0, _codecHelpers.getAv1Codec)(decodedTrack.codecPrivate);
- } else if (/A_ALAC/.test(decodedTrack.rawCodec)) {
- codec = 'alac';
- } else if (/A_MPEG\/L2/.test(decodedTrack.rawCodec)) {
- codec = 'mp2';
- } else if (/A_MPEG\/L3/.test(decodedTrack.rawCodec)) {
- codec = 'mp3';
- } else if (/^A_AAC/.test(decodedTrack.rawCodec)) {
- if (decodedTrack.codecPrivate) {
- codec = 'mp4a.40.' + (decodedTrack.codecPrivate[0] >>> 3).toString();
- } else {
- codec = 'mp4a.40.2';
- }
- } else if (/^A_AC3/.test(decodedTrack.rawCodec)) {
- codec = 'ac-3';
- } else if (/^A_PCM/.test(decodedTrack.rawCodec)) {
- codec = 'pcm';
- } else if (/^A_MS\/ACM/.test(decodedTrack.rawCodec)) {
- codec = 'speex';
- } else if (/^A_EAC3/.test(decodedTrack.rawCodec)) {
- codec = 'ec-3';
- } else if (/^A_VORBIS/.test(decodedTrack.rawCodec)) {
- codec = 'vorbis';
- } else if (/^A_FLAC/.test(decodedTrack.rawCodec)) {
- codec = 'flac';
- } else if (/^A_OPUS/.test(decodedTrack.rawCodec)) {
- codec = 'opus';
- }
-
- decodedTrack.codec = codec;
- decodedTracks.push(decodedTrack);
- });
- return decodedTracks.sort(function (a, b) {
- return a.number - b.number;
- });
-};
-
-exports.parseTracks = parseTracks;
-
-var parseData = function parseData(data, tracks) {
- var allBlocks = [];
- var segment = findEbml(data, [EBML_TAGS.Segment])[0];
- var timestampScale = findEbml(segment, [EBML_TAGS.SegmentInfo, EBML_TAGS.TimestampScale])[0]; // in nanoseconds, defaults to 1ms
-
- if (timestampScale && timestampScale.length) {
- timestampScale = (0, _byteHelpers.bytesToNumber)(timestampScale);
- } else {
- timestampScale = 1000000;
- }
-
- var clusters = findEbml(segment, [EBML_TAGS.Cluster]);
-
- if (!tracks) {
- tracks = parseTracks(segment);
- }
-
- clusters.forEach(function (cluster, ci) {
- var simpleBlocks = findEbml(cluster, [EBML_TAGS.SimpleBlock]).map(function (b) {
- return {
- type: 'simple',
- data: b
- };
- });
- var blockGroups = findEbml(cluster, [EBML_TAGS.BlockGroup]).map(function (b) {
- return {
- type: 'group',
- data: b
- };
- });
- var timestamp = findEbml(cluster, [EBML_TAGS.Timestamp])[0] || 0;
-
- if (timestamp && timestamp.length) {
- timestamp = (0, _byteHelpers.bytesToNumber)(timestamp);
- } // get all blocks then sort them into the correct order
-
-
- var blocks = simpleBlocks.concat(blockGroups).sort(function (a, b) {
- return a.data.byteOffset - b.data.byteOffset;
- });
- blocks.forEach(function (block, bi) {
- var decoded = decodeBlock(block.data, block.type, timestampScale, timestamp);
- allBlocks.push(decoded);
- });
- });
- return {
- tracks: tracks,
- blocks: allBlocks
- };
-};
-
-exports.parseData = parseData;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/format-parser.js b/node_modules/@videojs/vhs-utils/cjs/format-parser.js
deleted file mode 100644
index 422f928..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/format-parser.js
+++ /dev/null
@@ -1,408 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.parseFormatForBytes = void 0;
-
-var _byteHelpers = require("./byte-helpers.js");
-
-var _ebmlHelpers = require("./ebml-helpers.js");
-
-var _mp4Helpers = require("./mp4-helpers.js");
-
-var _riffHelpers = require("./riff-helpers.js");
-
-var _oggHelpers = require("./ogg-helpers.js");
-
-var _containers = require("./containers.js");
-
-var _nalHelpers = require("./nal-helpers.js");
-
-var _m2tsHelpers = require("./m2ts-helpers.js");
-
-var _codecHelpers = require("./codec-helpers.js");
-
-var _id3Helpers = require("./id3-helpers.js");
-
-// https://docs.microsoft.com/en-us/windows/win32/medfound/audio-subtype-guids
-// https://tools.ietf.org/html/rfc2361
-var wFormatTagCodec = function wFormatTagCodec(wFormatTag) {
- wFormatTag = (0, _byteHelpers.toUint8)(wFormatTag);
-
- if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0x00, 0x55])) {
- return 'mp3';
- } else if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0x16, 0x00]) || (0, _byteHelpers.bytesMatch)(wFormatTag, [0x00, 0xFF])) {
- return 'aac';
- } else if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0x70, 0x4f])) {
- return 'opus';
- } else if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0x6C, 0x61])) {
- return 'alac';
- } else if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0xF1, 0xAC])) {
- return 'flac';
- } else if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0x20, 0x00])) {
- return 'ac-3';
- } else if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0xFF, 0xFE])) {
- return 'ec-3';
- } else if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0x00, 0x50])) {
- return 'mp2';
- } else if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0x56, 0x6f])) {
- return 'vorbis';
- } else if ((0, _byteHelpers.bytesMatch)(wFormatTag, [0xA1, 0x09])) {
- return 'speex';
- }
-
- return '';
-};
-
-var formatMimetype = function formatMimetype(name, codecs) {
- var codecString = ['video', 'audio'].reduce(function (acc, type) {
- if (codecs[type]) {
- acc += (acc.length ? ',' : '') + codecs[type];
- }
-
- return acc;
- }, '');
- return (codecs.video ? 'video' : 'audio') + "/" + name + (codecString ? ";codecs=\"" + codecString + "\"" : '');
-};
-
-var parseCodecFrom = {
- mov: function mov(bytes) {
- // mov and mp4 both use a nearly identical box structure.
- var retval = parseCodecFrom.mp4(bytes);
-
- if (retval.mimetype) {
- retval.mimetype = retval.mimetype.replace('mp4', 'quicktime');
- }
-
- return retval;
- },
- mp4: function mp4(bytes) {
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var codecs = {};
- var tracks = (0, _mp4Helpers.parseTracks)(bytes);
-
- for (var i = 0; i < tracks.length; i++) {
- var track = tracks[i];
-
- if (track.type === 'audio' && !codecs.audio) {
- codecs.audio = track.codec;
- }
-
- if (track.type === 'video' && !codecs.video) {
- codecs.video = track.codec;
- }
- }
-
- return {
- codecs: codecs,
- mimetype: formatMimetype('mp4', codecs)
- };
- },
- '3gp': function gp(bytes) {
- return {
- codecs: {},
- mimetype: 'video/3gpp'
- };
- },
- ogg: function ogg(bytes) {
- var pages = (0, _oggHelpers.getPages)(bytes, 0, 4);
- var codecs = {};
- pages.forEach(function (page) {
- if ((0, _byteHelpers.bytesMatch)(page, [0x4F, 0x70, 0x75, 0x73], {
- offset: 28
- })) {
- codecs.audio = 'opus';
- } else if ((0, _byteHelpers.bytesMatch)(page, [0x56, 0x50, 0x38, 0x30], {
- offset: 29
- })) {
- codecs.video = 'vp8';
- } else if ((0, _byteHelpers.bytesMatch)(page, [0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {
- offset: 29
- })) {
- codecs.video = 'theora';
- } else if ((0, _byteHelpers.bytesMatch)(page, [0x46, 0x4C, 0x41, 0x43], {
- offset: 29
- })) {
- codecs.audio = 'flac';
- } else if ((0, _byteHelpers.bytesMatch)(page, [0x53, 0x70, 0x65, 0x65, 0x78], {
- offset: 28
- })) {
- codecs.audio = 'speex';
- } else if ((0, _byteHelpers.bytesMatch)(page, [0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {
- offset: 29
- })) {
- codecs.audio = 'vorbis';
- }
- });
- return {
- codecs: codecs,
- mimetype: formatMimetype('ogg', codecs)
- };
- },
- wav: function wav(bytes) {
- var format = (0, _riffHelpers.findFourCC)(bytes, ['WAVE', 'fmt'])[0];
- var wFormatTag = Array.prototype.slice.call(format, 0, 2).reverse();
- var mimetype = 'audio/vnd.wave';
- var codecs = {
- audio: wFormatTagCodec(wFormatTag)
- };
- var codecString = wFormatTag.reduce(function (acc, v) {
- if (v) {
- acc += (0, _byteHelpers.toHexString)(v);
- }
-
- return acc;
- }, '');
-
- if (codecString) {
- mimetype += ";codec=" + codecString;
- }
-
- if (codecString && !codecs.audio) {
- codecs.audio = codecString;
- }
-
- return {
- codecs: codecs,
- mimetype: mimetype
- };
- },
- avi: function avi(bytes) {
- var movi = (0, _riffHelpers.findFourCC)(bytes, ['AVI', 'movi'])[0];
- var strls = (0, _riffHelpers.findFourCC)(bytes, ['AVI', 'hdrl', 'strl']);
- var codecs = {};
- strls.forEach(function (strl) {
- var strh = (0, _riffHelpers.findFourCC)(strl, ['strh'])[0];
- var strf = (0, _riffHelpers.findFourCC)(strl, ['strf'])[0]; // now parse AVIStreamHeader to get codec and type:
- // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/api/avifmt/ns-avifmt-avistreamheader
-
- var type = (0, _byteHelpers.bytesToString)(strh.subarray(0, 4));
- var codec;
- var codecType;
-
- if (type === 'vids') {
- // https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader
- var handler = (0, _byteHelpers.bytesToString)(strh.subarray(4, 8));
- var compression = (0, _byteHelpers.bytesToString)(strf.subarray(16, 20)); // look for 00dc (compressed video fourcc code) or 00db (uncompressed video fourcc code)
-
- var videoData = (0, _riffHelpers.findFourCC)(movi, ['00dc'])[0] || (0, _riffHelpers.findFourCC)(movi, ['00db'][0]);
-
- if (handler === 'H264' || compression === 'H264') {
- if (videoData && videoData.length) {
- codec = parseCodecFrom.h264(videoData).codecs.video;
- } else {
- codec = 'avc1';
- }
- } else if (handler === 'HEVC' || compression === 'HEVC') {
- if (videoData && videoData.length) {
- codec = parseCodecFrom.h265(videoData).codecs.video;
- } else {
- codec = 'hev1';
- }
- } else if (handler === 'FMP4' || compression === 'FMP4') {
- if (movi.length) {
- codec = 'mp4v.20.' + movi[12].toString();
- } else {
- codec = 'mp4v.20';
- }
- } else if (handler === 'VP80' || compression === 'VP80') {
- codec = 'vp8';
- } else if (handler === 'VP90' || compression === 'VP90') {
- codec = 'vp9';
- } else if (handler === 'AV01' || compression === 'AV01') {
- codec = 'av01';
- } else if (handler === 'theo' || compression === 'theora') {
- codec = 'theora';
- } else {
- if (videoData && videoData.length) {
- var result = (0, _containers.detectContainerForBytes)(videoData);
-
- if (result === 'h264') {
- codec = parseCodecFrom.h264(movi).codecs.video;
- }
-
- if (result === 'h265') {
- codec = parseCodecFrom.h265(movi).codecs.video;
- }
- }
-
- if (!codec) {
- codec = handler || compression;
- }
- }
-
- codecType = 'video';
- } else if (type === 'auds') {
- codecType = 'audio'; // look for 00wb (audio data fourcc)
- // const audioData = findFourCC(movi, ['01wb']);
-
- var wFormatTag = Array.prototype.slice.call(strf, 0, 2).reverse();
- codecs.audio = wFormatTagCodec(wFormatTag);
- } else {
- return;
- }
-
- if (codec) {
- codecs[codecType] = codec;
- }
- });
- return {
- codecs: codecs,
- mimetype: formatMimetype('avi', codecs)
- };
- },
- ts: function ts(bytes) {
- var result = (0, _m2tsHelpers.parseTs)(bytes, 2);
- var codecs = {};
- Object.keys(result.streams).forEach(function (esPid) {
- var stream = result.streams[esPid];
-
- if (stream.codec === 'avc1' && stream.packets.length) {
- stream.codec = parseCodecFrom.h264(stream.packets[0]).codecs.video;
- } else if (stream.codec === 'hev1' && stream.packets.length) {
- stream.codec = parseCodecFrom.h265(stream.packets[0]).codecs.video;
- }
-
- codecs[stream.type] = stream.codec;
- });
- return {
- codecs: codecs,
- mimetype: formatMimetype('mp2t', codecs)
- };
- },
- webm: function webm(bytes) {
- // mkv and webm both use ebml to store code info
- var retval = parseCodecFrom.mkv(bytes);
-
- if (retval.mimetype) {
- retval.mimetype = retval.mimetype.replace('x-matroska', 'webm');
- }
-
- return retval;
- },
- mkv: function mkv(bytes) {
- var codecs = {};
- var tracks = (0, _ebmlHelpers.parseTracks)(bytes);
-
- for (var i = 0; i < tracks.length; i++) {
- var track = tracks[i];
-
- if (track.type === 'audio' && !codecs.audio) {
- codecs.audio = track.codec;
- }
-
- if (track.type === 'video' && !codecs.video) {
- codecs.video = track.codec;
- }
- }
-
- return {
- codecs: codecs,
- mimetype: formatMimetype('x-matroska', codecs)
- };
- },
- aac: function aac(bytes) {
- return {
- codecs: {
- audio: 'aac'
- },
- mimetype: 'audio/aac'
- };
- },
- ac3: function ac3(bytes) {
- // past id3 and syncword
- var offset = (0, _id3Helpers.getId3Offset)(bytes) + 2; // default to ac-3
-
- var codec = 'ac-3';
-
- if ((0, _byteHelpers.bytesMatch)(bytes, [0xB8, 0xE0], {
- offset: offset
- })) {
- codec = 'ac-3'; // 0x01, 0x7F
- } else if ((0, _byteHelpers.bytesMatch)(bytes, [0x01, 0x7f], {
- offset: offset
- })) {
- codec = 'ec-3';
- }
-
- return {
- codecs: {
- audio: codec
- },
- mimetype: 'audio/vnd.dolby.dd-raw'
- };
- },
- mp3: function mp3(bytes) {
- return {
- codecs: {
- audio: 'mp3'
- },
- mimetype: 'audio/mpeg'
- };
- },
- flac: function flac(bytes) {
- return {
- codecs: {
- audio: 'flac'
- },
- mimetype: 'audio/flac'
- };
- },
- 'h264': function h264(bytes) {
- // find seq_parameter_set_rbsp to get encoding settings for codec
- var nal = (0, _nalHelpers.findH264Nal)(bytes, 7, 3);
- var retval = {
- codecs: {
- video: 'avc1'
- },
- mimetype: 'video/h264'
- };
-
- if (nal.length) {
- retval.codecs.video += "." + (0, _codecHelpers.getAvcCodec)(nal);
- }
-
- return retval;
- },
- 'h265': function h265(bytes) {
- var retval = {
- codecs: {
- video: 'hev1'
- },
- mimetype: 'video/h265'
- }; // find video_parameter_set_rbsp or seq_parameter_set_rbsp
- // to get encoding settings for codec
-
- var nal = (0, _nalHelpers.findH265Nal)(bytes, [32, 33], 3);
-
- if (nal.length) {
- var type = nal[0] >> 1 & 0x3F; // profile_tier_level starts at byte 5 for video_parameter_set_rbsp
- // byte 2 for seq_parameter_set_rbsp
-
- retval.codecs.video += "." + (0, _codecHelpers.getHvcCodec)(nal.subarray(type === 32 ? 5 : 2));
- }
-
- return retval;
- }
-};
-
-var parseFormatForBytes = function parseFormatForBytes(bytes) {
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var result = {
- codecs: {},
- container: (0, _containers.detectContainerForBytes)(bytes),
- mimetype: ''
- };
- var parseCodecFn = parseCodecFrom[result.container];
-
- if (parseCodecFn) {
- var parsed = parseCodecFn ? parseCodecFn(bytes) : {};
- result.codecs = parsed.codecs || {};
- result.mimetype = parsed.mimetype || '';
- }
-
- return result;
-};
-
-exports.parseFormatForBytes = parseFormatForBytes;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/id3-helpers.js b/node_modules/@videojs/vhs-utils/cjs/id3-helpers.js
deleted file mode 100644
index 4609f57..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/id3-helpers.js
+++ /dev/null
@@ -1,51 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.getId3Offset = exports.getId3Size = void 0;
-
-var _byteHelpers = require("./byte-helpers.js");
-
-var ID3 = (0, _byteHelpers.toUint8)([0x49, 0x44, 0x33]);
-
-var getId3Size = function getId3Size(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var flags = bytes[offset + 5];
- var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
- var footerPresent = (flags & 16) >> 4;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
-};
-
-exports.getId3Size = getId3Size;
-
-var getId3Offset = function getId3Offset(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = (0, _byteHelpers.toUint8)(bytes);
-
- if (bytes.length - offset < 10 || !(0, _byteHelpers.bytesMatch)(bytes, ID3, {
- offset: offset
- })) {
- return offset;
- }
-
- offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
- // have multiple ID3 tag sections even though
- // they should not.
-
- return getId3Offset(bytes, offset);
-};
-
-exports.getId3Offset = getId3Offset;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/index.js b/node_modules/@videojs/vhs-utils/cjs/index.js
deleted file mode 100644
index 3aa9a75..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/index.js
+++ /dev/null
@@ -1,36 +0,0 @@
-"use strict";
-
-var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
-
-var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = void 0;
-
-var codecs = _interopRequireWildcard(require("./codecs"));
-
-var byteHelpers = _interopRequireWildcard(require("./byte-helpers.js"));
-
-var containers = _interopRequireWildcard(require("./containers.js"));
-
-var _decodeB64ToUint8Array = _interopRequireDefault(require("./decode-b64-to-uint8-array.js"));
-
-var mediaGroups = _interopRequireWildcard(require("./media-groups.js"));
-
-var _resolveUrl = _interopRequireDefault(require("./resolve-url.js"));
-
-var _stream = _interopRequireDefault(require("./stream.js"));
-
-var _default = {
- codecs: codecs,
- byteHelpers: byteHelpers,
- containers: containers,
- decodeB64ToUint8Array: _decodeB64ToUint8Array.default,
- mediaGroups: mediaGroups,
- resolveUrl: _resolveUrl.default,
- Stream: _stream.default
-};
-exports.default = _default;
-module.exports = exports.default;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/m2ts-helpers.js b/node_modules/@videojs/vhs-utils/cjs/m2ts-helpers.js
deleted file mode 100644
index 0045a83..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/m2ts-helpers.js
+++ /dev/null
@@ -1,116 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.parseTs = void 0;
-
-var _byteHelpers = require("./byte-helpers.js");
-
-var SYNC_BYTE = 0x47;
-
-var parseTs = function parseTs(bytes, maxPes) {
- if (maxPes === void 0) {
- maxPes = Infinity;
- }
-
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var startIndex = 0;
- var endIndex = 188;
- var pmt = {};
- var pesCount = 0;
-
- while (endIndex < bytes.byteLength && pesCount < maxPes) {
- if (bytes[startIndex] !== SYNC_BYTE && bytes[endIndex] !== SYNC_BYTE) {
- endIndex += 1;
- startIndex += 1;
- continue;
- }
-
- var packet = bytes.subarray(startIndex, endIndex);
- var pid = (packet[1] & 0x1f) << 8 | packet[2];
- var hasPusi = !!(packet[1] & 0x40);
- var hasAdaptationHeader = (packet[3] & 0x30) >>> 4 > 0x01;
- var payloadOffset = 4 + (hasAdaptationHeader ? packet[4] + 1 : 0);
-
- if (hasPusi) {
- payloadOffset += packet[payloadOffset] + 1;
- }
-
- if (pid === 0 && !pmt.pid) {
- pmt.pid = (packet[payloadOffset + 10] & 0x1f) << 8 | packet[payloadOffset + 11];
- } else if (pmt.pid && pid === pmt.pid && !pmt.streams) {
- var isNotForward = packet[payloadOffset + 5] & 0x01; // ignore forward pmt delarations
-
- if (!isNotForward) {
- continue;
- }
-
- pmt.streams = {};
- var sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
- var tableEnd = 3 + sectionLength - 4;
- var programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11];
- var offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- // add an entry that maps the elementary_pid to the stream_type
- var i = payloadOffset + offset;
- var type = packet[i];
- var esPid = (packet[i + 1] & 0x1F) << 8 | packet[i + 2];
- var esLength = (packet[i + 3] & 0x0f) << 8 | packet[i + 4];
- var esInfo = packet.subarray(i + 5, i + 5 + esLength);
- var stream = pmt.streams[esPid] = {
- esInfo: esInfo,
- typeNumber: type,
- packets: [],
- type: '',
- codec: ''
- };
-
- if (type === 0x06 && (0, _byteHelpers.bytesMatch)(esInfo, [0x4F, 0x70, 0x75, 0x73], {
- offset: 2
- })) {
- stream.type = 'audio';
- stream.codec = 'opus';
- } else if (type === 0x1B || type === 0x20) {
- stream.type = 'video';
- stream.codec = 'avc1';
- } else if (type === 0x24) {
- stream.type = 'video';
- stream.codec = 'hev1';
- } else if (type === 0x10) {
- stream.type = 'video';
- stream.codec = 'mp4v.20';
- } else if (type === 0x0F) {
- stream.type = 'audio';
- stream.codec = 'aac';
- } else if (type === 0x81) {
- stream.type = 'audio';
- stream.codec = 'ac-3';
- } else if (type === 0x87) {
- stream.type = 'audio';
- stream.codec = 'ec-3';
- } else if (type === 0x03 || type === 0x04) {
- stream.type = 'audio';
- stream.codec = 'mp3';
- }
-
- offset += esLength + 5;
- }
- } else if (pmt.pid && pmt.streams) {
- pmt.streams[pid].packets.push(packet.subarray(payloadOffset));
- pesCount++;
- }
-
- startIndex += 188;
- endIndex += 188;
- }
-
- if (!pmt.streams) {
- pmt.streams = {};
- }
-
- return pmt;
-};
-
-exports.parseTs = parseTs;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/media-groups.js b/node_modules/@videojs/vhs-utils/cjs/media-groups.js
deleted file mode 100644
index 85d3612..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/media-groups.js
+++ /dev/null
@@ -1,30 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.forEachMediaGroup = void 0;
-
-/**
- * Loops through all supported media groups in master and calls the provided
- * callback for each group
- *
- * @param {Object} master
- * The parsed master manifest object
- * @param {string[]} groups
- * The media groups to call the callback for
- * @param {Function} callback
- * Callback to call for each media group
- */
-var forEachMediaGroup = function forEachMediaGroup(master, groups, callback) {
- groups.forEach(function (mediaType) {
- for (var groupKey in master.mediaGroups[mediaType]) {
- for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
- var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
- callback(mediaProperties, mediaType, groupKey, labelKey);
- }
- }
- });
-};
-
-exports.forEachMediaGroup = forEachMediaGroup;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/media-types.js b/node_modules/@videojs/vhs-utils/cjs/media-types.js
deleted file mode 100644
index 3ad62ea..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/media-types.js
+++ /dev/null
@@ -1,44 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.simpleTypeFromSourceType = void 0;
-var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
-var DASH_REGEX = /^application\/dash\+xml/i;
-/**
- * Returns a string that describes the type of source based on a video source object's
- * media type.
- *
- * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
- *
- * @param {string} type
- * Video source object media type
- * @return {('hls'|'dash'|'vhs-json'|null)}
- * VHS source type string
- */
-
-var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
- if (MPEGURL_REGEX.test(type)) {
- return 'hls';
- }
-
- if (DASH_REGEX.test(type)) {
- return 'dash';
- } // Denotes the special case of a manifest object passed to http-streaming instead of a
- // source URL.
- //
- // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
- //
- // In this case, vnd stands for vendor, video.js for the organization, VHS for this
- // project, and the +json suffix identifies the structure of the media type.
-
-
- if (type === 'application/vnd.videojs.vhs+json') {
- return 'vhs-json';
- }
-
- return null;
-};
-
-exports.simpleTypeFromSourceType = simpleTypeFromSourceType;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/mp4-helpers.js b/node_modules/@videojs/vhs-utils/cjs/mp4-helpers.js
deleted file mode 100644
index 66c9a7b..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/mp4-helpers.js
+++ /dev/null
@@ -1,581 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.parseMediaInfo = exports.parseTracks = exports.addSampleDescription = exports.buildFrameTable = exports.findNamedBox = exports.findBox = exports.parseDescriptors = void 0;
-
-var _byteHelpers = require("./byte-helpers.js");
-
-var _codecHelpers = require("./codec-helpers.js");
-
-var _opusHelpers = require("./opus-helpers.js");
-
-var normalizePath = function normalizePath(path) {
- if (typeof path === 'string') {
- return (0, _byteHelpers.stringToBytes)(path);
- }
-
- if (typeof path === 'number') {
- return path;
- }
-
- return path;
-};
-
-var normalizePaths = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath(p);
- });
-};
-
-var DESCRIPTORS;
-
-var parseDescriptors = function parseDescriptors(bytes) {
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var results = [];
- var i = 0;
-
- while (bytes.length > i) {
- var tag = bytes[i];
- var size = 0;
- var headerSize = 0; // tag
-
- headerSize++;
- var byte = bytes[headerSize]; // first byte
-
- headerSize++;
-
- while (byte & 0x80) {
- size = (byte & 0x7F) << 7;
- byte = bytes[headerSize];
- headerSize++;
- }
-
- size += byte & 0x7F;
-
- for (var z = 0; z < DESCRIPTORS.length; z++) {
- var _DESCRIPTORS$z = DESCRIPTORS[z],
- id = _DESCRIPTORS$z.id,
- parser = _DESCRIPTORS$z.parser;
-
- if (tag === id) {
- results.push(parser(bytes.subarray(headerSize, headerSize + size)));
- break;
- }
- }
-
- i += size + headerSize;
- }
-
- return results;
-};
-
-exports.parseDescriptors = parseDescriptors;
-DESCRIPTORS = [{
- id: 0x03,
- parser: function parser(bytes) {
- var desc = {
- tag: 0x03,
- id: bytes[0] << 8 | bytes[1],
- flags: bytes[2],
- size: 3,
- dependsOnEsId: 0,
- ocrEsId: 0,
- descriptors: [],
- url: ''
- }; // depends on es id
-
- if (desc.flags & 0x80) {
- desc.dependsOnEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];
- desc.size += 2;
- } // url
-
-
- if (desc.flags & 0x40) {
- var len = bytes[desc.size];
- desc.url = (0, _byteHelpers.bytesToString)(bytes.subarray(desc.size + 1, desc.size + 1 + len));
- desc.size += len;
- } // ocr es id
-
-
- if (desc.flags & 0x20) {
- desc.ocrEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];
- desc.size += 2;
- }
-
- desc.descriptors = parseDescriptors(bytes.subarray(desc.size)) || [];
- return desc;
- }
-}, {
- id: 0x04,
- parser: function parser(bytes) {
- // DecoderConfigDescriptor
- var desc = {
- tag: 0x04,
- oti: bytes[0],
- streamType: bytes[1],
- bufferSize: bytes[2] << 16 | bytes[3] << 8 | bytes[4],
- maxBitrate: bytes[5] << 24 | bytes[6] << 16 | bytes[7] << 8 | bytes[8],
- avgBitrate: bytes[9] << 24 | bytes[10] << 16 | bytes[11] << 8 | bytes[12],
- descriptors: parseDescriptors(bytes.subarray(13))
- };
- return desc;
- }
-}, {
- id: 0x05,
- parser: function parser(bytes) {
- // DecoderSpecificInfo
- return {
- tag: 0x05,
- bytes: bytes
- };
- }
-}, {
- id: 0x06,
- parser: function parser(bytes) {
- // SLConfigDescriptor
- return {
- tag: 0x06,
- bytes: bytes
- };
- }
-}];
-/**
- * find any number of boxes by name given a path to it in an iso bmff
- * such as mp4.
- *
- * @param {TypedArray} bytes
- * bytes for the iso bmff to search for boxes in
- *
- * @param {Uint8Array[]|string[]|string|Uint8Array} name
- * An array of paths or a single path representing the name
- * of boxes to search through in bytes. Paths may be
- * uint8 (character codes) or strings.
- *
- * @param {boolean} [complete=false]
- * Should we search only for complete boxes on the final path.
- * This is very useful when you do not want to get back partial boxes
- * in the case of streaming files.
- *
- * @return {Uint8Array[]}
- * An array of the end paths that we found.
- */
-
-var findBox = function findBox(bytes, paths, complete) {
- if (complete === void 0) {
- complete = false;
- }
-
- paths = normalizePaths(paths);
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var results = [];
-
- if (!paths.length) {
- // short-circuit the search for empty paths
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
- var type = bytes.subarray(i + 4, i + 8); // invalid box format.
-
- if (size === 0) {
- break;
- }
-
- var end = i + size;
-
- if (end > bytes.length) {
- // this box is bigger than the number of bytes we have
- // and complete is set, we cannot find any more boxes.
- if (complete) {
- break;
- }
-
- end = bytes.length;
- }
-
- var data = bytes.subarray(i + 8, end);
-
- if ((0, _byteHelpers.bytesMatch)(type, paths[0])) {
- if (paths.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next box along the path
- results.push.apply(results, findBox(data, paths.slice(1), complete));
- }
- }
-
- i = end;
- } // we've finished searching all of bytes
-
-
- return results;
-};
-/**
- * Search for a single matching box by name in an iso bmff format like
- * mp4. This function is useful for finding codec boxes which
- * can be placed arbitrarily in sample descriptions depending
- * on the version of the file or file type.
- *
- * @param {TypedArray} bytes
- * bytes for the iso bmff to search for boxes in
- *
- * @param {string|Uint8Array} name
- * The name of the box to find.
- *
- * @return {Uint8Array[]}
- * a subarray of bytes representing the name boxed we found.
- */
-
-
-exports.findBox = findBox;
-
-var findNamedBox = function findNamedBox(bytes, name) {
- name = normalizePath(name);
-
- if (!name.length) {
- // short-circuit the search for empty paths
- return bytes.subarray(bytes.length);
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- if ((0, _byteHelpers.bytesMatch)(bytes.subarray(i, i + name.length), name)) {
- var size = (bytes[i - 4] << 24 | bytes[i - 3] << 16 | bytes[i - 2] << 8 | bytes[i - 1]) >>> 0;
- var end = size > 1 ? i + size : bytes.byteLength;
- return bytes.subarray(i + 4, end);
- }
-
- i++;
- } // we've finished searching all of bytes
-
-
- return bytes.subarray(bytes.length);
-};
-
-exports.findNamedBox = findNamedBox;
-
-var parseSamples = function parseSamples(data, entrySize, parseEntry) {
- if (entrySize === void 0) {
- entrySize = 4;
- }
-
- if (parseEntry === void 0) {
- parseEntry = function parseEntry(d) {
- return (0, _byteHelpers.bytesToNumber)(d);
- };
- }
-
- var entries = [];
-
- if (!data || !data.length) {
- return entries;
- }
-
- var entryCount = (0, _byteHelpers.bytesToNumber)(data.subarray(4, 8));
-
- for (var i = 8; entryCount; i += entrySize, entryCount--) {
- entries.push(parseEntry(data.subarray(i, i + entrySize)));
- }
-
- return entries;
-};
-
-var buildFrameTable = function buildFrameTable(stbl, timescale) {
- var keySamples = parseSamples(findBox(stbl, ['stss'])[0]);
- var chunkOffsets = parseSamples(findBox(stbl, ['stco'])[0]);
- var timeToSamples = parseSamples(findBox(stbl, ['stts'])[0], 8, function (entry) {
- return {
- sampleCount: (0, _byteHelpers.bytesToNumber)(entry.subarray(0, 4)),
- sampleDelta: (0, _byteHelpers.bytesToNumber)(entry.subarray(4, 8))
- };
- });
- var samplesToChunks = parseSamples(findBox(stbl, ['stsc'])[0], 12, function (entry) {
- return {
- firstChunk: (0, _byteHelpers.bytesToNumber)(entry.subarray(0, 4)),
- samplesPerChunk: (0, _byteHelpers.bytesToNumber)(entry.subarray(4, 8)),
- sampleDescriptionIndex: (0, _byteHelpers.bytesToNumber)(entry.subarray(8, 12))
- };
- });
- var stsz = findBox(stbl, ['stsz'])[0]; // stsz starts with a 4 byte sampleSize which we don't need
-
- var sampleSizes = parseSamples(stsz && stsz.length && stsz.subarray(4) || null);
- var frames = [];
-
- for (var chunkIndex = 0; chunkIndex < chunkOffsets.length; chunkIndex++) {
- var samplesInChunk = void 0;
-
- for (var i = 0; i < samplesToChunks.length; i++) {
- var sampleToChunk = samplesToChunks[i];
- var isThisOne = chunkIndex + 1 >= sampleToChunk.firstChunk && (i + 1 >= samplesToChunks.length || chunkIndex + 1 < samplesToChunks[i + 1].firstChunk);
-
- if (isThisOne) {
- samplesInChunk = sampleToChunk.samplesPerChunk;
- break;
- }
- }
-
- var chunkOffset = chunkOffsets[chunkIndex];
-
- for (var _i = 0; _i < samplesInChunk; _i++) {
- var frameEnd = sampleSizes[frames.length]; // if we don't have key samples every frame is a keyframe
-
- var keyframe = !keySamples.length;
-
- if (keySamples.length && keySamples.indexOf(frames.length + 1) !== -1) {
- keyframe = true;
- }
-
- var frame = {
- keyframe: keyframe,
- start: chunkOffset,
- end: chunkOffset + frameEnd
- };
-
- for (var k = 0; k < timeToSamples.length; k++) {
- var _timeToSamples$k = timeToSamples[k],
- sampleCount = _timeToSamples$k.sampleCount,
- sampleDelta = _timeToSamples$k.sampleDelta;
-
- if (frames.length <= sampleCount) {
- // ms to ns
- var lastTimestamp = frames.length ? frames[frames.length - 1].timestamp : 0;
- frame.timestamp = lastTimestamp + sampleDelta / timescale * 1000;
- frame.duration = sampleDelta;
- break;
- }
- }
-
- frames.push(frame);
- chunkOffset += frameEnd;
- }
- }
-
- return frames;
-};
-
-exports.buildFrameTable = buildFrameTable;
-
-var addSampleDescription = function addSampleDescription(track, bytes) {
- var codec = (0, _byteHelpers.bytesToString)(bytes.subarray(0, 4));
-
- if (track.type === 'video') {
- track.info = track.info || {};
- track.info.width = bytes[28] << 8 | bytes[29];
- track.info.height = bytes[30] << 8 | bytes[31];
- } else if (track.type === 'audio') {
- track.info = track.info || {};
- track.info.channels = bytes[20] << 8 | bytes[21];
- track.info.bitDepth = bytes[22] << 8 | bytes[23];
- track.info.sampleRate = bytes[28] << 8 | bytes[29];
- }
-
- if (codec === 'avc1') {
- var avcC = findNamedBox(bytes, 'avcC'); // AVCDecoderConfigurationRecord
-
- codec += "." + (0, _codecHelpers.getAvcCodec)(avcC);
- track.info.avcC = avcC; // TODO: do we need to parse all this?
-
- /* {
- configurationVersion: avcC[0],
- profile: avcC[1],
- profileCompatibility: avcC[2],
- level: avcC[3],
- lengthSizeMinusOne: avcC[4] & 0x3
- };
- let spsNalUnitCount = avcC[5] & 0x1F;
- const spsNalUnits = track.info.avc.spsNalUnits = [];
- // past spsNalUnitCount
- let offset = 6;
- while (spsNalUnitCount--) {
- const nalLen = avcC[offset] << 8 | avcC[offset + 1];
- spsNalUnits.push(avcC.subarray(offset + 2, offset + 2 + nalLen));
- offset += nalLen + 2;
- }
- let ppsNalUnitCount = avcC[offset];
- const ppsNalUnits = track.info.avc.ppsNalUnits = [];
- // past ppsNalUnitCount
- offset += 1;
- while (ppsNalUnitCount--) {
- const nalLen = avcC[offset] << 8 | avcC[offset + 1];
- ppsNalUnits.push(avcC.subarray(offset + 2, offset + 2 + nalLen));
- offset += nalLen + 2;
- }*/
- // HEVCDecoderConfigurationRecord
- } else if (codec === 'hvc1' || codec === 'hev1') {
- codec += "." + (0, _codecHelpers.getHvcCodec)(findNamedBox(bytes, 'hvcC'));
- } else if (codec === 'mp4a' || codec === 'mp4v') {
- var esds = findNamedBox(bytes, 'esds');
- var esDescriptor = parseDescriptors(esds.subarray(4))[0];
- var decoderConfig = esDescriptor && esDescriptor.descriptors.filter(function (_ref) {
- var tag = _ref.tag;
- return tag === 0x04;
- })[0];
-
- if (decoderConfig) {
- // most codecs do not have a further '.'
- // such as 0xa5 for ac-3 and 0xa6 for e-ac-3
- codec += '.' + (0, _byteHelpers.toHexString)(decoderConfig.oti);
-
- if (decoderConfig.oti === 0x40) {
- codec += '.' + (decoderConfig.descriptors[0].bytes[0] >> 3).toString();
- } else if (decoderConfig.oti === 0x20) {
- codec += '.' + decoderConfig.descriptors[0].bytes[4].toString();
- } else if (decoderConfig.oti === 0xdd) {
- codec = 'vorbis';
- }
- } else if (track.type === 'audio') {
- codec += '.40.2';
- } else {
- codec += '.20.9';
- }
- } else if (codec === 'av01') {
- // AV1DecoderConfigurationRecord
- codec += "." + (0, _codecHelpers.getAv1Codec)(findNamedBox(bytes, 'av1C'));
- } else if (codec === 'vp09') {
- // VPCodecConfigurationRecord
- var vpcC = findNamedBox(bytes, 'vpcC'); // https://www.webmproject.org/vp9/mp4/
-
- var profile = vpcC[0];
- var level = vpcC[1];
- var bitDepth = vpcC[2] >> 4;
- var chromaSubsampling = (vpcC[2] & 0x0F) >> 1;
- var videoFullRangeFlag = (vpcC[2] & 0x0F) >> 3;
- var colourPrimaries = vpcC[3];
- var transferCharacteristics = vpcC[4];
- var matrixCoefficients = vpcC[5];
- codec += "." + (0, _byteHelpers.padStart)(profile, 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(level, 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(bitDepth, 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(chromaSubsampling, 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(colourPrimaries, 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(transferCharacteristics, 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(matrixCoefficients, 2, '0');
- codec += "." + (0, _byteHelpers.padStart)(videoFullRangeFlag, 2, '0');
- } else if (codec === 'theo') {
- codec = 'theora';
- } else if (codec === 'spex') {
- codec = 'speex';
- } else if (codec === '.mp3') {
- codec = 'mp4a.40.34';
- } else if (codec === 'msVo') {
- codec = 'vorbis';
- } else if (codec === 'Opus') {
- codec = 'opus';
- var dOps = findNamedBox(bytes, 'dOps');
- track.info.opus = (0, _opusHelpers.parseOpusHead)(dOps); // TODO: should this go into the webm code??
- // Firefox requires a codecDelay for opus playback
- // see https://bugzilla.mozilla.org/show_bug.cgi?id=1276238
-
- track.info.codecDelay = 6500000;
- } else {
- codec = codec.toLowerCase();
- }
- /* eslint-enable */
- // flac, ac-3, ec-3, opus
-
-
- track.codec = codec;
-};
-
-exports.addSampleDescription = addSampleDescription;
-
-var parseTracks = function parseTracks(bytes, frameTable) {
- if (frameTable === void 0) {
- frameTable = true;
- }
-
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var traks = findBox(bytes, ['moov', 'trak'], true);
- var tracks = [];
- traks.forEach(function (trak) {
- var track = {
- bytes: trak
- };
- var mdia = findBox(trak, ['mdia'])[0];
- var hdlr = findBox(mdia, ['hdlr'])[0];
- var trakType = (0, _byteHelpers.bytesToString)(hdlr.subarray(8, 12));
-
- if (trakType === 'soun') {
- track.type = 'audio';
- } else if (trakType === 'vide') {
- track.type = 'video';
- } else {
- track.type = trakType;
- }
-
- var tkhd = findBox(trak, ['tkhd'])[0];
-
- if (tkhd) {
- var view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- var tkhdVersion = view.getUint8(0);
- track.number = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
- }
-
- var mdhd = findBox(mdia, ['mdhd'])[0];
-
- if (mdhd) {
- // mdhd is a FullBox, meaning it will have its own version as the first byte
- var version = mdhd[0];
- var index = version === 0 ? 12 : 20;
- track.timescale = (mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]) >>> 0;
- }
-
- var stbl = findBox(mdia, ['minf', 'stbl'])[0];
- var stsd = findBox(stbl, ['stsd'])[0];
- var descriptionCount = (0, _byteHelpers.bytesToNumber)(stsd.subarray(4, 8));
- var offset = 8; // add codec and codec info
-
- while (descriptionCount--) {
- var len = (0, _byteHelpers.bytesToNumber)(stsd.subarray(offset, offset + 4));
- var sampleDescriptor = stsd.subarray(offset + 4, offset + 4 + len);
- addSampleDescription(track, sampleDescriptor);
- offset += 4 + len;
- }
-
- if (frameTable) {
- track.frameTable = buildFrameTable(stbl, track.timescale);
- } // codec has no sub parameters
-
-
- tracks.push(track);
- });
- return tracks;
-};
-
-exports.parseTracks = parseTracks;
-
-var parseMediaInfo = function parseMediaInfo(bytes) {
- var mvhd = findBox(bytes, ['moov', 'mvhd'], true)[0];
-
- if (!mvhd || !mvhd.length) {
- return;
- }
-
- var info = {}; // ms to ns
- // mvhd v1 has 8 byte duration and other fields too
-
- if (mvhd[0] === 1) {
- info.timestampScale = (0, _byteHelpers.bytesToNumber)(mvhd.subarray(20, 24));
- info.duration = (0, _byteHelpers.bytesToNumber)(mvhd.subarray(24, 32));
- } else {
- info.timestampScale = (0, _byteHelpers.bytesToNumber)(mvhd.subarray(12, 16));
- info.duration = (0, _byteHelpers.bytesToNumber)(mvhd.subarray(16, 20));
- }
-
- info.bytes = mvhd;
- return info;
-};
-
-exports.parseMediaInfo = parseMediaInfo;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/nal-helpers.js b/node_modules/@videojs/vhs-utils/cjs/nal-helpers.js
deleted file mode 100644
index 3c4c811..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/nal-helpers.js
+++ /dev/null
@@ -1,135 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.findH265Nal = exports.findH264Nal = exports.findNal = exports.discardEmulationPreventionBytes = exports.EMULATION_PREVENTION = exports.NAL_TYPE_TWO = exports.NAL_TYPE_ONE = void 0;
-
-var _byteHelpers = require("./byte-helpers.js");
-
-var NAL_TYPE_ONE = (0, _byteHelpers.toUint8)([0x00, 0x00, 0x00, 0x01]);
-exports.NAL_TYPE_ONE = NAL_TYPE_ONE;
-var NAL_TYPE_TWO = (0, _byteHelpers.toUint8)([0x00, 0x00, 0x01]);
-exports.NAL_TYPE_TWO = NAL_TYPE_TWO;
-var EMULATION_PREVENTION = (0, _byteHelpers.toUint8)([0x00, 0x00, 0x03]);
-/**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- *
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
-exports.EMULATION_PREVENTION = EMULATION_PREVENTION;
-
-var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
- var positions = [];
- var i = 1; // Find all `Emulation Prevention Bytes`
-
- while (i < bytes.length - 2) {
- if ((0, _byteHelpers.bytesMatch)(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
- positions.push(i + 2);
- i++;
- }
-
- i++;
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (positions.length === 0) {
- return bytes;
- } // Create a new array to hold the NAL unit data
-
-
- var newLength = bytes.length - positions.length;
- var newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === positions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- positions.shift();
- }
-
- newData[i] = bytes[sourceIndex];
- }
-
- return newData;
-};
-
-exports.discardEmulationPreventionBytes = discardEmulationPreventionBytes;
-
-var findNal = function findNal(bytes, dataType, types, nalLimit) {
- if (nalLimit === void 0) {
- nalLimit = Infinity;
- }
-
- bytes = (0, _byteHelpers.toUint8)(bytes);
- types = [].concat(types);
- var i = 0;
- var nalStart;
- var nalsFound = 0; // keep searching until:
- // we reach the end of bytes
- // we reach the maximum number of nals they want to seach
- // NOTE: that we disregard nalLimit when we have found the start
- // of the nal we want so that we can find the end of the nal we want.
-
- while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
- var nalOffset = void 0;
-
- if ((0, _byteHelpers.bytesMatch)(bytes.subarray(i), NAL_TYPE_ONE)) {
- nalOffset = 4;
- } else if ((0, _byteHelpers.bytesMatch)(bytes.subarray(i), NAL_TYPE_TWO)) {
- nalOffset = 3;
- } // we are unsynced,
- // find the next nal unit
-
-
- if (!nalOffset) {
- i++;
- continue;
- }
-
- nalsFound++;
-
- if (nalStart) {
- return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
- }
-
- var nalType = void 0;
-
- if (dataType === 'h264') {
- nalType = bytes[i + nalOffset] & 0x1f;
- } else if (dataType === 'h265') {
- nalType = bytes[i + nalOffset] >> 1 & 0x3f;
- }
-
- if (types.indexOf(nalType) !== -1) {
- nalStart = i + nalOffset;
- } // nal header is 1 length for h264, and 2 for h265
-
-
- i += nalOffset + (dataType === 'h264' ? 1 : 2);
- }
-
- return bytes.subarray(0, 0);
-};
-
-exports.findNal = findNal;
-
-var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h264', type, nalLimit);
-};
-
-exports.findH264Nal = findH264Nal;
-
-var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h265', type, nalLimit);
-};
-
-exports.findH265Nal = findH265Nal;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/ogg-helpers.js b/node_modules/@videojs/vhs-utils/cjs/ogg-helpers.js
deleted file mode 100644
index bc0eb26..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/ogg-helpers.js
+++ /dev/null
@@ -1,39 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.getPages = void 0;
-
-var _byteHelpers = require("./byte-helpers");
-
-var SYNC_WORD = (0, _byteHelpers.toUint8)([0x4f, 0x67, 0x67, 0x53]);
-
-var getPages = function getPages(bytes, start, end) {
- if (end === void 0) {
- end = Infinity;
- }
-
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var pages = [];
- var i = 0;
-
- while (i < bytes.length && pages.length < end) {
- // we are unsynced,
- // find the next syncword
- if (!(0, _byteHelpers.bytesMatch)(bytes, SYNC_WORD, {
- offset: i
- })) {
- i++;
- continue;
- }
-
- var segmentLength = bytes[i + 27];
- pages.push(bytes.subarray(i, i + 28 + segmentLength));
- i += pages[pages.length - 1].length;
- }
-
- return pages.slice(start, end);
-};
-
-exports.getPages = getPages;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/opus-helpers.js b/node_modules/@videojs/vhs-utils/cjs/opus-helpers.js
deleted file mode 100644
index 1c58379..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/opus-helpers.js
+++ /dev/null
@@ -1,65 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.setOpusHead = exports.parseOpusHead = exports.OPUS_HEAD = void 0;
-var OPUS_HEAD = new Uint8Array([// O, p, u, s
-0x4f, 0x70, 0x75, 0x73, // H, e, a, d
-0x48, 0x65, 0x61, 0x64]); // https://wiki.xiph.org/OggOpus
-// https://vfrmaniac.fushizen.eu/contents/opus_in_isobmff.html
-// https://opus-codec.org/docs/opusfile_api-0.7/structOpusHead.html
-
-exports.OPUS_HEAD = OPUS_HEAD;
-
-var parseOpusHead = function parseOpusHead(bytes) {
- var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- var version = view.getUint8(0); // version 0, from mp4, does not use littleEndian.
-
- var littleEndian = version !== 0;
- var config = {
- version: version,
- channels: view.getUint8(1),
- preSkip: view.getUint16(2, littleEndian),
- sampleRate: view.getUint32(4, littleEndian),
- outputGain: view.getUint16(8, littleEndian),
- channelMappingFamily: view.getUint8(10)
- };
-
- if (config.channelMappingFamily > 0 && bytes.length > 10) {
- config.streamCount = view.getUint8(11);
- config.twoChannelStreamCount = view.getUint8(12);
- config.channelMapping = [];
-
- for (var c = 0; c < config.channels; c++) {
- config.channelMapping.push(view.getUint8(13 + c));
- }
- }
-
- return config;
-};
-
-exports.parseOpusHead = parseOpusHead;
-
-var setOpusHead = function setOpusHead(config) {
- var size = config.channelMappingFamily <= 0 ? 11 : 12 + config.channels;
- var view = new DataView(new ArrayBuffer(size));
- var littleEndian = config.version !== 0;
- view.setUint8(0, config.version);
- view.setUint8(1, config.channels);
- view.setUint16(2, config.preSkip, littleEndian);
- view.setUint32(4, config.sampleRate, littleEndian);
- view.setUint16(8, config.outputGain, littleEndian);
- view.setUint8(10, config.channelMappingFamily);
-
- if (config.channelMappingFamily > 0) {
- view.setUint8(11, config.streamCount);
- config.channelMapping.foreach(function (cm, i) {
- view.setUint8(12 + i, cm);
- });
- }
-
- return new Uint8Array(view.buffer);
-};
-
-exports.setOpusHead = setOpusHead;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/resolve-url.js b/node_modules/@videojs/vhs-utils/cjs/resolve-url.js
deleted file mode 100644
index 3562950..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/resolve-url.js
+++ /dev/null
@@ -1,60 +0,0 @@
-"use strict";
-
-var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = void 0;
-
-var _urlToolkit = _interopRequireDefault(require("url-toolkit"));
-
-var _window = _interopRequireDefault(require("global/window"));
-
-var DEFAULT_LOCATION = 'http://example.com';
-
-var resolveUrl = function resolveUrl(baseUrl, relativeUrl) {
- // return early if we don't need to resolve
- if (/^[a-z]+:/i.test(relativeUrl)) {
- return relativeUrl;
- } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
-
-
- if (/^data:/.test(baseUrl)) {
- baseUrl = _window.default.location && _window.default.location.href || '';
- } // IE11 supports URL but not the URL constructor
- // feature detect the behavior we want
-
-
- var nativeURL = typeof _window.default.URL === 'function';
- var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
- // and if baseUrl isn't an absolute url
-
- var removeLocation = !_window.default.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
-
- if (nativeURL) {
- baseUrl = new _window.default.URL(baseUrl, _window.default.location || DEFAULT_LOCATION);
- } else if (!/\/\//i.test(baseUrl)) {
- baseUrl = _urlToolkit.default.buildAbsoluteURL(_window.default.location && _window.default.location.href || '', baseUrl);
- }
-
- if (nativeURL) {
- var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
- // and if we're location-less, remove the location
- // otherwise, return the url unmodified
-
- if (removeLocation) {
- return newUrl.href.slice(DEFAULT_LOCATION.length);
- } else if (protocolLess) {
- return newUrl.href.slice(newUrl.protocol.length);
- }
-
- return newUrl.href;
- }
-
- return _urlToolkit.default.buildAbsoluteURL(baseUrl, relativeUrl);
-};
-
-var _default = resolveUrl;
-exports.default = _default;
-module.exports = exports.default;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/riff-helpers.js b/node_modules/@videojs/vhs-utils/cjs/riff-helpers.js
deleted file mode 100644
index 3f13ea9..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/riff-helpers.js
+++ /dev/null
@@ -1,84 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.findFourCC = void 0;
-
-var _byteHelpers = require("./byte-helpers.js");
-
-var CONSTANTS = {
- LIST: (0, _byteHelpers.toUint8)([0x4c, 0x49, 0x53, 0x54]),
- RIFF: (0, _byteHelpers.toUint8)([0x52, 0x49, 0x46, 0x46]),
- WAVE: (0, _byteHelpers.toUint8)([0x57, 0x41, 0x56, 0x45])
-};
-
-var normalizePath = function normalizePath(path) {
- if (typeof path === 'string') {
- return (0, _byteHelpers.stringToBytes)(path);
- }
-
- if (typeof path === 'number') {
- return path;
- }
-
- return path;
-};
-
-var normalizePaths = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath(p);
- });
-};
-
-var findFourCC = function findFourCC(bytes, paths) {
- paths = normalizePaths(paths);
- bytes = (0, _byteHelpers.toUint8)(bytes);
- var results = [];
-
- if (!paths.length) {
- // short-circuit the search for empty paths
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var type = bytes.subarray(i, i + 4);
- var size = (bytes[i + 7] << 24 | bytes[i + 6] << 16 | bytes[i + 5] << 8 | bytes[i + 4]) >>> 0; // skip LIST/RIFF and get the actual type
-
- if ((0, _byteHelpers.bytesMatch)(type, CONSTANTS.LIST) || (0, _byteHelpers.bytesMatch)(type, CONSTANTS.RIFF) || (0, _byteHelpers.bytesMatch)(type, CONSTANTS.WAVE)) {
- type = bytes.subarray(i + 8, i + 12);
- i += 4;
- size -= 4;
- }
-
- var data = bytes.subarray(i + 8, i + 8 + size);
-
- if ((0, _byteHelpers.bytesMatch)(type, paths[0])) {
- if (paths.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next box along the path
- var subresults = findFourCC(data, paths.slice(1));
-
- if (subresults.length) {
- results = results.concat(subresults);
- }
- }
- }
-
- i += 8 + data.length;
- } // we've finished searching all of bytes
-
-
- return results;
-};
-
-exports.findFourCC = findFourCC;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/cjs/stream.js b/node_modules/@videojs/vhs-utils/cjs/stream.js
deleted file mode 100644
index 0760fa4..0000000
--- a/node_modules/@videojs/vhs-utils/cjs/stream.js
+++ /dev/null
@@ -1,129 +0,0 @@
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = void 0;
-
-/**
- * @file stream.js
- */
-
-/**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
-var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
-}();
-
-exports.default = Stream;
-module.exports = exports.default;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/dist/vhs-utils.js b/node_modules/@videojs/vhs-utils/dist/vhs-utils.js
deleted file mode 100644
index 120f132..0000000
--- a/node_modules/@videojs/vhs-utils/dist/vhs-utils.js
+++ /dev/null
@@ -1,1576 +0,0 @@
-/*! @name @videojs/vhs-utils @version 3.0.2 @license MIT */
-(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('global/window')) :
- typeof define === 'function' && define.amd ? define(['global/window'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.vhsUtils = factory(global.window));
-}(this, (function (window) { 'use strict';
-
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
-
- var window__default = /*#__PURE__*/_interopDefaultLegacy(window);
-
- var regexs = {
- // to determine mime types
- mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
- webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
- ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
- // to determine if a codec is audio or video
- video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
- audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
- text: /^(stpp.ttml.im1t)/,
- // mux.js support regex
- muxerVideo: /^(avc0?1)/,
- muxerAudio: /^(mp4a)/,
- // match nothing as muxer does not support text right now.
- // there cannot never be a character before the start of a string
- // so this matches nothing.
- muxerText: /a^/
- };
- var mediaTypes = ['video', 'audio', 'text'];
- var upperMediaTypes = ['Video', 'Audio', 'Text'];
- /**
- * Replace the old apple-style `avc1..` codec string with the standard
- * `avc1.`
- *
- * @param {string} codec
- * Codec string to translate
- * @return {string}
- * The translated codec string
- */
-
- var translateLegacyCodec = function translateLegacyCodec(codec) {
- if (!codec) {
- return codec;
- }
-
- return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
- var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
- var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
- return 'avc1.' + profileHex + '00' + avcLevelHex;
- });
- };
- /**
- * Replace the old apple-style `avc1..` codec strings with the standard
- * `avc1.`
- *
- * @param {string[]} codecs
- * An array of codec strings to translate
- * @return {string[]}
- * The translated array of codec strings
- */
-
- var translateLegacyCodecs = function translateLegacyCodecs(codecs) {
- return codecs.map(translateLegacyCodec);
- };
- /**
- * Replace codecs in the codec string with the old apple-style `avc1..` to the
- * standard `avc1.`.
- *
- * @param {string} codecString
- * The codec string
- * @return {string}
- * The codec string with old apple-style codecs replaced
- *
- * @private
- */
-
- var mapLegacyAvcCodecs = function mapLegacyAvcCodecs(codecString) {
- return codecString.replace(/avc1\.(\d+)\.(\d+)/i, function (match) {
- return translateLegacyCodecs([match])[0];
- });
- };
- /**
- * @typedef {Object} ParsedCodecInfo
- * @property {number} codecCount
- * Number of codecs parsed
- * @property {string} [videoCodec]
- * Parsed video codec (if found)
- * @property {string} [videoObjectTypeIndicator]
- * Video object type indicator (if found)
- * @property {string|null} audioProfile
- * Audio profile
- */
-
- /**
- * Parses a codec string to retrieve the number of codecs specified, the video codec and
- * object type indicator, and the audio profile.
- *
- * @param {string} [codecString]
- * The codec string to parse
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
- var parseCodecs = function parseCodecs(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- var codecs = codecString.split(',');
- var result = [];
- codecs.forEach(function (codec) {
- codec = codec.trim();
- var codecType;
- mediaTypes.forEach(function (name) {
- var match = regexs[name].exec(codec.toLowerCase());
-
- if (!match || match.length <= 1) {
- return;
- }
-
- codecType = name; // maintain codec case
-
- var type = codec.substring(0, match[1].length);
- var details = codec.replace(type, '');
- result.push({
- type: type,
- details: details,
- mediaType: name
- });
- });
-
- if (!codecType) {
- result.push({
- type: codec,
- details: '',
- mediaType: 'unknown'
- });
- }
- });
- return result;
- };
- /**
- * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
- * a default alternate audio playlist for the provided audio group.
- *
- * @param {Object} master
- * The master playlist
- * @param {string} audioGroupId
- * ID of the audio group for which to find the default codec info
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
- var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
- if (!master.mediaGroups.AUDIO || !audioGroupId) {
- return null;
- }
-
- var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
-
- if (!audioGroup) {
- return null;
- }
-
- for (var name in audioGroup) {
- var audioType = audioGroup[name];
-
- if (audioType.default && audioType.playlists) {
- // codec should be the same for all playlists within the audio type
- return parseCodecs(audioType.playlists[0].attributes.CODECS);
- }
- }
-
- return null;
- };
- var isVideoCodec = function isVideoCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.video.test(codec.trim().toLowerCase());
- };
- var isAudioCodec = function isAudioCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.audio.test(codec.trim().toLowerCase());
- };
- var isTextCodec = function isTextCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.text.test(codec.trim().toLowerCase());
- };
- var getMimeForCodec = function getMimeForCodec(codecString) {
- if (!codecString || typeof codecString !== 'string') {
- return;
- }
-
- var codecs = codecString.toLowerCase().split(',').map(function (c) {
- return translateLegacyCodec(c.trim());
- }); // default to video type
-
- var type = 'video'; // only change to audio type if the only codec we have is
- // audio
-
- if (codecs.length === 1 && isAudioCodec(codecs[0])) {
- type = 'audio';
- } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
- // text uses application/ for now
- type = 'application';
- } // default the container to mp4
-
-
- var container = 'mp4'; // every codec must be able to go into the container
- // for that container to be the correct one
-
- if (codecs.every(function (c) {
- return regexs.mp4.test(c);
- })) {
- container = 'mp4';
- } else if (codecs.every(function (c) {
- return regexs.webm.test(c);
- })) {
- container = 'webm';
- } else if (codecs.every(function (c) {
- return regexs.ogg.test(c);
- })) {
- container = 'ogg';
- }
-
- return type + "/" + container + ";codecs=\"" + codecString + "\"";
- };
- var browserSupportsCodec = function browserSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return window__default['default'].MediaSource && window__default['default'].MediaSource.isTypeSupported && window__default['default'].MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
- };
- var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return codecString.toLowerCase().split(',').every(function (codec) {
- codec = codec.trim(); // any match is supported.
-
- for (var i = 0; i < upperMediaTypes.length; i++) {
- var type = upperMediaTypes[i];
-
- if (regexs["muxer" + type].test(codec)) {
- return true;
- }
- }
-
- return false;
- });
- };
- var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
- var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
-
- var codecs = /*#__PURE__*/Object.freeze({
- __proto__: null,
- translateLegacyCodec: translateLegacyCodec,
- translateLegacyCodecs: translateLegacyCodecs,
- mapLegacyAvcCodecs: mapLegacyAvcCodecs,
- parseCodecs: parseCodecs,
- codecsFromDefault: codecsFromDefault,
- isVideoCodec: isVideoCodec,
- isAudioCodec: isAudioCodec,
- isTextCodec: isTextCodec,
- getMimeForCodec: getMimeForCodec,
- browserSupportsCodec: browserSupportsCodec,
- muxerSupportsCodec: muxerSupportsCodec,
- DEFAULT_AUDIO_CODEC: DEFAULT_AUDIO_CODEC,
- DEFAULT_VIDEO_CODEC: DEFAULT_VIDEO_CODEC
- });
-
- var repeat = function repeat(str, len) {
- var acc = '';
-
- while (len--) {
- acc += str;
- }
-
- return acc;
- }; // count the number of bits it would take to represent a number
- // we used to do this with log2 but BigInt does not support builtin math
- // Math.ceil(log2(x));
-
-
- var countBits = function countBits(x) {
- return x.toString(2).length;
- }; // count the number of whole bytes it would take to represent a number
-
- var countBytes = function countBytes(x) {
- return Math.ceil(countBits(x) / 8);
- };
- var padStart = function padStart(b, len, str) {
- if (str === void 0) {
- str = ' ';
- }
-
- return (repeat(str, len) + b.toString()).slice(-len);
- };
- var isTypedArray = function isTypedArray(obj) {
- return ArrayBuffer.isView(obj);
- };
- var toUint8 = function toUint8(bytes) {
- if (bytes instanceof Uint8Array) {
- return bytes;
- }
-
- if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
- // any non-number or NaN leads to empty uint8array
- // eslint-disable-next-line
- if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
- bytes = 0;
- } else {
- bytes = [bytes];
- }
- }
-
- return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
- };
- var toHexString = function toHexString(bytes) {
- bytes = toUint8(bytes);
- var str = '';
-
- for (var i = 0; i < bytes.length; i++) {
- str += padStart(bytes[i].toString(16), 2, '0');
- }
-
- return str;
- };
- var toBinaryString = function toBinaryString(bytes) {
- bytes = toUint8(bytes);
- var str = '';
-
- for (var i = 0; i < bytes.length; i++) {
- str += padStart(bytes[i].toString(2), 8, '0');
- }
-
- return str;
- };
- var BigInt = window__default['default'].BigInt || Number;
- var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
- var ENDIANNESS = function () {
- var a = new Uint16Array([0xFFCC]);
- var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
-
- if (b[0] === 0xFF) {
- return 'big';
- }
-
- if (b[0] === 0xCC) {
- return 'little';
- }
-
- return 'unknown';
- }();
- var IS_BIG_ENDIAN = ENDIANNESS === 'big';
- var IS_LITTLE_ENDIAN = ENDIANNESS === 'little';
- var bytesToNumber = function bytesToNumber(bytes, _temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- _ref$signed = _ref.signed,
- signed = _ref$signed === void 0 ? false : _ref$signed,
- _ref$le = _ref.le,
- le = _ref$le === void 0 ? false : _ref$le;
-
- bytes = toUint8(bytes);
- var fn = le ? 'reduce' : 'reduceRight';
- var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
- var number = obj.call(bytes, function (total, byte, i) {
- var exponent = le ? i : Math.abs(i + 1 - bytes.length);
- return total + BigInt(byte) * BYTE_TABLE[exponent];
- }, BigInt(0));
-
- if (signed) {
- var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
- number = BigInt(number);
-
- if (number > max) {
- number -= max;
- number -= max;
- number -= BigInt(2);
- }
- }
-
- return Number(number);
- };
- var numberToBytes = function numberToBytes(number, _temp2) {
- var _ref2 = _temp2 === void 0 ? {} : _temp2,
- _ref2$le = _ref2.le,
- le = _ref2$le === void 0 ? false : _ref2$le;
-
- // eslint-disable-next-line
- if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
- number = 0;
- }
-
- number = BigInt(number);
- var byteCount = countBytes(number);
- var bytes = new Uint8Array(new ArrayBuffer(byteCount));
-
- for (var i = 0; i < byteCount; i++) {
- var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
- bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
-
- if (number < 0) {
- bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
- bytes[byteIndex] -= i === 0 ? 1 : 2;
- }
- }
-
- return bytes;
- };
- var bytesToString = function bytesToString(bytes) {
- if (!bytes) {
- return '';
- } // TODO: should toUint8 handle cases where we only have 8 bytes
- // but report more since this is a Uint16+ Array?
-
-
- bytes = Array.prototype.slice.call(bytes);
- var string = String.fromCharCode.apply(null, toUint8(bytes));
-
- try {
- return decodeURIComponent(escape(string));
- } catch (e) {// if decodeURIComponent/escape fails, we are dealing with partial
- // or full non string data. Just return the potentially garbled string.
- }
-
- return string;
- };
- var stringToBytes = function stringToBytes(string, stringIsBytes) {
- if (typeof string !== 'string' && string && typeof string.toString === 'function') {
- string = string.toString();
- }
-
- if (typeof string !== 'string') {
- return new Uint8Array();
- } // If the string already is bytes, we don't have to do this
- // otherwise we do this so that we split multi length characters
- // into individual bytes
-
-
- if (!stringIsBytes) {
- string = unescape(encodeURIComponent(string));
- }
-
- var view = new Uint8Array(string.length);
-
- for (var i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view;
- };
- var concatTypedArrays = function concatTypedArrays() {
- for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
- buffers[_key] = arguments[_key];
- }
-
- buffers = buffers.filter(function (b) {
- return b && (b.byteLength || b.length) && typeof b !== 'string';
- });
-
- if (buffers.length <= 1) {
- // for 0 length we will return empty uint8
- // for 1 length we return the first uint8
- return toUint8(buffers[0]);
- }
-
- var totalLen = buffers.reduce(function (total, buf, i) {
- return total + (buf.byteLength || buf.length);
- }, 0);
- var tempBuffer = new Uint8Array(totalLen);
- var offset = 0;
- buffers.forEach(function (buf) {
- buf = toUint8(buf);
- tempBuffer.set(buf, offset);
- offset += buf.byteLength;
- });
- return tempBuffer;
- };
- /**
- * Check if the bytes "b" are contained within bytes "a".
- *
- * @param {Uint8Array|Array} a
- * Bytes to check in
- *
- * @param {Uint8Array|Array} b
- * Bytes to check for
- *
- * @param {Object} options
- * options
- *
- * @param {Array|Uint8Array} [offset=0]
- * offset to use when looking at bytes in a
- *
- * @param {Array|Uint8Array} [mask=[]]
- * mask to use on bytes before comparison.
- *
- * @return {boolean}
- * If all bytes in b are inside of a, taking into account
- * bit masks.
- */
-
- var bytesMatch = function bytesMatch(a, b, _temp3) {
- var _ref3 = _temp3 === void 0 ? {} : _temp3,
- _ref3$offset = _ref3.offset,
- offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
- _ref3$mask = _ref3.mask,
- mask = _ref3$mask === void 0 ? [] : _ref3$mask;
-
- a = toUint8(a);
- b = toUint8(b); // ie 11 does not support uint8 every
-
- var fn = b.every ? b.every : Array.prototype.every;
- return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
- fn.call(b, function (bByte, i) {
- var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
- return bByte === aByte;
- });
- };
- var sliceBytes = function sliceBytes(src, start, end) {
- if (Uint8Array.prototype.slice) {
- return Uint8Array.prototype.slice.call(src, start, end);
- }
-
- return new Uint8Array(Array.prototype.slice.call(src, start, end));
- };
- var reverseBytes = function reverseBytes(src) {
- if (src.reverse) {
- return src.reverse();
- }
-
- return Array.prototype.reverse.call(src);
- };
-
- var byteHelpers = /*#__PURE__*/Object.freeze({
- __proto__: null,
- countBits: countBits,
- countBytes: countBytes,
- padStart: padStart,
- isTypedArray: isTypedArray,
- toUint8: toUint8,
- toHexString: toHexString,
- toBinaryString: toBinaryString,
- ENDIANNESS: ENDIANNESS,
- IS_BIG_ENDIAN: IS_BIG_ENDIAN,
- IS_LITTLE_ENDIAN: IS_LITTLE_ENDIAN,
- bytesToNumber: bytesToNumber,
- numberToBytes: numberToBytes,
- bytesToString: bytesToString,
- stringToBytes: stringToBytes,
- concatTypedArrays: concatTypedArrays,
- bytesMatch: bytesMatch,
- sliceBytes: sliceBytes,
- reverseBytes: reverseBytes
- });
-
- var normalizePath = function normalizePath(path) {
- if (typeof path === 'string') {
- return stringToBytes(path);
- }
-
- if (typeof path === 'number') {
- return path;
- }
-
- return path;
- };
-
- var normalizePaths = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath(p);
- });
- };
- /**
- * find any number of boxes by name given a path to it in an iso bmff
- * such as mp4.
- *
- * @param {TypedArray} bytes
- * bytes for the iso bmff to search for boxes in
- *
- * @param {Uint8Array[]|string[]|string|Uint8Array} name
- * An array of paths or a single path representing the name
- * of boxes to search through in bytes. Paths may be
- * uint8 (character codes) or strings.
- *
- * @param {boolean} [complete=false]
- * Should we search only for complete boxes on the final path.
- * This is very useful when you do not want to get back partial boxes
- * in the case of streaming files.
- *
- * @return {Uint8Array[]}
- * An array of the end paths that we found.
- */
-
- var findBox = function findBox(bytes, paths, complete) {
- if (complete === void 0) {
- complete = false;
- }
-
- paths = normalizePaths(paths);
- bytes = toUint8(bytes);
- var results = [];
-
- if (!paths.length) {
- // short-circuit the search for empty paths
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
- var type = bytes.subarray(i + 4, i + 8); // invalid box format.
-
- if (size === 0) {
- break;
- }
-
- var end = i + size;
-
- if (end > bytes.length) {
- // this box is bigger than the number of bytes we have
- // and complete is set, we cannot find any more boxes.
- if (complete) {
- break;
- }
-
- end = bytes.length;
- }
-
- var data = bytes.subarray(i + 8, end);
-
- if (bytesMatch(type, paths[0])) {
- if (paths.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next box along the path
- results.push.apply(results, findBox(data, paths.slice(1), complete));
- }
- }
-
- i = end;
- } // we've finished searching all of bytes
-
-
- return results;
- };
-
- // https://matroska-org.github.io/libebml/specs.html
- // https://www.matroska.org/technical/elements.html
- // https://www.webmproject.org/docs/container/
-
- var EBML_TAGS = {
- EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
- DocType: toUint8([0x42, 0x82]),
- Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
- SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
- Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
- Track: toUint8([0xAE]),
- TrackNumber: toUint8([0xd7]),
- DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
- TrackEntry: toUint8([0xAE]),
- TrackType: toUint8([0x83]),
- FlagDefault: toUint8([0x88]),
- CodecID: toUint8([0x86]),
- CodecPrivate: toUint8([0x63, 0xA2]),
- VideoTrack: toUint8([0xe0]),
- AudioTrack: toUint8([0xe1]),
- // Not used yet, but will be used for live webm/mkv
- // see https://www.matroska.org/technical/basics.html#block-structure
- // see https://www.matroska.org/technical/basics.html#simpleblock-structure
- Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
- Timestamp: toUint8([0xE7]),
- TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
- BlockGroup: toUint8([0xA0]),
- BlockDuration: toUint8([0x9B]),
- Block: toUint8([0xA1]),
- SimpleBlock: toUint8([0xA3])
- };
- /**
- * This is a simple table to determine the length
- * of things in ebml. The length is one based (starts at 1,
- * rather than zero) and for every zero bit before a one bit
- * we add one to length. We also need this table because in some
- * case we have to xor all the length bits from another value.
- */
-
- var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
-
- var getLength = function getLength(byte) {
- var len = 1;
-
- for (var i = 0; i < LENGTH_TABLE.length; i++) {
- if (byte & LENGTH_TABLE[i]) {
- break;
- }
-
- len++;
- }
-
- return len;
- }; // length in ebml is stored in the first 4 to 8 bits
- // of the first byte. 4 for the id length and 8 for the
- // data size length. Length is measured by converting the number to binary
- // then 1 + the number of zeros before a 1 is encountered starting
- // from the left.
-
-
- var getvint = function getvint(bytes, offset, removeLength, signed) {
- if (removeLength === void 0) {
- removeLength = true;
- }
-
- if (signed === void 0) {
- signed = false;
- }
-
- var length = getLength(bytes[offset]);
- var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
- // as they will be modified below to remove the dataSizeLen bits and we do not
- // want to modify the original data. normally we could just call slice on
- // uint8array but ie 11 does not support that...
-
- if (removeLength) {
- valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
- valueBytes[0] ^= LENGTH_TABLE[length - 1];
- }
-
- return {
- length: length,
- value: bytesToNumber(valueBytes, {
- signed: signed
- }),
- bytes: valueBytes
- };
- };
-
- var normalizePath$1 = function normalizePath(path) {
- if (typeof path === 'string') {
- return path.match(/.{1,2}/g).map(function (p) {
- return normalizePath(p);
- });
- }
-
- if (typeof path === 'number') {
- return numberToBytes(path);
- }
-
- return path;
- };
-
- var normalizePaths$1 = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath$1(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath$1(p);
- });
- };
-
- var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
- if (offset >= bytes.length) {
- return bytes.length;
- }
-
- var innerid = getvint(bytes, offset, false);
-
- if (bytesMatch(id.bytes, innerid.bytes)) {
- return offset;
- }
-
- var dataHeader = getvint(bytes, offset + innerid.length);
- return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
- };
- /**
- * Notes on the EBLM format.
- *
- * EBLM uses "vints" tags. Every vint tag contains
- * two parts
- *
- * 1. The length from the first byte. You get this by
- * converting the byte to binary and counting the zeros
- * before a 1. Then you add 1 to that. Examples
- * 00011111 = length 4 because there are 3 zeros before a 1.
- * 00100000 = length 3 because there are 2 zeros before a 1.
- * 00000011 = length 7 because there are 6 zeros before a 1.
- *
- * 2. The bits used for length are removed from the first byte
- * Then all the bytes are merged into a value. NOTE: this
- * is not the case for id ebml tags as there id includes
- * length bits.
- *
- */
-
-
- var findEbml = function findEbml(bytes, paths) {
- paths = normalizePaths$1(paths);
- bytes = toUint8(bytes);
- var results = [];
-
- if (!paths.length) {
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var id = getvint(bytes, i, false);
- var dataHeader = getvint(bytes, i + id.length);
- var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
-
- if (dataHeader.value === 0x7f) {
- dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
-
- if (dataHeader.value !== bytes.length) {
- dataHeader.value -= dataStart;
- }
- }
-
- var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
- var data = bytes.subarray(dataStart, dataEnd);
-
- if (bytesMatch(paths[0], id.bytes)) {
- if (paths.length === 1) {
- // this is the end of the paths and we've found the tag we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next tag inside of the data
- // of this one
- results = results.concat(findEbml(data, paths.slice(1)));
- }
- }
-
- var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
-
- i += totalLength;
- }
-
- return results;
- }; // see https://www.matroska.org/technical/basics.html#block-structure
-
- var ID3 = toUint8([0x49, 0x44, 0x33]);
- var getId3Size = function getId3Size(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = toUint8(bytes);
- var flags = bytes[offset + 5];
- var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
- var footerPresent = (flags & 16) >> 4;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
- };
- var getId3Offset = function getId3Offset(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = toUint8(bytes);
-
- if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
- offset: offset
- })) {
- return offset;
- }
-
- offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
- // have multiple ID3 tag sections even though
- // they should not.
-
- return getId3Offset(bytes, offset);
- };
-
- var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
- var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
- var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
- /**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- *
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
- var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
- var positions = [];
- var i = 1; // Find all `Emulation Prevention Bytes`
-
- while (i < bytes.length - 2) {
- if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
- positions.push(i + 2);
- i++;
- }
-
- i++;
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (positions.length === 0) {
- return bytes;
- } // Create a new array to hold the NAL unit data
-
-
- var newLength = bytes.length - positions.length;
- var newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === positions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- positions.shift();
- }
-
- newData[i] = bytes[sourceIndex];
- }
-
- return newData;
- };
- var findNal = function findNal(bytes, dataType, types, nalLimit) {
- if (nalLimit === void 0) {
- nalLimit = Infinity;
- }
-
- bytes = toUint8(bytes);
- types = [].concat(types);
- var i = 0;
- var nalStart;
- var nalsFound = 0; // keep searching until:
- // we reach the end of bytes
- // we reach the maximum number of nals they want to seach
- // NOTE: that we disregard nalLimit when we have found the start
- // of the nal we want so that we can find the end of the nal we want.
-
- while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
- var nalOffset = void 0;
-
- if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
- nalOffset = 4;
- } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
- nalOffset = 3;
- } // we are unsynced,
- // find the next nal unit
-
-
- if (!nalOffset) {
- i++;
- continue;
- }
-
- nalsFound++;
-
- if (nalStart) {
- return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
- }
-
- var nalType = void 0;
-
- if (dataType === 'h264') {
- nalType = bytes[i + nalOffset] & 0x1f;
- } else if (dataType === 'h265') {
- nalType = bytes[i + nalOffset] >> 1 & 0x3f;
- }
-
- if (types.indexOf(nalType) !== -1) {
- nalStart = i + nalOffset;
- } // nal header is 1 length for h264, and 2 for h265
-
-
- i += nalOffset + (dataType === 'h264' ? 1 : 2);
- }
-
- return bytes.subarray(0, 0);
- };
- var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h264', type, nalLimit);
- };
- var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h265', type, nalLimit);
- };
-
- var CONSTANTS = {
- // "webm" string literal in hex
- 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
- // "matroska" string literal in hex
- 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
- // "fLaC" string literal in hex
- 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
- // "OggS" string literal in hex
- 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
- // ac-3 sync byte, also works for ec-3 as that is simply a codec
- // of ac-3
- 'ac3': toUint8([0x0b, 0x77]),
- // "RIFF" string literal in hex used for wav and avi
- 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
- // "AVI" string literal in hex
- 'avi': toUint8([0x41, 0x56, 0x49]),
- // "WAVE" string literal in hex
- 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
- // "ftyp3g" string literal in hex
- '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
- // "ftyp" string literal in hex
- 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
- // "styp" string literal in hex
- 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
- // "ftyp" string literal in hex
- 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74])
- };
- var _isLikely = {
- aac: function aac(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, [0xFF, 0x10], {
- offset: offset,
- mask: [0xFF, 0x16]
- });
- },
- mp3: function mp3(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, [0xFF, 0x02], {
- offset: offset,
- mask: [0xFF, 0x06]
- });
- },
- webm: function webm(bytes) {
- var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
-
- return bytesMatch(docType, CONSTANTS.webm);
- },
- mkv: function mkv(bytes) {
- var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
-
- return bytesMatch(docType, CONSTANTS.matroska);
- },
- mp4: function mp4(bytes) {
- return !_isLikely['3gp'](bytes) && !_isLikely.mov(bytes) && (bytesMatch(bytes, CONSTANTS.mp4, {
- offset: 4
- }) || bytesMatch(bytes, CONSTANTS.fmp4, {
- offset: 4
- }));
- },
- mov: function mov(bytes) {
- return bytesMatch(bytes, CONSTANTS.mov, {
- offset: 4
- });
- },
- '3gp': function gp(bytes) {
- return bytesMatch(bytes, CONSTANTS['3gp'], {
- offset: 4
- });
- },
- ac3: function ac3(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, CONSTANTS.ac3, {
- offset: offset
- });
- },
- ts: function ts(bytes) {
- if (bytes.length < 189 && bytes.length >= 1) {
- return bytes[0] === 0x47;
- }
-
- var i = 0; // check the first 376 bytes for two matching sync bytes
-
- while (i + 188 < bytes.length && i < 188) {
- if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
- return true;
- }
-
- i += 1;
- }
-
- return false;
- },
- flac: function flac(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, CONSTANTS.flac, {
- offset: offset
- });
- },
- ogg: function ogg(bytes) {
- return bytesMatch(bytes, CONSTANTS.ogg);
- },
- avi: function avi(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
- offset: 8
- });
- },
- wav: function wav(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
- offset: 8
- });
- },
- 'h264': function h264(bytes) {
- // find seq_parameter_set_rbsp
- return findH264Nal(bytes, 7, 3).length;
- },
- 'h265': function h265(bytes) {
- // find video_parameter_set_rbsp or seq_parameter_set_rbsp
- return findH265Nal(bytes, [32, 33], 3).length;
- }
- }; // get all the isLikely functions
- // but make sure 'ts' is above h264 and h265
- // but below everything else as it is the least specific
-
- var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
- .filter(function (t) {
- return t !== 'ts' && t !== 'h264' && t !== 'h265';
- }) // add it back to the bottom
- .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
-
- isLikelyTypes.forEach(function (type) {
- var isLikelyFn = _isLikely[type];
-
- _isLikely[type] = function (bytes) {
- return isLikelyFn(toUint8(bytes));
- };
- }); // export after wrapping
-
- var isLikely = _isLikely; // A useful list of file signatures can be found here
- // https://en.wikipedia.org/wiki/List_of_file_signatures
-
- var detectContainerForBytes = function detectContainerForBytes(bytes) {
- bytes = toUint8(bytes);
-
- for (var i = 0; i < isLikelyTypes.length; i++) {
- var type = isLikelyTypes[i];
-
- if (isLikely[type](bytes)) {
- return type;
- }
- }
-
- return '';
- }; // fmp4 is not a container
-
- var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
- return findBox(bytes, ['moof']).length > 0;
- };
-
- var containers = /*#__PURE__*/Object.freeze({
- __proto__: null,
- isLikely: isLikely,
- detectContainerForBytes: detectContainerForBytes,
- isLikelyFmp4MediaSegment: isLikelyFmp4MediaSegment
- });
-
- var atob = function atob(s) {
- return window__default['default'].atob ? window__default['default'].atob(s) : Buffer.from(s, 'base64').toString('binary');
- };
-
- function decodeB64ToUint8Array(b64Text) {
- var decodedString = atob(b64Text);
- var array = new Uint8Array(decodedString.length);
-
- for (var i = 0; i < decodedString.length; i++) {
- array[i] = decodedString.charCodeAt(i);
- }
-
- return array;
- }
-
- /**
- * Loops through all supported media groups in master and calls the provided
- * callback for each group
- *
- * @param {Object} master
- * The parsed master manifest object
- * @param {string[]} groups
- * The media groups to call the callback for
- * @param {Function} callback
- * Callback to call for each media group
- */
- var forEachMediaGroup = function forEachMediaGroup(master, groups, callback) {
- groups.forEach(function (mediaType) {
- for (var groupKey in master.mediaGroups[mediaType]) {
- for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
- var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
- callback(mediaProperties, mediaType, groupKey, labelKey);
- }
- }
- });
- };
-
- var mediaGroups = /*#__PURE__*/Object.freeze({
- __proto__: null,
- forEachMediaGroup: forEachMediaGroup
- });
-
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
-
- function commonjsRequire () {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
-
- var urlToolkit = createCommonjsModule(function (module, exports) {
- // see https://tools.ietf.org/html/rfc1808
- (function (root) {
- var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/;
- var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
- var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
- var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
- var URLToolkit = {
- // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
- // E.g
- // With opts.alwaysNormalize = false (default, spec compliant)
- // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
- // With opts.alwaysNormalize = true (not spec compliant)
- // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
- buildAbsoluteURL: function buildAbsoluteURL(baseURL, relativeURL, opts) {
- opts = opts || {}; // remove any remaining space and CRLF
-
- baseURL = baseURL.trim();
- relativeURL = relativeURL.trim();
-
- if (!relativeURL) {
- // 2a) If the embedded URL is entirely empty, it inherits the
- // entire base URL (i.e., is set equal to the base URL)
- // and we are done.
- if (!opts.alwaysNormalize) {
- return baseURL;
- }
-
- var basePartsForNormalise = URLToolkit.parseURL(baseURL);
-
- if (!basePartsForNormalise) {
- throw new Error('Error trying to parse base URL.');
- }
-
- basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
- return URLToolkit.buildURLFromParts(basePartsForNormalise);
- }
-
- var relativeParts = URLToolkit.parseURL(relativeURL);
-
- if (!relativeParts) {
- throw new Error('Error trying to parse relative URL.');
- }
-
- if (relativeParts.scheme) {
- // 2b) If the embedded URL starts with a scheme name, it is
- // interpreted as an absolute URL and we are done.
- if (!opts.alwaysNormalize) {
- return relativeURL;
- }
-
- relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
- return URLToolkit.buildURLFromParts(relativeParts);
- }
-
- var baseParts = URLToolkit.parseURL(baseURL);
-
- if (!baseParts) {
- throw new Error('Error trying to parse base URL.');
- }
-
- if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
- // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
- // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
- var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
- baseParts.netLoc = pathParts[1];
- baseParts.path = pathParts[2];
- }
-
- if (baseParts.netLoc && !baseParts.path) {
- baseParts.path = '/';
- }
-
- var builtParts = {
- // 2c) Otherwise, the embedded URL inherits the scheme of
- // the base URL.
- scheme: baseParts.scheme,
- netLoc: relativeParts.netLoc,
- path: null,
- params: relativeParts.params,
- query: relativeParts.query,
- fragment: relativeParts.fragment
- };
-
- if (!relativeParts.netLoc) {
- // 3) If the embedded URL's is non-empty, we skip to
- // Step 7. Otherwise, the embedded URL inherits the
- // (if any) of the base URL.
- builtParts.netLoc = baseParts.netLoc; // 4) If the embedded URL path is preceded by a slash "/", the
- // path is not relative and we skip to Step 7.
-
- if (relativeParts.path[0] !== '/') {
- if (!relativeParts.path) {
- // 5) If the embedded URL path is empty (and not preceded by a
- // slash), then the embedded URL inherits the base URL path
- builtParts.path = baseParts.path; // 5a) if the embedded URL's is non-empty, we skip to
- // step 7; otherwise, it inherits the of the base
- // URL (if any) and
-
- if (!relativeParts.params) {
- builtParts.params = baseParts.params; // 5b) if the embedded URL's is non-empty, we skip to
- // step 7; otherwise, it inherits the of the base
- // URL (if any) and we skip to step 7.
-
- if (!relativeParts.query) {
- builtParts.query = baseParts.query;
- }
- }
- } else {
- // 6) The last segment of the base URL's path (anything
- // following the rightmost slash "/", or the entire path if no
- // slash is present) is removed and the embedded URL's path is
- // appended in its place.
- var baseURLPath = baseParts.path;
- var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
- builtParts.path = URLToolkit.normalizePath(newPath);
- }
- }
- }
-
- if (builtParts.path === null) {
- builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
- }
-
- return URLToolkit.buildURLFromParts(builtParts);
- },
- parseURL: function parseURL(url) {
- var parts = URL_REGEX.exec(url);
-
- if (!parts) {
- return null;
- }
-
- return {
- scheme: parts[1] || '',
- netLoc: parts[2] || '',
- path: parts[3] || '',
- params: parts[4] || '',
- query: parts[5] || '',
- fragment: parts[6] || ''
- };
- },
- normalizePath: function normalizePath(path) {
- // The following operations are
- // then applied, in order, to the new path:
- // 6a) All occurrences of "./", where "." is a complete path
- // segment, are removed.
- // 6b) If the path ends with "." as a complete path segment,
- // that "." is removed.
- path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "/../", where is a
- // complete path segment not equal to "..", are removed.
- // Removal of these path segments is performed iteratively,
- // removing the leftmost matching pattern on each iteration,
- // until no matching pattern remains.
- // 6d) If the path ends with "/..", where is a
- // complete path segment not equal to "..", that
- // "/.." is removed.
-
- while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
-
- return path.split('').reverse().join('');
- },
- buildURLFromParts: function buildURLFromParts(parts) {
- return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
- }
- };
- module.exports = URLToolkit;
- })();
- });
-
- var DEFAULT_LOCATION = 'http://example.com';
-
- var resolveUrl = function resolveUrl(baseUrl, relativeUrl) {
- // return early if we don't need to resolve
- if (/^[a-z]+:/i.test(relativeUrl)) {
- return relativeUrl;
- } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
-
-
- if (/^data:/.test(baseUrl)) {
- baseUrl = window__default['default'].location && window__default['default'].location.href || '';
- } // IE11 supports URL but not the URL constructor
- // feature detect the behavior we want
-
-
- var nativeURL = typeof window__default['default'].URL === 'function';
- var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
- // and if baseUrl isn't an absolute url
-
- var removeLocation = !window__default['default'].location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
-
- if (nativeURL) {
- baseUrl = new window__default['default'].URL(baseUrl, window__default['default'].location || DEFAULT_LOCATION);
- } else if (!/\/\//i.test(baseUrl)) {
- baseUrl = urlToolkit.buildAbsoluteURL(window__default['default'].location && window__default['default'].location.href || '', baseUrl);
- }
-
- if (nativeURL) {
- var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
- // and if we're location-less, remove the location
- // otherwise, return the url unmodified
-
- if (removeLocation) {
- return newUrl.href.slice(DEFAULT_LOCATION.length);
- } else if (protocolLess) {
- return newUrl.href.slice(newUrl.protocol.length);
- }
-
- return newUrl.href;
- }
-
- return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
- };
-
- /**
- * @file stream.js
- */
-
- /**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
- var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
- }();
-
- var index = {
- codecs: codecs,
- byteHelpers: byteHelpers,
- containers: containers,
- decodeB64ToUint8Array: decodeB64ToUint8Array,
- mediaGroups: mediaGroups,
- resolveUrl: resolveUrl,
- Stream: Stream
- };
-
- return index;
-
-})));
diff --git a/node_modules/@videojs/vhs-utils/dist/vhs-utils.min.js b/node_modules/@videojs/vhs-utils/dist/vhs-utils.min.js
deleted file mode 100644
index a0d9ca9..0000000
--- a/node_modules/@videojs/vhs-utils/dist/vhs-utils.min.js
+++ /dev/null
@@ -1,2 +0,0 @@
-/*! @name @videojs/vhs-utils @version 3.0.2 @license MIT */
-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("global/window")):"function"==typeof define&&define.amd?define(["global/window"],e):(t="undefined"!=typeof globalThis?globalThis:t||self).vhsUtils=e(t.window)}(this,(function(t){"use strict";function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r,n,o=e(t),a={mp4:/^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,webm:/^(vp0?[89]|av0?1|opus|vorbis)/,ogg:/^(vp0?[89]|theora|flac|opus|vorbis)/,video:/^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,audio:/^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,text:/^(stpp.ttml.im1t)/,muxerVideo:/^(avc0?1)/,muxerAudio:/^(mp4a)/,muxerText:/a^/},i=["video","audio","text"],u=["Video","Audio","Text"],f=function(t){return t?t.replace(/avc1\.(\d+)\.(\d+)/i,(function(t,e,r){return"avc1."+("00"+Number(e).toString(16)).slice(-2)+"00"+("00"+Number(r).toString(16)).slice(-2)})):t},c=function(t){return t.map(f)},s=function(t){void 0===t&&(t="");var e=t.split(","),r=[];return e.forEach((function(t){var e;t=t.trim(),i.forEach((function(n){var o=a[n].exec(t.toLowerCase());if(o&&!(o.length<=1)){e=n;var i=t.substring(0,o[1].length),u=t.replace(i,"");r.push({type:i,details:u,mediaType:n})}})),e||r.push({type:t,details:"",mediaType:"unknown"})})),r},l=function(t){return void 0===t&&(t=""),a.audio.test(t.trim().toLowerCase())},p=function(t){return void 0===t&&(t=""),a.text.test(t.trim().toLowerCase())},h=function(t){if(t&&"string"==typeof t){var e=t.toLowerCase().split(",").map((function(t){return f(t.trim())})),r="video";1===e.length&&l(e[0])?r="audio":1===e.length&&p(e[0])&&(r="application");var n="mp4";return e.every((function(t){return a.mp4.test(t)}))?n="mp4":e.every((function(t){return a.webm.test(t)}))?n="webm":e.every((function(t){return a.ogg.test(t)}))&&(n="ogg"),r+"/"+n+';codecs="'+t+'"'}},v=Object.freeze({__proto__:null,translateLegacyCodec:f,translateLegacyCodecs:c,mapLegacyAvcCodecs:function(t){return t.replace(/avc1\.(\d+)\.(\d+)/i,(function(t){return c([t])[0]}))},parseCodecs:s,codecsFromDefault:function(t,e){if(!t.mediaGroups.AUDIO||!e)return null;var r=t.mediaGroups.AUDIO[e];if(!r)return null;for(var n in r){var o=r[n];if(o.default&&o.playlists)return s(o.playlists[0].attributes.CODECS)}return null},isVideoCodec:function(t){return void 0===t&&(t=""),a.video.test(t.trim().toLowerCase())},isAudioCodec:l,isTextCodec:p,getMimeForCodec:h,browserSupportsCodec:function(t){return void 0===t&&(t=""),o.default.MediaSource&&o.default.MediaSource.isTypeSupported&&o.default.MediaSource.isTypeSupported(h(t))||!1},muxerSupportsCodec:function(t){return void 0===t&&(t=""),t.toLowerCase().split(",").every((function(t){t=t.trim();for(var e=0;ec&&(f-=c,f-=c,f-=A(2))}return Number(f)},C=function(t,e){var r=(void 0===e?{}:e).le,n=void 0!==r&&r;("bigint"!=typeof t&&"number"!=typeof t||"number"==typeof t&&t!=t)&&(t=0),t=A(t);for(var o=g(t),a=new Uint8Array(new ArrayBuffer(o)),i=0;i=e.length&&f.call(e,(function(e,r){return e===(u[r]?u[r]&t[a+r]:t[a+r])}))},k=Object.freeze({__proto__:null,countBits:y,countBytes:g,padStart:d,isTypedArray:m,toUint8:b,toHexString:function(t){t=b(t);for(var e="",r=0;r>>0,u=e.subarray(a+4,a+8);if(0===i)break;var f=a+i;if(f>e.length){if(n)break;f=e.length}var c=e.subarray(a+8,f);E(u,r[0])&&(1===r.length?o.push(c):o.push.apply(o,t(c,r.slice(1),n))),a=f}return o},D={EBML:b([26,69,223,163]),DocType:b([66,130]),Segment:b([24,83,128,103]),SegmentInfo:b([21,73,169,102]),Tracks:b([22,84,174,107]),Track:b([174]),TrackNumber:b([215]),DefaultDuration:b([35,227,131]),TrackEntry:b([174]),TrackType:b([131]),FlagDefault:b([136]),CodecID:b([134]),CodecPrivate:b([99,162]),VideoTrack:b([224]),AudioTrack:b([225]),Cluster:b([31,67,182,117]),Timestamp:b([231]),TimestampScale:b([42,215,177]),BlockGroup:b([160]),BlockDuration:b([155]),Block:b([161]),SimpleBlock:b([163])},R=[128,64,32,16,8,4,2,1],I=function(t,e,r,n){void 0===r&&(r=!0),void 0===n&&(n=!1);var o=function(t){for(var e=1,r=0;r=r.length)return r.length;var o=I(r,n,!1);if(E(e.bytes,o.bytes))return n;var a=I(r,n+o.length);return t(e,r,n+a.length+a.value+o.length)},z=function t(e,r){r=function(t){return Array.isArray(t)?t.map((function(t){return N(t)})):[N(t)]}(r),e=b(e);var n=[];if(!r.length)return n;for(var o=0;oe.length?e.length:u+i.value,c=e.subarray(u,f);E(r[0],a.bytes)&&(1===r.length?n.push(c):n=n.concat(t(c,r.slice(1)))),o+=a.length+i.length+c.length}return n},M=b([73,68,51]),F=function t(e,r){return void 0===r&&(r=0),(e=b(e)).length-r<10||!E(e,M,{offset:r})?r:(r+=function(t,e){void 0===e&&(e=0);var r=(t=b(t))[e+5],n=t[e+6]<<21|t[e+7]<<14|t[e+8]<<7|t[e+9];return(16&r)>>4?n+20:n+10}(e,r),t(e,r))},j=b([0,0,0,1]),q=b([0,0,1]),P=b([0,0,3]),G=function(t){for(var e=[],r=1;r>1&63),-1!==r.indexOf(f)&&(o=a+u),a+=u+("h264"===e?1:2)}else a++}return t.subarray(0,0)},H={webm:b([119,101,98,109]),matroska:b([109,97,116,114,111,115,107,97]),flac:b([102,76,97,67]),ogg:b([79,103,103,83]),ac3:b([11,119]),riff:b([82,73,70,70]),avi:b([65,86,73]),wav:b([87,65,86,69]),"3gp":b([102,116,121,112,51,103]),mp4:b([102,116,121,112]),fmp4:b([115,116,121,112]),mov:b([102,116,121,112,113,116])},$={aac:function(t){var e=F(t);return E(t,[255,16],{offset:e,mask:[255,22]})},mp3:function(t){var e=F(t);return E(t,[255,2],{offset:e,mask:[255,6]})},webm:function(t){var e=z(t,[D.EBML,D.DocType])[0];return E(e,H.webm)},mkv:function(t){var e=z(t,[D.EBML,D.DocType])[0];return E(e,H.matroska)},mp4:function(t){return!$["3gp"](t)&&!$.mov(t)&&(E(t,H.mp4,{offset:4})||E(t,H.fmp4,{offset:4}))},mov:function(t){return E(t,H.mov,{offset:4})},"3gp":function(t){return E(t,H["3gp"],{offset:4})},ac3:function(t){var e=F(t);return E(t,H.ac3,{offset:e})},ts:function(t){if(t.length<189&&t.length>=1)return 71===t[0];for(var e=0;e+1880}});var Q=Object.freeze({__proto__:null,forEachMediaGroup:function(t,e,r){e.forEach((function(e){for(var n in t.mediaGroups[e])for(var o in t.mediaGroups[e][n]){var a=t.mediaGroups[e][n][o];r(a,e,n,o)}}))}});var W=function(t,e,r){return t(r={path:e,exports:{},require:function(t,e){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==e&&r.path)}},r.exports),r.exports}((function(t,e){var r,n,o,a,i;r=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/,n=/^([^\/?#]*)(.*)$/,o=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,i={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var o=i.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");return o.path=i.normalizePath(o.path),i.buildURLFromParts(o)}var a=i.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=i.normalizePath(a.path),i.buildURLFromParts(a)):e;var u=i.parseURL(t);if(!u)throw new Error("Error trying to parse base URL.");if(!u.netLoc&&u.path&&"/"!==u.path[0]){var f=n.exec(u.path);u.netLoc=f[1],u.path=f[2]}u.netLoc&&!u.path&&(u.path="/");var c={scheme:u.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(c.netLoc=u.netLoc,"/"!==a.path[0]))if(a.path){var s=u.path,l=s.substring(0,s.lastIndexOf("/")+1)+a.path;c.path=i.normalizePath(l)}else c.path=u.path,a.params||(c.params=u.params,a.query||(c.query=u.query));return null===c.path&&(c.path=r.alwaysNormalize?i.normalizePath(a.path):a.path),i.buildURLFromParts(c)},parseURL:function(t){var e=r.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(o,"");t.length!==(t=t.replace(a,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=i})),X="http://example.com";return{codecs:v,byteHelpers:k,containers:K,decodeB64ToUint8Array:function(t){for(var e,r=(e=t,o.default.atob?o.default.atob(e):Buffer.from(e,"base64").toString("binary")),n=new Uint8Array(r.length),a=0;a-1},e.trigger=function(t){var e=this.listeners[t];if(e)if(2===arguments.length)for(var r=e.length,n=0;n (Math.log(x) / Math.log(2));
-
-var repeat = function repeat(str, len) {
- var acc = '';
-
- while (len--) {
- acc += str;
- }
-
- return acc;
-}; // count the number of bits it would take to represent a number
-// we used to do this with log2 but BigInt does not support builtin math
-// Math.ceil(log2(x));
-
-
-export var countBits = function countBits(x) {
- return x.toString(2).length;
-}; // count the number of whole bytes it would take to represent a number
-
-export var countBytes = function countBytes(x) {
- return Math.ceil(countBits(x) / 8);
-};
-export var padStart = function padStart(b, len, str) {
- if (str === void 0) {
- str = ' ';
- }
-
- return (repeat(str, len) + b.toString()).slice(-len);
-};
-export var isTypedArray = function isTypedArray(obj) {
- return ArrayBuffer.isView(obj);
-};
-export var toUint8 = function toUint8(bytes) {
- if (bytes instanceof Uint8Array) {
- return bytes;
- }
-
- if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
- // any non-number or NaN leads to empty uint8array
- // eslint-disable-next-line
- if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
- bytes = 0;
- } else {
- bytes = [bytes];
- }
- }
-
- return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
-};
-export var toHexString = function toHexString(bytes) {
- bytes = toUint8(bytes);
- var str = '';
-
- for (var i = 0; i < bytes.length; i++) {
- str += padStart(bytes[i].toString(16), 2, '0');
- }
-
- return str;
-};
-export var toBinaryString = function toBinaryString(bytes) {
- bytes = toUint8(bytes);
- var str = '';
-
- for (var i = 0; i < bytes.length; i++) {
- str += padStart(bytes[i].toString(2), 8, '0');
- }
-
- return str;
-};
-var BigInt = window.BigInt || Number;
-var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
-export var ENDIANNESS = function () {
- var a = new Uint16Array([0xFFCC]);
- var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
-
- if (b[0] === 0xFF) {
- return 'big';
- }
-
- if (b[0] === 0xCC) {
- return 'little';
- }
-
- return 'unknown';
-}();
-export var IS_BIG_ENDIAN = ENDIANNESS === 'big';
-export var IS_LITTLE_ENDIAN = ENDIANNESS === 'little';
-export var bytesToNumber = function bytesToNumber(bytes, _temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- _ref$signed = _ref.signed,
- signed = _ref$signed === void 0 ? false : _ref$signed,
- _ref$le = _ref.le,
- le = _ref$le === void 0 ? false : _ref$le;
-
- bytes = toUint8(bytes);
- var fn = le ? 'reduce' : 'reduceRight';
- var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
- var number = obj.call(bytes, function (total, byte, i) {
- var exponent = le ? i : Math.abs(i + 1 - bytes.length);
- return total + BigInt(byte) * BYTE_TABLE[exponent];
- }, BigInt(0));
-
- if (signed) {
- var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
- number = BigInt(number);
-
- if (number > max) {
- number -= max;
- number -= max;
- number -= BigInt(2);
- }
- }
-
- return Number(number);
-};
-export var numberToBytes = function numberToBytes(number, _temp2) {
- var _ref2 = _temp2 === void 0 ? {} : _temp2,
- _ref2$le = _ref2.le,
- le = _ref2$le === void 0 ? false : _ref2$le;
-
- // eslint-disable-next-line
- if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
- number = 0;
- }
-
- number = BigInt(number);
- var byteCount = countBytes(number);
- var bytes = new Uint8Array(new ArrayBuffer(byteCount));
-
- for (var i = 0; i < byteCount; i++) {
- var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
- bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
-
- if (number < 0) {
- bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
- bytes[byteIndex] -= i === 0 ? 1 : 2;
- }
- }
-
- return bytes;
-};
-export var bytesToString = function bytesToString(bytes) {
- if (!bytes) {
- return '';
- } // TODO: should toUint8 handle cases where we only have 8 bytes
- // but report more since this is a Uint16+ Array?
-
-
- bytes = Array.prototype.slice.call(bytes);
- var string = String.fromCharCode.apply(null, toUint8(bytes));
-
- try {
- return decodeURIComponent(escape(string));
- } catch (e) {// if decodeURIComponent/escape fails, we are dealing with partial
- // or full non string data. Just return the potentially garbled string.
- }
-
- return string;
-};
-export var stringToBytes = function stringToBytes(string, stringIsBytes) {
- if (typeof string !== 'string' && string && typeof string.toString === 'function') {
- string = string.toString();
- }
-
- if (typeof string !== 'string') {
- return new Uint8Array();
- } // If the string already is bytes, we don't have to do this
- // otherwise we do this so that we split multi length characters
- // into individual bytes
-
-
- if (!stringIsBytes) {
- string = unescape(encodeURIComponent(string));
- }
-
- var view = new Uint8Array(string.length);
-
- for (var i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
-
- return view;
-};
-export var concatTypedArrays = function concatTypedArrays() {
- for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
- buffers[_key] = arguments[_key];
- }
-
- buffers = buffers.filter(function (b) {
- return b && (b.byteLength || b.length) && typeof b !== 'string';
- });
-
- if (buffers.length <= 1) {
- // for 0 length we will return empty uint8
- // for 1 length we return the first uint8
- return toUint8(buffers[0]);
- }
-
- var totalLen = buffers.reduce(function (total, buf, i) {
- return total + (buf.byteLength || buf.length);
- }, 0);
- var tempBuffer = new Uint8Array(totalLen);
- var offset = 0;
- buffers.forEach(function (buf) {
- buf = toUint8(buf);
- tempBuffer.set(buf, offset);
- offset += buf.byteLength;
- });
- return tempBuffer;
-};
-/**
- * Check if the bytes "b" are contained within bytes "a".
- *
- * @param {Uint8Array|Array} a
- * Bytes to check in
- *
- * @param {Uint8Array|Array} b
- * Bytes to check for
- *
- * @param {Object} options
- * options
- *
- * @param {Array|Uint8Array} [offset=0]
- * offset to use when looking at bytes in a
- *
- * @param {Array|Uint8Array} [mask=[]]
- * mask to use on bytes before comparison.
- *
- * @return {boolean}
- * If all bytes in b are inside of a, taking into account
- * bit masks.
- */
-
-export var bytesMatch = function bytesMatch(a, b, _temp3) {
- var _ref3 = _temp3 === void 0 ? {} : _temp3,
- _ref3$offset = _ref3.offset,
- offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
- _ref3$mask = _ref3.mask,
- mask = _ref3$mask === void 0 ? [] : _ref3$mask;
-
- a = toUint8(a);
- b = toUint8(b); // ie 11 does not support uint8 every
-
- var fn = b.every ? b.every : Array.prototype.every;
- return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
- fn.call(b, function (bByte, i) {
- var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
- return bByte === aByte;
- });
-};
-export var sliceBytes = function sliceBytes(src, start, end) {
- if (Uint8Array.prototype.slice) {
- return Uint8Array.prototype.slice.call(src, start, end);
- }
-
- return new Uint8Array(Array.prototype.slice.call(src, start, end));
-};
-export var reverseBytes = function reverseBytes(src) {
- if (src.reverse) {
- return src.reverse();
- }
-
- return Array.prototype.reverse.call(src);
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/codec-helpers.js b/node_modules/@videojs/vhs-utils/es/codec-helpers.js
deleted file mode 100644
index ece8f3b..0000000
--- a/node_modules/@videojs/vhs-utils/es/codec-helpers.js
+++ /dev/null
@@ -1,96 +0,0 @@
-import { padStart, toHexString, toBinaryString } from './byte-helpers.js'; // https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
-// https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter#AV1
-
-export var getAv1Codec = function getAv1Codec(bytes) {
- var codec = '';
- var profile = bytes[1] >>> 3;
- var level = bytes[1] & 0x1F;
- var tier = bytes[2] >>> 7;
- var highBitDepth = (bytes[2] & 0x40) >> 6;
- var twelveBit = (bytes[2] & 0x20) >> 5;
- var monochrome = (bytes[2] & 0x10) >> 4;
- var chromaSubsamplingX = (bytes[2] & 0x08) >> 3;
- var chromaSubsamplingY = (bytes[2] & 0x04) >> 2;
- var chromaSamplePosition = bytes[2] & 0x03;
- codec += profile + "." + padStart(level, 2, '0');
-
- if (tier === 0) {
- codec += 'M';
- } else if (tier === 1) {
- codec += 'H';
- }
-
- var bitDepth;
-
- if (profile === 2 && highBitDepth) {
- bitDepth = twelveBit ? 12 : 10;
- } else {
- bitDepth = highBitDepth ? 10 : 8;
- }
-
- codec += "." + padStart(bitDepth, 2, '0'); // TODO: can we parse color range??
-
- codec += "." + monochrome;
- codec += "." + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition;
- return codec;
-};
-export var getAvcCodec = function getAvcCodec(bytes) {
- var profileId = toHexString(bytes[1]);
- var constraintFlags = toHexString(bytes[2] & 0xFC);
- var levelId = toHexString(bytes[3]);
- return "" + profileId + constraintFlags + levelId;
-};
-export var getHvcCodec = function getHvcCodec(bytes) {
- var codec = '';
- var profileSpace = bytes[1] >> 6;
- var profileId = bytes[1] & 0x1F;
- var tierFlag = (bytes[1] & 0x20) >> 5;
- var profileCompat = bytes.subarray(2, 6);
- var constraintIds = bytes.subarray(6, 12);
- var levelId = bytes[12];
-
- if (profileSpace === 1) {
- codec += 'A';
- } else if (profileSpace === 2) {
- codec += 'B';
- } else if (profileSpace === 3) {
- codec += 'C';
- }
-
- codec += profileId + "."; // ffmpeg does this in big endian
-
- var profileCompatVal = parseInt(toBinaryString(profileCompat).split('').reverse().join(''), 2); // apple does this in little endian...
-
- if (profileCompatVal > 255) {
- profileCompatVal = parseInt(toBinaryString(profileCompat), 2);
- }
-
- codec += profileCompatVal.toString(16) + ".";
-
- if (tierFlag === 0) {
- codec += 'L';
- } else {
- codec += 'H';
- }
-
- codec += levelId;
- var constraints = '';
-
- for (var i = 0; i < constraintIds.length; i++) {
- var v = constraintIds[i];
-
- if (v) {
- if (constraints) {
- constraints += '.';
- }
-
- constraints += v.toString(16);
- }
- }
-
- if (constraints) {
- codec += "." + constraints;
- }
-
- return codec;
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/codecs.js b/node_modules/@videojs/vhs-utils/es/codecs.js
deleted file mode 100644
index 816a7ce..0000000
--- a/node_modules/@videojs/vhs-utils/es/codecs.js
+++ /dev/null
@@ -1,253 +0,0 @@
-import window from 'global/window';
-var regexs = {
- // to determine mime types
- mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
- webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
- ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
- // to determine if a codec is audio or video
- video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
- audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
- text: /^(stpp.ttml.im1t)/,
- // mux.js support regex
- muxerVideo: /^(avc0?1)/,
- muxerAudio: /^(mp4a)/,
- // match nothing as muxer does not support text right now.
- // there cannot never be a character before the start of a string
- // so this matches nothing.
- muxerText: /a^/
-};
-var mediaTypes = ['video', 'audio', 'text'];
-var upperMediaTypes = ['Video', 'Audio', 'Text'];
-/**
- * Replace the old apple-style `avc1..` codec string with the standard
- * `avc1.`
- *
- * @param {string} codec
- * Codec string to translate
- * @return {string}
- * The translated codec string
- */
-
-export var translateLegacyCodec = function translateLegacyCodec(codec) {
- if (!codec) {
- return codec;
- }
-
- return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
- var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
- var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
- return 'avc1.' + profileHex + '00' + avcLevelHex;
- });
-};
-/**
- * Replace the old apple-style `avc1..` codec strings with the standard
- * `avc1.`
- *
- * @param {string[]} codecs
- * An array of codec strings to translate
- * @return {string[]}
- * The translated array of codec strings
- */
-
-export var translateLegacyCodecs = function translateLegacyCodecs(codecs) {
- return codecs.map(translateLegacyCodec);
-};
-/**
- * Replace codecs in the codec string with the old apple-style `avc1..` to the
- * standard `avc1.`.
- *
- * @param {string} codecString
- * The codec string
- * @return {string}
- * The codec string with old apple-style codecs replaced
- *
- * @private
- */
-
-export var mapLegacyAvcCodecs = function mapLegacyAvcCodecs(codecString) {
- return codecString.replace(/avc1\.(\d+)\.(\d+)/i, function (match) {
- return translateLegacyCodecs([match])[0];
- });
-};
-/**
- * @typedef {Object} ParsedCodecInfo
- * @property {number} codecCount
- * Number of codecs parsed
- * @property {string} [videoCodec]
- * Parsed video codec (if found)
- * @property {string} [videoObjectTypeIndicator]
- * Video object type indicator (if found)
- * @property {string|null} audioProfile
- * Audio profile
- */
-
-/**
- * Parses a codec string to retrieve the number of codecs specified, the video codec and
- * object type indicator, and the audio profile.
- *
- * @param {string} [codecString]
- * The codec string to parse
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
-export var parseCodecs = function parseCodecs(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- var codecs = codecString.split(',');
- var result = [];
- codecs.forEach(function (codec) {
- codec = codec.trim();
- var codecType;
- mediaTypes.forEach(function (name) {
- var match = regexs[name].exec(codec.toLowerCase());
-
- if (!match || match.length <= 1) {
- return;
- }
-
- codecType = name; // maintain codec case
-
- var type = codec.substring(0, match[1].length);
- var details = codec.replace(type, '');
- result.push({
- type: type,
- details: details,
- mediaType: name
- });
- });
-
- if (!codecType) {
- result.push({
- type: codec,
- details: '',
- mediaType: 'unknown'
- });
- }
- });
- return result;
-};
-/**
- * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
- * a default alternate audio playlist for the provided audio group.
- *
- * @param {Object} master
- * The master playlist
- * @param {string} audioGroupId
- * ID of the audio group for which to find the default codec info
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-
-export var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
- if (!master.mediaGroups.AUDIO || !audioGroupId) {
- return null;
- }
-
- var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
-
- if (!audioGroup) {
- return null;
- }
-
- for (var name in audioGroup) {
- var audioType = audioGroup[name];
-
- if (audioType.default && audioType.playlists) {
- // codec should be the same for all playlists within the audio type
- return parseCodecs(audioType.playlists[0].attributes.CODECS);
- }
- }
-
- return null;
-};
-export var isVideoCodec = function isVideoCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.video.test(codec.trim().toLowerCase());
-};
-export var isAudioCodec = function isAudioCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.audio.test(codec.trim().toLowerCase());
-};
-export var isTextCodec = function isTextCodec(codec) {
- if (codec === void 0) {
- codec = '';
- }
-
- return regexs.text.test(codec.trim().toLowerCase());
-};
-export var getMimeForCodec = function getMimeForCodec(codecString) {
- if (!codecString || typeof codecString !== 'string') {
- return;
- }
-
- var codecs = codecString.toLowerCase().split(',').map(function (c) {
- return translateLegacyCodec(c.trim());
- }); // default to video type
-
- var type = 'video'; // only change to audio type if the only codec we have is
- // audio
-
- if (codecs.length === 1 && isAudioCodec(codecs[0])) {
- type = 'audio';
- } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
- // text uses application/ for now
- type = 'application';
- } // default the container to mp4
-
-
- var container = 'mp4'; // every codec must be able to go into the container
- // for that container to be the correct one
-
- if (codecs.every(function (c) {
- return regexs.mp4.test(c);
- })) {
- container = 'mp4';
- } else if (codecs.every(function (c) {
- return regexs.webm.test(c);
- })) {
- container = 'webm';
- } else if (codecs.every(function (c) {
- return regexs.ogg.test(c);
- })) {
- container = 'ogg';
- }
-
- return type + "/" + container + ";codecs=\"" + codecString + "\"";
-};
-export var browserSupportsCodec = function browserSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
-};
-export var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
- if (codecString === void 0) {
- codecString = '';
- }
-
- return codecString.toLowerCase().split(',').every(function (codec) {
- codec = codec.trim(); // any match is supported.
-
- for (var i = 0; i < upperMediaTypes.length; i++) {
- var type = upperMediaTypes[i];
-
- if (regexs["muxer" + type].test(codec)) {
- return true;
- }
- }
-
- return false;
- });
-};
-export var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
-export var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/containers.js b/node_modules/@videojs/vhs-utils/es/containers.js
deleted file mode 100644
index 088606c..0000000
--- a/node_modules/@videojs/vhs-utils/es/containers.js
+++ /dev/null
@@ -1,162 +0,0 @@
-import { toUint8, bytesMatch } from './byte-helpers.js';
-import { findBox } from './mp4-helpers.js';
-import { findEbml, EBML_TAGS } from './ebml-helpers.js';
-import { getId3Offset } from './id3-helpers.js';
-import { findH264Nal, findH265Nal } from './nal-helpers.js';
-var CONSTANTS = {
- // "webm" string literal in hex
- 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
- // "matroska" string literal in hex
- 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
- // "fLaC" string literal in hex
- 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
- // "OggS" string literal in hex
- 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
- // ac-3 sync byte, also works for ec-3 as that is simply a codec
- // of ac-3
- 'ac3': toUint8([0x0b, 0x77]),
- // "RIFF" string literal in hex used for wav and avi
- 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
- // "AVI" string literal in hex
- 'avi': toUint8([0x41, 0x56, 0x49]),
- // "WAVE" string literal in hex
- 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
- // "ftyp3g" string literal in hex
- '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
- // "ftyp" string literal in hex
- 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
- // "styp" string literal in hex
- 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
- // "ftyp" string literal in hex
- 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74])
-};
-var _isLikely = {
- aac: function aac(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, [0xFF, 0x10], {
- offset: offset,
- mask: [0xFF, 0x16]
- });
- },
- mp3: function mp3(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, [0xFF, 0x02], {
- offset: offset,
- mask: [0xFF, 0x06]
- });
- },
- webm: function webm(bytes) {
- var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
-
- return bytesMatch(docType, CONSTANTS.webm);
- },
- mkv: function mkv(bytes) {
- var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
-
- return bytesMatch(docType, CONSTANTS.matroska);
- },
- mp4: function mp4(bytes) {
- return !_isLikely['3gp'](bytes) && !_isLikely.mov(bytes) && (bytesMatch(bytes, CONSTANTS.mp4, {
- offset: 4
- }) || bytesMatch(bytes, CONSTANTS.fmp4, {
- offset: 4
- }));
- },
- mov: function mov(bytes) {
- return bytesMatch(bytes, CONSTANTS.mov, {
- offset: 4
- });
- },
- '3gp': function gp(bytes) {
- return bytesMatch(bytes, CONSTANTS['3gp'], {
- offset: 4
- });
- },
- ac3: function ac3(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, CONSTANTS.ac3, {
- offset: offset
- });
- },
- ts: function ts(bytes) {
- if (bytes.length < 189 && bytes.length >= 1) {
- return bytes[0] === 0x47;
- }
-
- var i = 0; // check the first 376 bytes for two matching sync bytes
-
- while (i + 188 < bytes.length && i < 188) {
- if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
- return true;
- }
-
- i += 1;
- }
-
- return false;
- },
- flac: function flac(bytes) {
- var offset = getId3Offset(bytes);
- return bytesMatch(bytes, CONSTANTS.flac, {
- offset: offset
- });
- },
- ogg: function ogg(bytes) {
- return bytesMatch(bytes, CONSTANTS.ogg);
- },
- avi: function avi(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
- offset: 8
- });
- },
- wav: function wav(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
- offset: 8
- });
- },
- 'h264': function h264(bytes) {
- // find seq_parameter_set_rbsp
- return findH264Nal(bytes, 7, 3).length;
- },
- 'h265': function h265(bytes) {
- // find video_parameter_set_rbsp or seq_parameter_set_rbsp
- return findH265Nal(bytes, [32, 33], 3).length;
- }
-}; // get all the isLikely functions
-// but make sure 'ts' is above h264 and h265
-// but below everything else as it is the least specific
-
-var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
-.filter(function (t) {
- return t !== 'ts' && t !== 'h264' && t !== 'h265';
-}) // add it back to the bottom
-.concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
-
-isLikelyTypes.forEach(function (type) {
- var isLikelyFn = _isLikely[type];
-
- _isLikely[type] = function (bytes) {
- return isLikelyFn(toUint8(bytes));
- };
-}); // export after wrapping
-
-export var isLikely = _isLikely; // A useful list of file signatures can be found here
-// https://en.wikipedia.org/wiki/List_of_file_signatures
-
-export var detectContainerForBytes = function detectContainerForBytes(bytes) {
- bytes = toUint8(bytes);
-
- for (var i = 0; i < isLikelyTypes.length; i++) {
- var type = isLikelyTypes[i];
-
- if (isLikely[type](bytes)) {
- return type;
- }
- }
-
- return '';
-}; // fmp4 is not a container
-
-export var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
- return findBox(bytes, ['moof']).length > 0;
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/decode-b64-to-uint8-array.js b/node_modules/@videojs/vhs-utils/es/decode-b64-to-uint8-array.js
deleted file mode 100644
index 7d96cf8..0000000
--- a/node_modules/@videojs/vhs-utils/es/decode-b64-to-uint8-array.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import window from 'global/window';
-
-var atob = function atob(s) {
- return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
-};
-
-export default function decodeB64ToUint8Array(b64Text) {
- var decodedString = atob(b64Text);
- var array = new Uint8Array(decodedString.length);
-
- for (var i = 0; i < decodedString.length; i++) {
- array[i] = decodedString.charCodeAt(i);
- }
-
- return array;
-}
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/ebml-helpers.js b/node_modules/@videojs/vhs-utils/es/ebml-helpers.js
deleted file mode 100644
index 9f16cf0..0000000
--- a/node_modules/@videojs/vhs-utils/es/ebml-helpers.js
+++ /dev/null
@@ -1,497 +0,0 @@
-import { toUint8, bytesToNumber, bytesMatch, bytesToString, numberToBytes, padStart } from './byte-helpers';
-import { getAvcCodec, getHvcCodec, getAv1Codec } from './codec-helpers.js'; // relevant specs for this parser:
-// https://matroska-org.github.io/libebml/specs.html
-// https://www.matroska.org/technical/elements.html
-// https://www.webmproject.org/docs/container/
-
-export var EBML_TAGS = {
- EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
- DocType: toUint8([0x42, 0x82]),
- Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
- SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
- Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
- Track: toUint8([0xAE]),
- TrackNumber: toUint8([0xd7]),
- DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
- TrackEntry: toUint8([0xAE]),
- TrackType: toUint8([0x83]),
- FlagDefault: toUint8([0x88]),
- CodecID: toUint8([0x86]),
- CodecPrivate: toUint8([0x63, 0xA2]),
- VideoTrack: toUint8([0xe0]),
- AudioTrack: toUint8([0xe1]),
- // Not used yet, but will be used for live webm/mkv
- // see https://www.matroska.org/technical/basics.html#block-structure
- // see https://www.matroska.org/technical/basics.html#simpleblock-structure
- Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
- Timestamp: toUint8([0xE7]),
- TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
- BlockGroup: toUint8([0xA0]),
- BlockDuration: toUint8([0x9B]),
- Block: toUint8([0xA1]),
- SimpleBlock: toUint8([0xA3])
-};
-/**
- * This is a simple table to determine the length
- * of things in ebml. The length is one based (starts at 1,
- * rather than zero) and for every zero bit before a one bit
- * we add one to length. We also need this table because in some
- * case we have to xor all the length bits from another value.
- */
-
-var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
-
-var getLength = function getLength(byte) {
- var len = 1;
-
- for (var i = 0; i < LENGTH_TABLE.length; i++) {
- if (byte & LENGTH_TABLE[i]) {
- break;
- }
-
- len++;
- }
-
- return len;
-}; // length in ebml is stored in the first 4 to 8 bits
-// of the first byte. 4 for the id length and 8 for the
-// data size length. Length is measured by converting the number to binary
-// then 1 + the number of zeros before a 1 is encountered starting
-// from the left.
-
-
-var getvint = function getvint(bytes, offset, removeLength, signed) {
- if (removeLength === void 0) {
- removeLength = true;
- }
-
- if (signed === void 0) {
- signed = false;
- }
-
- var length = getLength(bytes[offset]);
- var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
- // as they will be modified below to remove the dataSizeLen bits and we do not
- // want to modify the original data. normally we could just call slice on
- // uint8array but ie 11 does not support that...
-
- if (removeLength) {
- valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
- valueBytes[0] ^= LENGTH_TABLE[length - 1];
- }
-
- return {
- length: length,
- value: bytesToNumber(valueBytes, {
- signed: signed
- }),
- bytes: valueBytes
- };
-};
-
-var normalizePath = function normalizePath(path) {
- if (typeof path === 'string') {
- return path.match(/.{1,2}/g).map(function (p) {
- return normalizePath(p);
- });
- }
-
- if (typeof path === 'number') {
- return numberToBytes(path);
- }
-
- return path;
-};
-
-var normalizePaths = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath(p);
- });
-};
-
-var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
- if (offset >= bytes.length) {
- return bytes.length;
- }
-
- var innerid = getvint(bytes, offset, false);
-
- if (bytesMatch(id.bytes, innerid.bytes)) {
- return offset;
- }
-
- var dataHeader = getvint(bytes, offset + innerid.length);
- return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
-};
-/**
- * Notes on the EBLM format.
- *
- * EBLM uses "vints" tags. Every vint tag contains
- * two parts
- *
- * 1. The length from the first byte. You get this by
- * converting the byte to binary and counting the zeros
- * before a 1. Then you add 1 to that. Examples
- * 00011111 = length 4 because there are 3 zeros before a 1.
- * 00100000 = length 3 because there are 2 zeros before a 1.
- * 00000011 = length 7 because there are 6 zeros before a 1.
- *
- * 2. The bits used for length are removed from the first byte
- * Then all the bytes are merged into a value. NOTE: this
- * is not the case for id ebml tags as there id includes
- * length bits.
- *
- */
-
-
-export var findEbml = function findEbml(bytes, paths) {
- paths = normalizePaths(paths);
- bytes = toUint8(bytes);
- var results = [];
-
- if (!paths.length) {
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var id = getvint(bytes, i, false);
- var dataHeader = getvint(bytes, i + id.length);
- var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
-
- if (dataHeader.value === 0x7f) {
- dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
-
- if (dataHeader.value !== bytes.length) {
- dataHeader.value -= dataStart;
- }
- }
-
- var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
- var data = bytes.subarray(dataStart, dataEnd);
-
- if (bytesMatch(paths[0], id.bytes)) {
- if (paths.length === 1) {
- // this is the end of the paths and we've found the tag we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next tag inside of the data
- // of this one
- results = results.concat(findEbml(data, paths.slice(1)));
- }
- }
-
- var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
-
- i += totalLength;
- }
-
- return results;
-}; // see https://www.matroska.org/technical/basics.html#block-structure
-
-export var decodeBlock = function decodeBlock(block, type, timestampScale, clusterTimestamp) {
- var duration;
-
- if (type === 'group') {
- duration = findEbml(block, [EBML_TAGS.BlockDuration])[0];
-
- if (duration) {
- duration = bytesToNumber(duration);
- duration = 1 / timestampScale * duration * timestampScale / 1000;
- }
-
- block = findEbml(block, [EBML_TAGS.Block])[0];
- type = 'block'; // treat data as a block after this point
- }
-
- var dv = new DataView(block.buffer, block.byteOffset, block.byteLength);
- var trackNumber = getvint(block, 0);
- var timestamp = dv.getInt16(trackNumber.length, false);
- var flags = block[trackNumber.length + 2];
- var data = block.subarray(trackNumber.length + 3); // pts/dts in seconds
-
- var ptsdts = 1 / timestampScale * (clusterTimestamp + timestamp) * timestampScale / 1000; // return the frame
-
- var parsed = {
- duration: duration,
- trackNumber: trackNumber.value,
- keyframe: type === 'simple' && flags >> 7 === 1,
- invisible: (flags & 0x08) >> 3 === 1,
- lacing: (flags & 0x06) >> 1,
- discardable: type === 'simple' && (flags & 0x01) === 1,
- frames: [],
- pts: ptsdts,
- dts: ptsdts,
- timestamp: timestamp
- };
-
- if (!parsed.lacing) {
- parsed.frames.push(data);
- return parsed;
- }
-
- var numberOfFrames = data[0] + 1;
- var frameSizes = [];
- var offset = 1; // Fixed
-
- if (parsed.lacing === 2) {
- var sizeOfFrame = (data.length - offset) / numberOfFrames;
-
- for (var i = 0; i < numberOfFrames; i++) {
- frameSizes.push(sizeOfFrame);
- }
- } // xiph
-
-
- if (parsed.lacing === 1) {
- for (var _i = 0; _i < numberOfFrames - 1; _i++) {
- var size = 0;
-
- do {
- size += data[offset];
- offset++;
- } while (data[offset - 1] === 0xFF);
-
- frameSizes.push(size);
- }
- } // ebml
-
-
- if (parsed.lacing === 3) {
- // first vint is unsinged
- // after that vints are singed and
- // based on a compounding size
- var _size = 0;
-
- for (var _i2 = 0; _i2 < numberOfFrames - 1; _i2++) {
- var vint = _i2 === 0 ? getvint(data, offset) : getvint(data, offset, true, true);
- _size += vint.value;
- frameSizes.push(_size);
- offset += vint.length;
- }
- }
-
- frameSizes.forEach(function (size) {
- parsed.frames.push(data.subarray(offset, offset + size));
- offset += size;
- });
- return parsed;
-}; // VP9 Codec Feature Metadata (CodecPrivate)
-// https://www.webmproject.org/docs/container/
-
-var parseVp9Private = function parseVp9Private(bytes) {
- var i = 0;
- var params = {};
-
- while (i < bytes.length) {
- var id = bytes[i] & 0x7f;
- var len = bytes[i + 1];
- var val = void 0;
-
- if (len === 1) {
- val = bytes[i + 2];
- } else {
- val = bytes.subarray(i + 2, i + 2 + len);
- }
-
- if (id === 1) {
- params.profile = val;
- } else if (id === 2) {
- params.level = val;
- } else if (id === 3) {
- params.bitDepth = val;
- } else if (id === 4) {
- params.chromaSubsampling = val;
- } else {
- params[id] = val;
- }
-
- i += 2 + len;
- }
-
- return params;
-};
-
-export var parseTracks = function parseTracks(bytes) {
- bytes = toUint8(bytes);
- var decodedTracks = [];
- var tracks = findEbml(bytes, [EBML_TAGS.Segment, EBML_TAGS.Tracks, EBML_TAGS.Track]);
-
- if (!tracks.length) {
- tracks = findEbml(bytes, [EBML_TAGS.Tracks, EBML_TAGS.Track]);
- }
-
- if (!tracks.length) {
- tracks = findEbml(bytes, [EBML_TAGS.Track]);
- }
-
- if (!tracks.length) {
- return decodedTracks;
- }
-
- tracks.forEach(function (track) {
- var trackType = findEbml(track, EBML_TAGS.TrackType)[0];
-
- if (!trackType || !trackType.length) {
- return;
- } // 1 is video, 2 is audio, 17 is subtitle
- // other values are unimportant in this context
-
-
- if (trackType[0] === 1) {
- trackType = 'video';
- } else if (trackType[0] === 2) {
- trackType = 'audio';
- } else if (trackType[0] === 17) {
- trackType = 'subtitle';
- } else {
- return;
- } // todo parse language
-
-
- var decodedTrack = {
- rawCodec: bytesToString(findEbml(track, [EBML_TAGS.CodecID])[0]),
- type: trackType,
- codecPrivate: findEbml(track, [EBML_TAGS.CodecPrivate])[0],
- number: bytesToNumber(findEbml(track, [EBML_TAGS.TrackNumber])[0]),
- defaultDuration: bytesToNumber(findEbml(track, [EBML_TAGS.DefaultDuration])[0]),
- default: findEbml(track, [EBML_TAGS.FlagDefault])[0],
- rawData: track
- };
- var codec = '';
-
- if (/V_MPEG4\/ISO\/AVC/.test(decodedTrack.rawCodec)) {
- codec = "avc1." + getAvcCodec(decodedTrack.codecPrivate);
- } else if (/V_MPEGH\/ISO\/HEVC/.test(decodedTrack.rawCodec)) {
- codec = "hev1." + getHvcCodec(decodedTrack.codecPrivate);
- } else if (/V_MPEG4\/ISO\/ASP/.test(decodedTrack.rawCodec)) {
- if (decodedTrack.codecPrivate) {
- codec = 'mp4v.20.' + decodedTrack.codecPrivate[4].toString();
- } else {
- codec = 'mp4v.20.9';
- }
- } else if (/^V_THEORA/.test(decodedTrack.rawCodec)) {
- codec = 'theora';
- } else if (/^V_VP8/.test(decodedTrack.rawCodec)) {
- codec = 'vp8';
- } else if (/^V_VP9/.test(decodedTrack.rawCodec)) {
- if (decodedTrack.codecPrivate) {
- var _parseVp9Private = parseVp9Private(decodedTrack.codecPrivate),
- profile = _parseVp9Private.profile,
- level = _parseVp9Private.level,
- bitDepth = _parseVp9Private.bitDepth,
- chromaSubsampling = _parseVp9Private.chromaSubsampling;
-
- codec = 'vp09.';
- codec += padStart(profile, 2, '0') + ".";
- codec += padStart(level, 2, '0') + ".";
- codec += padStart(bitDepth, 2, '0') + ".";
- codec += "" + padStart(chromaSubsampling, 2, '0'); // Video -> Colour -> Ebml name
-
- var matrixCoefficients = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xB1]])[0] || [];
- var videoFullRangeFlag = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xB9]])[0] || [];
- var transferCharacteristics = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xBA]])[0] || [];
- var colourPrimaries = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xBB]])[0] || []; // if we find any optional codec parameter specify them all.
-
- if (matrixCoefficients.length || videoFullRangeFlag.length || transferCharacteristics.length || colourPrimaries.length) {
- codec += "." + padStart(colourPrimaries[0], 2, '0');
- codec += "." + padStart(transferCharacteristics[0], 2, '0');
- codec += "." + padStart(matrixCoefficients[0], 2, '0');
- codec += "." + padStart(videoFullRangeFlag[0], 2, '0');
- }
- } else {
- codec = 'vp9';
- }
- } else if (/^V_AV1/.test(decodedTrack.rawCodec)) {
- codec = "av01." + getAv1Codec(decodedTrack.codecPrivate);
- } else if (/A_ALAC/.test(decodedTrack.rawCodec)) {
- codec = 'alac';
- } else if (/A_MPEG\/L2/.test(decodedTrack.rawCodec)) {
- codec = 'mp2';
- } else if (/A_MPEG\/L3/.test(decodedTrack.rawCodec)) {
- codec = 'mp3';
- } else if (/^A_AAC/.test(decodedTrack.rawCodec)) {
- if (decodedTrack.codecPrivate) {
- codec = 'mp4a.40.' + (decodedTrack.codecPrivate[0] >>> 3).toString();
- } else {
- codec = 'mp4a.40.2';
- }
- } else if (/^A_AC3/.test(decodedTrack.rawCodec)) {
- codec = 'ac-3';
- } else if (/^A_PCM/.test(decodedTrack.rawCodec)) {
- codec = 'pcm';
- } else if (/^A_MS\/ACM/.test(decodedTrack.rawCodec)) {
- codec = 'speex';
- } else if (/^A_EAC3/.test(decodedTrack.rawCodec)) {
- codec = 'ec-3';
- } else if (/^A_VORBIS/.test(decodedTrack.rawCodec)) {
- codec = 'vorbis';
- } else if (/^A_FLAC/.test(decodedTrack.rawCodec)) {
- codec = 'flac';
- } else if (/^A_OPUS/.test(decodedTrack.rawCodec)) {
- codec = 'opus';
- }
-
- decodedTrack.codec = codec;
- decodedTracks.push(decodedTrack);
- });
- return decodedTracks.sort(function (a, b) {
- return a.number - b.number;
- });
-};
-export var parseData = function parseData(data, tracks) {
- var allBlocks = [];
- var segment = findEbml(data, [EBML_TAGS.Segment])[0];
- var timestampScale = findEbml(segment, [EBML_TAGS.SegmentInfo, EBML_TAGS.TimestampScale])[0]; // in nanoseconds, defaults to 1ms
-
- if (timestampScale && timestampScale.length) {
- timestampScale = bytesToNumber(timestampScale);
- } else {
- timestampScale = 1000000;
- }
-
- var clusters = findEbml(segment, [EBML_TAGS.Cluster]);
-
- if (!tracks) {
- tracks = parseTracks(segment);
- }
-
- clusters.forEach(function (cluster, ci) {
- var simpleBlocks = findEbml(cluster, [EBML_TAGS.SimpleBlock]).map(function (b) {
- return {
- type: 'simple',
- data: b
- };
- });
- var blockGroups = findEbml(cluster, [EBML_TAGS.BlockGroup]).map(function (b) {
- return {
- type: 'group',
- data: b
- };
- });
- var timestamp = findEbml(cluster, [EBML_TAGS.Timestamp])[0] || 0;
-
- if (timestamp && timestamp.length) {
- timestamp = bytesToNumber(timestamp);
- } // get all blocks then sort them into the correct order
-
-
- var blocks = simpleBlocks.concat(blockGroups).sort(function (a, b) {
- return a.data.byteOffset - b.data.byteOffset;
- });
- blocks.forEach(function (block, bi) {
- var decoded = decodeBlock(block.data, block.type, timestampScale, timestamp);
- allBlocks.push(decoded);
- });
- });
- return {
- tracks: tracks,
- blocks: allBlocks
- };
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/format-parser.js b/node_modules/@videojs/vhs-utils/es/format-parser.js
deleted file mode 100644
index 7560c01..0000000
--- a/node_modules/@videojs/vhs-utils/es/format-parser.js
+++ /dev/null
@@ -1,388 +0,0 @@
-import { bytesToString, toUint8, toHexString, bytesMatch } from './byte-helpers.js';
-import { parseTracks as parseEbmlTracks } from './ebml-helpers.js';
-import { parseTracks as parseMp4Tracks } from './mp4-helpers.js';
-import { findFourCC } from './riff-helpers.js';
-import { getPages } from './ogg-helpers.js';
-import { detectContainerForBytes } from './containers.js';
-import { findH264Nal, findH265Nal } from './nal-helpers.js';
-import { parseTs } from './m2ts-helpers.js';
-import { getAvcCodec, getHvcCodec } from './codec-helpers.js';
-import { getId3Offset } from './id3-helpers.js'; // https://docs.microsoft.com/en-us/windows/win32/medfound/audio-subtype-guids
-// https://tools.ietf.org/html/rfc2361
-
-var wFormatTagCodec = function wFormatTagCodec(wFormatTag) {
- wFormatTag = toUint8(wFormatTag);
-
- if (bytesMatch(wFormatTag, [0x00, 0x55])) {
- return 'mp3';
- } else if (bytesMatch(wFormatTag, [0x16, 0x00]) || bytesMatch(wFormatTag, [0x00, 0xFF])) {
- return 'aac';
- } else if (bytesMatch(wFormatTag, [0x70, 0x4f])) {
- return 'opus';
- } else if (bytesMatch(wFormatTag, [0x6C, 0x61])) {
- return 'alac';
- } else if (bytesMatch(wFormatTag, [0xF1, 0xAC])) {
- return 'flac';
- } else if (bytesMatch(wFormatTag, [0x20, 0x00])) {
- return 'ac-3';
- } else if (bytesMatch(wFormatTag, [0xFF, 0xFE])) {
- return 'ec-3';
- } else if (bytesMatch(wFormatTag, [0x00, 0x50])) {
- return 'mp2';
- } else if (bytesMatch(wFormatTag, [0x56, 0x6f])) {
- return 'vorbis';
- } else if (bytesMatch(wFormatTag, [0xA1, 0x09])) {
- return 'speex';
- }
-
- return '';
-};
-
-var formatMimetype = function formatMimetype(name, codecs) {
- var codecString = ['video', 'audio'].reduce(function (acc, type) {
- if (codecs[type]) {
- acc += (acc.length ? ',' : '') + codecs[type];
- }
-
- return acc;
- }, '');
- return (codecs.video ? 'video' : 'audio') + "/" + name + (codecString ? ";codecs=\"" + codecString + "\"" : '');
-};
-
-var parseCodecFrom = {
- mov: function mov(bytes) {
- // mov and mp4 both use a nearly identical box structure.
- var retval = parseCodecFrom.mp4(bytes);
-
- if (retval.mimetype) {
- retval.mimetype = retval.mimetype.replace('mp4', 'quicktime');
- }
-
- return retval;
- },
- mp4: function mp4(bytes) {
- bytes = toUint8(bytes);
- var codecs = {};
- var tracks = parseMp4Tracks(bytes);
-
- for (var i = 0; i < tracks.length; i++) {
- var track = tracks[i];
-
- if (track.type === 'audio' && !codecs.audio) {
- codecs.audio = track.codec;
- }
-
- if (track.type === 'video' && !codecs.video) {
- codecs.video = track.codec;
- }
- }
-
- return {
- codecs: codecs,
- mimetype: formatMimetype('mp4', codecs)
- };
- },
- '3gp': function gp(bytes) {
- return {
- codecs: {},
- mimetype: 'video/3gpp'
- };
- },
- ogg: function ogg(bytes) {
- var pages = getPages(bytes, 0, 4);
- var codecs = {};
- pages.forEach(function (page) {
- if (bytesMatch(page, [0x4F, 0x70, 0x75, 0x73], {
- offset: 28
- })) {
- codecs.audio = 'opus';
- } else if (bytesMatch(page, [0x56, 0x50, 0x38, 0x30], {
- offset: 29
- })) {
- codecs.video = 'vp8';
- } else if (bytesMatch(page, [0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {
- offset: 29
- })) {
- codecs.video = 'theora';
- } else if (bytesMatch(page, [0x46, 0x4C, 0x41, 0x43], {
- offset: 29
- })) {
- codecs.audio = 'flac';
- } else if (bytesMatch(page, [0x53, 0x70, 0x65, 0x65, 0x78], {
- offset: 28
- })) {
- codecs.audio = 'speex';
- } else if (bytesMatch(page, [0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {
- offset: 29
- })) {
- codecs.audio = 'vorbis';
- }
- });
- return {
- codecs: codecs,
- mimetype: formatMimetype('ogg', codecs)
- };
- },
- wav: function wav(bytes) {
- var format = findFourCC(bytes, ['WAVE', 'fmt'])[0];
- var wFormatTag = Array.prototype.slice.call(format, 0, 2).reverse();
- var mimetype = 'audio/vnd.wave';
- var codecs = {
- audio: wFormatTagCodec(wFormatTag)
- };
- var codecString = wFormatTag.reduce(function (acc, v) {
- if (v) {
- acc += toHexString(v);
- }
-
- return acc;
- }, '');
-
- if (codecString) {
- mimetype += ";codec=" + codecString;
- }
-
- if (codecString && !codecs.audio) {
- codecs.audio = codecString;
- }
-
- return {
- codecs: codecs,
- mimetype: mimetype
- };
- },
- avi: function avi(bytes) {
- var movi = findFourCC(bytes, ['AVI', 'movi'])[0];
- var strls = findFourCC(bytes, ['AVI', 'hdrl', 'strl']);
- var codecs = {};
- strls.forEach(function (strl) {
- var strh = findFourCC(strl, ['strh'])[0];
- var strf = findFourCC(strl, ['strf'])[0]; // now parse AVIStreamHeader to get codec and type:
- // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/api/avifmt/ns-avifmt-avistreamheader
-
- var type = bytesToString(strh.subarray(0, 4));
- var codec;
- var codecType;
-
- if (type === 'vids') {
- // https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader
- var handler = bytesToString(strh.subarray(4, 8));
- var compression = bytesToString(strf.subarray(16, 20)); // look for 00dc (compressed video fourcc code) or 00db (uncompressed video fourcc code)
-
- var videoData = findFourCC(movi, ['00dc'])[0] || findFourCC(movi, ['00db'][0]);
-
- if (handler === 'H264' || compression === 'H264') {
- if (videoData && videoData.length) {
- codec = parseCodecFrom.h264(videoData).codecs.video;
- } else {
- codec = 'avc1';
- }
- } else if (handler === 'HEVC' || compression === 'HEVC') {
- if (videoData && videoData.length) {
- codec = parseCodecFrom.h265(videoData).codecs.video;
- } else {
- codec = 'hev1';
- }
- } else if (handler === 'FMP4' || compression === 'FMP4') {
- if (movi.length) {
- codec = 'mp4v.20.' + movi[12].toString();
- } else {
- codec = 'mp4v.20';
- }
- } else if (handler === 'VP80' || compression === 'VP80') {
- codec = 'vp8';
- } else if (handler === 'VP90' || compression === 'VP90') {
- codec = 'vp9';
- } else if (handler === 'AV01' || compression === 'AV01') {
- codec = 'av01';
- } else if (handler === 'theo' || compression === 'theora') {
- codec = 'theora';
- } else {
- if (videoData && videoData.length) {
- var result = detectContainerForBytes(videoData);
-
- if (result === 'h264') {
- codec = parseCodecFrom.h264(movi).codecs.video;
- }
-
- if (result === 'h265') {
- codec = parseCodecFrom.h265(movi).codecs.video;
- }
- }
-
- if (!codec) {
- codec = handler || compression;
- }
- }
-
- codecType = 'video';
- } else if (type === 'auds') {
- codecType = 'audio'; // look for 00wb (audio data fourcc)
- // const audioData = findFourCC(movi, ['01wb']);
-
- var wFormatTag = Array.prototype.slice.call(strf, 0, 2).reverse();
- codecs.audio = wFormatTagCodec(wFormatTag);
- } else {
- return;
- }
-
- if (codec) {
- codecs[codecType] = codec;
- }
- });
- return {
- codecs: codecs,
- mimetype: formatMimetype('avi', codecs)
- };
- },
- ts: function ts(bytes) {
- var result = parseTs(bytes, 2);
- var codecs = {};
- Object.keys(result.streams).forEach(function (esPid) {
- var stream = result.streams[esPid];
-
- if (stream.codec === 'avc1' && stream.packets.length) {
- stream.codec = parseCodecFrom.h264(stream.packets[0]).codecs.video;
- } else if (stream.codec === 'hev1' && stream.packets.length) {
- stream.codec = parseCodecFrom.h265(stream.packets[0]).codecs.video;
- }
-
- codecs[stream.type] = stream.codec;
- });
- return {
- codecs: codecs,
- mimetype: formatMimetype('mp2t', codecs)
- };
- },
- webm: function webm(bytes) {
- // mkv and webm both use ebml to store code info
- var retval = parseCodecFrom.mkv(bytes);
-
- if (retval.mimetype) {
- retval.mimetype = retval.mimetype.replace('x-matroska', 'webm');
- }
-
- return retval;
- },
- mkv: function mkv(bytes) {
- var codecs = {};
- var tracks = parseEbmlTracks(bytes);
-
- for (var i = 0; i < tracks.length; i++) {
- var track = tracks[i];
-
- if (track.type === 'audio' && !codecs.audio) {
- codecs.audio = track.codec;
- }
-
- if (track.type === 'video' && !codecs.video) {
- codecs.video = track.codec;
- }
- }
-
- return {
- codecs: codecs,
- mimetype: formatMimetype('x-matroska', codecs)
- };
- },
- aac: function aac(bytes) {
- return {
- codecs: {
- audio: 'aac'
- },
- mimetype: 'audio/aac'
- };
- },
- ac3: function ac3(bytes) {
- // past id3 and syncword
- var offset = getId3Offset(bytes) + 2; // default to ac-3
-
- var codec = 'ac-3';
-
- if (bytesMatch(bytes, [0xB8, 0xE0], {
- offset: offset
- })) {
- codec = 'ac-3'; // 0x01, 0x7F
- } else if (bytesMatch(bytes, [0x01, 0x7f], {
- offset: offset
- })) {
- codec = 'ec-3';
- }
-
- return {
- codecs: {
- audio: codec
- },
- mimetype: 'audio/vnd.dolby.dd-raw'
- };
- },
- mp3: function mp3(bytes) {
- return {
- codecs: {
- audio: 'mp3'
- },
- mimetype: 'audio/mpeg'
- };
- },
- flac: function flac(bytes) {
- return {
- codecs: {
- audio: 'flac'
- },
- mimetype: 'audio/flac'
- };
- },
- 'h264': function h264(bytes) {
- // find seq_parameter_set_rbsp to get encoding settings for codec
- var nal = findH264Nal(bytes, 7, 3);
- var retval = {
- codecs: {
- video: 'avc1'
- },
- mimetype: 'video/h264'
- };
-
- if (nal.length) {
- retval.codecs.video += "." + getAvcCodec(nal);
- }
-
- return retval;
- },
- 'h265': function h265(bytes) {
- var retval = {
- codecs: {
- video: 'hev1'
- },
- mimetype: 'video/h265'
- }; // find video_parameter_set_rbsp or seq_parameter_set_rbsp
- // to get encoding settings for codec
-
- var nal = findH265Nal(bytes, [32, 33], 3);
-
- if (nal.length) {
- var type = nal[0] >> 1 & 0x3F; // profile_tier_level starts at byte 5 for video_parameter_set_rbsp
- // byte 2 for seq_parameter_set_rbsp
-
- retval.codecs.video += "." + getHvcCodec(nal.subarray(type === 32 ? 5 : 2));
- }
-
- return retval;
- }
-};
-export var parseFormatForBytes = function parseFormatForBytes(bytes) {
- bytes = toUint8(bytes);
- var result = {
- codecs: {},
- container: detectContainerForBytes(bytes),
- mimetype: ''
- };
- var parseCodecFn = parseCodecFrom[result.container];
-
- if (parseCodecFn) {
- var parsed = parseCodecFn ? parseCodecFn(bytes) : {};
- result.codecs = parsed.codecs || {};
- result.mimetype = parsed.mimetype || '';
- }
-
- return result;
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/id3-helpers.js b/node_modules/@videojs/vhs-utils/es/id3-helpers.js
deleted file mode 100644
index 36904d8..0000000
--- a/node_modules/@videojs/vhs-utils/es/id3-helpers.js
+++ /dev/null
@@ -1,37 +0,0 @@
-import { toUint8, bytesMatch } from './byte-helpers.js';
-var ID3 = toUint8([0x49, 0x44, 0x33]);
-export var getId3Size = function getId3Size(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = toUint8(bytes);
- var flags = bytes[offset + 5];
- var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
- var footerPresent = (flags & 16) >> 4;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
-};
-export var getId3Offset = function getId3Offset(bytes, offset) {
- if (offset === void 0) {
- offset = 0;
- }
-
- bytes = toUint8(bytes);
-
- if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
- offset: offset
- })) {
- return offset;
- }
-
- offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
- // have multiple ID3 tag sections even though
- // they should not.
-
- return getId3Offset(bytes, offset);
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/index.js b/node_modules/@videojs/vhs-utils/es/index.js
deleted file mode 100644
index adbae4b..0000000
--- a/node_modules/@videojs/vhs-utils/es/index.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import * as codecs from './codecs';
-import * as byteHelpers from './byte-helpers.js';
-import * as containers from './containers.js';
-import decodeB64ToUint8Array from './decode-b64-to-uint8-array.js';
-import * as mediaGroups from './media-groups.js';
-import resolveUrl from './resolve-url.js';
-import Stream from './stream.js';
-export default {
- codecs: codecs,
- byteHelpers: byteHelpers,
- containers: containers,
- decodeB64ToUint8Array: decodeB64ToUint8Array,
- mediaGroups: mediaGroups,
- resolveUrl: resolveUrl,
- Stream: Stream
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/m2ts-helpers.js b/node_modules/@videojs/vhs-utils/es/m2ts-helpers.js
deleted file mode 100644
index aa4c1a5..0000000
--- a/node_modules/@videojs/vhs-utils/es/m2ts-helpers.js
+++ /dev/null
@@ -1,105 +0,0 @@
-import { bytesMatch, toUint8 } from './byte-helpers.js';
-var SYNC_BYTE = 0x47;
-export var parseTs = function parseTs(bytes, maxPes) {
- if (maxPes === void 0) {
- maxPes = Infinity;
- }
-
- bytes = toUint8(bytes);
- var startIndex = 0;
- var endIndex = 188;
- var pmt = {};
- var pesCount = 0;
-
- while (endIndex < bytes.byteLength && pesCount < maxPes) {
- if (bytes[startIndex] !== SYNC_BYTE && bytes[endIndex] !== SYNC_BYTE) {
- endIndex += 1;
- startIndex += 1;
- continue;
- }
-
- var packet = bytes.subarray(startIndex, endIndex);
- var pid = (packet[1] & 0x1f) << 8 | packet[2];
- var hasPusi = !!(packet[1] & 0x40);
- var hasAdaptationHeader = (packet[3] & 0x30) >>> 4 > 0x01;
- var payloadOffset = 4 + (hasAdaptationHeader ? packet[4] + 1 : 0);
-
- if (hasPusi) {
- payloadOffset += packet[payloadOffset] + 1;
- }
-
- if (pid === 0 && !pmt.pid) {
- pmt.pid = (packet[payloadOffset + 10] & 0x1f) << 8 | packet[payloadOffset + 11];
- } else if (pmt.pid && pid === pmt.pid && !pmt.streams) {
- var isNotForward = packet[payloadOffset + 5] & 0x01; // ignore forward pmt delarations
-
- if (!isNotForward) {
- continue;
- }
-
- pmt.streams = {};
- var sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
- var tableEnd = 3 + sectionLength - 4;
- var programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11];
- var offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- // add an entry that maps the elementary_pid to the stream_type
- var i = payloadOffset + offset;
- var type = packet[i];
- var esPid = (packet[i + 1] & 0x1F) << 8 | packet[i + 2];
- var esLength = (packet[i + 3] & 0x0f) << 8 | packet[i + 4];
- var esInfo = packet.subarray(i + 5, i + 5 + esLength);
- var stream = pmt.streams[esPid] = {
- esInfo: esInfo,
- typeNumber: type,
- packets: [],
- type: '',
- codec: ''
- };
-
- if (type === 0x06 && bytesMatch(esInfo, [0x4F, 0x70, 0x75, 0x73], {
- offset: 2
- })) {
- stream.type = 'audio';
- stream.codec = 'opus';
- } else if (type === 0x1B || type === 0x20) {
- stream.type = 'video';
- stream.codec = 'avc1';
- } else if (type === 0x24) {
- stream.type = 'video';
- stream.codec = 'hev1';
- } else if (type === 0x10) {
- stream.type = 'video';
- stream.codec = 'mp4v.20';
- } else if (type === 0x0F) {
- stream.type = 'audio';
- stream.codec = 'aac';
- } else if (type === 0x81) {
- stream.type = 'audio';
- stream.codec = 'ac-3';
- } else if (type === 0x87) {
- stream.type = 'audio';
- stream.codec = 'ec-3';
- } else if (type === 0x03 || type === 0x04) {
- stream.type = 'audio';
- stream.codec = 'mp3';
- }
-
- offset += esLength + 5;
- }
- } else if (pmt.pid && pmt.streams) {
- pmt.streams[pid].packets.push(packet.subarray(payloadOffset));
- pesCount++;
- }
-
- startIndex += 188;
- endIndex += 188;
- }
-
- if (!pmt.streams) {
- pmt.streams = {};
- }
-
- return pmt;
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/media-groups.js b/node_modules/@videojs/vhs-utils/es/media-groups.js
deleted file mode 100644
index 87de53e..0000000
--- a/node_modules/@videojs/vhs-utils/es/media-groups.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Loops through all supported media groups in master and calls the provided
- * callback for each group
- *
- * @param {Object} master
- * The parsed master manifest object
- * @param {string[]} groups
- * The media groups to call the callback for
- * @param {Function} callback
- * Callback to call for each media group
- */
-export var forEachMediaGroup = function forEachMediaGroup(master, groups, callback) {
- groups.forEach(function (mediaType) {
- for (var groupKey in master.mediaGroups[mediaType]) {
- for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
- var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
- callback(mediaProperties, mediaType, groupKey, labelKey);
- }
- }
- });
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/media-types.js b/node_modules/@videojs/vhs-utils/es/media-types.js
deleted file mode 100644
index e4f86f1..0000000
--- a/node_modules/@videojs/vhs-utils/es/media-types.js
+++ /dev/null
@@ -1,36 +0,0 @@
-var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
-var DASH_REGEX = /^application\/dash\+xml/i;
-/**
- * Returns a string that describes the type of source based on a video source object's
- * media type.
- *
- * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
- *
- * @param {string} type
- * Video source object media type
- * @return {('hls'|'dash'|'vhs-json'|null)}
- * VHS source type string
- */
-
-export var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
- if (MPEGURL_REGEX.test(type)) {
- return 'hls';
- }
-
- if (DASH_REGEX.test(type)) {
- return 'dash';
- } // Denotes the special case of a manifest object passed to http-streaming instead of a
- // source URL.
- //
- // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
- //
- // In this case, vnd stands for vendor, video.js for the organization, VHS for this
- // project, and the +json suffix identifies the structure of the media type.
-
-
- if (type === 'application/vnd.videojs.vhs+json') {
- return 'vhs-json';
- }
-
- return null;
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/mp4-helpers.js b/node_modules/@videojs/vhs-utils/es/mp4-helpers.js
deleted file mode 100644
index ae84aa4..0000000
--- a/node_modules/@videojs/vhs-utils/es/mp4-helpers.js
+++ /dev/null
@@ -1,553 +0,0 @@
-import { stringToBytes, toUint8, bytesMatch, bytesToString, toHexString, padStart, bytesToNumber } from './byte-helpers.js';
-import { getAvcCodec, getHvcCodec, getAv1Codec } from './codec-helpers.js';
-import { parseOpusHead } from './opus-helpers.js';
-
-var normalizePath = function normalizePath(path) {
- if (typeof path === 'string') {
- return stringToBytes(path);
- }
-
- if (typeof path === 'number') {
- return path;
- }
-
- return path;
-};
-
-var normalizePaths = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath(p);
- });
-};
-
-var DESCRIPTORS;
-export var parseDescriptors = function parseDescriptors(bytes) {
- bytes = toUint8(bytes);
- var results = [];
- var i = 0;
-
- while (bytes.length > i) {
- var tag = bytes[i];
- var size = 0;
- var headerSize = 0; // tag
-
- headerSize++;
- var byte = bytes[headerSize]; // first byte
-
- headerSize++;
-
- while (byte & 0x80) {
- size = (byte & 0x7F) << 7;
- byte = bytes[headerSize];
- headerSize++;
- }
-
- size += byte & 0x7F;
-
- for (var z = 0; z < DESCRIPTORS.length; z++) {
- var _DESCRIPTORS$z = DESCRIPTORS[z],
- id = _DESCRIPTORS$z.id,
- parser = _DESCRIPTORS$z.parser;
-
- if (tag === id) {
- results.push(parser(bytes.subarray(headerSize, headerSize + size)));
- break;
- }
- }
-
- i += size + headerSize;
- }
-
- return results;
-};
-DESCRIPTORS = [{
- id: 0x03,
- parser: function parser(bytes) {
- var desc = {
- tag: 0x03,
- id: bytes[0] << 8 | bytes[1],
- flags: bytes[2],
- size: 3,
- dependsOnEsId: 0,
- ocrEsId: 0,
- descriptors: [],
- url: ''
- }; // depends on es id
-
- if (desc.flags & 0x80) {
- desc.dependsOnEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];
- desc.size += 2;
- } // url
-
-
- if (desc.flags & 0x40) {
- var len = bytes[desc.size];
- desc.url = bytesToString(bytes.subarray(desc.size + 1, desc.size + 1 + len));
- desc.size += len;
- } // ocr es id
-
-
- if (desc.flags & 0x20) {
- desc.ocrEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];
- desc.size += 2;
- }
-
- desc.descriptors = parseDescriptors(bytes.subarray(desc.size)) || [];
- return desc;
- }
-}, {
- id: 0x04,
- parser: function parser(bytes) {
- // DecoderConfigDescriptor
- var desc = {
- tag: 0x04,
- oti: bytes[0],
- streamType: bytes[1],
- bufferSize: bytes[2] << 16 | bytes[3] << 8 | bytes[4],
- maxBitrate: bytes[5] << 24 | bytes[6] << 16 | bytes[7] << 8 | bytes[8],
- avgBitrate: bytes[9] << 24 | bytes[10] << 16 | bytes[11] << 8 | bytes[12],
- descriptors: parseDescriptors(bytes.subarray(13))
- };
- return desc;
- }
-}, {
- id: 0x05,
- parser: function parser(bytes) {
- // DecoderSpecificInfo
- return {
- tag: 0x05,
- bytes: bytes
- };
- }
-}, {
- id: 0x06,
- parser: function parser(bytes) {
- // SLConfigDescriptor
- return {
- tag: 0x06,
- bytes: bytes
- };
- }
-}];
-/**
- * find any number of boxes by name given a path to it in an iso bmff
- * such as mp4.
- *
- * @param {TypedArray} bytes
- * bytes for the iso bmff to search for boxes in
- *
- * @param {Uint8Array[]|string[]|string|Uint8Array} name
- * An array of paths or a single path representing the name
- * of boxes to search through in bytes. Paths may be
- * uint8 (character codes) or strings.
- *
- * @param {boolean} [complete=false]
- * Should we search only for complete boxes on the final path.
- * This is very useful when you do not want to get back partial boxes
- * in the case of streaming files.
- *
- * @return {Uint8Array[]}
- * An array of the end paths that we found.
- */
-
-export var findBox = function findBox(bytes, paths, complete) {
- if (complete === void 0) {
- complete = false;
- }
-
- paths = normalizePaths(paths);
- bytes = toUint8(bytes);
- var results = [];
-
- if (!paths.length) {
- // short-circuit the search for empty paths
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
- var type = bytes.subarray(i + 4, i + 8); // invalid box format.
-
- if (size === 0) {
- break;
- }
-
- var end = i + size;
-
- if (end > bytes.length) {
- // this box is bigger than the number of bytes we have
- // and complete is set, we cannot find any more boxes.
- if (complete) {
- break;
- }
-
- end = bytes.length;
- }
-
- var data = bytes.subarray(i + 8, end);
-
- if (bytesMatch(type, paths[0])) {
- if (paths.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next box along the path
- results.push.apply(results, findBox(data, paths.slice(1), complete));
- }
- }
-
- i = end;
- } // we've finished searching all of bytes
-
-
- return results;
-};
-/**
- * Search for a single matching box by name in an iso bmff format like
- * mp4. This function is useful for finding codec boxes which
- * can be placed arbitrarily in sample descriptions depending
- * on the version of the file or file type.
- *
- * @param {TypedArray} bytes
- * bytes for the iso bmff to search for boxes in
- *
- * @param {string|Uint8Array} name
- * The name of the box to find.
- *
- * @return {Uint8Array[]}
- * a subarray of bytes representing the name boxed we found.
- */
-
-export var findNamedBox = function findNamedBox(bytes, name) {
- name = normalizePath(name);
-
- if (!name.length) {
- // short-circuit the search for empty paths
- return bytes.subarray(bytes.length);
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- if (bytesMatch(bytes.subarray(i, i + name.length), name)) {
- var size = (bytes[i - 4] << 24 | bytes[i - 3] << 16 | bytes[i - 2] << 8 | bytes[i - 1]) >>> 0;
- var end = size > 1 ? i + size : bytes.byteLength;
- return bytes.subarray(i + 4, end);
- }
-
- i++;
- } // we've finished searching all of bytes
-
-
- return bytes.subarray(bytes.length);
-};
-
-var parseSamples = function parseSamples(data, entrySize, parseEntry) {
- if (entrySize === void 0) {
- entrySize = 4;
- }
-
- if (parseEntry === void 0) {
- parseEntry = function parseEntry(d) {
- return bytesToNumber(d);
- };
- }
-
- var entries = [];
-
- if (!data || !data.length) {
- return entries;
- }
-
- var entryCount = bytesToNumber(data.subarray(4, 8));
-
- for (var i = 8; entryCount; i += entrySize, entryCount--) {
- entries.push(parseEntry(data.subarray(i, i + entrySize)));
- }
-
- return entries;
-};
-
-export var buildFrameTable = function buildFrameTable(stbl, timescale) {
- var keySamples = parseSamples(findBox(stbl, ['stss'])[0]);
- var chunkOffsets = parseSamples(findBox(stbl, ['stco'])[0]);
- var timeToSamples = parseSamples(findBox(stbl, ['stts'])[0], 8, function (entry) {
- return {
- sampleCount: bytesToNumber(entry.subarray(0, 4)),
- sampleDelta: bytesToNumber(entry.subarray(4, 8))
- };
- });
- var samplesToChunks = parseSamples(findBox(stbl, ['stsc'])[0], 12, function (entry) {
- return {
- firstChunk: bytesToNumber(entry.subarray(0, 4)),
- samplesPerChunk: bytesToNumber(entry.subarray(4, 8)),
- sampleDescriptionIndex: bytesToNumber(entry.subarray(8, 12))
- };
- });
- var stsz = findBox(stbl, ['stsz'])[0]; // stsz starts with a 4 byte sampleSize which we don't need
-
- var sampleSizes = parseSamples(stsz && stsz.length && stsz.subarray(4) || null);
- var frames = [];
-
- for (var chunkIndex = 0; chunkIndex < chunkOffsets.length; chunkIndex++) {
- var samplesInChunk = void 0;
-
- for (var i = 0; i < samplesToChunks.length; i++) {
- var sampleToChunk = samplesToChunks[i];
- var isThisOne = chunkIndex + 1 >= sampleToChunk.firstChunk && (i + 1 >= samplesToChunks.length || chunkIndex + 1 < samplesToChunks[i + 1].firstChunk);
-
- if (isThisOne) {
- samplesInChunk = sampleToChunk.samplesPerChunk;
- break;
- }
- }
-
- var chunkOffset = chunkOffsets[chunkIndex];
-
- for (var _i = 0; _i < samplesInChunk; _i++) {
- var frameEnd = sampleSizes[frames.length]; // if we don't have key samples every frame is a keyframe
-
- var keyframe = !keySamples.length;
-
- if (keySamples.length && keySamples.indexOf(frames.length + 1) !== -1) {
- keyframe = true;
- }
-
- var frame = {
- keyframe: keyframe,
- start: chunkOffset,
- end: chunkOffset + frameEnd
- };
-
- for (var k = 0; k < timeToSamples.length; k++) {
- var _timeToSamples$k = timeToSamples[k],
- sampleCount = _timeToSamples$k.sampleCount,
- sampleDelta = _timeToSamples$k.sampleDelta;
-
- if (frames.length <= sampleCount) {
- // ms to ns
- var lastTimestamp = frames.length ? frames[frames.length - 1].timestamp : 0;
- frame.timestamp = lastTimestamp + sampleDelta / timescale * 1000;
- frame.duration = sampleDelta;
- break;
- }
- }
-
- frames.push(frame);
- chunkOffset += frameEnd;
- }
- }
-
- return frames;
-};
-export var addSampleDescription = function addSampleDescription(track, bytes) {
- var codec = bytesToString(bytes.subarray(0, 4));
-
- if (track.type === 'video') {
- track.info = track.info || {};
- track.info.width = bytes[28] << 8 | bytes[29];
- track.info.height = bytes[30] << 8 | bytes[31];
- } else if (track.type === 'audio') {
- track.info = track.info || {};
- track.info.channels = bytes[20] << 8 | bytes[21];
- track.info.bitDepth = bytes[22] << 8 | bytes[23];
- track.info.sampleRate = bytes[28] << 8 | bytes[29];
- }
-
- if (codec === 'avc1') {
- var avcC = findNamedBox(bytes, 'avcC'); // AVCDecoderConfigurationRecord
-
- codec += "." + getAvcCodec(avcC);
- track.info.avcC = avcC; // TODO: do we need to parse all this?
-
- /* {
- configurationVersion: avcC[0],
- profile: avcC[1],
- profileCompatibility: avcC[2],
- level: avcC[3],
- lengthSizeMinusOne: avcC[4] & 0x3
- };
- let spsNalUnitCount = avcC[5] & 0x1F;
- const spsNalUnits = track.info.avc.spsNalUnits = [];
- // past spsNalUnitCount
- let offset = 6;
- while (spsNalUnitCount--) {
- const nalLen = avcC[offset] << 8 | avcC[offset + 1];
- spsNalUnits.push(avcC.subarray(offset + 2, offset + 2 + nalLen));
- offset += nalLen + 2;
- }
- let ppsNalUnitCount = avcC[offset];
- const ppsNalUnits = track.info.avc.ppsNalUnits = [];
- // past ppsNalUnitCount
- offset += 1;
- while (ppsNalUnitCount--) {
- const nalLen = avcC[offset] << 8 | avcC[offset + 1];
- ppsNalUnits.push(avcC.subarray(offset + 2, offset + 2 + nalLen));
- offset += nalLen + 2;
- }*/
- // HEVCDecoderConfigurationRecord
- } else if (codec === 'hvc1' || codec === 'hev1') {
- codec += "." + getHvcCodec(findNamedBox(bytes, 'hvcC'));
- } else if (codec === 'mp4a' || codec === 'mp4v') {
- var esds = findNamedBox(bytes, 'esds');
- var esDescriptor = parseDescriptors(esds.subarray(4))[0];
- var decoderConfig = esDescriptor && esDescriptor.descriptors.filter(function (_ref) {
- var tag = _ref.tag;
- return tag === 0x04;
- })[0];
-
- if (decoderConfig) {
- // most codecs do not have a further '.'
- // such as 0xa5 for ac-3 and 0xa6 for e-ac-3
- codec += '.' + toHexString(decoderConfig.oti);
-
- if (decoderConfig.oti === 0x40) {
- codec += '.' + (decoderConfig.descriptors[0].bytes[0] >> 3).toString();
- } else if (decoderConfig.oti === 0x20) {
- codec += '.' + decoderConfig.descriptors[0].bytes[4].toString();
- } else if (decoderConfig.oti === 0xdd) {
- codec = 'vorbis';
- }
- } else if (track.type === 'audio') {
- codec += '.40.2';
- } else {
- codec += '.20.9';
- }
- } else if (codec === 'av01') {
- // AV1DecoderConfigurationRecord
- codec += "." + getAv1Codec(findNamedBox(bytes, 'av1C'));
- } else if (codec === 'vp09') {
- // VPCodecConfigurationRecord
- var vpcC = findNamedBox(bytes, 'vpcC'); // https://www.webmproject.org/vp9/mp4/
-
- var profile = vpcC[0];
- var level = vpcC[1];
- var bitDepth = vpcC[2] >> 4;
- var chromaSubsampling = (vpcC[2] & 0x0F) >> 1;
- var videoFullRangeFlag = (vpcC[2] & 0x0F) >> 3;
- var colourPrimaries = vpcC[3];
- var transferCharacteristics = vpcC[4];
- var matrixCoefficients = vpcC[5];
- codec += "." + padStart(profile, 2, '0');
- codec += "." + padStart(level, 2, '0');
- codec += "." + padStart(bitDepth, 2, '0');
- codec += "." + padStart(chromaSubsampling, 2, '0');
- codec += "." + padStart(colourPrimaries, 2, '0');
- codec += "." + padStart(transferCharacteristics, 2, '0');
- codec += "." + padStart(matrixCoefficients, 2, '0');
- codec += "." + padStart(videoFullRangeFlag, 2, '0');
- } else if (codec === 'theo') {
- codec = 'theora';
- } else if (codec === 'spex') {
- codec = 'speex';
- } else if (codec === '.mp3') {
- codec = 'mp4a.40.34';
- } else if (codec === 'msVo') {
- codec = 'vorbis';
- } else if (codec === 'Opus') {
- codec = 'opus';
- var dOps = findNamedBox(bytes, 'dOps');
- track.info.opus = parseOpusHead(dOps); // TODO: should this go into the webm code??
- // Firefox requires a codecDelay for opus playback
- // see https://bugzilla.mozilla.org/show_bug.cgi?id=1276238
-
- track.info.codecDelay = 6500000;
- } else {
- codec = codec.toLowerCase();
- }
- /* eslint-enable */
- // flac, ac-3, ec-3, opus
-
-
- track.codec = codec;
-};
-export var parseTracks = function parseTracks(bytes, frameTable) {
- if (frameTable === void 0) {
- frameTable = true;
- }
-
- bytes = toUint8(bytes);
- var traks = findBox(bytes, ['moov', 'trak'], true);
- var tracks = [];
- traks.forEach(function (trak) {
- var track = {
- bytes: trak
- };
- var mdia = findBox(trak, ['mdia'])[0];
- var hdlr = findBox(mdia, ['hdlr'])[0];
- var trakType = bytesToString(hdlr.subarray(8, 12));
-
- if (trakType === 'soun') {
- track.type = 'audio';
- } else if (trakType === 'vide') {
- track.type = 'video';
- } else {
- track.type = trakType;
- }
-
- var tkhd = findBox(trak, ['tkhd'])[0];
-
- if (tkhd) {
- var view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- var tkhdVersion = view.getUint8(0);
- track.number = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
- }
-
- var mdhd = findBox(mdia, ['mdhd'])[0];
-
- if (mdhd) {
- // mdhd is a FullBox, meaning it will have its own version as the first byte
- var version = mdhd[0];
- var index = version === 0 ? 12 : 20;
- track.timescale = (mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]) >>> 0;
- }
-
- var stbl = findBox(mdia, ['minf', 'stbl'])[0];
- var stsd = findBox(stbl, ['stsd'])[0];
- var descriptionCount = bytesToNumber(stsd.subarray(4, 8));
- var offset = 8; // add codec and codec info
-
- while (descriptionCount--) {
- var len = bytesToNumber(stsd.subarray(offset, offset + 4));
- var sampleDescriptor = stsd.subarray(offset + 4, offset + 4 + len);
- addSampleDescription(track, sampleDescriptor);
- offset += 4 + len;
- }
-
- if (frameTable) {
- track.frameTable = buildFrameTable(stbl, track.timescale);
- } // codec has no sub parameters
-
-
- tracks.push(track);
- });
- return tracks;
-};
-export var parseMediaInfo = function parseMediaInfo(bytes) {
- var mvhd = findBox(bytes, ['moov', 'mvhd'], true)[0];
-
- if (!mvhd || !mvhd.length) {
- return;
- }
-
- var info = {}; // ms to ns
- // mvhd v1 has 8 byte duration and other fields too
-
- if (mvhd[0] === 1) {
- info.timestampScale = bytesToNumber(mvhd.subarray(20, 24));
- info.duration = bytesToNumber(mvhd.subarray(24, 32));
- } else {
- info.timestampScale = bytesToNumber(mvhd.subarray(12, 16));
- info.duration = bytesToNumber(mvhd.subarray(16, 20));
- }
-
- info.bytes = mvhd;
- return info;
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/nal-helpers.js b/node_modules/@videojs/vhs-utils/es/nal-helpers.js
deleted file mode 100644
index 29d5a67..0000000
--- a/node_modules/@videojs/vhs-utils/es/nal-helpers.js
+++ /dev/null
@@ -1,112 +0,0 @@
-import { bytesMatch, toUint8 } from './byte-helpers.js';
-export var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
-export var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
-export var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
-/**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- *
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-
-export var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
- var positions = [];
- var i = 1; // Find all `Emulation Prevention Bytes`
-
- while (i < bytes.length - 2) {
- if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
- positions.push(i + 2);
- i++;
- }
-
- i++;
- } // If no Emulation Prevention Bytes were found just return the original
- // array
-
-
- if (positions.length === 0) {
- return bytes;
- } // Create a new array to hold the NAL unit data
-
-
- var newLength = bytes.length - positions.length;
- var newData = new Uint8Array(newLength);
- var sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === positions[0]) {
- // Skip this byte
- sourceIndex++; // Remove this position index
-
- positions.shift();
- }
-
- newData[i] = bytes[sourceIndex];
- }
-
- return newData;
-};
-export var findNal = function findNal(bytes, dataType, types, nalLimit) {
- if (nalLimit === void 0) {
- nalLimit = Infinity;
- }
-
- bytes = toUint8(bytes);
- types = [].concat(types);
- var i = 0;
- var nalStart;
- var nalsFound = 0; // keep searching until:
- // we reach the end of bytes
- // we reach the maximum number of nals they want to seach
- // NOTE: that we disregard nalLimit when we have found the start
- // of the nal we want so that we can find the end of the nal we want.
-
- while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
- var nalOffset = void 0;
-
- if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
- nalOffset = 4;
- } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
- nalOffset = 3;
- } // we are unsynced,
- // find the next nal unit
-
-
- if (!nalOffset) {
- i++;
- continue;
- }
-
- nalsFound++;
-
- if (nalStart) {
- return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
- }
-
- var nalType = void 0;
-
- if (dataType === 'h264') {
- nalType = bytes[i + nalOffset] & 0x1f;
- } else if (dataType === 'h265') {
- nalType = bytes[i + nalOffset] >> 1 & 0x3f;
- }
-
- if (types.indexOf(nalType) !== -1) {
- nalStart = i + nalOffset;
- } // nal header is 1 length for h264, and 2 for h265
-
-
- i += nalOffset + (dataType === 'h264' ? 1 : 2);
- }
-
- return bytes.subarray(0, 0);
-};
-export var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h264', type, nalLimit);
-};
-export var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
- return findNal(bytes, 'h265', type, nalLimit);
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/ogg-helpers.js b/node_modules/@videojs/vhs-utils/es/ogg-helpers.js
deleted file mode 100644
index 78a6752..0000000
--- a/node_modules/@videojs/vhs-utils/es/ogg-helpers.js
+++ /dev/null
@@ -1,28 +0,0 @@
-import { bytesMatch, toUint8 } from './byte-helpers';
-var SYNC_WORD = toUint8([0x4f, 0x67, 0x67, 0x53]);
-export var getPages = function getPages(bytes, start, end) {
- if (end === void 0) {
- end = Infinity;
- }
-
- bytes = toUint8(bytes);
- var pages = [];
- var i = 0;
-
- while (i < bytes.length && pages.length < end) {
- // we are unsynced,
- // find the next syncword
- if (!bytesMatch(bytes, SYNC_WORD, {
- offset: i
- })) {
- i++;
- continue;
- }
-
- var segmentLength = bytes[i + 27];
- pages.push(bytes.subarray(i, i + 28 + segmentLength));
- i += pages[pages.length - 1].length;
- }
-
- return pages.slice(start, end);
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/opus-helpers.js b/node_modules/@videojs/vhs-utils/es/opus-helpers.js
deleted file mode 100644
index 45cc64e..0000000
--- a/node_modules/@videojs/vhs-utils/es/opus-helpers.js
+++ /dev/null
@@ -1,52 +0,0 @@
-export var OPUS_HEAD = new Uint8Array([// O, p, u, s
-0x4f, 0x70, 0x75, 0x73, // H, e, a, d
-0x48, 0x65, 0x61, 0x64]); // https://wiki.xiph.org/OggOpus
-// https://vfrmaniac.fushizen.eu/contents/opus_in_isobmff.html
-// https://opus-codec.org/docs/opusfile_api-0.7/structOpusHead.html
-
-export var parseOpusHead = function parseOpusHead(bytes) {
- var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- var version = view.getUint8(0); // version 0, from mp4, does not use littleEndian.
-
- var littleEndian = version !== 0;
- var config = {
- version: version,
- channels: view.getUint8(1),
- preSkip: view.getUint16(2, littleEndian),
- sampleRate: view.getUint32(4, littleEndian),
- outputGain: view.getUint16(8, littleEndian),
- channelMappingFamily: view.getUint8(10)
- };
-
- if (config.channelMappingFamily > 0 && bytes.length > 10) {
- config.streamCount = view.getUint8(11);
- config.twoChannelStreamCount = view.getUint8(12);
- config.channelMapping = [];
-
- for (var c = 0; c < config.channels; c++) {
- config.channelMapping.push(view.getUint8(13 + c));
- }
- }
-
- return config;
-};
-export var setOpusHead = function setOpusHead(config) {
- var size = config.channelMappingFamily <= 0 ? 11 : 12 + config.channels;
- var view = new DataView(new ArrayBuffer(size));
- var littleEndian = config.version !== 0;
- view.setUint8(0, config.version);
- view.setUint8(1, config.channels);
- view.setUint16(2, config.preSkip, littleEndian);
- view.setUint32(4, config.sampleRate, littleEndian);
- view.setUint16(8, config.outputGain, littleEndian);
- view.setUint8(10, config.channelMappingFamily);
-
- if (config.channelMappingFamily > 0) {
- view.setUint8(11, config.streamCount);
- config.channelMapping.foreach(function (cm, i) {
- view.setUint8(12 + i, cm);
- });
- }
-
- return new Uint8Array(view.buffer);
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/resolve-url.js b/node_modules/@videojs/vhs-utils/es/resolve-url.js
deleted file mode 100644
index c3b0326..0000000
--- a/node_modules/@videojs/vhs-utils/es/resolve-url.js
+++ /dev/null
@@ -1,47 +0,0 @@
-import URLToolkit from 'url-toolkit';
-import window from 'global/window';
-var DEFAULT_LOCATION = 'http://example.com';
-
-var resolveUrl = function resolveUrl(baseUrl, relativeUrl) {
- // return early if we don't need to resolve
- if (/^[a-z]+:/i.test(relativeUrl)) {
- return relativeUrl;
- } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
-
-
- if (/^data:/.test(baseUrl)) {
- baseUrl = window.location && window.location.href || '';
- } // IE11 supports URL but not the URL constructor
- // feature detect the behavior we want
-
-
- var nativeURL = typeof window.URL === 'function';
- var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
- // and if baseUrl isn't an absolute url
-
- var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
-
- if (nativeURL) {
- baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
- } else if (!/\/\//i.test(baseUrl)) {
- baseUrl = URLToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
- }
-
- if (nativeURL) {
- var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
- // and if we're location-less, remove the location
- // otherwise, return the url unmodified
-
- if (removeLocation) {
- return newUrl.href.slice(DEFAULT_LOCATION.length);
- } else if (protocolLess) {
- return newUrl.href.slice(newUrl.protocol.length);
- }
-
- return newUrl.href;
- }
-
- return URLToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
-};
-
-export default resolveUrl;
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/riff-helpers.js b/node_modules/@videojs/vhs-utils/es/riff-helpers.js
deleted file mode 100644
index 9129c13..0000000
--- a/node_modules/@videojs/vhs-utils/es/riff-helpers.js
+++ /dev/null
@@ -1,74 +0,0 @@
-import { toUint8, stringToBytes, bytesMatch } from './byte-helpers.js';
-var CONSTANTS = {
- LIST: toUint8([0x4c, 0x49, 0x53, 0x54]),
- RIFF: toUint8([0x52, 0x49, 0x46, 0x46]),
- WAVE: toUint8([0x57, 0x41, 0x56, 0x45])
-};
-
-var normalizePath = function normalizePath(path) {
- if (typeof path === 'string') {
- return stringToBytes(path);
- }
-
- if (typeof path === 'number') {
- return path;
- }
-
- return path;
-};
-
-var normalizePaths = function normalizePaths(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map(function (p) {
- return normalizePath(p);
- });
-};
-
-export var findFourCC = function findFourCC(bytes, paths) {
- paths = normalizePaths(paths);
- bytes = toUint8(bytes);
- var results = [];
-
- if (!paths.length) {
- // short-circuit the search for empty paths
- return results;
- }
-
- var i = 0;
-
- while (i < bytes.length) {
- var type = bytes.subarray(i, i + 4);
- var size = (bytes[i + 7] << 24 | bytes[i + 6] << 16 | bytes[i + 5] << 8 | bytes[i + 4]) >>> 0; // skip LIST/RIFF and get the actual type
-
- if (bytesMatch(type, CONSTANTS.LIST) || bytesMatch(type, CONSTANTS.RIFF) || bytesMatch(type, CONSTANTS.WAVE)) {
- type = bytes.subarray(i + 8, i + 12);
- i += 4;
- size -= 4;
- }
-
- var data = bytes.subarray(i + 8, i + 8 + size);
-
- if (bytesMatch(type, paths[0])) {
- if (paths.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next box along the path
- var subresults = findFourCC(data, paths.slice(1));
-
- if (subresults.length) {
- results = results.concat(subresults);
- }
- }
- }
-
- i += 8 + data.length;
- } // we've finished searching all of bytes
-
-
- return results;
-};
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/es/stream.js b/node_modules/@videojs/vhs-utils/es/stream.js
deleted file mode 100644
index 8a3cc02..0000000
--- a/node_modules/@videojs/vhs-utils/es/stream.js
+++ /dev/null
@@ -1,121 +0,0 @@
-/**
- * @file stream.js
- */
-
-/**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
-var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
-}();
-
-export { Stream as default };
\ No newline at end of file
diff --git a/node_modules/@videojs/vhs-utils/index.html b/node_modules/@videojs/vhs-utils/index.html
deleted file mode 100644
index e3c7925..0000000
--- a/node_modules/@videojs/vhs-utils/index.html
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
- @videojs/vhs-utils Demo
-
-
-
- Test things with window.vhsUtils.* in the console
-
-
-
-
-
diff --git a/node_modules/@videojs/vhs-utils/package.json b/node_modules/@videojs/vhs-utils/package.json
deleted file mode 100644
index 42dcf81..0000000
--- a/node_modules/@videojs/vhs-utils/package.json
+++ /dev/null
@@ -1,135 +0,0 @@
-{
- "_from": "@videojs/vhs-utils@^3.0.2",
- "_id": "@videojs/vhs-utils@3.0.2",
- "_inBundle": false,
- "_integrity": "sha512-r8Yas1/tNGsGRNoIaDJuiWiQgM0P2yaEnobgzw5JcBiEqxnS8EXoUm4QtKH7nJtnppZ1yqBx1agBZCvBMKXA2w==",
- "_location": "/@videojs/vhs-utils",
- "_phantomChildren": {},
- "_requested": {
- "type": "range",
- "registry": true,
- "raw": "@videojs/vhs-utils@^3.0.2",
- "name": "@videojs/vhs-utils",
- "escapedName": "@videojs%2fvhs-utils",
- "scope": "@videojs",
- "rawSpec": "^3.0.2",
- "saveSpec": null,
- "fetchSpec": "^3.0.2"
- },
- "_requiredBy": [
- "/@videojs/http-streaming",
- "/aes-decrypter",
- "/m3u8-parser",
- "/mpd-parser",
- "/video.js"
- ],
- "_resolved": "https://registry.npmjs.org/@videojs/vhs-utils/-/vhs-utils-3.0.2.tgz",
- "_shasum": "0203418ecaaff29bc33c69b6ad707787347b7614",
- "_spec": "@videojs/vhs-utils@^3.0.2",
- "_where": "F:\\Documents\\websites\\BMM\\node_modules\\video.js",
- "author": {
- "name": "brandonocasey",
- "email": "brandonocasey@gmail.com"
- },
- "browser": "./dist/vhs-utils.js",
- "browserslist": [
- "defaults",
- "ie 11"
- ],
- "bugs": {
- "url": "https://github.com/videojs/vhs-utils/issues"
- },
- "bundleDependencies": false,
- "dependencies": {
- "@babel/runtime": "^7.12.5",
- "global": "^4.4.0",
- "url-toolkit": "^2.2.1"
- },
- "deprecated": false,
- "description": "Objects and functions shared throughtout @videojs/http-streaming code",
- "devDependencies": {
- "@babel/cli": "^7.12.8",
- "@videojs/babel-config": "^0.2.0",
- "@videojs/generator-helpers": "~2.0.1",
- "karma": "^5.2.3",
- "rollup": "^2.28.2",
- "videojs-generate-karma-config": "~7.0.0",
- "videojs-generate-rollup-config": "~6.0.0",
- "videojs-generator-verify": "~3.0.3",
- "videojs-standard": "^8.0.4"
- },
- "engines": {
- "node": ">=8",
- "npm": ">=5"
- },
- "files": [
- "CONTRIBUTING.md",
- "es/",
- "cjs/",
- "dist/",
- "docs/",
- "index.html",
- "scripts/",
- "src/",
- "test/"
- ],
- "generator-videojs-plugin": {
- "version": "7.7.1"
- },
- "homepage": "https://github.com/videojs/vhs-utils#readme",
- "husky": {
- "hooks": {
- "pre-commit": "lint-staged"
- }
- },
- "keywords": [
- "videojs",
- "videojs-plugin"
- ],
- "license": "MIT",
- "lint-staged": {
- "*.js": "vjsstandard --fix",
- "README.md": "doctoc --notitle"
- },
- "main": "./cjs/index.js",
- "module": "./es/index.js",
- "name": "@videojs/vhs-utils",
- "repository": {
- "type": "git",
- "url": "git+ssh://git@github.com/videojs/vhs-utils.git"
- },
- "scripts": {
- "build": "npm-run-all -s clean -p build:*",
- "build-prod": "cross-env-shell NO_TEST_BUNDLE=1 'npm run build'",
- "build-test": "cross-env-shell TEST_BUNDLE_ONLY=1 'npm run build'",
- "build:cjs": "babel-config-cjs -d ./cjs ./src",
- "build:es": "babel-config-es -d ./es ./src",
- "build:js": "rollup -c scripts/rollup.config.js",
- "clean": "shx rm -rf ./dist ./test/dist ./cjs ./es && shx mkdir -p ./test/dist ./cjs ./es",
- "lint": "vjsstandard",
- "posttest": "shx cat test/dist/coverage/text.txt",
- "prepublishOnly": "npm-run-all build-prod && vjsverify --verbose",
- "preversion": "npm test",
- "server": "karma start scripts/karma.conf.js --singleRun=false --auto-watch",
- "start": "npm-run-all -p server watch",
- "test": "npm-run-all lint build-test && npm-run-all test:*",
- "test:browser": "karma start scripts/karma.conf.js",
- "test:node": "qunit test/dist/bundle.js",
- "update-changelog": "conventional-changelog -p videojs -i CHANGELOG.md -s",
- "version": "is-prerelease || npm run update-changelog && git add CHANGELOG.md",
- "watch": "npm-run-all -p watch:*",
- "watch:cjs": "npm run build:cjs -- -w",
- "watch:es": "npm run build:es -- -w",
- "watch:js": "npm run build:js -- -w"
- },
- "version": "3.0.2",
- "vjsstandard": {
- "ignore": [
- "dist",
- "cjs",
- "es",
- "docs",
- "test/dist"
- ]
- }
-}
diff --git a/node_modules/@videojs/vhs-utils/scripts/create-test-data.js b/node_modules/@videojs/vhs-utils/scripts/create-test-data.js
deleted file mode 100644
index cc2009c..0000000
--- a/node_modules/@videojs/vhs-utils/scripts/create-test-data.js
+++ /dev/null
@@ -1,96 +0,0 @@
-const fs = require('fs');
-const path = require('path');
-const baseDir = path.join(__dirname, '..');
-const formatDir = path.join(baseDir, 'test', 'fixtures', 'formats');
-const parsingDir = path.join(baseDir, 'test', 'fixtures', 'parsing');
-
-const getFiles = (dir) => (fs.readdirSync(dir) || []).reduce((acc, d) => {
- d = path.resolve(dir, d);
-
- const stat = fs.statSync(d);
-
- if (!stat.isDirectory()) {
- return acc;
- }
-
- const subfiles = fs.readdirSync(d).map((f) => path.resolve(d, f));
-
- return acc.concat(subfiles);
-}, []);
-
-const buildDataString = function(files, id) {
- const data = {};
-
- files.forEach((file) => {
- // read the file directly as a buffer before converting to base64
- const base64 = fs.readFileSync(file).toString('base64');
-
- data[path.basename(file)] = base64;
- });
-
- const dataExportStrings = Object.keys(data).reduce((acc, key) => {
- // use a function since the segment may be cleared out on usage
- acc.push(`${id}Files['${key}'] = () => {
- cache['${key}'] = cache['${key}'] || base64ToUint8Array('${data[key]}');
- const dest = new Uint8Array(cache['${key}'].byteLength);
- dest.set(cache['${key}']);
- return dest;
- };`);
- return acc;
- }, []);
-
- const file =
- '/* istanbul ignore file */\n' +
- '\n' +
- `import base64ToUint8Array from "${path.resolve(baseDir, 'src/decode-b64-to-uint8-array.js')}";\n` +
- 'const cache = {};\n' +
- `const ${id}Files = {};\n` +
- dataExportStrings.join('\n') +
- `export default ${id}Files`;
-
- return file;
-};
-
-/* we refer to them as .js, so that babel and other plugins can work on them */
-const formatsKey = 'create-test-data!formats.js';
-const parsingKey = 'create-test-data!parsing.js';
-
-module.exports = function() {
- return {
- name: 'createTestData',
- buildStart() {
- this.addWatchFile(formatDir);
- this.addWatchFile(parsingDir);
-
- getFiles(formatDir).forEach((file) => this.addWatchFile(file));
- getFiles(parsingDir).forEach((file) => this.addWatchFile(file));
- },
- resolveId(importee, importer) {
- // if this is not an id we can resolve return
- if (importee.indexOf('create-test-data!') !== 0) {
- return;
- }
-
- const name = importee.split('!')[1];
-
- if (name.indexOf('formats') !== -1) {
- return formatsKey;
- }
-
- if (name.indexOf('parsing') !== -1) {
- return parsingKey;
- }
-
- return null;
- },
- load(id) {
- if (id === formatsKey) {
- return buildDataString.call(this, getFiles(formatDir), 'format');
- }
-
- if (id === parsingKey) {
- return buildDataString.call(this, getFiles(parsingDir), 'parsing');
- }
- }
- };
-};
diff --git a/node_modules/@videojs/vhs-utils/scripts/karma.conf.js b/node_modules/@videojs/vhs-utils/scripts/karma.conf.js
deleted file mode 100644
index da8e7f6..0000000
--- a/node_modules/@videojs/vhs-utils/scripts/karma.conf.js
+++ /dev/null
@@ -1,16 +0,0 @@
-const generate = require('videojs-generate-karma-config');
-
-module.exports = function(config) {
-
- // see https://github.com/videojs/videojs-generate-karma-config
- // for options
- const options = {
- serverBrowsers() {
- return [];
- }
- };
-
- config = generate(config, options);
-
- // any other custom stuff not supported by options here!
-};
diff --git a/node_modules/@videojs/vhs-utils/scripts/rollup.config.js b/node_modules/@videojs/vhs-utils/scripts/rollup.config.js
deleted file mode 100644
index e3e15a7..0000000
--- a/node_modules/@videojs/vhs-utils/scripts/rollup.config.js
+++ /dev/null
@@ -1,28 +0,0 @@
-const createTestData = require('./create-test-data.js');
-const generate = require('videojs-generate-rollup-config');
-// see https://github.com/videojs/videojs-generate-rollup-config
-// for options
-const options = {
- input: 'src/index.js',
- exportName: 'vhsUtils',
- distName: 'vhs-utils',
- primedPlugins(defaults) {
- return Object.assign(defaults, {
- createTestData: createTestData()
- });
- },
- plugins(defaults) {
- defaults.test.splice(0, 0, 'createTestData');
- return defaults;
- }
-};
-const config = generate(options);
-
-if (config.builds.module) {
- delete config.builds.module;
-}
-
-// Add additonal builds/customization here!
-
-// export the builds to rollup
-export default Object.values(config.builds);
diff --git a/node_modules/@videojs/vhs-utils/src/byte-helpers.js b/node_modules/@videojs/vhs-utils/src/byte-helpers.js
deleted file mode 100644
index d33200c..0000000
--- a/node_modules/@videojs/vhs-utils/src/byte-helpers.js
+++ /dev/null
@@ -1,272 +0,0 @@
-import window from 'global/window';
-
-// const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
-
-const repeat = function(str, len) {
- let acc = '';
-
- while (len--) {
- acc += str;
- }
-
- return acc;
-};
-
-// count the number of bits it would take to represent a number
-// we used to do this with log2 but BigInt does not support builtin math
-// Math.ceil(log2(x));
-export const countBits = (x) => x.toString(2).length;
-// count the number of whole bytes it would take to represent a number
-export const countBytes = (x) => Math.ceil(countBits(x) / 8);
-export const padStart = (b, len, str = ' ') => (repeat(str, len) + b.toString()).slice(-len);
-export const isTypedArray = (obj) => ArrayBuffer.isView(obj);
-
-export const toUint8 = function(bytes) {
- if (bytes instanceof Uint8Array) {
- return bytes;
- }
-
- if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
- // any non-number or NaN leads to empty uint8array
- // eslint-disable-next-line
- if (typeof bytes !== 'number' || (typeof bytes === 'number' && bytes !== bytes)) {
- bytes = 0;
- } else {
- bytes = [bytes];
- }
- }
-
- return new Uint8Array(
- bytes && bytes.buffer || bytes,
- bytes && bytes.byteOffset || 0,
- bytes && bytes.byteLength || 0
- );
-};
-
-export const toHexString = function(bytes) {
- bytes = toUint8(bytes);
- let str = '';
-
- for (let i = 0; i < bytes.length; i++) {
- str += padStart(bytes[i].toString(16), 2, '0');
- }
-
- return str;
-};
-
-export const toBinaryString = function(bytes) {
- bytes = toUint8(bytes);
- let str = '';
-
- for (let i = 0; i < bytes.length; i++) {
- str += padStart(bytes[i].toString(2), 8, '0');
- }
-
- return str;
-};
-const BigInt = window.BigInt || Number;
-
-const BYTE_TABLE = [
- BigInt('0x1'),
- BigInt('0x100'),
- BigInt('0x10000'),
- BigInt('0x1000000'),
- BigInt('0x100000000'),
- BigInt('0x10000000000'),
- BigInt('0x1000000000000'),
- BigInt('0x100000000000000'),
- BigInt('0x10000000000000000')
-];
-
-export const ENDIANNESS = (function() {
- const a = new Uint16Array([0xFFCC]);
- const b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
-
- if (b[0] === 0xFF) {
- return 'big';
- }
-
- if (b[0] === 0xCC) {
- return 'little';
- }
-
- return 'unknown';
-})();
-
-export const IS_BIG_ENDIAN = ENDIANNESS === 'big';
-export const IS_LITTLE_ENDIAN = ENDIANNESS === 'little';
-
-export const bytesToNumber = function(bytes, {signed = false, le = false} = {}) {
- bytes = toUint8(bytes);
-
- const fn = le ? 'reduce' : 'reduceRight';
- const obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
-
- let number = obj.call(bytes, function(total, byte, i) {
- const exponent = le ? i : Math.abs(i + 1 - bytes.length);
-
- return total + (BigInt(byte) * BYTE_TABLE[exponent]);
- }, BigInt(0));
-
- if (signed) {
- const max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
-
- number = BigInt(number);
-
- if (number > max) {
- number -= max;
- number -= max;
- number -= BigInt(2);
- }
- }
-
- return Number(number);
-};
-
-export const numberToBytes = function(number, {le = false} = {}) {
- // eslint-disable-next-line
- if ((typeof number !== 'bigint' && typeof number !== 'number') || (typeof number === 'number' && number !== number)) {
- number = 0;
- }
-
- number = BigInt(number);
-
- const byteCount = countBytes(number);
-
- const bytes = new Uint8Array(new ArrayBuffer(byteCount));
-
- for (let i = 0; i < byteCount; i++) {
- const byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
-
- bytes[byteIndex] = Number((number / BYTE_TABLE[i]) & BigInt(0xFF));
-
- if (number < 0) {
- bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
- bytes[byteIndex] -= i === 0 ? 1 : 2;
- }
- }
-
- return bytes;
-};
-export const bytesToString = (bytes) => {
- if (!bytes) {
- return '';
- }
-
- // TODO: should toUint8 handle cases where we only have 8 bytes
- // but report more since this is a Uint16+ Array?
- bytes = Array.prototype.slice.call(bytes);
-
- const string = String.fromCharCode.apply(null, toUint8(bytes));
-
- try {
- return decodeURIComponent(escape(string));
- } catch (e) {
- // if decodeURIComponent/escape fails, we are dealing with partial
- // or full non string data. Just return the potentially garbled string.
- }
-
- return string;
-};
-
-export const stringToBytes = (string, stringIsBytes) => {
- if (typeof string !== 'string' && string && typeof string.toString === 'function') {
- string = string.toString();
- }
-
- if (typeof string !== 'string') {
- return new Uint8Array();
- }
-
- // If the string already is bytes, we don't have to do this
- // otherwise we do this so that we split multi length characters
- // into individual bytes
- if (!stringIsBytes) {
- string = unescape(encodeURIComponent(string));
- }
-
- const view = new Uint8Array(string.length);
-
- for (let i = 0; i < string.length; i++) {
- view[i] = string.charCodeAt(i);
- }
- return view;
-};
-
-export const concatTypedArrays = (...buffers) => {
- buffers = buffers.filter((b) => b && (b.byteLength || b.length) && typeof b !== 'string');
-
- if (buffers.length <= 1) {
- // for 0 length we will return empty uint8
- // for 1 length we return the first uint8
- return toUint8(buffers[0]);
- }
-
- const totalLen = buffers.reduce((total, buf, i) => total + (buf.byteLength || buf.length), 0);
- const tempBuffer = new Uint8Array(totalLen);
-
- let offset = 0;
-
- buffers.forEach(function(buf) {
- buf = toUint8(buf);
-
- tempBuffer.set(buf, offset);
- offset += buf.byteLength;
- });
-
- return tempBuffer;
-};
-
-/**
- * Check if the bytes "b" are contained within bytes "a".
- *
- * @param {Uint8Array|Array} a
- * Bytes to check in
- *
- * @param {Uint8Array|Array} b
- * Bytes to check for
- *
- * @param {Object} options
- * options
- *
- * @param {Array|Uint8Array} [offset=0]
- * offset to use when looking at bytes in a
- *
- * @param {Array|Uint8Array} [mask=[]]
- * mask to use on bytes before comparison.
- *
- * @return {boolean}
- * If all bytes in b are inside of a, taking into account
- * bit masks.
- */
-export const bytesMatch = (a, b, {offset = 0, mask = []} = {}) => {
- a = toUint8(a);
- b = toUint8(b);
-
- // ie 11 does not support uint8 every
- const fn = b.every ? b.every : Array.prototype.every;
-
- return b.length &&
- a.length - offset >= b.length &&
- // ie 11 doesn't support every on uin8
- fn.call(b, (bByte, i) => {
- const aByte = (mask[i] ? (mask[i] & a[offset + i]) : a[offset + i]);
-
- return bByte === aByte;
- });
-};
-
-export const sliceBytes = function(src, start, end) {
- if (Uint8Array.prototype.slice) {
- return Uint8Array.prototype.slice.call(src, start, end);
- }
- return new Uint8Array(Array.prototype.slice.call(src, start, end));
-};
-
-export const reverseBytes = function(src) {
- if (src.reverse) {
- return src.reverse();
- }
-
- return Array.prototype.reverse.call(src);
-};
diff --git a/node_modules/@videojs/vhs-utils/src/codec-helpers.js b/node_modules/@videojs/vhs-utils/src/codec-helpers.js
deleted file mode 100644
index 372869d..0000000
--- a/node_modules/@videojs/vhs-utils/src/codec-helpers.js
+++ /dev/null
@@ -1,106 +0,0 @@
-import {padStart, toHexString, toBinaryString} from './byte-helpers.js';
-
-// https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
-// https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter#AV1
-export const getAv1Codec = function(bytes) {
- let codec = '';
- const profile = bytes[1] >>> 3;
- const level = bytes[1] & 0x1F;
- const tier = bytes[2] >>> 7;
- const highBitDepth = (bytes[2] & 0x40) >> 6;
- const twelveBit = (bytes[2] & 0x20) >> 5;
- const monochrome = (bytes[2] & 0x10) >> 4;
- const chromaSubsamplingX = (bytes[2] & 0x08) >> 3;
- const chromaSubsamplingY = (bytes[2] & 0x04) >> 2;
- const chromaSamplePosition = bytes[2] & 0x03;
-
- codec += `${profile}.${padStart(level, 2, '0')}`;
-
- if (tier === 0) {
- codec += 'M';
- } else if (tier === 1) {
- codec += 'H';
- }
-
- let bitDepth;
-
- if (profile === 2 && highBitDepth) {
- bitDepth = twelveBit ? 12 : 10;
- } else {
- bitDepth = highBitDepth ? 10 : 8;
- }
-
- codec += `.${padStart(bitDepth, 2, '0')}`;
-
- // TODO: can we parse color range??
- codec += `.${monochrome}`;
- codec += `.${chromaSubsamplingX}${chromaSubsamplingY}${chromaSamplePosition}`;
-
- return codec;
-};
-
-export const getAvcCodec = function(bytes) {
- const profileId = toHexString(bytes[1]);
- const constraintFlags = toHexString(bytes[2] & 0xFC);
- const levelId = toHexString(bytes[3]);
-
- return `${profileId}${constraintFlags}${levelId}`;
-};
-
-export const getHvcCodec = function(bytes) {
- let codec = '';
- const profileSpace = bytes[1] >> 6;
- const profileId = bytes[1] & 0x1F;
- const tierFlag = (bytes[1] & 0x20) >> 5;
-
- const profileCompat = bytes.subarray(2, 6);
- const constraintIds = bytes.subarray(6, 12);
- const levelId = bytes[12];
-
- if (profileSpace === 1) {
- codec += 'A';
- } else if (profileSpace === 2) {
- codec += 'B';
- } else if (profileSpace === 3) {
- codec += 'C';
- }
-
- codec += `${profileId}.`;
-
- // ffmpeg does this in big endian
- let profileCompatVal = parseInt(toBinaryString(profileCompat).split('').reverse().join(''), 2);
-
- // apple does this in little endian...
- if (profileCompatVal > 255) {
- profileCompatVal = parseInt(toBinaryString(profileCompat), 2);
- }
-
- codec += `${profileCompatVal.toString(16)}.`;
-
- if (tierFlag === 0) {
- codec += 'L';
- } else {
- codec += 'H';
- }
-
- codec += levelId;
-
- let constraints = '';
-
- for (let i = 0; i < constraintIds.length; i++) {
- const v = constraintIds[i];
-
- if (v) {
- if (constraints) {
- constraints += '.';
- }
- constraints += v.toString(16);
- }
- }
-
- if (constraints) {
- codec += `.${constraints}`;
- }
-
- return codec;
-};
diff --git a/node_modules/@videojs/vhs-utils/src/codecs.js b/node_modules/@videojs/vhs-utils/src/codecs.js
deleted file mode 100644
index 7974142..0000000
--- a/node_modules/@videojs/vhs-utils/src/codecs.js
+++ /dev/null
@@ -1,225 +0,0 @@
-import window from 'global/window';
-
-const regexs = {
- // to determine mime types
- mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
- webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
- ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
-
- // to determine if a codec is audio or video
- video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
- audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
- text: /^(stpp.ttml.im1t)/,
-
- // mux.js support regex
- muxerVideo: /^(avc0?1)/,
- muxerAudio: /^(mp4a)/,
- // match nothing as muxer does not support text right now.
- // there cannot never be a character before the start of a string
- // so this matches nothing.
- muxerText: /a^/
-};
-
-const mediaTypes = ['video', 'audio', 'text'];
-const upperMediaTypes = ['Video', 'Audio', 'Text'];
-
-/**
- * Replace the old apple-style `avc1..` codec string with the standard
- * `avc1.`
- *
- * @param {string} codec
- * Codec string to translate
- * @return {string}
- * The translated codec string
- */
-export const translateLegacyCodec = function(codec) {
- if (!codec) {
- return codec;
- }
-
- return codec.replace(/avc1\.(\d+)\.(\d+)/i, function(orig, profile, avcLevel) {
- const profileHex = ('00' + Number(profile).toString(16)).slice(-2);
- const avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
-
- return 'avc1.' + profileHex + '00' + avcLevelHex;
- });
-};
-
-/**
- * Replace the old apple-style `avc1..` codec strings with the standard
- * `avc1.`
- *
- * @param {string[]} codecs
- * An array of codec strings to translate
- * @return {string[]}
- * The translated array of codec strings
- */
-export const translateLegacyCodecs = function(codecs) {
- return codecs.map(translateLegacyCodec);
-};
-
-/**
- * Replace codecs in the codec string with the old apple-style `avc1..` to the
- * standard `avc1.`.
- *
- * @param {string} codecString
- * The codec string
- * @return {string}
- * The codec string with old apple-style codecs replaced
- *
- * @private
- */
-export const mapLegacyAvcCodecs = function(codecString) {
- return codecString.replace(/avc1\.(\d+)\.(\d+)/i, (match) => {
- return translateLegacyCodecs([match])[0];
- });
-};
-
-/**
- * @typedef {Object} ParsedCodecInfo
- * @property {number} codecCount
- * Number of codecs parsed
- * @property {string} [videoCodec]
- * Parsed video codec (if found)
- * @property {string} [videoObjectTypeIndicator]
- * Video object type indicator (if found)
- * @property {string|null} audioProfile
- * Audio profile
- */
-
-/**
- * Parses a codec string to retrieve the number of codecs specified, the video codec and
- * object type indicator, and the audio profile.
- *
- * @param {string} [codecString]
- * The codec string to parse
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-export const parseCodecs = function(codecString = '') {
- const codecs = codecString.split(',');
- const result = [];
-
- codecs.forEach(function(codec) {
- codec = codec.trim();
- let codecType;
-
- mediaTypes.forEach(function(name) {
- const match = regexs[name].exec(codec.toLowerCase());
-
- if (!match || match.length <= 1) {
- return;
- }
- codecType = name;
-
- // maintain codec case
- const type = codec.substring(0, match[1].length);
- const details = codec.replace(type, '');
-
- result.push({type, details, mediaType: name});
- });
-
- if (!codecType) {
- result.push({type: codec, details: '', mediaType: 'unknown'});
- }
- });
-
- return result;
-};
-
-/**
- * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
- * a default alternate audio playlist for the provided audio group.
- *
- * @param {Object} master
- * The master playlist
- * @param {string} audioGroupId
- * ID of the audio group for which to find the default codec info
- * @return {ParsedCodecInfo}
- * Parsed codec info
- */
-export const codecsFromDefault = (master, audioGroupId) => {
- if (!master.mediaGroups.AUDIO || !audioGroupId) {
- return null;
- }
-
- const audioGroup = master.mediaGroups.AUDIO[audioGroupId];
-
- if (!audioGroup) {
- return null;
- }
-
- for (const name in audioGroup) {
- const audioType = audioGroup[name];
-
- if (audioType.default && audioType.playlists) {
- // codec should be the same for all playlists within the audio type
- return parseCodecs(audioType.playlists[0].attributes.CODECS);
- }
- }
-
- return null;
-};
-
-export const isVideoCodec = (codec = '') => regexs.video.test(codec.trim().toLowerCase());
-export const isAudioCodec = (codec = '') => regexs.audio.test(codec.trim().toLowerCase());
-export const isTextCodec = (codec = '') => regexs.text.test(codec.trim().toLowerCase());
-
-export const getMimeForCodec = (codecString) => {
- if (!codecString || typeof codecString !== 'string') {
- return;
- }
- const codecs = codecString
- .toLowerCase()
- .split(',')
- .map((c) => translateLegacyCodec(c.trim()));
-
- // default to video type
- let type = 'video';
-
- // only change to audio type if the only codec we have is
- // audio
- if (codecs.length === 1 && isAudioCodec(codecs[0])) {
- type = 'audio';
- } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
- // text uses application/ for now
- type = 'application';
- }
-
- // default the container to mp4
- let container = 'mp4';
-
- // every codec must be able to go into the container
- // for that container to be the correct one
- if (codecs.every((c) => regexs.mp4.test(c))) {
- container = 'mp4';
- } else if (codecs.every((c) => regexs.webm.test(c))) {
- container = 'webm';
- } else if (codecs.every((c) => regexs.ogg.test(c))) {
- container = 'ogg';
- }
-
- return `${type}/${container};codecs="${codecString}"`;
-};
-
-export const browserSupportsCodec = (codecString = '') => window.MediaSource &&
- window.MediaSource.isTypeSupported &&
- window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
-
-export const muxerSupportsCodec = (codecString = '') => codecString.toLowerCase().split(',').every((codec) => {
- codec = codec.trim();
-
- // any match is supported.
- for (let i = 0; i < upperMediaTypes.length; i++) {
- const type = upperMediaTypes[i];
-
- if (regexs[`muxer${type}`].test(codec)) {
- return true;
- }
- }
-
- return false;
-});
-
-export const DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
-export const DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
diff --git a/node_modules/@videojs/vhs-utils/src/containers.js b/node_modules/@videojs/vhs-utils/src/containers.js
deleted file mode 100644
index ae90fef..0000000
--- a/node_modules/@videojs/vhs-utils/src/containers.js
+++ /dev/null
@@ -1,172 +0,0 @@
-import {toUint8, bytesMatch} from './byte-helpers.js';
-import {findBox} from './mp4-helpers.js';
-import {findEbml, EBML_TAGS} from './ebml-helpers.js';
-import {getId3Offset} from './id3-helpers.js';
-import {findH264Nal, findH265Nal} from './nal-helpers.js';
-
-const CONSTANTS = {
- // "webm" string literal in hex
- 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
-
- // "matroska" string literal in hex
- 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
-
- // "fLaC" string literal in hex
- 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
-
- // "OggS" string literal in hex
- 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
-
- // ac-3 sync byte, also works for ec-3 as that is simply a codec
- // of ac-3
- 'ac3': toUint8([0x0b, 0x77]),
-
- // "RIFF" string literal in hex used for wav and avi
- 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
-
- // "AVI" string literal in hex
- 'avi': toUint8([0x41, 0x56, 0x49]),
-
- // "WAVE" string literal in hex
- 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
-
- // "ftyp3g" string literal in hex
- '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
-
- // "ftyp" string literal in hex
- 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
-
- // "styp" string literal in hex
- 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
-
- // "ftyp" string literal in hex
- 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74])
-};
-
-const _isLikely = {
- aac(bytes) {
- const offset = getId3Offset(bytes);
-
- return bytesMatch(bytes, [0xFF, 0x10], {offset, mask: [0xFF, 0x16]});
- },
-
- mp3(bytes) {
- const offset = getId3Offset(bytes);
-
- return bytesMatch(bytes, [0xFF, 0x02], {offset, mask: [0xFF, 0x06]});
- },
-
- webm(bytes) {
- const docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0];
-
- // check if DocType EBML tag is webm
- return bytesMatch(docType, CONSTANTS.webm);
- },
-
- mkv(bytes) {
- const docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0];
-
- // check if DocType EBML tag is matroska
- return bytesMatch(docType, CONSTANTS.matroska);
- },
-
- mp4(bytes) {
- return !_isLikely['3gp'](bytes) && !_isLikely.mov(bytes) &&
- (bytesMatch(bytes, CONSTANTS.mp4, {offset: 4}) ||
- bytesMatch(bytes, CONSTANTS.fmp4, {offset: 4}));
- },
- mov(bytes) {
- return bytesMatch(bytes, CONSTANTS.mov, {offset: 4});
- },
- '3gp'(bytes) {
- return bytesMatch(bytes, CONSTANTS['3gp'], {offset: 4});
- },
- ac3(bytes) {
- const offset = getId3Offset(bytes);
-
- return bytesMatch(bytes, CONSTANTS.ac3, {offset});
- },
-
- ts(bytes) {
- if (bytes.length < 189 && bytes.length >= 1) {
- return bytes[0] === 0x47;
- }
-
- let i = 0;
-
- // check the first 376 bytes for two matching sync bytes
- while (i + 188 < bytes.length && i < 188) {
- if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
- return true;
- }
- i += 1;
- }
-
- return false;
- },
-
- flac(bytes) {
- const offset = getId3Offset(bytes);
-
- return bytesMatch(bytes, CONSTANTS.flac, {offset});
- },
- ogg(bytes) {
- return bytesMatch(bytes, CONSTANTS.ogg);
- },
- avi(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) &&
- bytesMatch(bytes, CONSTANTS.avi, {offset: 8});
- },
- wav(bytes) {
- return bytesMatch(bytes, CONSTANTS.riff) &&
- bytesMatch(bytes, CONSTANTS.wav, {offset: 8});
- },
- 'h264'(bytes) {
- // find seq_parameter_set_rbsp
- return findH264Nal(bytes, 7, 3).length;
- },
- 'h265'(bytes) {
- // find video_parameter_set_rbsp or seq_parameter_set_rbsp
- return findH265Nal(bytes, [32, 33], 3).length;
- }
-};
-
-// get all the isLikely functions
-// but make sure 'ts' is above h264 and h265
-// but below everything else as it is the least specific
-const isLikelyTypes = Object.keys(_isLikely)
- // remove ts, h264, h265
- .filter((t) => t !== 'ts' && t !== 'h264' && t !== 'h265')
- // add it back to the bottom
- .concat(['ts', 'h264', 'h265']);
-
-// make sure we are dealing with uint8 data.
-isLikelyTypes.forEach(function(type) {
- const isLikelyFn = _isLikely[type];
-
- _isLikely[type] = (bytes) => isLikelyFn(toUint8(bytes));
-});
-
-// export after wrapping
-export const isLikely = _isLikely;
-
-// A useful list of file signatures can be found here
-// https://en.wikipedia.org/wiki/List_of_file_signatures
-export const detectContainerForBytes = (bytes) => {
- bytes = toUint8(bytes);
-
- for (let i = 0; i < isLikelyTypes.length; i++) {
- const type = isLikelyTypes[i];
-
- if (isLikely[type](bytes)) {
- return type;
- }
- }
-
- return '';
-};
-
-// fmp4 is not a container
-export const isLikelyFmp4MediaSegment = (bytes) => {
- return findBox(bytes, ['moof']).length > 0;
-};
diff --git a/node_modules/@videojs/vhs-utils/src/decode-b64-to-uint8-array.js b/node_modules/@videojs/vhs-utils/src/decode-b64-to-uint8-array.js
deleted file mode 100644
index 8948b3d..0000000
--- a/node_modules/@videojs/vhs-utils/src/decode-b64-to-uint8-array.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import window from 'global/window';
-
-const atob = (s) => window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
-
-export default function decodeB64ToUint8Array(b64Text) {
- const decodedString = atob(b64Text);
- const array = new Uint8Array(decodedString.length);
-
- for (let i = 0; i < decodedString.length; i++) {
- array[i] = decodedString.charCodeAt(i);
- }
- return array;
-}
diff --git a/node_modules/@videojs/vhs-utils/src/ebml-helpers.js b/node_modules/@videojs/vhs-utils/src/ebml-helpers.js
deleted file mode 100644
index 0c47c19..0000000
--- a/node_modules/@videojs/vhs-utils/src/ebml-helpers.js
+++ /dev/null
@@ -1,503 +0,0 @@
-import {
- toUint8,
- bytesToNumber,
- bytesMatch,
- bytesToString,
- numberToBytes,
- padStart
-} from './byte-helpers';
-import {getAvcCodec, getHvcCodec, getAv1Codec} from './codec-helpers.js';
-
-// relevant specs for this parser:
-// https://matroska-org.github.io/libebml/specs.html
-// https://www.matroska.org/technical/elements.html
-// https://www.webmproject.org/docs/container/
-
-export const EBML_TAGS = {
- EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
- DocType: toUint8([0x42, 0x82]),
- Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
- SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
- Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
- Track: toUint8([0xAE]),
- TrackNumber: toUint8([0xd7]),
- DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
- TrackEntry: toUint8([0xAE]),
- TrackType: toUint8([0x83]),
- FlagDefault: toUint8([0x88]),
- CodecID: toUint8([0x86]),
- CodecPrivate: toUint8([0x63, 0xA2]),
- VideoTrack: toUint8([0xe0]),
- AudioTrack: toUint8([0xe1]),
-
- // Not used yet, but will be used for live webm/mkv
- // see https://www.matroska.org/technical/basics.html#block-structure
- // see https://www.matroska.org/technical/basics.html#simpleblock-structure
- Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
- Timestamp: toUint8([0xE7]),
- TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
- BlockGroup: toUint8([0xA0]),
- BlockDuration: toUint8([0x9B]),
- Block: toUint8([0xA1]),
- SimpleBlock: toUint8([0xA3])
-};
-
-/**
- * This is a simple table to determine the length
- * of things in ebml. The length is one based (starts at 1,
- * rather than zero) and for every zero bit before a one bit
- * we add one to length. We also need this table because in some
- * case we have to xor all the length bits from another value.
- */
-const LENGTH_TABLE = [
- 0b10000000,
- 0b01000000,
- 0b00100000,
- 0b00010000,
- 0b00001000,
- 0b00000100,
- 0b00000010,
- 0b00000001
-];
-
-const getLength = function(byte) {
- let len = 1;
-
- for (let i = 0; i < LENGTH_TABLE.length; i++) {
- if (byte & LENGTH_TABLE[i]) {
- break;
- }
-
- len++;
- }
-
- return len;
-};
-
-// length in ebml is stored in the first 4 to 8 bits
-// of the first byte. 4 for the id length and 8 for the
-// data size length. Length is measured by converting the number to binary
-// then 1 + the number of zeros before a 1 is encountered starting
-// from the left.
-const getvint = function(bytes, offset, removeLength = true, signed = false) {
- const length = getLength(bytes[offset]);
- let valueBytes = bytes.subarray(offset, offset + length);
-
- // NOTE that we do **not** subarray here because we need to copy these bytes
- // as they will be modified below to remove the dataSizeLen bits and we do not
- // want to modify the original data. normally we could just call slice on
- // uint8array but ie 11 does not support that...
- if (removeLength) {
- valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
- valueBytes[0] ^= LENGTH_TABLE[length - 1];
- }
-
- return {
- length,
- value: bytesToNumber(valueBytes, {signed}),
- bytes: valueBytes
- };
-};
-
-const normalizePath = function(path) {
- if (typeof path === 'string') {
- return path.match(/.{1,2}/g).map((p) => normalizePath(p));
- }
-
- if (typeof path === 'number') {
- return numberToBytes(path);
- }
-
- return path;
-};
-
-const normalizePaths = function(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map((p) => normalizePath(p));
-};
-
-const getInfinityDataSize = (id, bytes, offset) => {
- if (offset >= bytes.length) {
- return bytes.length;
- }
- const innerid = getvint(bytes, offset, false);
-
- if (bytesMatch(id.bytes, innerid.bytes)) {
- return offset;
- }
-
- const dataHeader = getvint(bytes, offset + innerid.length);
-
- return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
-};
-
-/**
- * Notes on the EBLM format.
- *
- * EBLM uses "vints" tags. Every vint tag contains
- * two parts
- *
- * 1. The length from the first byte. You get this by
- * converting the byte to binary and counting the zeros
- * before a 1. Then you add 1 to that. Examples
- * 00011111 = length 4 because there are 3 zeros before a 1.
- * 00100000 = length 3 because there are 2 zeros before a 1.
- * 00000011 = length 7 because there are 6 zeros before a 1.
- *
- * 2. The bits used for length are removed from the first byte
- * Then all the bytes are merged into a value. NOTE: this
- * is not the case for id ebml tags as there id includes
- * length bits.
- *
- */
-export const findEbml = function(bytes, paths) {
- paths = normalizePaths(paths);
- bytes = toUint8(bytes);
- let results = [];
-
- if (!paths.length) {
- return results;
- }
-
- let i = 0;
-
- while (i < bytes.length) {
- const id = getvint(bytes, i, false);
- const dataHeader = getvint(bytes, i + id.length);
- const dataStart = i + id.length + dataHeader.length;
-
- // dataSize is unknown or this is a live stream
- if (dataHeader.value === 0x7f) {
- dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
-
- if (dataHeader.value !== bytes.length) {
- dataHeader.value -= dataStart;
- }
- }
- const dataEnd = (dataStart + dataHeader.value) > bytes.length ? bytes.length : (dataStart + dataHeader.value);
- const data = bytes.subarray(dataStart, dataEnd);
-
- if (bytesMatch(paths[0], id.bytes)) {
- if (paths.length === 1) {
- // this is the end of the paths and we've found the tag we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next tag inside of the data
- // of this one
- results = results.concat(findEbml(data, paths.slice(1)));
- }
- }
-
- const totalLength = id.length + dataHeader.length + data.length;
-
- // move past this tag entirely, we are not looking for it
- i += totalLength;
- }
-
- return results;
-};
-
-// see https://www.matroska.org/technical/basics.html#block-structure
-export const decodeBlock = function(block, type, timestampScale, clusterTimestamp) {
- let duration;
-
- if (type === 'group') {
- duration = findEbml(block, [EBML_TAGS.BlockDuration])[0];
- if (duration) {
- duration = bytesToNumber(duration);
- duration = (((1 / timestampScale) * (duration)) * timestampScale) / 1000;
- }
- block = findEbml(block, [EBML_TAGS.Block])[0];
- type = 'block';
- // treat data as a block after this point
- }
- const dv = new DataView(block.buffer, block.byteOffset, block.byteLength);
- const trackNumber = getvint(block, 0);
- const timestamp = dv.getInt16(trackNumber.length, false);
- const flags = block[trackNumber.length + 2];
- const data = block.subarray(trackNumber.length + 3);
- // pts/dts in seconds
- const ptsdts = (((1 / timestampScale) * (clusterTimestamp + timestamp)) * timestampScale) / 1000;
-
- // return the frame
- const parsed = {
- duration,
- trackNumber: trackNumber.value,
- keyframe: type === 'simple' && (flags >> 7) === 1,
- invisible: ((flags & 0x08) >> 3) === 1,
- lacing: ((flags & 0x06) >> 1),
- discardable: type === 'simple' && (flags & 0x01) === 1,
- frames: [],
- pts: ptsdts,
- dts: ptsdts,
- timestamp
- };
-
- if (!parsed.lacing) {
- parsed.frames.push(data);
- return parsed;
- }
-
- const numberOfFrames = data[0] + 1;
-
- const frameSizes = [];
- let offset = 1;
-
- // Fixed
- if (parsed.lacing === 2) {
- const sizeOfFrame = (data.length - offset) / numberOfFrames;
-
- for (let i = 0; i < numberOfFrames; i++) {
- frameSizes.push(sizeOfFrame);
- }
- }
-
- // xiph
- if (parsed.lacing === 1) {
- for (let i = 0; i < numberOfFrames - 1; i++) {
- let size = 0;
-
- do {
- size += data[offset];
- offset++;
- } while (data[offset - 1] === 0xFF);
-
- frameSizes.push(size);
- }
- }
-
- // ebml
- if (parsed.lacing === 3) {
- // first vint is unsinged
- // after that vints are singed and
- // based on a compounding size
- let size = 0;
-
- for (let i = 0; i < numberOfFrames - 1; i++) {
- const vint = i === 0 ? getvint(data, offset) : getvint(data, offset, true, true);
-
- size += vint.value;
- frameSizes.push(size);
- offset += vint.length;
- }
- }
-
- frameSizes.forEach(function(size) {
- parsed.frames.push(data.subarray(offset, offset + size));
- offset += size;
- });
-
- return parsed;
-};
-
-// VP9 Codec Feature Metadata (CodecPrivate)
-// https://www.webmproject.org/docs/container/
-const parseVp9Private = (bytes) => {
- let i = 0;
- const params = {};
-
- while (i < bytes.length) {
- const id = bytes[i] & 0x7f;
- const len = bytes[i + 1];
- let val;
-
- if (len === 1) {
- val = bytes[i + 2];
- } else {
- val = bytes.subarray(i + 2, i + 2 + len);
- }
-
- if (id === 1) {
- params.profile = val;
- } else if (id === 2) {
- params.level = val;
- } else if (id === 3) {
- params.bitDepth = val;
- } else if (id === 4) {
- params.chromaSubsampling = val;
- } else {
- params[id] = val;
- }
-
- i += 2 + len;
- }
-
- return params;
-};
-
-export const parseTracks = function(bytes) {
- bytes = toUint8(bytes);
- const decodedTracks = [];
- let tracks = findEbml(bytes, [EBML_TAGS.Segment, EBML_TAGS.Tracks, EBML_TAGS.Track]);
-
- if (!tracks.length) {
- tracks = findEbml(bytes, [EBML_TAGS.Tracks, EBML_TAGS.Track]);
- }
-
- if (!tracks.length) {
- tracks = findEbml(bytes, [EBML_TAGS.Track]);
- }
-
- if (!tracks.length) {
- return decodedTracks;
- }
-
- tracks.forEach(function(track) {
- let trackType = findEbml(track, EBML_TAGS.TrackType)[0];
-
- if (!trackType || !trackType.length) {
- return;
- }
-
- // 1 is video, 2 is audio, 17 is subtitle
- // other values are unimportant in this context
- if (trackType[0] === 1) {
- trackType = 'video';
- } else if (trackType[0] === 2) {
- trackType = 'audio';
- } else if (trackType[0] === 17) {
- trackType = 'subtitle';
- } else {
- return;
- }
-
- // todo parse language
- const decodedTrack = {
- rawCodec: bytesToString(findEbml(track, [EBML_TAGS.CodecID])[0]),
- type: trackType,
- codecPrivate: findEbml(track, [EBML_TAGS.CodecPrivate])[0],
- number: bytesToNumber(findEbml(track, [EBML_TAGS.TrackNumber])[0]),
- defaultDuration: bytesToNumber(findEbml(track, [EBML_TAGS.DefaultDuration])[0]),
- default: findEbml(track, [EBML_TAGS.FlagDefault])[0],
- rawData: track
- };
-
- let codec = '';
-
- if ((/V_MPEG4\/ISO\/AVC/).test(decodedTrack.rawCodec)) {
- codec = `avc1.${getAvcCodec(decodedTrack.codecPrivate)}`;
- } else if ((/V_MPEGH\/ISO\/HEVC/).test(decodedTrack.rawCodec)) {
- codec = `hev1.${getHvcCodec(decodedTrack.codecPrivate)}`;
- } else if ((/V_MPEG4\/ISO\/ASP/).test(decodedTrack.rawCodec)) {
- if (decodedTrack.codecPrivate) {
- codec = 'mp4v.20.' + decodedTrack.codecPrivate[4].toString();
- } else {
- codec = 'mp4v.20.9';
- }
- } else if ((/^V_THEORA/).test(decodedTrack.rawCodec)) {
- codec = 'theora';
- } else if ((/^V_VP8/).test(decodedTrack.rawCodec)) {
- codec = 'vp8';
- } else if ((/^V_VP9/).test(decodedTrack.rawCodec)) {
- if (decodedTrack.codecPrivate) {
- const {profile, level, bitDepth, chromaSubsampling} = parseVp9Private(decodedTrack.codecPrivate);
-
- codec = 'vp09.';
- codec += `${padStart(profile, 2, '0')}.`;
- codec += `${padStart(level, 2, '0')}.`;
- codec += `${padStart(bitDepth, 2, '0')}.`;
- codec += `${padStart(chromaSubsampling, 2, '0')}`;
-
- // Video -> Colour -> Ebml name
- const matrixCoefficients = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xB1]])[0] || [];
- const videoFullRangeFlag = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xB9]])[0] || [];
- const transferCharacteristics = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xBA]])[0] || [];
- const colourPrimaries = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xBB]])[0] || [];
-
- // if we find any optional codec parameter specify them all.
- if (matrixCoefficients.length ||
- videoFullRangeFlag.length ||
- transferCharacteristics.length ||
- colourPrimaries.length) {
- codec += `.${padStart(colourPrimaries[0], 2, '0')}`;
- codec += `.${padStart(transferCharacteristics[0], 2, '0')}`;
- codec += `.${padStart(matrixCoefficients[0], 2, '0')}`;
- codec += `.${padStart(videoFullRangeFlag[0], 2, '0')}`;
- }
-
- } else {
- codec = 'vp9';
- }
- } else if ((/^V_AV1/).test(decodedTrack.rawCodec)) {
- codec = `av01.${getAv1Codec(decodedTrack.codecPrivate)}`;
- } else if ((/A_ALAC/).test(decodedTrack.rawCodec)) {
- codec = 'alac';
- } else if ((/A_MPEG\/L2/).test(decodedTrack.rawCodec)) {
- codec = 'mp2';
- } else if ((/A_MPEG\/L3/).test(decodedTrack.rawCodec)) {
- codec = 'mp3';
- } else if ((/^A_AAC/).test(decodedTrack.rawCodec)) {
- if (decodedTrack.codecPrivate) {
- codec = 'mp4a.40.' + (decodedTrack.codecPrivate[0] >>> 3).toString();
- } else {
- codec = 'mp4a.40.2';
- }
- } else if ((/^A_AC3/).test(decodedTrack.rawCodec)) {
- codec = 'ac-3';
- } else if ((/^A_PCM/).test(decodedTrack.rawCodec)) {
- codec = 'pcm';
- } else if ((/^A_MS\/ACM/).test(decodedTrack.rawCodec)) {
- codec = 'speex';
- } else if ((/^A_EAC3/).test(decodedTrack.rawCodec)) {
- codec = 'ec-3';
- } else if ((/^A_VORBIS/).test(decodedTrack.rawCodec)) {
- codec = 'vorbis';
- } else if ((/^A_FLAC/).test(decodedTrack.rawCodec)) {
- codec = 'flac';
- } else if ((/^A_OPUS/).test(decodedTrack.rawCodec)) {
- codec = 'opus';
- }
-
- decodedTrack.codec = codec;
- decodedTracks.push(decodedTrack);
- });
-
- return decodedTracks.sort((a, b) => a.number - b.number);
-};
-
-export const parseData = function(data, tracks) {
- const allBlocks = [];
-
- const segment = findEbml(data, [EBML_TAGS.Segment])[0];
- let timestampScale = findEbml(segment, [EBML_TAGS.SegmentInfo, EBML_TAGS.TimestampScale])[0];
-
- // in nanoseconds, defaults to 1ms
- if (timestampScale && timestampScale.length) {
- timestampScale = bytesToNumber(timestampScale);
- } else {
- timestampScale = 1000000;
- }
-
- const clusters = findEbml(segment, [EBML_TAGS.Cluster]);
-
- if (!tracks) {
- tracks = parseTracks(segment);
- }
-
- clusters.forEach(function(cluster, ci) {
- const simpleBlocks = findEbml(cluster, [EBML_TAGS.SimpleBlock]).map((b) => ({type: 'simple', data: b}));
- const blockGroups = findEbml(cluster, [EBML_TAGS.BlockGroup]).map((b) => ({type: 'group', data: b}));
- let timestamp = findEbml(cluster, [EBML_TAGS.Timestamp])[0] || 0;
-
- if (timestamp && timestamp.length) {
- timestamp = bytesToNumber(timestamp);
- }
-
- // get all blocks then sort them into the correct order
- const blocks = simpleBlocks
- .concat(blockGroups)
- .sort((a, b) => a.data.byteOffset - b.data.byteOffset);
-
- blocks.forEach(function(block, bi) {
- const decoded = decodeBlock(block.data, block.type, timestampScale, timestamp);
-
- allBlocks.push(decoded);
- });
- });
-
- return {tracks, blocks: allBlocks};
-};
diff --git a/node_modules/@videojs/vhs-utils/src/format-parser.js b/node_modules/@videojs/vhs-utils/src/format-parser.js
deleted file mode 100644
index 96fef04..0000000
--- a/node_modules/@videojs/vhs-utils/src/format-parser.js
+++ /dev/null
@@ -1,338 +0,0 @@
-import {bytesToString, toUint8, toHexString, bytesMatch} from './byte-helpers.js';
-import {parseTracks as parseEbmlTracks} from './ebml-helpers.js';
-import {parseTracks as parseMp4Tracks} from './mp4-helpers.js';
-import {findFourCC} from './riff-helpers.js';
-import {getPages} from './ogg-helpers.js';
-import {detectContainerForBytes} from './containers.js';
-import {findH264Nal, findH265Nal} from './nal-helpers.js';
-import {parseTs} from './m2ts-helpers.js';
-import {getAvcCodec, getHvcCodec} from './codec-helpers.js';
-import {getId3Offset} from './id3-helpers.js';
-
-// https://docs.microsoft.com/en-us/windows/win32/medfound/audio-subtype-guids
-// https://tools.ietf.org/html/rfc2361
-const wFormatTagCodec = function(wFormatTag) {
- wFormatTag = toUint8(wFormatTag);
-
- if (bytesMatch(wFormatTag, [0x00, 0x55])) {
- return 'mp3';
- } else if (bytesMatch(wFormatTag, [0x16, 0x00]) || bytesMatch(wFormatTag, [0x00, 0xFF])) {
- return 'aac';
- } else if (bytesMatch(wFormatTag, [0x70, 0x4f])) {
- return 'opus';
- } else if (bytesMatch(wFormatTag, [0x6C, 0x61])) {
- return 'alac';
- } else if (bytesMatch(wFormatTag, [0xF1, 0xAC])) {
- return 'flac';
- } else if (bytesMatch(wFormatTag, [0x20, 0x00])) {
- return 'ac-3';
- } else if (bytesMatch(wFormatTag, [0xFF, 0xFE])) {
- return 'ec-3';
- } else if (bytesMatch(wFormatTag, [0x00, 0x50])) {
- return 'mp2';
- } else if (bytesMatch(wFormatTag, [0x56, 0x6f])) {
- return 'vorbis';
- } else if (bytesMatch(wFormatTag, [0xA1, 0x09])) {
- return 'speex';
- }
-
- return '';
-};
-
-const formatMimetype = (name, codecs) => {
- const codecString = ['video', 'audio'].reduce((acc, type) => {
- if (codecs[type]) {
- acc += (acc.length ? ',' : '') + codecs[type];
- }
-
- return acc;
- }, '');
-
- return `${(codecs.video ? 'video' : 'audio')}/${name}${codecString ? `;codecs="${codecString}"` : ''}`;
-};
-
-const parseCodecFrom = {
- mov(bytes) {
- // mov and mp4 both use a nearly identical box structure.
- const retval = parseCodecFrom.mp4(bytes);
-
- if (retval.mimetype) {
- retval.mimetype = retval.mimetype.replace('mp4', 'quicktime');
- }
-
- return retval;
- },
- mp4(bytes) {
- bytes = toUint8(bytes);
- const codecs = {};
- const tracks = parseMp4Tracks(bytes);
-
- for (let i = 0; i < tracks.length; i++) {
- const track = tracks[i];
-
- if (track.type === 'audio' && !codecs.audio) {
- codecs.audio = track.codec;
- }
-
- if (track.type === 'video' && !codecs.video) {
- codecs.video = track.codec;
- }
- }
-
- return {codecs, mimetype: formatMimetype('mp4', codecs)};
- },
- '3gp'(bytes) {
- return {codecs: {}, mimetype: 'video/3gpp'};
- },
- ogg(bytes) {
- const pages = getPages(bytes, 0, 4);
- const codecs = {};
-
- pages.forEach(function(page) {
- if (bytesMatch(page, [0x4F, 0x70, 0x75, 0x73], {offset: 28})) {
- codecs.audio = 'opus';
- } else if (bytesMatch(page, [0x56, 0x50, 0x38, 0x30], {offset: 29})) {
- codecs.video = 'vp8';
- } else if (bytesMatch(page, [0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {offset: 29})) {
- codecs.video = 'theora';
- } else if (bytesMatch(page, [0x46, 0x4C, 0x41, 0x43], {offset: 29})) {
- codecs.audio = 'flac';
- } else if (bytesMatch(page, [0x53, 0x70, 0x65, 0x65, 0x78], {offset: 28})) {
- codecs.audio = 'speex';
- } else if (bytesMatch(page, [0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {offset: 29})) {
- codecs.audio = 'vorbis';
- }
- });
-
- return {codecs, mimetype: formatMimetype('ogg', codecs)};
- },
- wav(bytes) {
- const format = findFourCC(bytes, ['WAVE', 'fmt'])[0];
- const wFormatTag = Array.prototype.slice.call(format, 0, 2).reverse();
- let mimetype = 'audio/vnd.wave';
- const codecs = {
- audio: wFormatTagCodec(wFormatTag)
- };
-
- const codecString = wFormatTag.reduce(function(acc, v) {
- if (v) {
- acc += toHexString(v);
- }
- return acc;
- }, '');
-
- if (codecString) {
- mimetype += `;codec=${codecString}`;
- }
-
- if (codecString && !codecs.audio) {
- codecs.audio = codecString;
- }
-
- return {codecs, mimetype};
- },
- avi(bytes) {
- const movi = findFourCC(bytes, ['AVI', 'movi'])[0];
- const strls = findFourCC(bytes, ['AVI', 'hdrl', 'strl']);
- const codecs = {};
-
- strls.forEach(function(strl) {
- const strh = findFourCC(strl, ['strh'])[0];
- const strf = findFourCC(strl, ['strf'])[0];
-
- // now parse AVIStreamHeader to get codec and type:
- // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/api/avifmt/ns-avifmt-avistreamheader
- const type = bytesToString(strh.subarray(0, 4));
- let codec;
- let codecType;
-
- if (type === 'vids') {
- // https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader
- const handler = bytesToString(strh.subarray(4, 8));
- const compression = bytesToString(strf.subarray(16, 20));
- // look for 00dc (compressed video fourcc code) or 00db (uncompressed video fourcc code)
- const videoData = findFourCC(movi, ['00dc'])[0] || findFourCC(movi, ['00db'][0]);
-
- if (handler === 'H264' || compression === 'H264') {
- if (videoData && videoData.length) {
- codec = parseCodecFrom.h264(videoData).codecs.video;
- } else {
- codec = 'avc1';
- }
- } else if (handler === 'HEVC' || compression === 'HEVC') {
- if (videoData && videoData.length) {
- codec = parseCodecFrom.h265(videoData).codecs.video;
- } else {
- codec = 'hev1';
- }
- } else if (handler === 'FMP4' || compression === 'FMP4') {
- if (movi.length) {
- codec = 'mp4v.20.' + movi[12].toString();
- } else {
- codec = 'mp4v.20';
- }
- } else if (handler === 'VP80' || compression === 'VP80') {
- codec = 'vp8';
- } else if (handler === 'VP90' || compression === 'VP90') {
- codec = 'vp9';
- } else if (handler === 'AV01' || compression === 'AV01') {
- codec = 'av01';
- } else if (handler === 'theo' || compression === 'theora') {
- codec = 'theora';
- } else {
- if (videoData && videoData.length) {
- const result = detectContainerForBytes(videoData);
-
- if (result === 'h264') {
- codec = parseCodecFrom.h264(movi).codecs.video;
- }
- if (result === 'h265') {
- codec = parseCodecFrom.h265(movi).codecs.video;
- }
- }
-
- if (!codec) {
- codec = handler || compression;
- }
- }
-
- codecType = 'video';
- } else if (type === 'auds') {
- codecType = 'audio';
- // look for 00wb (audio data fourcc)
- // const audioData = findFourCC(movi, ['01wb']);
- const wFormatTag = Array.prototype.slice.call(strf, 0, 2).reverse();
-
- codecs.audio = wFormatTagCodec(wFormatTag);
-
- } else {
- return;
- }
-
- if (codec) {
- codecs[codecType] = codec;
- }
- });
-
- return {codecs, mimetype: formatMimetype('avi', codecs)};
- },
-
- ts(bytes) {
- const result = parseTs(bytes, 2);
- const codecs = {};
-
- Object.keys(result.streams).forEach(function(esPid) {
- const stream = result.streams[esPid];
-
- if (stream.codec === 'avc1' && stream.packets.length) {
- stream.codec = parseCodecFrom.h264(stream.packets[0]).codecs.video;
- } else if (stream.codec === 'hev1' && stream.packets.length) {
- stream.codec = parseCodecFrom.h265(stream.packets[0]).codecs.video;
- }
-
- codecs[stream.type] = stream.codec;
- });
-
- return {codecs, mimetype: formatMimetype('mp2t', codecs)};
- },
- webm(bytes) {
- // mkv and webm both use ebml to store code info
- const retval = parseCodecFrom.mkv(bytes);
-
- if (retval.mimetype) {
- retval.mimetype = retval.mimetype.replace('x-matroska', 'webm');
- }
-
- return retval;
- },
- mkv(bytes) {
- const codecs = {};
- const tracks = parseEbmlTracks(bytes);
-
- for (let i = 0; i < tracks.length; i++) {
- const track = tracks[i];
-
- if (track.type === 'audio' && !codecs.audio) {
- codecs.audio = track.codec;
- }
-
- if (track.type === 'video' && !codecs.video) {
- codecs.video = track.codec;
- }
- }
-
- return {codecs, mimetype: formatMimetype('x-matroska', codecs)};
- },
- aac(bytes) {
- return {codecs: {audio: 'aac'}, mimetype: 'audio/aac'};
- },
- ac3(bytes) {
- // past id3 and syncword
- const offset = getId3Offset(bytes) + 2;
- // default to ac-3
- let codec = 'ac-3';
-
- if (bytesMatch(bytes, [0xB8, 0xE0], {offset})) {
- codec = 'ac-3';
- // 0x01, 0x7F
- } else if (bytesMatch(bytes, [0x01, 0x7f], {offset})) {
- codec = 'ec-3';
- }
- return {codecs: {audio: codec}, mimetype: 'audio/vnd.dolby.dd-raw'};
- },
- mp3(bytes) {
- return {codecs: {audio: 'mp3'}, mimetype: 'audio/mpeg'};
- },
- flac(bytes) {
- return {codecs: {audio: 'flac'}, mimetype: 'audio/flac'};
- },
- 'h264'(bytes) {
- // find seq_parameter_set_rbsp to get encoding settings for codec
- const nal = findH264Nal(bytes, 7, 3);
- const retval = {codecs: {video: 'avc1'}, mimetype: 'video/h264'};
-
- if (nal.length) {
- retval.codecs.video += `.${getAvcCodec(nal)}`;
- }
-
- return retval;
- },
- 'h265'(bytes) {
- const retval = {codecs: {video: 'hev1'}, mimetype: 'video/h265'};
-
- // find video_parameter_set_rbsp or seq_parameter_set_rbsp
- // to get encoding settings for codec
- const nal = findH265Nal(bytes, [32, 33], 3);
-
- if (nal.length) {
- const type = (nal[0] >> 1) & 0x3F;
-
- // profile_tier_level starts at byte 5 for video_parameter_set_rbsp
- // byte 2 for seq_parameter_set_rbsp
- retval.codecs.video += `.${getHvcCodec(nal.subarray(type === 32 ? 5 : 2))}`;
- }
-
- return retval;
- }
-};
-
-export const parseFormatForBytes = (bytes) => {
- bytes = toUint8(bytes);
- const result = {
- codecs: {},
- container: detectContainerForBytes(bytes),
- mimetype: ''
- };
-
- const parseCodecFn = parseCodecFrom[result.container];
-
- if (parseCodecFn) {
- const parsed = parseCodecFn ? parseCodecFn(bytes) : {};
-
- result.codecs = parsed.codecs || {};
- result.mimetype = parsed.mimetype || '';
- }
-
- return result;
-};
-
diff --git a/node_modules/@videojs/vhs-utils/src/id3-helpers.js b/node_modules/@videojs/vhs-utils/src/id3-helpers.js
deleted file mode 100644
index 95f2a72..0000000
--- a/node_modules/@videojs/vhs-utils/src/id3-helpers.js
+++ /dev/null
@@ -1,35 +0,0 @@
-import {toUint8, bytesMatch} from './byte-helpers.js';
-const ID3 = toUint8([0x49, 0x44, 0x33]);
-
-export const getId3Size = function(bytes, offset = 0) {
- bytes = toUint8(bytes);
-
- const flags = bytes[offset + 5];
- const returnSize = (bytes[offset + 6] << 21) |
- (bytes[offset + 7] << 14) |
- (bytes[offset + 8] << 7) |
- (bytes[offset + 9]);
- const footerPresent = (flags & 16) >> 4;
-
- if (footerPresent) {
- return returnSize + 20;
- }
-
- return returnSize + 10;
-};
-
-export const getId3Offset = function(bytes, offset = 0) {
- bytes = toUint8(bytes);
-
- if ((bytes.length - offset) < 10 || !bytesMatch(bytes, ID3, {offset})) {
- return offset;
- }
-
- offset += getId3Size(bytes, offset);
-
- // recursive check for id3 tags as some files
- // have multiple ID3 tag sections even though
- // they should not.
- return getId3Offset(bytes, offset);
-};
-
diff --git a/node_modules/@videojs/vhs-utils/src/index.js b/node_modules/@videojs/vhs-utils/src/index.js
deleted file mode 100644
index f491489..0000000
--- a/node_modules/@videojs/vhs-utils/src/index.js
+++ /dev/null
@@ -1,17 +0,0 @@
-import * as codecs from './codecs';
-import * as byteHelpers from './byte-helpers.js';
-import * as containers from './containers.js';
-import decodeB64ToUint8Array from './decode-b64-to-uint8-array.js';
-import * as mediaGroups from './media-groups.js';
-import resolveUrl from './resolve-url.js';
-import Stream from './stream.js';
-
-export default {
- codecs,
- byteHelpers,
- containers,
- decodeB64ToUint8Array,
- mediaGroups,
- resolveUrl,
- Stream
-};
diff --git a/node_modules/@videojs/vhs-utils/src/m2ts-helpers.js b/node_modules/@videojs/vhs-utils/src/m2ts-helpers.js
deleted file mode 100644
index 038dea4..0000000
--- a/node_modules/@videojs/vhs-utils/src/m2ts-helpers.js
+++ /dev/null
@@ -1,101 +0,0 @@
-import {bytesMatch, toUint8} from './byte-helpers.js';
-const SYNC_BYTE = 0x47;
-
-export const parseTs = function(bytes, maxPes = Infinity) {
- bytes = toUint8(bytes);
-
- let startIndex = 0;
- let endIndex = 188;
- const pmt = {};
- let pesCount = 0;
-
- while (endIndex < bytes.byteLength && pesCount < maxPes) {
- if (bytes[startIndex] !== SYNC_BYTE && bytes[endIndex] !== SYNC_BYTE) {
- endIndex += 1;
- startIndex += 1;
- continue;
- }
- const packet = bytes.subarray(startIndex, endIndex);
- const pid = (((packet[1] & 0x1f) << 8) | packet[2]);
- const hasPusi = !!(packet[1] & 0x40);
- const hasAdaptationHeader = (((packet[3] & 0x30) >>> 4) > 0x01);
- let payloadOffset = 4 + (hasAdaptationHeader ? (packet[4] + 1) : 0);
-
- if (hasPusi) {
- payloadOffset += packet[payloadOffset] + 1;
- }
-
- if (pid === 0 && !pmt.pid) {
- pmt.pid = (packet[payloadOffset + 10] & 0x1f) << 8 | packet[payloadOffset + 11];
- } else if (pmt.pid && pid === pmt.pid && !pmt.streams) {
- const isNotForward = packet[payloadOffset + 5] & 0x01;
-
- // ignore forward pmt delarations
- if (!isNotForward) {
- continue;
- }
- pmt.streams = {};
-
- const sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
- const tableEnd = 3 + sectionLength - 4;
- const programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11];
- let offset = 12 + programInfoLength;
-
- while (offset < tableEnd) {
- // add an entry that maps the elementary_pid to the stream_type
- const i = payloadOffset + offset;
- const type = packet[i];
- const esPid = (packet[i + 1] & 0x1F) << 8 | packet[i + 2];
- const esLength = ((packet[i + 3] & 0x0f) << 8 | (packet[i + 4]));
- const esInfo = packet.subarray(i + 5, i + 5 + esLength);
- const stream = pmt.streams[esPid] = {
- esInfo,
- typeNumber: type,
- packets: [],
- type: '',
- codec: ''
- };
-
- if (type === 0x06 && bytesMatch(esInfo, [0x4F, 0x70, 0x75, 0x73], {offset: 2})) {
- stream.type = 'audio';
- stream.codec = 'opus';
- } else if (type === 0x1B || type === 0x20) {
- stream.type = 'video';
- stream.codec = 'avc1';
- } else if (type === 0x24) {
- stream.type = 'video';
- stream.codec = 'hev1';
- } else if (type === 0x10) {
- stream.type = 'video';
- stream.codec = 'mp4v.20';
- } else if (type === 0x0F) {
- stream.type = 'audio';
- stream.codec = 'aac';
- } else if (type === 0x81) {
- stream.type = 'audio';
- stream.codec = 'ac-3';
- } else if (type === 0x87) {
- stream.type = 'audio';
- stream.codec = 'ec-3';
- } else if (type === 0x03 || type === 0x04) {
- stream.type = 'audio';
- stream.codec = 'mp3';
- }
-
- offset += esLength + 5;
- }
- } else if (pmt.pid && pmt.streams) {
- pmt.streams[pid].packets.push(packet.subarray(payloadOffset));
- pesCount++;
- }
-
- startIndex += 188;
- endIndex += 188;
- }
-
- if (!pmt.streams) {
- pmt.streams = {};
- }
-
- return pmt;
-};
diff --git a/node_modules/@videojs/vhs-utils/src/media-groups.js b/node_modules/@videojs/vhs-utils/src/media-groups.js
deleted file mode 100644
index 3cbc903..0000000
--- a/node_modules/@videojs/vhs-utils/src/media-groups.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * Loops through all supported media groups in master and calls the provided
- * callback for each group
- *
- * @param {Object} master
- * The parsed master manifest object
- * @param {string[]} groups
- * The media groups to call the callback for
- * @param {Function} callback
- * Callback to call for each media group
- */
-export const forEachMediaGroup = (master, groups, callback) => {
- groups.forEach((mediaType) => {
- for (const groupKey in master.mediaGroups[mediaType]) {
- for (const labelKey in master.mediaGroups[mediaType][groupKey]) {
- const mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
-
- callback(mediaProperties, mediaType, groupKey, labelKey);
- }
- }
- });
-};
diff --git a/node_modules/@videojs/vhs-utils/src/media-types.js b/node_modules/@videojs/vhs-utils/src/media-types.js
deleted file mode 100644
index 148f241..0000000
--- a/node_modules/@videojs/vhs-utils/src/media-types.js
+++ /dev/null
@@ -1,36 +0,0 @@
-const MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
-const DASH_REGEX = /^application\/dash\+xml/i;
-
-/**
- * Returns a string that describes the type of source based on a video source object's
- * media type.
- *
- * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
- *
- * @param {string} type
- * Video source object media type
- * @return {('hls'|'dash'|'vhs-json'|null)}
- * VHS source type string
- */
-export const simpleTypeFromSourceType = (type) => {
- if (MPEGURL_REGEX.test(type)) {
- return 'hls';
- }
-
- if (DASH_REGEX.test(type)) {
- return 'dash';
- }
-
- // Denotes the special case of a manifest object passed to http-streaming instead of a
- // source URL.
- //
- // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
- //
- // In this case, vnd stands for vendor, video.js for the organization, VHS for this
- // project, and the +json suffix identifies the structure of the media type.
- if (type === 'application/vnd.videojs.vhs+json') {
- return 'vhs-json';
- }
-
- return null;
-};
diff --git a/node_modules/@videojs/vhs-utils/src/mp4-helpers.js b/node_modules/@videojs/vhs-utils/src/mp4-helpers.js
deleted file mode 100644
index 2b100f5..0000000
--- a/node_modules/@videojs/vhs-utils/src/mp4-helpers.js
+++ /dev/null
@@ -1,564 +0,0 @@
-import {
- stringToBytes,
- toUint8,
- bytesMatch,
- bytesToString,
- toHexString,
- padStart,
- bytesToNumber
-} from './byte-helpers.js';
-import {getAvcCodec, getHvcCodec, getAv1Codec} from './codec-helpers.js';
-import {parseOpusHead} from './opus-helpers.js';
-
-const normalizePath = function(path) {
- if (typeof path === 'string') {
- return stringToBytes(path);
- }
-
- if (typeof path === 'number') {
- return path;
- }
-
- return path;
-};
-
-const normalizePaths = function(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map((p) => normalizePath(p));
-};
-
-let DESCRIPTORS;
-
-export const parseDescriptors = function(bytes) {
- bytes = toUint8(bytes);
- const results = [];
- let i = 0;
-
- while (bytes.length > i) {
- const tag = bytes[i];
- let size = 0;
- let headerSize = 0;
-
- // tag
- headerSize++;
-
- let byte = bytes[headerSize];
-
- // first byte
- headerSize++;
-
- while (byte & 0x80) {
- size = (byte & 0x7F) << 7;
- byte = bytes[headerSize];
- headerSize++;
- }
-
- size += byte & 0x7F;
-
- for (let z = 0; z < DESCRIPTORS.length; z++) {
- const {id, parser} = DESCRIPTORS[z];
-
- if (tag === id) {
- results.push(parser(bytes.subarray(headerSize, headerSize + size)));
- break;
- }
- }
-
- i += size + headerSize;
- }
-
- return results;
-
-};
-
-DESCRIPTORS = [
- {id: 0x03, parser(bytes) {
- const desc = {
- tag: 0x03,
- id: bytes[0] << 8 | bytes[1],
- flags: bytes[2],
- size: 3,
- dependsOnEsId: 0,
- ocrEsId: 0,
- descriptors: [],
- url: ''
- };
-
- // depends on es id
- if (desc.flags & 0x80) {
- desc.dependsOnEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];
- desc.size += 2;
- }
-
- // url
- if (desc.flags & 0x40) {
- const len = bytes[desc.size];
-
- desc.url = bytesToString(bytes.subarray(desc.size + 1, desc.size + 1 + len));
-
- desc.size += len;
- }
-
- // ocr es id
- if (desc.flags & 0x20) {
- desc.ocrEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];
- desc.size += 2;
- }
-
- desc.descriptors = parseDescriptors(bytes.subarray(desc.size)) || [];
-
- return desc;
- }},
- {id: 0x04, parser(bytes) {
- // DecoderConfigDescriptor
- const desc = {
- tag: 0x04,
- oti: bytes[0],
- streamType: bytes[1],
- bufferSize: bytes[2] << 16 | bytes [3] << 8 | bytes[4],
- maxBitrate: bytes[5] << 24 | bytes[6] << 16 | bytes [7] << 8 | bytes[8],
- avgBitrate: bytes[9] << 24 | bytes[10] << 16 | bytes [11] << 8 | bytes[12],
- descriptors: parseDescriptors(bytes.subarray(13))
- };
-
- return desc;
- }},
- {id: 0x05, parser(bytes) {
- // DecoderSpecificInfo
-
- return {tag: 0x05, bytes};
- }},
- {id: 0x06, parser(bytes) {
- // SLConfigDescriptor
-
- return {tag: 0x06, bytes};
- }}
-];
-
-/**
- * find any number of boxes by name given a path to it in an iso bmff
- * such as mp4.
- *
- * @param {TypedArray} bytes
- * bytes for the iso bmff to search for boxes in
- *
- * @param {Uint8Array[]|string[]|string|Uint8Array} name
- * An array of paths or a single path representing the name
- * of boxes to search through in bytes. Paths may be
- * uint8 (character codes) or strings.
- *
- * @param {boolean} [complete=false]
- * Should we search only for complete boxes on the final path.
- * This is very useful when you do not want to get back partial boxes
- * in the case of streaming files.
- *
- * @return {Uint8Array[]}
- * An array of the end paths that we found.
- */
-export const findBox = function(bytes, paths, complete = false) {
- paths = normalizePaths(paths);
- bytes = toUint8(bytes);
-
- const results = [];
-
- if (!paths.length) {
- // short-circuit the search for empty paths
- return results;
- }
- let i = 0;
-
- while (i < bytes.length) {
- const size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
- const type = bytes.subarray(i + 4, i + 8);
-
- // invalid box format.
- if (size === 0) {
- break;
- }
- let end = i + size;
-
- if (end > bytes.length) {
- // this box is bigger than the number of bytes we have
- // and complete is set, we cannot find any more boxes.
- if (complete) {
- break;
- }
-
- end = bytes.length;
- }
-
- const data = bytes.subarray(i + 8, end);
-
- if (bytesMatch(type, paths[0])) {
- if (paths.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next box along the path
- results.push.apply(results, findBox(data, paths.slice(1), complete));
- }
- }
-
- i = end;
- }
-
- // we've finished searching all of bytes
- return results;
-};
-
-/**
- * Search for a single matching box by name in an iso bmff format like
- * mp4. This function is useful for finding codec boxes which
- * can be placed arbitrarily in sample descriptions depending
- * on the version of the file or file type.
- *
- * @param {TypedArray} bytes
- * bytes for the iso bmff to search for boxes in
- *
- * @param {string|Uint8Array} name
- * The name of the box to find.
- *
- * @return {Uint8Array[]}
- * a subarray of bytes representing the name boxed we found.
- */
-export const findNamedBox = function(bytes, name) {
- name = normalizePath(name);
-
- if (!name.length) {
- // short-circuit the search for empty paths
- return bytes.subarray(bytes.length);
- }
-
- let i = 0;
-
- while (i < bytes.length) {
- if (bytesMatch(bytes.subarray(i, i + name.length), name)) {
- const size = (bytes[i - 4] << 24 | bytes[i - 3] << 16 | bytes[i - 2] << 8 | bytes[i - 1]) >>> 0;
- const end = size > 1 ? i + size : bytes.byteLength;
-
- return bytes.subarray(i + 4, end);
- }
-
- i++;
- }
-
- // we've finished searching all of bytes
- return bytes.subarray(bytes.length);
-};
-
-const parseSamples = function(data, entrySize = 4, parseEntry = (d) => bytesToNumber(d)) {
- const entries = [];
-
- if (!data || !data.length) {
- return entries;
- }
-
- let entryCount = bytesToNumber(data.subarray(4, 8));
-
- for (let i = 8; entryCount; i += entrySize, entryCount--) {
- entries.push(parseEntry(data.subarray(i, i + entrySize)));
- }
-
- return entries;
-};
-
-export const buildFrameTable = function(stbl, timescale) {
- const keySamples = parseSamples(findBox(stbl, ['stss'])[0]);
- const chunkOffsets = parseSamples(findBox(stbl, ['stco'])[0]);
- const timeToSamples = parseSamples(findBox(stbl, ['stts'])[0], 8, (entry) => ({
- sampleCount: bytesToNumber(entry.subarray(0, 4)),
- sampleDelta: bytesToNumber(entry.subarray(4, 8))
- }));
- const samplesToChunks = parseSamples(findBox(stbl, ['stsc'])[0], 12, (entry) => ({
- firstChunk: bytesToNumber(entry.subarray(0, 4)),
- samplesPerChunk: bytesToNumber(entry.subarray(4, 8)),
- sampleDescriptionIndex: bytesToNumber(entry.subarray(8, 12))
- }));
-
- const stsz = findBox(stbl, ['stsz'])[0];
-
- // stsz starts with a 4 byte sampleSize which we don't need
- const sampleSizes = parseSamples(stsz && stsz.length && stsz.subarray(4) || null);
- const frames = [];
-
- for (let chunkIndex = 0; chunkIndex < chunkOffsets.length; chunkIndex++) {
- let samplesInChunk;
-
- for (let i = 0; i < samplesToChunks.length; i++) {
- const sampleToChunk = samplesToChunks[i];
- const isThisOne = (chunkIndex + 1) >= sampleToChunk.firstChunk &&
- (i + 1 >= samplesToChunks.length || (chunkIndex + 1) < samplesToChunks[i + 1].firstChunk);
-
- if (isThisOne) {
- samplesInChunk = sampleToChunk.samplesPerChunk;
- break;
- }
- }
-
- let chunkOffset = chunkOffsets[chunkIndex];
-
- for (let i = 0; i < samplesInChunk; i++) {
- const frameEnd = sampleSizes[frames.length];
-
- // if we don't have key samples every frame is a keyframe
- let keyframe = !keySamples.length;
-
- if (keySamples.length && keySamples.indexOf(frames.length + 1) !== -1) {
- keyframe = true;
- }
-
- const frame = {
- keyframe,
- start: chunkOffset,
- end: chunkOffset + frameEnd
- };
-
- for (let k = 0; k < timeToSamples.length; k++) {
- const {sampleCount, sampleDelta} = timeToSamples[k];
-
- if ((frames.length) <= sampleCount) {
- // ms to ns
- const lastTimestamp = frames.length ? frames[frames.length - 1].timestamp : 0;
-
- frame.timestamp = lastTimestamp + ((sampleDelta / timescale) * 1000);
- frame.duration = sampleDelta;
- break;
- }
- }
-
- frames.push(frame);
-
- chunkOffset += frameEnd;
- }
- }
-
- return frames;
-};
-
-export const addSampleDescription = function(track, bytes) {
- let codec = bytesToString(bytes.subarray(0, 4));
-
- if (track.type === 'video') {
- track.info = track.info || {};
- track.info.width = bytes[28] << 8 | bytes[29];
- track.info.height = bytes[30] << 8 | bytes[31];
- } else if (track.type === 'audio') {
- track.info = track.info || {};
- track.info.channels = bytes[20] << 8 | bytes[21];
- track.info.bitDepth = bytes[22] << 8 | bytes[23];
- track.info.sampleRate = bytes[28] << 8 | bytes[29];
- }
-
- if (codec === 'avc1') {
- const avcC = findNamedBox(bytes, 'avcC');
-
- // AVCDecoderConfigurationRecord
- codec += `.${getAvcCodec(avcC)}`;
- track.info.avcC = avcC;
- // TODO: do we need to parse all this?
- /* {
- configurationVersion: avcC[0],
- profile: avcC[1],
- profileCompatibility: avcC[2],
- level: avcC[3],
- lengthSizeMinusOne: avcC[4] & 0x3
- };
-
- let spsNalUnitCount = avcC[5] & 0x1F;
- const spsNalUnits = track.info.avc.spsNalUnits = [];
-
- // past spsNalUnitCount
- let offset = 6;
-
- while (spsNalUnitCount--) {
- const nalLen = avcC[offset] << 8 | avcC[offset + 1];
-
- spsNalUnits.push(avcC.subarray(offset + 2, offset + 2 + nalLen));
-
- offset += nalLen + 2;
- }
- let ppsNalUnitCount = avcC[offset];
- const ppsNalUnits = track.info.avc.ppsNalUnits = [];
-
- // past ppsNalUnitCount
- offset += 1;
-
- while (ppsNalUnitCount--) {
- const nalLen = avcC[offset] << 8 | avcC[offset + 1];
-
- ppsNalUnits.push(avcC.subarray(offset + 2, offset + 2 + nalLen));
-
- offset += nalLen + 2;
- }*/
-
- // HEVCDecoderConfigurationRecord
- } else if (codec === 'hvc1' || codec === 'hev1') {
- codec += `.${getHvcCodec(findNamedBox(bytes, 'hvcC'))}`;
- } else if (codec === 'mp4a' || codec === 'mp4v') {
- const esds = findNamedBox(bytes, 'esds');
- const esDescriptor = parseDescriptors(esds.subarray(4))[0];
- const decoderConfig = esDescriptor && esDescriptor.descriptors.filter(({tag}) => tag === 0x04)[0];
-
- if (decoderConfig) {
- // most codecs do not have a further '.'
- // such as 0xa5 for ac-3 and 0xa6 for e-ac-3
- codec += '.' + toHexString(decoderConfig.oti);
- if (decoderConfig.oti === 0x40) {
- codec += '.' + (decoderConfig.descriptors[0].bytes[0] >> 3).toString();
- } else if (decoderConfig.oti === 0x20) {
- codec += '.' + (decoderConfig.descriptors[0].bytes[4]).toString();
- } else if (decoderConfig.oti === 0xdd) {
- codec = 'vorbis';
- }
- } else if (track.type === 'audio') {
- codec += '.40.2';
- } else {
- codec += '.20.9';
- }
- } else if (codec === 'av01') {
- // AV1DecoderConfigurationRecord
- codec += `.${getAv1Codec(findNamedBox(bytes, 'av1C'))}`;
- } else if (codec === 'vp09') {
- // VPCodecConfigurationRecord
- const vpcC = findNamedBox(bytes, 'vpcC');
-
- // https://www.webmproject.org/vp9/mp4/
- const profile = vpcC[0];
- const level = vpcC[1];
- const bitDepth = vpcC[2] >> 4;
- const chromaSubsampling = (vpcC[2] & 0x0F) >> 1;
- const videoFullRangeFlag = (vpcC[2] & 0x0F) >> 3;
- const colourPrimaries = vpcC[3];
- const transferCharacteristics = vpcC[4];
- const matrixCoefficients = vpcC[5];
-
- codec += `.${padStart(profile, 2, '0')}`;
- codec += `.${padStart(level, 2, '0')}`;
- codec += `.${padStart(bitDepth, 2, '0')}`;
- codec += `.${padStart(chromaSubsampling, 2, '0')}`;
- codec += `.${padStart(colourPrimaries, 2, '0')}`;
- codec += `.${padStart(transferCharacteristics, 2, '0')}`;
- codec += `.${padStart(matrixCoefficients, 2, '0')}`;
- codec += `.${padStart(videoFullRangeFlag, 2, '0')}`;
- } else if (codec === 'theo') {
- codec = 'theora';
- } else if (codec === 'spex') {
- codec = 'speex';
- } else if (codec === '.mp3') {
- codec = 'mp4a.40.34';
- } else if (codec === 'msVo') {
- codec = 'vorbis';
- } else if (codec === 'Opus') {
- codec = 'opus';
- const dOps = findNamedBox(bytes, 'dOps');
-
- track.info.opus = parseOpusHead(dOps);
-
- // TODO: should this go into the webm code??
- // Firefox requires a codecDelay for opus playback
- // see https://bugzilla.mozilla.org/show_bug.cgi?id=1276238
- track.info.codecDelay = 6500000;
- } else {
- codec = codec.toLowerCase();
- }
- /* eslint-enable */
- // flac, ac-3, ec-3, opus
- track.codec = codec;
-};
-
-export const parseTracks = function(bytes, frameTable = true) {
- bytes = toUint8(bytes);
-
- const traks = findBox(bytes, ['moov', 'trak'], true);
- const tracks = [];
-
- traks.forEach(function(trak) {
- const track = {bytes: trak};
- const mdia = findBox(trak, ['mdia'])[0];
-
- const hdlr = findBox(mdia, ['hdlr'])[0];
- const trakType = bytesToString(hdlr.subarray(8, 12));
-
- if (trakType === 'soun') {
- track.type = 'audio';
- } else if (trakType === 'vide') {
- track.type = 'video';
- } else {
- track.type = trakType;
- }
-
- const tkhd = findBox(trak, ['tkhd'])[0];
-
- if (tkhd) {
- const view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
- const tkhdVersion = view.getUint8(0);
-
- track.number = (tkhdVersion === 0) ? view.getUint32(12) : view.getUint32(20);
- }
-
- const mdhd = findBox(mdia, ['mdhd'])[0];
-
- if (mdhd) {
- // mdhd is a FullBox, meaning it will have its own version as the first byte
- const version = mdhd[0];
- const index = version === 0 ? 12 : 20;
-
- track.timescale = (
- mdhd[index] << 24 |
- mdhd[index + 1] << 16 |
- mdhd[index + 2] << 8 |
- mdhd[index + 3]
- ) >>> 0;
- }
-
- const stbl = findBox(mdia, ['minf', 'stbl'])[0];
- const stsd = findBox(stbl, ['stsd'])[0];
- let descriptionCount = bytesToNumber(stsd.subarray(4, 8));
- let offset = 8;
-
- // add codec and codec info
- while (descriptionCount--) {
- const len = bytesToNumber(stsd.subarray(offset, offset + 4));
- const sampleDescriptor = stsd.subarray(offset + 4, offset + 4 + len);
-
- addSampleDescription(track, sampleDescriptor);
-
- offset += 4 + len;
- }
-
- if (frameTable) {
- track.frameTable = buildFrameTable(stbl, track.timescale);
- }
-
- // codec has no sub parameters
- tracks.push(track);
- });
-
- return tracks;
-};
-
-export const parseMediaInfo = function(bytes) {
- const mvhd = findBox(bytes, ['moov', 'mvhd'], true)[0];
-
- if (!mvhd || !mvhd.length) {
- return;
- }
- const info = {};
-
- // ms to ns
- // mvhd v1 has 8 byte duration and other fields too
- if (mvhd[0] === 1) {
- info.timestampScale = bytesToNumber(mvhd.subarray(20, 24));
- info.duration = bytesToNumber(mvhd.subarray(24, 32));
- } else {
- info.timestampScale = bytesToNumber(mvhd.subarray(12, 16));
- info.duration = bytesToNumber(mvhd.subarray(16, 20));
- }
- info.bytes = mvhd;
-
- return info;
-};
diff --git a/node_modules/@videojs/vhs-utils/src/nal-helpers.js b/node_modules/@videojs/vhs-utils/src/nal-helpers.js
deleted file mode 100644
index af27dc6..0000000
--- a/node_modules/@videojs/vhs-utils/src/nal-helpers.js
+++ /dev/null
@@ -1,109 +0,0 @@
-import {bytesMatch, toUint8} from './byte-helpers.js';
-
-export const NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
-export const NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
-export const EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
-
-/**
- * Expunge any "Emulation Prevention" bytes from a "Raw Byte
- * Sequence Payload"
- *
- * @param data {Uint8Array} the bytes of a RBSP from a NAL
- * unit
- * @return {Uint8Array} the RBSP without any Emulation
- * Prevention Bytes
- */
-export const discardEmulationPreventionBytes = function(bytes) {
- const positions = [];
-
- let i = 1;
-
- // Find all `Emulation Prevention Bytes`
- while (i < bytes.length - 2) {
- if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
- positions.push(i + 2);
- i++;
- }
-
- i++;
- }
-
- // If no Emulation Prevention Bytes were found just return the original
- // array
- if (positions.length === 0) {
- return bytes;
- }
-
- // Create a new array to hold the NAL unit data
- const newLength = bytes.length - positions.length;
- const newData = new Uint8Array(newLength);
- let sourceIndex = 0;
-
- for (i = 0; i < newLength; sourceIndex++, i++) {
- if (sourceIndex === positions[0]) {
- // Skip this byte
- sourceIndex++;
- // Remove this position index
- positions.shift();
- }
- newData[i] = bytes[sourceIndex];
- }
-
- return newData;
-};
-
-export const findNal = function(bytes, dataType, types, nalLimit = Infinity) {
- bytes = toUint8(bytes);
- types = [].concat(types);
-
- let i = 0;
- let nalStart;
- let nalsFound = 0;
-
- // keep searching until:
- // we reach the end of bytes
- // we reach the maximum number of nals they want to seach
- // NOTE: that we disregard nalLimit when we have found the start
- // of the nal we want so that we can find the end of the nal we want.
- while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
- let nalOffset;
-
- if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
- nalOffset = 4;
- } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
- nalOffset = 3;
- }
-
- // we are unsynced,
- // find the next nal unit
- if (!nalOffset) {
- i++;
- continue;
- }
- nalsFound++;
-
- if (nalStart) {
- return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
- }
-
- let nalType;
-
- if (dataType === 'h264') {
- nalType = (bytes[i + nalOffset] & 0x1f);
- } else if (dataType === 'h265') {
- nalType = (bytes[i + nalOffset] >> 1) & 0x3f;
- }
-
- if (types.indexOf(nalType) !== -1) {
- nalStart = i + nalOffset;
- }
-
- // nal header is 1 length for h264, and 2 for h265
- i += nalOffset + (dataType === 'h264' ? 1 : 2);
- }
-
- return bytes.subarray(0, 0);
-};
-
-export const findH264Nal = (bytes, type, nalLimit) => findNal(bytes, 'h264', type, nalLimit);
-export const findH265Nal = (bytes, type, nalLimit) => findNal(bytes, 'h265', type, nalLimit);
diff --git a/node_modules/@videojs/vhs-utils/src/ogg-helpers.js b/node_modules/@videojs/vhs-utils/src/ogg-helpers.js
deleted file mode 100644
index 2868eb8..0000000
--- a/node_modules/@videojs/vhs-utils/src/ogg-helpers.js
+++ /dev/null
@@ -1,27 +0,0 @@
-import {bytesMatch, toUint8} from './byte-helpers';
-
-const SYNC_WORD = toUint8([0x4f, 0x67, 0x67, 0x53]);
-
-export const getPages = function(bytes, start, end = Infinity) {
- bytes = toUint8(bytes);
-
- const pages = [];
- let i = 0;
-
- while (i < bytes.length && pages.length < end) {
- // we are unsynced,
- // find the next syncword
- if (!bytesMatch(bytes, SYNC_WORD, {offset: i})) {
- i++;
- continue;
- }
-
- const segmentLength = bytes[i + 27];
-
- pages.push(bytes.subarray(i, i + 28 + segmentLength));
-
- i += pages[pages.length - 1].length;
- }
-
- return pages.slice(start, end);
-};
diff --git a/node_modules/@videojs/vhs-utils/src/opus-helpers.js b/node_modules/@videojs/vhs-utils/src/opus-helpers.js
deleted file mode 100644
index a5572c4..0000000
--- a/node_modules/@videojs/vhs-utils/src/opus-helpers.js
+++ /dev/null
@@ -1,61 +0,0 @@
-export const OPUS_HEAD = new Uint8Array([
- // O, p, u, s
- 0x4f, 0x70, 0x75, 0x73,
- // H, e, a, d
- 0x48, 0x65, 0x61, 0x64
-]);
-
-// https://wiki.xiph.org/OggOpus
-// https://vfrmaniac.fushizen.eu/contents/opus_in_isobmff.html
-// https://opus-codec.org/docs/opusfile_api-0.7/structOpusHead.html
-export const parseOpusHead = function(bytes) {
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
-
- const version = view.getUint8(0);
- // version 0, from mp4, does not use littleEndian.
- const littleEndian = version !== 0;
-
- const config = {
- version,
- channels: view.getUint8(1),
- preSkip: view.getUint16(2, littleEndian),
- sampleRate: view.getUint32(4, littleEndian),
- outputGain: view.getUint16(8, littleEndian),
- channelMappingFamily: view.getUint8(10)
- };
-
- if (config.channelMappingFamily > 0 && bytes.length > 10) {
- config.streamCount = view.getUint8(11);
- config.twoChannelStreamCount = view.getUint8(12);
- config.channelMapping = [];
-
- for (let c = 0; c < config.channels; c++) {
- config.channelMapping.push(view.getUint8(13 + c));
- }
- }
-
- return config;
-};
-
-export const setOpusHead = function(config) {
- const size = config.channelMappingFamily <= 0 ? 11 : (12 + config.channels);
- const view = new DataView(new ArrayBuffer(size));
- const littleEndian = config.version !== 0;
-
- view.setUint8(0, config.version);
- view.setUint8(1, config.channels);
- view.setUint16(2, config.preSkip, littleEndian);
- view.setUint32(4, config.sampleRate, littleEndian);
- view.setUint16(8, config.outputGain, littleEndian);
- view.setUint8(10, config.channelMappingFamily);
-
- if (config.channelMappingFamily > 0) {
- view.setUint8(11, config.streamCount);
-
- config.channelMapping.foreach(function(cm, i) {
- view.setUint8(12 + i, cm);
- });
- }
-
- return new Uint8Array(view.buffer);
-};
diff --git a/node_modules/@videojs/vhs-utils/src/resolve-url.js b/node_modules/@videojs/vhs-utils/src/resolve-url.js
deleted file mode 100644
index 006b00d..0000000
--- a/node_modules/@videojs/vhs-utils/src/resolve-url.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import URLToolkit from 'url-toolkit';
-import window from 'global/window';
-
-const DEFAULT_LOCATION = 'http://example.com';
-
-const resolveUrl = (baseUrl, relativeUrl) => {
- // return early if we don't need to resolve
- if ((/^[a-z]+:/i).test(relativeUrl)) {
- return relativeUrl;
- }
-
- // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
- if ((/^data:/).test(baseUrl)) {
- baseUrl = window.location && window.location.href || '';
- }
-
- // IE11 supports URL but not the URL constructor
- // feature detect the behavior we want
- const nativeURL = typeof window.URL === 'function';
-
- const protocolLess = (/^\/\//.test(baseUrl));
- // remove location if window.location isn't available (i.e. we're in node)
- // and if baseUrl isn't an absolute url
- const removeLocation = !window.location && !(/\/\//i).test(baseUrl);
-
- // if the base URL is relative then combine with the current location
- if (nativeURL) {
- baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
- } else if (!(/\/\//i).test(baseUrl)) {
- baseUrl = URLToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
- }
-
- if (nativeURL) {
- const newUrl = new URL(relativeUrl, baseUrl);
-
- // if we're a protocol-less url, remove the protocol
- // and if we're location-less, remove the location
- // otherwise, return the url unmodified
- if (removeLocation) {
- return newUrl.href.slice(DEFAULT_LOCATION.length);
- } else if (protocolLess) {
- return newUrl.href.slice(newUrl.protocol.length);
- }
-
- return newUrl.href;
- }
- return URLToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
-
-};
-
-export default resolveUrl;
diff --git a/node_modules/@videojs/vhs-utils/src/riff-helpers.js b/node_modules/@videojs/vhs-utils/src/riff-helpers.js
deleted file mode 100644
index db016a8..0000000
--- a/node_modules/@videojs/vhs-utils/src/riff-helpers.js
+++ /dev/null
@@ -1,75 +0,0 @@
-import {toUint8, stringToBytes, bytesMatch} from './byte-helpers.js';
-
-const CONSTANTS = {
- LIST: toUint8([0x4c, 0x49, 0x53, 0x54]),
- RIFF: toUint8([0x52, 0x49, 0x46, 0x46]),
- WAVE: toUint8([0x57, 0x41, 0x56, 0x45])
-};
-
-const normalizePath = function(path) {
- if (typeof path === 'string') {
- return stringToBytes(path);
- }
-
- if (typeof path === 'number') {
- return path;
- }
-
- return path;
-};
-
-const normalizePaths = function(paths) {
- if (!Array.isArray(paths)) {
- return [normalizePath(paths)];
- }
-
- return paths.map((p) => normalizePath(p));
-};
-
-export const findFourCC = function(bytes, paths) {
- paths = normalizePaths(paths);
- bytes = toUint8(bytes);
-
- let results = [];
-
- if (!paths.length) {
- // short-circuit the search for empty paths
- return results;
- }
-
- let i = 0;
-
- while (i < bytes.length) {
- let type = bytes.subarray(i, i + 4);
- let size = ((bytes[i + 7] << 24 | bytes[i + 6] << 16 | bytes[i + 5] << 8 | bytes[i + 4]) >>> 0);
-
- // skip LIST/RIFF and get the actual type
- if (bytesMatch(type, CONSTANTS.LIST) || bytesMatch(type, CONSTANTS.RIFF) || bytesMatch(type, CONSTANTS.WAVE)) {
- type = bytes.subarray(i + 8, i + 12);
- i += 4;
- size -= 4;
- }
-
- const data = bytes.subarray(i + 8, i + 8 + size);
-
- if (bytesMatch(type, paths[0])) {
- if (paths.length === 1) {
- // this is the end of the path and we've found the box we were
- // looking for
- results.push(data);
- } else {
- // recursively search for the next box along the path
- const subresults = findFourCC(data, paths.slice(1));
-
- if (subresults.length) {
- results = results.concat(subresults);
- }
- }
- }
-
- i += 8 + data.length;
- }
-
- // we've finished searching all of bytes
- return results;
-};
diff --git a/node_modules/@videojs/vhs-utils/src/stream.js b/node_modules/@videojs/vhs-utils/src/stream.js
deleted file mode 100644
index 64f9238..0000000
--- a/node_modules/@videojs/vhs-utils/src/stream.js
+++ /dev/null
@@ -1,108 +0,0 @@
-/**
- * @file stream.js
- */
-/**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
-export default class Stream {
- constructor() {
- this.listeners = {};
- }
-
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
- on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
- this.listeners[type].push(listener);
- }
-
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- const index = this.listeners[type].indexOf(listener);
-
- // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
-
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- trigger(type) {
- const callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- }
-
- // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
- if (arguments.length === 2) {
- const length = callbacks.length;
-
- for (let i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- const args = Array.prototype.slice.call(arguments, 1);
- const length = callbacks.length;
-
- for (let i = 0; i < length; ++i) {
- callbacks[i].apply(this, args);
- }
- }
- }
-
- /**
- * Destroys the stream and cleans up.
- */
- dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- pipe(destination) {
- this.on('data', function(data) {
- destination.push(data);
- });
- }
-}
diff --git a/node_modules/@videojs/vhs-utils/test/byte-helpers.test.js b/node_modules/@videojs/vhs-utils/test/byte-helpers.test.js
deleted file mode 100644
index 2defac2..0000000
--- a/node_modules/@videojs/vhs-utils/test/byte-helpers.test.js
+++ /dev/null
@@ -1,321 +0,0 @@
-import QUnit from 'qunit';
-import {
- bytesToString,
- stringToBytes,
- toUint8,
- concatTypedArrays,
- toHexString,
- toBinaryString,
- bytesToNumber,
- numberToBytes,
- bytesMatch
-} from '../src/byte-helpers.js';
-import window from 'global/window';
-
-const arrayNames = [];
-const BigInt = window.BigInt;
-
-[
- 'Array',
- 'Int8Array',
- 'Uint8Array',
- 'Uint8ClampedArray',
- 'Int16Array',
- 'Uint16Array',
- 'Int32Array',
- 'Uint32Array',
- 'Float32Array',
- 'Float64Array'
-].forEach(function(name) {
- if (window[name]) {
- arrayNames.push(name);
- }
-});
-
-QUnit.module('bytesToString');
-
-const testString = 'hello竜';
-const testBytes = toUint8([
- // h
- 0x68,
- // e
- 0x65,
- // l
- 0x6c,
- // l
- 0x6c,
- // o
- 0x6f,
- // 竜
- 0xe7, 0xab, 0x9c
-]);
-
-const rawBytes = toUint8([0x47, 0x40, 0x00, 0x10, 0x00, 0x00, 0xb0, 0x0d, 0x00, 0x01]);
-
-QUnit.test('should function as expected', function(assert) {
- arrayNames.forEach(function(name) {
- const testObj = name === 'Array' ? testBytes : new window[name](testBytes);
-
- assert.equal(bytesToString(testObj), testString, `testString work as a string arg with ${name}`);
- assert.equal(bytesToString(new window[name]()), '', `empty ${name} returns empty string`);
- });
-
- assert.equal(bytesToString(), '', 'undefined returns empty string');
- assert.equal(bytesToString(null), '', 'null returns empty string');
- assert.equal(bytesToString(stringToBytes(testString)), testString, 'stringToBytes -> bytesToString works');
-});
-
-QUnit.module('stringToBytes');
-
-QUnit.test('should function as expected', function(assert) {
- assert.deepEqual(stringToBytes(testString), testBytes, 'returns an array of bytes');
- assert.deepEqual(stringToBytes(), toUint8(), 'empty array for undefined');
- assert.deepEqual(stringToBytes(null), toUint8(), 'empty array for null');
- assert.deepEqual(stringToBytes(''), toUint8(), 'empty array for empty string');
- assert.deepEqual(stringToBytes(10), toUint8([0x31, 0x30]), 'converts numbers to strings');
- assert.deepEqual(stringToBytes(bytesToString(testBytes)), testBytes, 'bytesToString -> stringToBytes works');
- assert.deepEqual(stringToBytes(bytesToString(rawBytes), true), rawBytes, 'equal to original with raw bytes mode');
- assert.notDeepEqual(stringToBytes(bytesToString(rawBytes)), rawBytes, 'without raw byte mode works, not equal');
-});
-
-QUnit.module('toUint8');
-
-QUnit.test('should function as expected', function(assert) {
- const tests = {
- undef: {
- data: undefined,
- expected: new Uint8Array()
- },
- null: {
- data: null,
- expected: new Uint8Array()
- },
- string: {
- data: 'foo',
- expected: new Uint8Array()
- },
- NaN: {
- data: NaN,
- expected: new Uint8Array()
- },
- object: {
- data: {},
- expected: new Uint8Array()
- },
- number: {
- data: 0x11,
- expected: new Uint8Array([0x11])
- }
- };
-
- Object.keys(tests).forEach(function(name) {
- const {data, expected} = tests[name];
- const result = toUint8(data);
-
- assert.ok(result instanceof Uint8Array, `obj is a Uint8Array for ${name}`);
- assert.deepEqual(result, expected, `data is as expected for ${name}`);
- });
-
- arrayNames.forEach(function(name) {
- const testObj = name === 'Array' ? testBytes : new window[name](testBytes);
- const uint = toUint8(testObj);
-
- assert.ok(uint instanceof Uint8Array && uint.length > 0, `converted ${name} to Uint8Array`);
- });
-
-});
-
-QUnit.module('concatTypedArrays');
-
-QUnit.test('should function as expected', function(assert) {
- const tests = {
- undef: {
- data: concatTypedArrays(),
- expected: toUint8([])
- },
- empty: {
- data: concatTypedArrays(toUint8([])),
- expected: toUint8([])
- },
- single: {
- data: concatTypedArrays([0x01]),
- expected: toUint8([0x01])
- },
- array: {
- data: concatTypedArrays([0x01], [0x02]),
- expected: toUint8([0x01, 0x02])
- },
- uint: {
- data: concatTypedArrays(toUint8([0x01]), toUint8([0x02])),
- expected: toUint8([0x01, 0x02])
- },
- buffer: {
- data: concatTypedArrays(toUint8([0x01]).buffer, toUint8([0x02]).buffer),
- expected: toUint8([0x01, 0x02])
- },
- manyarray: {
- data: concatTypedArrays([0x01], [0x02], [0x03], [0x04]),
- expected: toUint8([0x01, 0x02, 0x03, 0x04])
- },
- manyuint: {
- data: concatTypedArrays(toUint8([0x01]), toUint8([0x02]), toUint8([0x03]), toUint8([0x04])),
- expected: toUint8([0x01, 0x02, 0x03, 0x04])
- }
- };
-
- Object.keys(tests).forEach(function(name) {
- const {data, expected} = tests[name];
-
- assert.ok(data instanceof Uint8Array, `obj is a Uint8Array for ${name}`);
- assert.deepEqual(data, expected, `data is as expected for ${name}`);
- });
-});
-
-QUnit.module('toHexString');
-QUnit.test('should function as expected', function(assert) {
- assert.equal(toHexString(0xFF), 'ff', 'works with single value');
- assert.equal(toHexString([0xFF, 0xaa]), 'ffaa', 'works with array');
- assert.equal(toHexString(toUint8([0xFF, 0xaa])), 'ffaa', 'works with uint8');
- assert.equal(toHexString(toUint8([0xFF, 0xaa]).buffer), 'ffaa', 'works with buffer');
- assert.equal(toHexString(toUint8([0xFF, 0xaa, 0xbb]).subarray(1, 3)), 'aabb', 'works with subarray');
- assert.equal(toHexString([0x01, 0x02, 0x03]), '010203', 'works with single digits');
-});
-
-QUnit.module('toBinaryString');
-QUnit.test('should function as expected', function(assert) {
- const ff = '11111111';
- const aa = '10101010';
- const bb = '10111011';
- const zerof = '00001111';
- const one = '00000001';
- const zero = '00000000';
- const fzero = '11110000';
-
- assert.equal(toBinaryString(0xFF), ff, 'works with single value');
- assert.equal(toBinaryString([0xFF, 0xaa]), ff + aa, 'works with array');
- assert.equal(toBinaryString(toUint8([0xFF, 0xbb])), ff + bb, 'works with uint8');
- assert.equal(toBinaryString(toUint8([0xFF, 0xaa]).buffer), ff + aa, 'works with buffer');
- assert.equal(toBinaryString(toUint8([0xFF, 0xaa, 0xbb]).subarray(1, 3)), aa + bb, 'works with subarray');
- assert.equal(toBinaryString([0x0F, 0x01, 0xF0, 0x00]), zerof + one + fzero + zero, 'works with varying digits digits');
-});
-
-QUnit.module('bytesToNumber');
-QUnit.test('sanity', function(assert) {
- assert.equal(bytesToNumber(0xFF), 0xFF, 'single value');
- assert.equal(bytesToNumber([0xFF, 0x01]), 0xFF01, 'works with array');
- assert.equal(bytesToNumber(toUint8([0xFF, 0xbb])), 0xFFBB, 'works with uint8');
- assert.equal(bytesToNumber(toUint8([0xFF, 0xaa]).buffer), 0xFFAA, 'works with buffer');
- assert.equal(bytesToNumber(toUint8([0xFF, 0xaa, 0xbb]).subarray(1, 3)), 0xAABB, 'works with subarray');
-});
-QUnit.test('unsigned and littleEndian work', function(assert) {
- // works with any number of bits
- assert.equal(bytesToNumber([0xFF]), 0xFF, 'u8');
- assert.equal(bytesToNumber([0xFF, 0xAA]), 0xFFAA, 'u16');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB]), 0xFFAABB, 'u24');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC]), 0xFFAABBCC, 'u32');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC, 0xDD]), 0xFFAABBCCDD, 'u40');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE]), 0xFFAABBCCDDEE, 'u48');
-
- assert.equal(bytesToNumber([0xFF], {le: true}), 0xFF, 'u8 le');
- assert.equal(bytesToNumber([0xFF, 0xAA], {le: true}), 0xAAFF, 'u16 le');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB], {le: true}), 0xBBAAFF, 'u24 le');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC], {le: true}), 0xCCBBAAFF, 'u32 le');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC, 0xDD], {le: true}), 0xDDCCBBAAFF, 'u40 le');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE], {le: true}), 0xEEDDCCBBAAFF, 'u48 le');
-
- if (BigInt) {
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0x99]), 0xFFAABBCCDDEE99, 'u56');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0x99, 0x88]), 0xFFAABBCCDDEE9988, 'u64');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0x99], {le: true}), 0x99EEDDCCBBAAFF, 'u56 le');
- assert.equal(bytesToNumber([0xFF, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0x99, 0x88], {le: true}), 0x8899EEDDCCBBAAFF, 'u64 le');
- }
-});
-
-QUnit.test('signed and littleEndian work', function(assert) {
- assert.equal(bytesToNumber([0xF0], {signed: true}), -16, 'i8');
- assert.equal(bytesToNumber([0x80, 0x70], {signed: true}), -32656, 'i16');
- assert.equal(bytesToNumber([0x80, 0x70, 0x9f], {signed: true}), -8359777, 'i24');
- assert.equal(bytesToNumber([0x80, 0x70, 0x9f, 0xFF], {signed: true}), -2140102657, 'i32');
- assert.equal(bytesToNumber([0x80, 0x70, 0x9f, 0xFF, 0x10], {signed: true}), -547866280176, 'i40');
- assert.equal(bytesToNumber([0x80, 0x70, 0x9f, 0xFF, 0x10, 0x89], {signed: true}), -140253767724919, 'i48');
-
- assert.equal(bytesToNumber([0xF0], {signed: true, le: true}), -16, 'i8 le');
- assert.equal(bytesToNumber([0x80, 0x70], {signed: true, le: true}), 0x7080, 'i16 le');
- assert.equal(bytesToNumber([0x80, 0x70, 0x9f], {signed: true, le: true}), -6328192, 'i24 le');
- assert.equal(bytesToNumber([0x80, 0x70, 0x9f, 0xFF], {signed: true, le: true}), -6328192, 'i32 le');
- assert.equal(bytesToNumber([0x80, 0x70, 0x9f, 0xFF, 0x10], {signed: true, le: true}), 73008115840, 'i40 le');
- assert.equal(bytesToNumber([0x80, 0x70, 0x9f, 0xFF, 0x10, 0x89], {signed: true, le: true}), -130768875589504, 'i48 le');
-
- if (BigInt) {
- assert.equal(bytesToNumber([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], {signed: true}), -1, 'i56');
- assert.equal(bytesToNumber([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], {signed: true}), -1, 'i64');
- assert.equal(bytesToNumber([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], {signed: true, le: true}), -1, 'i56 le');
- assert.equal(bytesToNumber([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], {signed: true, le: true}), -1, 'i64 le');
- }
-});
-
-QUnit.module('numberToBytes');
-
-QUnit.test('unsigned negative and positive', function(assert) {
- assert.deepEqual(numberToBytes(), toUint8([0x00]), 'no bytes');
- assert.deepEqual(numberToBytes(0xFF), toUint8([0xFF]), 'u8');
- assert.deepEqual(numberToBytes(0xFFaa), toUint8([0xFF, 0xaa]), 'u16');
- assert.deepEqual(numberToBytes(0xFFaabb), toUint8([0xFF, 0xaa, 0xbb]), 'u24');
- assert.deepEqual(numberToBytes(0xFFaabbcc), toUint8([0xFF, 0xaa, 0xbb, 0xcc]), 'u32');
- assert.deepEqual(numberToBytes(0xFFaabbccdd), toUint8([0xFF, 0xaa, 0xbb, 0xcc, 0xdd]), 'u40');
- assert.deepEqual(numberToBytes(0xFFaabbccddee), toUint8([0xFF, 0xaa, 0xbb, 0xcc, 0xdd, 0xee]), 'u48');
-
- assert.deepEqual(numberToBytes(-16), toUint8([0xF0]), 'negative to u8');
- assert.deepEqual(numberToBytes(-32640), toUint8([0x80, 0x80]), 'negative to u16');
- assert.deepEqual(numberToBytes(-3264062), toUint8([0xce, 0x31, 0xc2]), 'negative to u24');
- assert.deepEqual(numberToBytes(-2139062144), toUint8([0x80, 0x80, 0x80, 0x80]), 'negative to u32');
- assert.deepEqual(numberToBytes(-3139062144), toUint8([0xff, 0x44, 0xe5, 0xb6, 0x80]), 'negative u40');
- assert.deepEqual(numberToBytes(-3139062144444), toUint8([0xfd, 0x25, 0x21, 0x50, 0xe2, 0x44]), 'negative u48');
-
- if (BigInt) {
- assert.deepEqual(numberToBytes(BigInt('0xFFaabbccddee99')), toUint8([0xFF, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0x99]), 'u56');
- assert.deepEqual(numberToBytes(BigInt('0xFFaabbccddee9988')), toUint8([0xFF, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0x99, 0x88]), 'u64');
- assert.deepEqual(numberToBytes(BigInt('-31390621444448812')), toUint8([0x90, 0x7a, 0x65, 0x67, 0x86, 0x5d, 0xd4]), 'negative to u56');
- assert.deepEqual(numberToBytes(BigInt('-9187201950435737472')), toUint8([0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80]), 'u64');
- }
-});
-
-QUnit.test('unsigned littleEndian negative and positive', function(assert) {
- assert.deepEqual(numberToBytes(0xFF, {le: true}), toUint8([0xFF]), 'u8');
- assert.deepEqual(numberToBytes(0xFFaa, {le: true}), toUint8([0xaa, 0xFF]), 'u16');
- assert.deepEqual(numberToBytes(0xFFaabb, {le: true}), toUint8([0xbb, 0xaa, 0xFF]), 'u24');
- assert.deepEqual(numberToBytes(0xFFaabbcc, {le: true}), toUint8([0xcc, 0xbb, 0xaa, 0xff]), 'u32');
- assert.deepEqual(numberToBytes(0xFFaabbccdd, {le: true}), toUint8([0xdd, 0xcc, 0xbb, 0xaa, 0xff]), 'u40');
- assert.deepEqual(numberToBytes(0xFFaabbccddee, {le: true}), toUint8([0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0xff]), 'u48');
-
- assert.deepEqual(numberToBytes(-16, {le: true}), toUint8([0xF0]), 'negative to u8');
- assert.deepEqual(numberToBytes(-32640, {le: true}), toUint8([0x80, 0x80]), 'negative to u16');
- assert.deepEqual(numberToBytes(-3264062, {le: true}), toUint8([0xc2, 0x31, 0xce]), 'negative to u24');
- assert.deepEqual(numberToBytes(-2139062144, {le: true}), toUint8([0x80, 0x80, 0x80, 0x80]), 'negative to u32');
- assert.deepEqual(numberToBytes(-3139062144, {le: true}), toUint8([0x80, 0xb6, 0xe5, 0x44, 0xff]), 'negative u40');
- assert.deepEqual(numberToBytes(-3139062144444, {le: true}), toUint8([0x44, 0xe2, 0x50, 0x21, 0x25, 0xfd]), 'negative u48');
-
- if (BigInt) {
- assert.deepEqual(numberToBytes(BigInt('0xFFaabbccddee99'), {le: true}), toUint8([0x99, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0xff]), 'u56');
- assert.deepEqual(numberToBytes(BigInt('0xFFaabbccddee9988'), {le: true}), toUint8([0x88, 0x99, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0xff]), 'u64');
- assert.deepEqual(numberToBytes(BigInt('-31390621444448812'), {le: true}), toUint8([0xd4, 0x5d, 0x86, 0x67, 0x65, 0x7a, 0x90]), 'negative to u56');
- assert.deepEqual(numberToBytes(BigInt('-9187201950435737472'), {le: true}), toUint8([0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80]), 'u64');
- }
-});
-
-QUnit.module('bytesMatch');
-QUnit.test('should function as expected', function(assert) {
- assert.equal(bytesMatch(), false, 'no a or b bytes, false');
- assert.equal(bytesMatch(null, []), false, 'no a bytes, false');
- assert.equal(bytesMatch([]), false, 'no b bytes, false');
- assert.equal(bytesMatch([0x00], [0x00, 0x02]), false, 'not enough bytes');
- assert.equal(bytesMatch([0x00], [0x00], {offset: 1}), false, 'not due to offset');
- assert.equal(bytesMatch([0xbb, 0xaa], [0xaa]), false, 'bytes do not match');
- assert.equal(bytesMatch([0xaa], [0xaa], {mask: [0x10]}), false, 'bytes do not match due to mask');
- assert.equal(bytesMatch([0xaa], [0xaa]), true, 'bytes match');
- assert.equal(bytesMatch([0xbb, 0xaa], [0xbb]), true, 'bytes match more a');
- assert.equal(bytesMatch([0xbb, 0xaa], [0xaa], {offset: 1}), true, 'bytes match with offset');
- assert.equal(bytesMatch([0xaa], [0x20], {mask: [0x20]}), true, 'bytes match with mask');
- assert.equal(bytesMatch([0xbb, 0xaa], [0x20], {mask: [0x20], offset: 1}), true, 'bytes match with mask and offset');
- assert.equal(bytesMatch([0xbb, 0xaa, 0xaa], [0x20, 0x20], {mask: [0x20, 0x20], offset: 1}), true, 'bytes match with many masks and offset');
-});
diff --git a/node_modules/@videojs/vhs-utils/test/codecs.test.js b/node_modules/@videojs/vhs-utils/test/codecs.test.js
deleted file mode 100644
index 895bd60..0000000
--- a/node_modules/@videojs/vhs-utils/test/codecs.test.js
+++ /dev/null
@@ -1,472 +0,0 @@
-import window from 'global/window';
-import QUnit from 'qunit';
-import {
- mapLegacyAvcCodecs,
- translateLegacyCodecs,
- parseCodecs,
- codecsFromDefault,
- isVideoCodec,
- isAudioCodec,
- muxerSupportsCodec,
- browserSupportsCodec,
- getMimeForCodec
-} from '../src/codecs';
-
-const supportedMuxerCodecs = [
- 'mp4a',
- 'avc1'
-];
-
-const unsupportedMuxerCodecs = [
- 'hvc1',
- 'ac-3',
- 'ec-3',
- 'mp3'
-];
-
-QUnit.module('Legacy Codecs');
-
-QUnit.test('maps legacy AVC codecs', function(assert) {
- assert.equal(
- mapLegacyAvcCodecs('avc1.deadbeef'),
- 'avc1.deadbeef',
- 'does nothing for non legacy pattern'
- );
- assert.equal(
- mapLegacyAvcCodecs('avc1.dead.beef, mp4a.something'),
- 'avc1.dead.beef, mp4a.something',
- 'does nothing for non legacy pattern'
- );
- assert.equal(
- mapLegacyAvcCodecs('avc1.dead.beef,mp4a.something'),
- 'avc1.dead.beef,mp4a.something',
- 'does nothing for non legacy pattern'
- );
- assert.equal(
- mapLegacyAvcCodecs('mp4a.something,avc1.dead.beef'),
- 'mp4a.something,avc1.dead.beef',
- 'does nothing for non legacy pattern'
- );
- assert.equal(
- mapLegacyAvcCodecs('mp4a.something, avc1.dead.beef'),
- 'mp4a.something, avc1.dead.beef',
- 'does nothing for non legacy pattern'
- );
- assert.equal(
- mapLegacyAvcCodecs('avc1.42001e'),
- 'avc1.42001e',
- 'does nothing for non legacy pattern'
- );
- assert.equal(
- mapLegacyAvcCodecs('avc1.4d0020,mp4a.40.2'),
- 'avc1.4d0020,mp4a.40.2',
- 'does nothing for non legacy pattern'
- );
- assert.equal(
- mapLegacyAvcCodecs('mp4a.40.2,avc1.4d0020'),
- 'mp4a.40.2,avc1.4d0020',
- 'does nothing for non legacy pattern'
- );
- assert.equal(
- mapLegacyAvcCodecs('mp4a.40.40'),
- 'mp4a.40.40',
- 'does nothing for non video codecs'
- );
-
- assert.equal(
- mapLegacyAvcCodecs('avc1.66.30'),
- 'avc1.42001e',
- 'translates legacy video codec alone'
- );
- assert.equal(
- mapLegacyAvcCodecs('avc1.66.30, mp4a.40.2'),
- 'avc1.42001e, mp4a.40.2',
- 'translates legacy video codec when paired with audio'
- );
- assert.equal(
- mapLegacyAvcCodecs('mp4a.40.2, avc1.66.30'),
- 'mp4a.40.2, avc1.42001e',
- 'translates video codec when specified second'
- );
-});
-
-QUnit.test('translates legacy codecs', function(assert) {
- assert.deepEqual(
- translateLegacyCodecs(['avc1.66.30', 'avc1.66.30']),
- ['avc1.42001e', 'avc1.42001e'],
- 'translates legacy avc1.66.30 codec'
- );
-
- assert.deepEqual(
- translateLegacyCodecs(['avc1.42C01E', 'avc1.42C01E']),
- ['avc1.42C01E', 'avc1.42C01E'],
- 'does not translate modern codecs'
- );
-
- assert.deepEqual(
- translateLegacyCodecs(['avc1.42C01E', 'avc1.66.30']),
- ['avc1.42C01E', 'avc1.42001e'],
- 'only translates legacy codecs when mixed'
- );
-
- assert.deepEqual(
- translateLegacyCodecs(['avc1.4d0020', 'avc1.100.41', 'avc1.77.41',
- 'avc1.77.32', 'avc1.77.31', 'avc1.77.30',
- 'avc1.66.30', 'avc1.66.21', 'avc1.42C01e']),
- ['avc1.4d0020', 'avc1.640029', 'avc1.4d0029',
- 'avc1.4d0020', 'avc1.4d001f', 'avc1.4d001e',
- 'avc1.42001e', 'avc1.420015', 'avc1.42C01e'],
- 'translates a whole bunch'
- );
-});
-
-QUnit.module('parseCodecs');
-
-QUnit.test('parses text only codec string', function(assert) {
- assert.deepEqual(
- parseCodecs('stpp.ttml.im1t'),
- [{mediaType: 'text', type: 'stpp.ttml.im1t', details: ''}],
- 'parsed text only codec string'
- );
-});
-
-QUnit.test('parses video only codec string', function(assert) {
- assert.deepEqual(
- parseCodecs('avc1.42001e'),
- [{mediaType: 'video', type: 'avc1', details: '.42001e'}],
- 'parsed video only codec string'
- );
-});
-
-QUnit.test('parses audio only codec string', function(assert) {
- assert.deepEqual(
- parseCodecs('mp4a.40.2'),
- [{mediaType: 'audio', type: 'mp4a', details: '.40.2'}],
- 'parsed audio only codec string'
- );
-});
-
-QUnit.test('parses video, audio, and text codec string', function(assert) {
- assert.deepEqual(
- parseCodecs('avc1.42001e, mp4a.40.2, stpp.ttml.im1t'),
- [
- {mediaType: 'video', type: 'avc1', details: '.42001e'},
- {mediaType: 'audio', type: 'mp4a', details: '.40.2'},
- {mediaType: 'text', type: 'stpp.ttml.im1t', details: ''}
- ],
- 'parsed video, audio, and text codec string'
- );
-});
-
-QUnit.test('parses video, audio, and text codec with mixed case', function(assert) {
- assert.deepEqual(
- parseCodecs('AvC1.42001E, Mp4A.40.E, stpp.TTML.im1T'),
- [
- {mediaType: 'video', type: 'AvC1', details: '.42001E'},
- {mediaType: 'audio', type: 'Mp4A', details: '.40.E'},
- {mediaType: 'text', type: 'stpp.TTML.im1T', details: ''}
- ],
- 'parsed video, audio, and text codec string'
- );
-});
-
-QUnit.test('parses two unknown codec', function(assert) {
- assert.deepEqual(
- parseCodecs('fake.codec, other-fake'),
- [
- {mediaType: 'unknown', type: 'fake.codec', details: ''},
- {mediaType: 'unknown', type: 'other-fake', details: ''}
- ],
- 'parsed faked codecs as video/audio'
- );
-});
-
-QUnit.test('parses an unknown codec with a known audio', function(assert) {
- assert.deepEqual(
- parseCodecs('fake.codec, mp4a.40.2'),
- [
- {mediaType: 'unknown', type: 'fake.codec', details: ''},
- {mediaType: 'audio', type: 'mp4a', details: '.40.2'}
- ],
- 'parsed audio and unknwon'
- );
-});
-
-QUnit.test('parses an unknown codec with a known video', function(assert) {
- assert.deepEqual(
- parseCodecs('avc1.42001e, other-fake'),
- [
- {mediaType: 'video', type: 'avc1', details: '.42001e'},
- {mediaType: 'unknown', type: 'other-fake', details: ''}
- ],
- 'parsed video and unknown'
- );
-});
-
-QUnit.test('parses an unknown codec with a known text', function(assert) {
- assert.deepEqual(
- parseCodecs('stpp.ttml.im1t, other-fake'),
- [
- {mediaType: 'text', type: 'stpp.ttml.im1t', details: ''},
- {mediaType: 'unknown', type: 'other-fake', details: ''}
- ],
- 'parsed text and unknown'
- );
-});
-
-QUnit.test('parses an unknown codec with a known audio/video/text', function(assert) {
- assert.deepEqual(
- parseCodecs('fake.codec, avc1.42001e, mp4a.40.2, stpp.ttml.im1t'),
- [
- {mediaType: 'unknown', type: 'fake.codec', details: ''},
- {mediaType: 'video', type: 'avc1', details: '.42001e'},
- {mediaType: 'audio', type: 'mp4a', details: '.40.2'},
- {mediaType: 'text', type: 'stpp.ttml.im1t', details: ''}
- ],
- 'parsed video/audio/text and unknown codecs'
- );
-});
-
-QUnit.module('codecsFromDefault');
-
-QUnit.test('returns falsey when no audio group ID', function(assert) {
- assert.notOk(
- codecsFromDefault(
- { mediaGroups: { AUDIO: {} } },
- '',
- ),
- 'returns falsey when no audio group ID'
- );
-});
-
-QUnit.test('returns falsey when no matching audio group', function(assert) {
- assert.notOk(
- codecsFromDefault(
- {
- mediaGroups: {
- AUDIO: {
- au1: {
- en: {
- default: false,
- playlists: [{
- attributes: { CODECS: 'mp4a.40.2' }
- }]
- },
- es: {
- default: true,
- playlists: [{
- attributes: { CODECS: 'mp4a.40.5' }
- }]
- }
- }
- }
- }
- },
- 'au2'
- ),
- 'returned falsey when no matching audio group'
- );
-});
-
-QUnit.test('returns falsey when no default for audio group', function(assert) {
- assert.notOk(
- codecsFromDefault(
- {
- mediaGroups: {
- AUDIO: {
- au1: {
- en: {
- default: false,
- playlists: [{
- attributes: { CODECS: 'mp4a.40.2' }
- }]
- },
- es: {
- default: false,
- playlists: [{
- attributes: { CODECS: 'mp4a.40.5' }
- }]
- }
- }
- }
- }
- },
- 'au1'
- ),
- 'returned falsey when no default for audio group'
- );
-});
-
-QUnit.test('returns parsed audio codecs for default in audio group', function(assert) {
- assert.deepEqual(
- codecsFromDefault(
- {
- mediaGroups: {
- AUDIO: {
- au1: {
- en: {
- default: false,
- playlists: [{
- attributes: { CODECS: 'mp4a.40.2, mp4a.40.20' }
- }]
- },
- es: {
- default: true,
- playlists: [{
- attributes: { CODECS: 'mp4a.40.5, mp4a.40.7' }
- }]
- }
- }
- }
- }
- },
- 'au1'
- ),
- [
- {mediaType: 'audio', type: 'mp4a', details: '.40.5'},
- {mediaType: 'audio', type: 'mp4a', details: '.40.7'}
- ],
- 'returned parsed codec audio profile'
- );
-});
-
-QUnit.module('isVideoCodec');
-QUnit.test('works as expected', function(assert) {
- [
- 'av1',
- 'avc01',
- 'avc1',
- 'avc02',
- 'avc2',
- 'vp09',
- 'vp9',
- 'vp8',
- 'vp08',
- 'hvc1',
- 'hev1',
- 'theora',
- 'mp4v'
- ].forEach(function(codec) {
- assert.ok(isVideoCodec(codec), `"${codec}" is seen as a video codec`);
- assert.ok(isVideoCodec(` ${codec} `), `" ${codec} " is seen as video codec`);
- assert.ok(isVideoCodec(codec.toUpperCase()), `"${codec.toUpperCase()}" is seen as video codec`);
- });
-
- ['invalid', 'foo', 'mp4a', 'opus', 'vorbis'].forEach(function(codec) {
- assert.notOk(isVideoCodec(codec), `${codec} is not a video codec`);
- });
-
-});
-
-QUnit.module('isAudioCodec');
-QUnit.test('works as expected', function(assert) {
- [
- 'mp4a',
- 'flac',
- 'vorbis',
- 'opus',
- 'ac-3',
- 'ac-4',
- 'ec-3',
- 'alac',
- 'speex',
- 'aac',
- 'mp3'
- ].forEach(function(codec) {
- assert.ok(isAudioCodec(codec), `"${codec}" is seen as an audio codec`);
- assert.ok(isAudioCodec(` ${codec} `), `" ${codec} " is seen as an audio codec`);
- assert.ok(isAudioCodec(codec.toUpperCase()), `"${codec.toUpperCase()}" is seen as an audio codec`);
- });
-
- ['invalid', 'foo', 'bar', 'avc1', 'av1'].forEach(function(codec) {
- assert.notOk(isAudioCodec(codec), `${codec} is not an audio codec`);
- });
-});
-
-QUnit.module('muxerSupportsCodec');
-QUnit.test('works as expected', function(assert) {
- const validMuxerCodecs = [];
- const invalidMuxerCodecs = [];
-
- unsupportedMuxerCodecs.forEach(function(badCodec) {
- invalidMuxerCodecs.push(badCodec);
- supportedMuxerCodecs.forEach(function(goodCodec) {
- invalidMuxerCodecs.push(`${goodCodec}, ${badCodec}`);
- });
- });
-
- // generate all combinations of valid codecs
- supportedMuxerCodecs.forEach(function(codec, i) {
- validMuxerCodecs.push(codec);
-
- supportedMuxerCodecs.forEach(function(_codec, z) {
- if (z === i) {
- return;
- }
- validMuxerCodecs.push(`${codec}, ${_codec}`);
- validMuxerCodecs.push(`${codec},${_codec}`);
- });
- });
-
- validMuxerCodecs.forEach(function(codec) {
- assert.ok(muxerSupportsCodec(codec), `"${codec}" is supported`);
- assert.ok(muxerSupportsCodec(` ${codec} `), `" ${codec} " is supported`);
- assert.ok(muxerSupportsCodec(codec.toUpperCase()), `"${codec.toUpperCase()}" is supported`);
- });
-
- invalidMuxerCodecs.forEach(function(codec) {
- assert.notOk(muxerSupportsCodec(codec), `${codec} not supported`);
- });
-});
-
-QUnit.module('browserSupportsCodec', {
- beforeEach() {
- this.oldMediaSource = window.MediaSource;
- },
- afterEach() {
- window.MediaSource = this.oldMediaSource;
- }
-});
-
-QUnit.test('works as expected', function(assert) {
- window.MediaSource = {isTypeSupported: () => true};
- assert.ok(browserSupportsCodec('test'), 'isTypeSupported true, browser does support codec');
-
- window.MediaSource = {isTypeSupported: () => false};
- assert.notOk(browserSupportsCodec('test'), 'isTypeSupported false, browser does not support codec');
-
- window.MediaSource = null;
- assert.notOk(browserSupportsCodec('test'), 'no MediaSource, browser does not support codec');
-
- window.MediaSource = {isTypeSupported: null};
- assert.notOk(browserSupportsCodec('test'), 'no isTypeSupported, browser does not support codec');
-});
-
-QUnit.module('getMimeForCodec');
-
-QUnit.test('works as expected', function(assert) {
- // mp4
- assert.equal(getMimeForCodec('vp9,mp4a'), 'video/mp4;codecs="vp9,mp4a"', 'mp4 video/audio works');
- assert.equal(getMimeForCodec('vp9'), 'video/mp4;codecs="vp9"', 'mp4 video works');
- assert.equal(getMimeForCodec('mp4a'), 'audio/mp4;codecs="mp4a"', 'mp4 audio works');
-
- // webm
- assert.equal(getMimeForCodec('vp8,opus'), 'video/webm;codecs="vp8,opus"', 'webm video/audio works');
- assert.equal(getMimeForCodec('vp8'), 'video/webm;codecs="vp8"', 'webm video works');
- assert.equal(getMimeForCodec('vorbis'), 'audio/webm;codecs="vorbis"', 'webm audio works');
-
- // ogg
- assert.equal(getMimeForCodec('theora,vorbis'), 'video/ogg;codecs="theora,vorbis"', 'ogg video/audio works');
- assert.equal(getMimeForCodec('theora'), 'video/ogg;codecs="theora"', 'ogg video works');
- // ogg will never be selected for audio only
-
- // mixed
- assert.equal(getMimeForCodec('opus'), 'audio/mp4;codecs="opus"', 'mp4 takes priority over everything');
- assert.equal(getMimeForCodec('vorbis'), 'audio/webm;codecs="vorbis"', 'webm takes priority over ogg');
- assert.equal(getMimeForCodec('foo'), 'video/mp4;codecs="foo"', 'mp4 is the default');
-
- assert.notOk(getMimeForCodec(), 'invalid codec returns undefined');
-
- assert.equal(getMimeForCodec('Mp4A.40.2,AvC1.42001E'), 'video/mp4;codecs="Mp4A.40.2,AvC1.42001E"', 'case is preserved');
- assert.equal(getMimeForCodec('stpp.ttml.im1t'), 'application/mp4;codecs="stpp.ttml.im1t"', 'text is parsed');
-});
diff --git a/node_modules/@videojs/vhs-utils/test/container.test.js b/node_modules/@videojs/vhs-utils/test/container.test.js
deleted file mode 100644
index cf4e2c6..0000000
--- a/node_modules/@videojs/vhs-utils/test/container.test.js
+++ /dev/null
@@ -1,197 +0,0 @@
-import QUnit from 'qunit';
-import {detectContainerForBytes, isLikelyFmp4MediaSegment} from '../src/containers.js';
-import {stringToBytes, concatTypedArrays, toUint8} from '../src/byte-helpers.js';
-
-const filler = (size) => {
- const view = new Uint8Array(size);
-
- for (let i = 0; i < size; i++) {
- view[i] = 0;
- }
-
- return view;
-};
-
-const otherMp4Data = concatTypedArrays([0x00, 0x00, 0x00, 0x00], stringToBytes('stypiso'));
-const id3Data = Array.prototype.slice.call(concatTypedArrays(
- stringToBytes('ID3'),
- // id3 header is 10 bytes without footer
- // 10th byte is length 0x23 or 35 in decimal
- // so a total length of 45
- [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23],
- // add in the id3 content
- filler(35)
-));
-
-const id3DataWithFooter = Array.prototype.slice.call(concatTypedArrays(
- stringToBytes('ID3'),
- // id3 header is 20 bytes with footer
- // "we have a footer" is the sixth byte
- // 10th byte is length of 0x23 or 35 in decimal
- // so a total length of 55
- [0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x23],
- // add in the id3 content
- filler(45)
-));
-
-const testData = {
- // EBML tag + dataSize
- // followed by DocType + dataSize and then actual data for that tag
- 'mkv': concatTypedArrays([0x1a, 0x45, 0xdf, 0xa3, 0x99, 0x42, 0x82, 0x88], stringToBytes('matroska')),
- 'webm': concatTypedArrays([0x1a, 0x45, 0xdf, 0xa3, 0x99, 0x42, 0x82, 0x88], stringToBytes('webm')),
- 'flac': stringToBytes('fLaC'),
- 'ogg': stringToBytes('OggS'),
- 'aac': toUint8([0xFF, 0xF1]),
- 'ac3': toUint8([0x0B, 0x77]),
- 'mp3': toUint8([0xFF, 0xFB]),
- '3gp': concatTypedArrays([0x00, 0x00, 0x00, 0x00], stringToBytes('ftyp3g')),
- 'mp4': concatTypedArrays([0x00, 0x00, 0x00, 0x00], stringToBytes('ftypiso')),
- 'mov': concatTypedArrays([0x00, 0x00, 0x00, 0x00], stringToBytes('ftypqt')),
- 'avi': toUint8([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x41, 0x56, 0x49]),
- 'wav': toUint8([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45]),
- 'ts': toUint8([0x47]),
- // seq_parameter_set_rbsp
- 'h264': toUint8([0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x0d, 0xd9, 0x01, 0xa1, 0xfa, 0x10, 0x00, 0x00, 0x03, 0x20, 0x00, 0x00, 0x95, 0xe0, 0xf1, 0x42, 0xa4, 0x80, 0x00, 0x00, 0x00, 0x01]),
- // video_parameter_set_rbsp
- 'h265': toUint8([0x00, 0x00, 0x00, 0x01, 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x24, 0x08, 0x00, 0x00, 0x00, 0x9c, 0x08, 0x00, 0x00, 0x00, 0x00, 0x78, 0x95, 0x98, 0x09, 0x00, 0x00, 0x00, 0x01])
-};
-
-// seq_parameter_set_rbsp
-const h265seq = toUint8([
- 0x00, 0x00, 0x00, 0x01,
- 0x42, 0x01, 0x01, 0x21,
- 0x60, 0x00, 0x00, 0x00,
- 0x90, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x78, 0xa0,
- 0x0d, 0x08, 0x0f, 0x16,
- 0x59, 0x59, 0xa4, 0x93,
- 0x2b, 0x9a, 0x02, 0x00,
- 0x00, 0x00, 0x64, 0x00,
- 0x00, 0x09, 0x5e, 0x10,
- 0x00, 0x00, 0x00, 0x01
-]);
-
-const h264shortnal = Array.prototype.slice.call(testData.h264);
-
-// remove 0x00 from the front
-h264shortnal.splice(0, 1);
-// remove 0x00 from the back
-h264shortnal.splice(h264shortnal.length - 2, 1);
-
-const h265shortnal = Array.prototype.slice.call(testData.h265);
-
-// remove 0x00 from the front
-h265shortnal.splice(0, 1);
-// remove 0x00 from the back
-h265shortnal.splice(h265shortnal.length - 2, 1);
-
-QUnit.module('detectContainerForBytes');
-
-QUnit.test('should identify known types', function(assert) {
- Object.keys(testData).forEach(function(key) {
- const data = new Uint8Array(testData[key]);
-
- assert.equal(detectContainerForBytes(testData[key]), key, `found ${key} with Array`);
- assert.equal(detectContainerForBytes(data.buffer), key, `found ${key} with ArrayBuffer`);
- assert.equal(detectContainerForBytes(data), key, `found ${key} with Uint8Array`);
- });
-
- const mp4Bytes = concatTypedArrays([0x00, 0x00, 0x00, 0x00], stringToBytes('styp'));
-
- assert.equal(detectContainerForBytes(mp4Bytes), 'mp4', 'styp mp4 detected as mp4');
-
- // mp3/aac/flac/ac3 audio can have id3 data before the
- // signature for the file, so we need to handle that.
- ['mp3', 'aac', 'flac', 'ac3'].forEach(function(type) {
- const dataWithId3 = concatTypedArrays(id3Data, testData[type]);
- const dataWithId3Footer = concatTypedArrays(id3DataWithFooter, testData[type]);
- const recursiveDataWithId3 = concatTypedArrays(
- id3Data,
- id3Data,
- id3Data,
- testData[type]
- );
- const recursiveDataWithId3Footer = concatTypedArrays(
- id3DataWithFooter,
- id3DataWithFooter,
- id3DataWithFooter,
- testData[type]
- );
-
- const differentId3Sections = concatTypedArrays(
- id3DataWithFooter,
- id3Data,
- id3DataWithFooter,
- id3Data,
- testData[type]
- );
-
- assert.equal(detectContainerForBytes(dataWithId3), type, `id3 skipped and ${type} detected`);
- assert.equal(detectContainerForBytes(dataWithId3Footer), type, `id3 + footer skipped and ${type} detected`);
-
- assert.equal(detectContainerForBytes(recursiveDataWithId3), type, `id3 x3 skipped and ${type} detected`);
- assert.equal(detectContainerForBytes(recursiveDataWithId3Footer), type, `id3 + footer x3 skipped and ${type} detected`);
- assert.equal(detectContainerForBytes(differentId3Sections), type, `id3 with/without footer skipped and ${type} detected`);
-
- });
-
- const notTs = concatTypedArrays(testData.ts, filler(188));
- const longTs = concatTypedArrays(testData.ts, filler(187), testData.ts);
- const unsyncTs = concatTypedArrays(filler(187), testData.ts, filler(187), testData.ts);
- const badTs = concatTypedArrays(filler(188), testData.ts, filler(187), testData.ts);
-
- assert.equal(detectContainerForBytes(longTs), 'ts', 'long ts data is detected');
- assert.equal(detectContainerForBytes(unsyncTs), 'ts', 'unsynced ts is detected');
- assert.equal(detectContainerForBytes(badTs), '', 'ts without a sync byte in 188 bytes is not detected');
- assert.equal(detectContainerForBytes(notTs), '', 'ts missing 0x47 at 188 is not ts at all');
- assert.equal(detectContainerForBytes(otherMp4Data), 'mp4', 'fmp4 detected as mp4');
- assert.equal(detectContainerForBytes(new Uint8Array()), '', 'no type');
- assert.equal(detectContainerForBytes(), '', 'no type');
-
- assert.equal(detectContainerForBytes(h265seq), 'h265', 'h265 with only seq_parameter_set_rbsp, works');
- assert.equal(detectContainerForBytes(h265shortnal), 'h265', 'h265 with short nals works');
- assert.equal(detectContainerForBytes(h264shortnal), 'h264', 'h265 with short nals works');
-});
-
-const createBox = function(type) {
- const size = 0x20;
-
- return concatTypedArrays(
- // size bytes
- [0x00, 0x00, 0x00, size],
- // box identfier styp
- stringToBytes(type),
- // filler data for size minus identfier and size bytes
- filler(size - 8)
- );
-};
-
-QUnit.module('isLikelyFmp4MediaSegment');
-QUnit.test('works as expected', function(assert) {
- const fmp4Data = concatTypedArrays(
- createBox('styp'),
- createBox('sidx'),
- createBox('moof')
- );
-
- const mp4Data = concatTypedArrays(
- createBox('ftyp'),
- createBox('sidx'),
- createBox('moov')
- );
-
- const fmp4Fake = concatTypedArrays(
- createBox('test'),
- createBox('moof'),
- createBox('fooo'),
- createBox('bar')
- );
-
- assert.ok(isLikelyFmp4MediaSegment(fmp4Data), 'fmp4 is recognized as fmp4');
- assert.ok(isLikelyFmp4MediaSegment(fmp4Fake), 'fmp4 with moof and unknown boxes is still fmp4');
- assert.ok(isLikelyFmp4MediaSegment(createBox('moof')), 'moof alone is recognized as fmp4');
- assert.notOk(isLikelyFmp4MediaSegment(mp4Data), 'mp4 is not recognized');
- assert.notOk(isLikelyFmp4MediaSegment(concatTypedArrays(id3DataWithFooter, testData.mp3)), 'bad data is not recognized');
- assert.notOk(isLikelyFmp4MediaSegment(new Uint8Array()), 'no errors on empty data');
- assert.notOk(isLikelyFmp4MediaSegment(), 'no errors on empty data');
-});
diff --git a/node_modules/@videojs/vhs-utils/test/decode-b64-to-uint8-array.test.js b/node_modules/@videojs/vhs-utils/test/decode-b64-to-uint8-array.test.js
deleted file mode 100644
index e54401e..0000000
--- a/node_modules/@videojs/vhs-utils/test/decode-b64-to-uint8-array.test.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import QUnit from 'qunit';
-import decodeB64ToUint8Array from '../src/decode-b64-to-uint8-array.js';
-
-QUnit.module('decodeB64ToUint8Array');
-
-// slightly modified version of m3u8 test
-// 'parses Widevine #EXT-X-KEY attributes and attaches to manifest'
-QUnit.test('can decode', function(assert) {
- const b64 = 'AAAAPnBzc2gAAAAA7e+LqXnWSs6jyCfc1R0h7QAAAB4iFnNoYWthX2NlYzJmNjRhYTc4OTBhMTFI49yVmwY';
- const result = decodeB64ToUint8Array(b64);
-
- assert.deepEqual(result.byteLength, 62, 'decoded');
-});
diff --git a/node_modules/@videojs/vhs-utils/test/ebml-helpers.test.js b/node_modules/@videojs/vhs-utils/test/ebml-helpers.test.js
deleted file mode 100644
index 21b8db7..0000000
--- a/node_modules/@videojs/vhs-utils/test/ebml-helpers.test.js
+++ /dev/null
@@ -1,57 +0,0 @@
-import QUnit from 'qunit';
-import formatFiles from 'create-test-data!formats';
-import parsingFiles from 'create-test-data!parsing';
-import {parseData} from '../src/ebml-helpers.js';
-import {doesCodecMatch, codecsFromFile} from './test-helpers.js';
-
-const files = [];
-
-// seperate files into modules by extension
-Object.keys(formatFiles).forEach((file) => {
- const extension = file.split('.').pop();
-
- if (extension === 'webm' || extension === 'mkv') {
- files.push(file);
- }
-
-});
-
-QUnit.module('parseData');
-
-files.forEach((file) => QUnit.test(`${file} can be parsed for tracks and blocks`, function(assert) {
- const {blocks, tracks} = parseData(formatFiles[file]());
- const codecs = codecsFromFile(file);
-
- assert.equal(tracks.length, Object.keys(codecs).length, 'tracks as expected');
-
- tracks.forEach(function(track) {
- assert.ok(doesCodecMatch(track.codec, codecs[track.type]), `${track.codec} is ${codecs[track.type]}`);
- });
-
- assert.ok(blocks.length, `has ${blocks.length} blocks`);
- assert.notOk(blocks.filter((b) => !b.frames.length).length, 'all blocks have frame data');
-}));
-
-QUnit.test('xiph and ebml lacing', function(assert) {
- const {blocks} = parseData(parsingFiles['xiph-ebml-lacing.mkv']());
-
- assert.ok(blocks.length, `has ${blocks.length} blocks`);
- assert.notOk(blocks.filter((b) => !b.frames.length).length, 'all blocks have frame data');
- assert.equal(blocks[1].lacing, 1, 'xiph lacing');
- assert.equal(blocks[2].lacing, 3, 'ebml lacing');
-});
-
-QUnit.test('fixed lacing', function(assert) {
- const {blocks} = parseData(parsingFiles['fixed-lacing.mkv']());
-
- assert.ok(blocks.length, `has ${blocks.length} blocks`);
- assert.notOk(blocks.filter((b) => !b.frames.length).length, 'all blocks have frame data');
- assert.equal(blocks[12].lacing, 2, 'fixed lacing');
-});
-
-QUnit.test('live data', function(assert) {
- const {blocks} = parseData(parsingFiles['live.mkv']());
-
- assert.ok(blocks.length, 6, 'has 6 blocks, even with "infinite" cluster dataSize');
- assert.notOk(blocks.filter((b) => !b.frames.length).length, 'all blocks have frame data');
-});
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/aac/aac.aac b/node_modules/@videojs/vhs-utils/test/fixtures/formats/aac/aac.aac
deleted file mode 100644
index 4efda7e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/aac/aac.aac and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ac3/ac-3.ac3 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ac3/ac-3.ac3
deleted file mode 100644
index 93f630a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ac3/ac-3.ac3 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ac3/ec-3.ac3 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ac3/ec-3.ac3
deleted file mode 100644
index c291fb4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ac3/ec-3.ac3 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/aac.avi
deleted file mode 100644
index e6b18c2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/ac-3.avi
deleted file mode 100644
index 15e30cc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,aac.avi
deleted file mode 100644
index 5495010..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,ac-3.avi
deleted file mode 100644
index 91351b7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,ec-3.avi
deleted file mode 100644
index 5898eec..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,flac.avi
deleted file mode 100644
index 006a9fe..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp3.avi
deleted file mode 100644
index 4f25e96..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.2.avi
deleted file mode 100644
index 131ce1d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.29.avi
deleted file mode 100644
index 95f5891..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.34.avi
deleted file mode 100644
index 08f82e4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.5.avi
deleted file mode 100644
index c1556da..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,speex.avi
deleted file mode 100644
index 1f39297..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,vorbis.avi
deleted file mode 100644
index 1bea933..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01.avi
deleted file mode 100644
index bb2e36f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/av01.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,aac.avi
deleted file mode 100644
index bc6255d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,ac-3.avi
deleted file mode 100644
index 58f9f17..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,ec-3.avi
deleted file mode 100644
index 300255b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,flac.avi
deleted file mode 100644
index 2c657e3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp3.avi
deleted file mode 100644
index bfda3dc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.2.avi
deleted file mode 100644
index 1c324c6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.29.avi
deleted file mode 100644
index ae05a38..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.34.avi
deleted file mode 100644
index 65142dd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.5.avi
deleted file mode 100644
index 309be08..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,speex.avi
deleted file mode 100644
index b05b583..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,vorbis.avi
deleted file mode 100644
index 1bca43f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d.avi
deleted file mode 100644
index 3bde18d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.42c00d.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,aac.avi
deleted file mode 100644
index b255ccd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,ac-3.avi
deleted file mode 100644
index 30d4fd0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,ec-3.avi
deleted file mode 100644
index 6180b70..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,flac.avi
deleted file mode 100644
index 9bb22fc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp3.avi
deleted file mode 100644
index affe531..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.2.avi
deleted file mode 100644
index ccfeb95..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.29.avi
deleted file mode 100644
index 0b940bf..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.34.avi
deleted file mode 100644
index 4d3a449..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.5.avi
deleted file mode 100644
index aea1066..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,speex.avi
deleted file mode 100644
index fe1a330..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,vorbis.avi
deleted file mode 100644
index 5ccaec0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e.avi
deleted file mode 100644
index c5b745e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.4d401e.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,aac.avi
deleted file mode 100644
index 4ac453d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,ac-3.avi
deleted file mode 100644
index 8c0ceac..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,ec-3.avi
deleted file mode 100644
index 6f6fcdc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,flac.avi
deleted file mode 100644
index f47274c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp3.avi
deleted file mode 100644
index 3166317..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.2.avi
deleted file mode 100644
index 55d3e4a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.29.avi
deleted file mode 100644
index d9d887c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.34.avi
deleted file mode 100644
index 6d9ea11..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.5.avi
deleted file mode 100644
index 60bbbe2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,speex.avi
deleted file mode 100644
index 373a463..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,vorbis.avi
deleted file mode 100644
index 53c73eb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028.avi
deleted file mode 100644
index 63d61ff..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/avc1.640028.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/ec-3.avi
deleted file mode 100644
index f584e12..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/flac.avi
deleted file mode 100644
index 797b82a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,aac.avi
deleted file mode 100644
index 77218a3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,ac-3.avi
deleted file mode 100644
index e19cf0e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,ec-3.avi
deleted file mode 100644
index 37f38cd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,flac.avi
deleted file mode 100644
index 2bce16b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp3.avi
deleted file mode 100644
index 3280052..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.2.avi
deleted file mode 100644
index fd8d93e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.29.avi
deleted file mode 100644
index 2d99cf8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.34.avi
deleted file mode 100644
index 4d1699f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.5.avi
deleted file mode 100644
index fb845ee..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,speex.avi
deleted file mode 100644
index 6b43a31..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,vorbis.avi
deleted file mode 100644
index 67a3ca3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90.avi
deleted file mode 100644
index ce82fe3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H120.90.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,aac.avi
deleted file mode 100644
index 960ba38..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,ac-3.avi
deleted file mode 100644
index 3976f15..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,ec-3.avi
deleted file mode 100644
index 7e5dad0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,flac.avi
deleted file mode 100644
index 6db1d25..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp3.avi
deleted file mode 100644
index 88e94d6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.2.avi
deleted file mode 100644
index 7e3fcbc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.29.avi
deleted file mode 100644
index 1bd1a80..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.34.avi
deleted file mode 100644
index 08e533f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.5.avi
deleted file mode 100644
index 360e1a7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,speex.avi
deleted file mode 100644
index 3c2a773..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,vorbis.avi
deleted file mode 100644
index 8150b14..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90.avi
deleted file mode 100644
index 6c4d848..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.H150.90.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,aac.avi
deleted file mode 100644
index 1685f8c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,ac-3.avi
deleted file mode 100644
index 01f71fb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,ec-3.avi
deleted file mode 100644
index f7ae8fa..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,flac.avi
deleted file mode 100644
index 999a68d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp3.avi
deleted file mode 100644
index 80fc9a7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.2.avi
deleted file mode 100644
index d2e79ba..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.29.avi
deleted file mode 100644
index 2cfd953..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.34.avi
deleted file mode 100644
index 079edf6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.5.avi
deleted file mode 100644
index 9178bbc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,speex.avi
deleted file mode 100644
index 0b23a20..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,vorbis.avi
deleted file mode 100644
index e709273..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90.avi
deleted file mode 100644
index 6109d8b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.1.6.L60.90.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,aac.avi
deleted file mode 100644
index 5666cd0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,ac-3.avi
deleted file mode 100644
index ec91b3e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,ec-3.avi
deleted file mode 100644
index 91e08f6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,flac.avi
deleted file mode 100644
index b5276d7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp3.avi
deleted file mode 100644
index 805215f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.2.avi
deleted file mode 100644
index 7c0becd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.29.avi
deleted file mode 100644
index 1569697..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.34.avi
deleted file mode 100644
index a67caf4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.5.avi
deleted file mode 100644
index ab7972d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,speex.avi
deleted file mode 100644
index f5d5c07..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,vorbis.avi
deleted file mode 100644
index 9282fc8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8.avi
deleted file mode 100644
index 80e31b6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/hev1.4.10.H120.9c.8.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp3.avi
deleted file mode 100644
index 0daf1ba..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.2.avi
deleted file mode 100644
index a69240f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.29.avi
deleted file mode 100644
index 37c2fb1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.34.avi
deleted file mode 100644
index c2c98d8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.5.avi
deleted file mode 100644
index d671149..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,aac.avi
deleted file mode 100644
index ecbbcaa..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,ac-3.avi
deleted file mode 100644
index 5939cc4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,ec-3.avi
deleted file mode 100644
index 3c236ce..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,flac.avi
deleted file mode 100644
index f8dbe8e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp3.avi
deleted file mode 100644
index bf841e5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.2.avi
deleted file mode 100644
index 1b661ff..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.29.avi
deleted file mode 100644
index 9ee1993..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.34.avi
deleted file mode 100644
index ed1ce64..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.5.avi
deleted file mode 100644
index fa6685d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,speex.avi
deleted file mode 100644
index 47f4330..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,vorbis.avi
deleted file mode 100644
index 2dfbd07..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240.avi
deleted file mode 100644
index f53257b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.240.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,aac.avi
deleted file mode 100644
index 274483e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,ac-3.avi
deleted file mode 100644
index cbcb80d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,ec-3.avi
deleted file mode 100644
index fe67034..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,flac.avi
deleted file mode 100644
index b8882f9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp3.avi
deleted file mode 100644
index e8d3fcc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.2.avi
deleted file mode 100644
index 99afdaf..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.29.avi
deleted file mode 100644
index 7cc1cf6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.34.avi
deleted file mode 100644
index 3ba78c5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.5.avi
deleted file mode 100644
index 7f59b65..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,speex.avi
deleted file mode 100644
index 5074e16..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,vorbis.avi
deleted file mode 100644
index f25ab97..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9.avi
deleted file mode 100644
index a8a8ebf..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/mp4v.20.9.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/speex.avi
deleted file mode 100644
index e3332f3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,aac.avi
deleted file mode 100644
index 8695004..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,ac-3.avi
deleted file mode 100644
index 903816a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,ec-3.avi
deleted file mode 100644
index 7085d01..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,flac.avi
deleted file mode 100644
index db561b3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp3.avi
deleted file mode 100644
index 274c02e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.2.avi
deleted file mode 100644
index a37c112..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.29.avi
deleted file mode 100644
index 07077b5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.34.avi
deleted file mode 100644
index 722c716..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.5.avi
deleted file mode 100644
index f460a98..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,speex.avi
deleted file mode 100644
index ea53f51..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,vorbis.avi
deleted file mode 100644
index 375c17c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora.avi
deleted file mode 100644
index 0b30b97..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/theora.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vorbis.avi
deleted file mode 100644
index 1bb0033..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,aac.avi
deleted file mode 100644
index 34c0888..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,ac-3.avi
deleted file mode 100644
index 99b747b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,ec-3.avi
deleted file mode 100644
index 4611c57..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,flac.avi
deleted file mode 100644
index 251cc25..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp3.avi
deleted file mode 100644
index b216f27..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.2.avi
deleted file mode 100644
index 4a0a8d9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.29.avi
deleted file mode 100644
index de854df..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.34.avi
deleted file mode 100644
index 4173363..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.5.avi
deleted file mode 100644
index 62550ab..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,speex.avi
deleted file mode 100644
index 5a8524e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,vorbis.avi
deleted file mode 100644
index 8e64f12..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8.avi
deleted file mode 100644
index 8a85c6e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp8.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,aac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,aac.avi
deleted file mode 100644
index 8204dce..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,aac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,ac-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,ac-3.avi
deleted file mode 100644
index 851d252..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,ac-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,ec-3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,ec-3.avi
deleted file mode 100644
index 634580b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,ec-3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,flac.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,flac.avi
deleted file mode 100644
index c2c6a6e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,flac.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp3.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp3.avi
deleted file mode 100644
index ad6527c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp3.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.2.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.2.avi
deleted file mode 100644
index 7ee42d7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.2.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.29.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.29.avi
deleted file mode 100644
index 18f551e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.29.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.34.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.34.avi
deleted file mode 100644
index 51eb1b0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.34.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.5.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.5.avi
deleted file mode 100644
index 1cbd268..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,mp4a.40.5.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,speex.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,speex.avi
deleted file mode 100644
index 68b311d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,speex.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,vorbis.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,vorbis.avi
deleted file mode 100644
index 57bf528..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9,vorbis.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9.avi b/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9.avi
deleted file mode 100644
index 36480f1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/avi/vp9.avi and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/flac/flac.flac b/node_modules/@videojs/vhs-utils/test/fixtures/formats/flac/flac.flac
deleted file mode 100644
index c9e3071..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/flac/flac.flac and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h264/avc1.42c00d.h264 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/h264/avc1.42c00d.h264
deleted file mode 100644
index 3ed90ad..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h264/avc1.42c00d.h264 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h264/avc1.4d401e.h264 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/h264/avc1.4d401e.h264
deleted file mode 100644
index 85be2e9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h264/avc1.4d401e.h264 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h264/avc1.640028.h264 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/h264/avc1.640028.h264
deleted file mode 100644
index 4e4595d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h264/avc1.640028.h264 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.1.6.H120.90.h265 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.1.6.H120.90.h265
deleted file mode 100644
index a00b400..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.1.6.H120.90.h265 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.1.6.H150.90.h265 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.1.6.H150.90.h265
deleted file mode 100644
index 3b56444..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.1.6.H150.90.h265 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.1.6.L60.90.h265 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.1.6.L60.90.h265
deleted file mode 100644
index 2ee6623..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.1.6.L60.90.h265 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.4.10.H120.9c.8.h265 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.4.10.H120.9c.8.h265
deleted file mode 100644
index 38f914e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/h265/hev1.4.10.H120.9c.8.h265 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/aac.mkv
deleted file mode 100644
index 82e3b4e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/ac-3.mkv
deleted file mode 100644
index 3960f3f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/alac.mkv
deleted file mode 100644
index 8869111..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,aac.mkv
deleted file mode 100644
index 3654fbb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,ac-3.mkv
deleted file mode 100644
index 19d53c6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,alac.mkv
deleted file mode 100644
index 4b4e725..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,ec-3.mkv
deleted file mode 100644
index 90454e6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,flac.mkv
deleted file mode 100644
index 3c5b3e2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp3.mkv
deleted file mode 100644
index 5ee256d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.2.mkv
deleted file mode 100644
index ad75cb8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.29.mkv
deleted file mode 100644
index ee630eb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.34.mkv
deleted file mode 100644
index f8da68e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.5.mkv
deleted file mode 100644
index 857f4aa..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,opus.mkv
deleted file mode 100644
index 9146aa3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,speex.mkv
deleted file mode 100644
index fe9e08b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,vorbis.mkv
deleted file mode 100644
index cad9612..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110.mkv
deleted file mode 100644
index 195d33b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/av01.0.00M.08.0.110.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,aac.mkv
deleted file mode 100644
index 928f2d8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,ac-3.mkv
deleted file mode 100644
index ea8bd4a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,alac.mkv
deleted file mode 100644
index 6b58426..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,ec-3.mkv
deleted file mode 100644
index 45f6b73..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,flac.mkv
deleted file mode 100644
index 26e39d3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp3.mkv
deleted file mode 100644
index da45c37..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.2.mkv
deleted file mode 100644
index 6a8d030..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.29.mkv
deleted file mode 100644
index 5349913..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.34.mkv
deleted file mode 100644
index 38b8ee0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.5.mkv
deleted file mode 100644
index 0473385..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,opus.mkv
deleted file mode 100644
index 8610cf1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,speex.mkv
deleted file mode 100644
index 0285d9b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,vorbis.mkv
deleted file mode 100644
index cd0f1a9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d.mkv
deleted file mode 100644
index 514d82e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.42c00d.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,aac.mkv
deleted file mode 100644
index 829030b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,ac-3.mkv
deleted file mode 100644
index 42e34a8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,alac.mkv
deleted file mode 100644
index ac2d67b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,ec-3.mkv
deleted file mode 100644
index 83a5339..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,flac.mkv
deleted file mode 100644
index b03e9d3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp3.mkv
deleted file mode 100644
index 2c80abd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.2.mkv
deleted file mode 100644
index 18b94db..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.29.mkv
deleted file mode 100644
index 9fe709c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.34.mkv
deleted file mode 100644
index d54fbac..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.5.mkv
deleted file mode 100644
index bdda1ea..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,opus.mkv
deleted file mode 100644
index 543c467..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,speex.mkv
deleted file mode 100644
index 810c162..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,vorbis.mkv
deleted file mode 100644
index f195163..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e.mkv
deleted file mode 100644
index 002bba4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.4d401e.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,aac.mkv
deleted file mode 100644
index fd1ef6d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,ac-3.mkv
deleted file mode 100644
index 15a57e5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,alac.mkv
deleted file mode 100644
index e0f6bcb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,ec-3.mkv
deleted file mode 100644
index 2e279ae..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,flac.mkv
deleted file mode 100644
index aabcba9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp3.mkv
deleted file mode 100644
index fcc197b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.2.mkv
deleted file mode 100644
index 41e1a44..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.29.mkv
deleted file mode 100644
index 3cfb5f3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.34.mkv
deleted file mode 100644
index d069ebb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.5.mkv
deleted file mode 100644
index d6da7df..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,opus.mkv
deleted file mode 100644
index fc681cf..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,speex.mkv
deleted file mode 100644
index 0e7f9d8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,vorbis.mkv
deleted file mode 100644
index 786a985..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028.mkv
deleted file mode 100644
index e4b9d71..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/avc1.640028.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/ec-3.mkv
deleted file mode 100644
index 7ea403a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/flac.mkv
deleted file mode 100644
index bfdc469..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,aac.mkv
deleted file mode 100644
index 0e7154f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,ac-3.mkv
deleted file mode 100644
index c86432a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,alac.mkv
deleted file mode 100644
index 8c7b0e8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,ec-3.mkv
deleted file mode 100644
index 73d0697..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,flac.mkv
deleted file mode 100644
index 2a4dc80..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp3.mkv
deleted file mode 100644
index 6e7aa68..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.2.mkv
deleted file mode 100644
index 9ff689e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.29.mkv
deleted file mode 100644
index eadc0c6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.34.mkv
deleted file mode 100644
index 9a41aff..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.5.mkv
deleted file mode 100644
index 4e922d5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,opus.mkv
deleted file mode 100644
index b545f6a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,speex.mkv
deleted file mode 100644
index d46518f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,vorbis.mkv
deleted file mode 100644
index f69c627..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90.mkv
deleted file mode 100644
index e160a39..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H120.90.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,aac.mkv
deleted file mode 100644
index 70578dd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,ac-3.mkv
deleted file mode 100644
index bbdae55..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,alac.mkv
deleted file mode 100644
index 77ef2d6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,ec-3.mkv
deleted file mode 100644
index a1a22c9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,flac.mkv
deleted file mode 100644
index 5e7fce9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp3.mkv
deleted file mode 100644
index d9ca04d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.2.mkv
deleted file mode 100644
index a79a9ba..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.29.mkv
deleted file mode 100644
index 6b4b899..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.34.mkv
deleted file mode 100644
index ba6b378..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.5.mkv
deleted file mode 100644
index ebd1319..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,opus.mkv
deleted file mode 100644
index 31fa7ab..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,speex.mkv
deleted file mode 100644
index 98bdbee..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,vorbis.mkv
deleted file mode 100644
index 6e5ad77..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90.mkv
deleted file mode 100644
index d58287c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.H150.90.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,aac.mkv
deleted file mode 100644
index a8e8a7d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,ac-3.mkv
deleted file mode 100644
index 9149a49..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,alac.mkv
deleted file mode 100644
index 0d7b3cd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,ec-3.mkv
deleted file mode 100644
index dc04fad..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,flac.mkv
deleted file mode 100644
index 9b329c4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp3.mkv
deleted file mode 100644
index 43a280a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.2.mkv
deleted file mode 100644
index 5a353f1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.29.mkv
deleted file mode 100644
index fc9d1fb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.34.mkv
deleted file mode 100644
index 02be2a9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.5.mkv
deleted file mode 100644
index 2ef7a0d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,opus.mkv
deleted file mode 100644
index 0767e36..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,speex.mkv
deleted file mode 100644
index 38f9490..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,vorbis.mkv
deleted file mode 100644
index d487ee5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90.mkv
deleted file mode 100644
index f815abe..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.1.6.L60.90.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,aac.mkv
deleted file mode 100644
index 1dbfdad..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,ac-3.mkv
deleted file mode 100644
index de875b1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,alac.mkv
deleted file mode 100644
index 1e2d6c0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,ec-3.mkv
deleted file mode 100644
index 0e26fe3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,flac.mkv
deleted file mode 100644
index 3a81be4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp3.mkv
deleted file mode 100644
index f0f9a3e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.2.mkv
deleted file mode 100644
index 56d0af6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.29.mkv
deleted file mode 100644
index 8604e68..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.34.mkv
deleted file mode 100644
index 78a59fd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.5.mkv
deleted file mode 100644
index 5e54f99..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,opus.mkv
deleted file mode 100644
index 33d2ea8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,speex.mkv
deleted file mode 100644
index 2190b27..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,vorbis.mkv
deleted file mode 100644
index aa17036..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8.mkv
deleted file mode 100644
index ee33c79..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/hev1.4.10.H120.9c.8.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp3.mkv
deleted file mode 100644
index 0ddfde8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.2.mkv
deleted file mode 100644
index dec5724..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.29.mkv
deleted file mode 100644
index 96e3772..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.34.mkv
deleted file mode 100644
index 22311ad..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.5.mkv
deleted file mode 100644
index d0480e7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,aac.mkv
deleted file mode 100644
index a8acc02..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,ac-3.mkv
deleted file mode 100644
index c075f02..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,alac.mkv
deleted file mode 100644
index 14d9f8f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,ec-3.mkv
deleted file mode 100644
index be496d9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,flac.mkv
deleted file mode 100644
index f4aafdc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp3.mkv
deleted file mode 100644
index e8ecaf8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.2.mkv
deleted file mode 100644
index cb99186..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.29.mkv
deleted file mode 100644
index 49174e9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.34.mkv
deleted file mode 100644
index 0d9231b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.5.mkv
deleted file mode 100644
index 4ea9835..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,opus.mkv
deleted file mode 100644
index 9726f80..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,speex.mkv
deleted file mode 100644
index 2fba245..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,vorbis.mkv
deleted file mode 100644
index 266ace8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240.mkv
deleted file mode 100644
index 6e031b2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.240.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,aac.mkv
deleted file mode 100644
index d26bcfb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,ac-3.mkv
deleted file mode 100644
index 33589b5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,alac.mkv
deleted file mode 100644
index 10feefb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,ec-3.mkv
deleted file mode 100644
index db07063..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,flac.mkv
deleted file mode 100644
index 1d3cc6e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp3.mkv
deleted file mode 100644
index 64626a8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.2.mkv
deleted file mode 100644
index 7cf9bc4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.29.mkv
deleted file mode 100644
index 56b9805..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.34.mkv
deleted file mode 100644
index 6cf21b9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.5.mkv
deleted file mode 100644
index 0127293..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,opus.mkv
deleted file mode 100644
index 8b89a10..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,speex.mkv
deleted file mode 100644
index 6d19bc1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,vorbis.mkv
deleted file mode 100644
index c9b02d9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9.mkv
deleted file mode 100644
index bdc1bfb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/mp4v.20.9.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/opus.mkv
deleted file mode 100644
index 1d4e7d5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/speex.mkv
deleted file mode 100644
index b30919c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,aac.mkv
deleted file mode 100644
index 5843852..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,ac-3.mkv
deleted file mode 100644
index 2a7b8ee..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,alac.mkv
deleted file mode 100644
index 2b6d610..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,ec-3.mkv
deleted file mode 100644
index d263cb8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,flac.mkv
deleted file mode 100644
index d7da5cf..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp3.mkv
deleted file mode 100644
index d02b22b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.2.mkv
deleted file mode 100644
index bff36ac..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.29.mkv
deleted file mode 100644
index 1c742fa..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.34.mkv
deleted file mode 100644
index b4d5d31..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.5.mkv
deleted file mode 100644
index 674a75c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,opus.mkv
deleted file mode 100644
index 0ef7839..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,speex.mkv
deleted file mode 100644
index 848ed1a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,vorbis.mkv
deleted file mode 100644
index 4f01d38..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora.mkv
deleted file mode 100644
index 3bc731c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/theora.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vorbis.mkv
deleted file mode 100644
index 29469a2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,aac.mkv
deleted file mode 100644
index af2ae4c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,ac-3.mkv
deleted file mode 100644
index 5bd4359..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,alac.mkv
deleted file mode 100644
index c9e577c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,ec-3.mkv
deleted file mode 100644
index c0a849e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,flac.mkv
deleted file mode 100644
index 1686db5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp3.mkv
deleted file mode 100644
index 3d31915..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.2.mkv
deleted file mode 100644
index f36099c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.29.mkv
deleted file mode 100644
index 043effa..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.34.mkv
deleted file mode 100644
index 35495b4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.5.mkv
deleted file mode 100644
index 21e3d8e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,opus.mkv
deleted file mode 100644
index 2768a82..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,speex.mkv
deleted file mode 100644
index 7bc8cb6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,vorbis.mkv
deleted file mode 100644
index 8d3528c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8.mkv
deleted file mode 100644
index b36192b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp8.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,aac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,aac.mkv
deleted file mode 100644
index 65d09e0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,aac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,ac-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,ac-3.mkv
deleted file mode 100644
index e75a429..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,ac-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,alac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,alac.mkv
deleted file mode 100644
index 2fc891e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,alac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,ec-3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,ec-3.mkv
deleted file mode 100644
index 10d40df..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,ec-3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,flac.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,flac.mkv
deleted file mode 100644
index a8b1960..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,flac.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp3.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp3.mkv
deleted file mode 100644
index 993088f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp3.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.2.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.2.mkv
deleted file mode 100644
index 6179d0b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.2.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.29.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.29.mkv
deleted file mode 100644
index 2366e84..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.29.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.34.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.34.mkv
deleted file mode 100644
index 978d985..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.34.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.5.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.5.mkv
deleted file mode 100644
index b15e0b7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,mp4a.40.5.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,opus.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,opus.mkv
deleted file mode 100644
index 63017f5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,opus.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,speex.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,speex.mkv
deleted file mode 100644
index d647cbc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,speex.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,vorbis.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,vorbis.mkv
deleted file mode 100644
index a023107..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9,vorbis.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9.mkv
deleted file mode 100644
index 7f93565..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mkv/vp9.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/aac.mov
deleted file mode 100644
index 3bc8e60..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/ac-3.mov
deleted file mode 100644
index ab9dbb2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/alac.mov
deleted file mode 100644
index b1c03e2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,aac.mov
deleted file mode 100644
index 7883e16..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,ac-3.mov
deleted file mode 100644
index 15d2fcc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,alac.mov
deleted file mode 100644
index 3a3844a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,ec-3.mov
deleted file mode 100644
index bbab6fa..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp3.mov
deleted file mode 100644
index 531cd77..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.2.mov
deleted file mode 100644
index f0a611b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.29.mov
deleted file mode 100644
index 63b6ff5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.34.mov
deleted file mode 100644
index 57adc83..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.5.mov
deleted file mode 100644
index 64d0db6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,speex.mov
deleted file mode 100644
index 07c6b79..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,vorbis.mov
deleted file mode 100644
index d4fe67b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d.mov
deleted file mode 100644
index 0888fb2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.42c00d.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,aac.mov
deleted file mode 100644
index ca79cce..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,ac-3.mov
deleted file mode 100644
index 37be85f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,alac.mov
deleted file mode 100644
index e32754f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,ec-3.mov
deleted file mode 100644
index 5713650..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp3.mov
deleted file mode 100644
index 9341a6d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.2.mov
deleted file mode 100644
index 0aed412..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.29.mov
deleted file mode 100644
index bb567e3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.34.mov
deleted file mode 100644
index 35028e7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.5.mov
deleted file mode 100644
index ce4b914..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,speex.mov
deleted file mode 100644
index ef74351..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,vorbis.mov
deleted file mode 100644
index 5148d43..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e.mov
deleted file mode 100644
index 17f659c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.4d401e.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,aac.mov
deleted file mode 100644
index b16553d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,ac-3.mov
deleted file mode 100644
index cb3b187..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,alac.mov
deleted file mode 100644
index 48fca00..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,ec-3.mov
deleted file mode 100644
index d82c962..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp3.mov
deleted file mode 100644
index 6fe1b8a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.2.mov
deleted file mode 100644
index f9ca03a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.29.mov
deleted file mode 100644
index 37c1730..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.34.mov
deleted file mode 100644
index 18d8849..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.5.mov
deleted file mode 100644
index 70b7e1a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,speex.mov
deleted file mode 100644
index 44bffa4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,vorbis.mov
deleted file mode 100644
index d4b4361..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028.mov
deleted file mode 100644
index f2c9865..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/avc1.640028.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/ec-3.mov
deleted file mode 100644
index 26b3277..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,aac.mov
deleted file mode 100644
index d718756..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,ac-3.mov
deleted file mode 100644
index 07f34cb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,alac.mov
deleted file mode 100644
index 2b57e2c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,ec-3.mov
deleted file mode 100644
index 8f94c27..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp3.mov
deleted file mode 100644
index d37971d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.2.mov
deleted file mode 100644
index 382e65d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.29.mov
deleted file mode 100644
index 76d8cc4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.34.mov
deleted file mode 100644
index d39c0e8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.5.mov
deleted file mode 100644
index 887810f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,speex.mov
deleted file mode 100644
index b4daa1d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,vorbis.mov
deleted file mode 100644
index 884062c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90.mov
deleted file mode 100644
index 8a4cab3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H120.90.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,aac.mov
deleted file mode 100644
index a5aafe6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,ac-3.mov
deleted file mode 100644
index 24afcf9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,alac.mov
deleted file mode 100644
index 02a33b4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,ec-3.mov
deleted file mode 100644
index bed1971..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp3.mov
deleted file mode 100644
index 29aeb08..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.2.mov
deleted file mode 100644
index bb623cb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.29.mov
deleted file mode 100644
index 43a18db..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.34.mov
deleted file mode 100644
index ee2bdbc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.5.mov
deleted file mode 100644
index 544a73a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,speex.mov
deleted file mode 100644
index 845172b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,vorbis.mov
deleted file mode 100644
index d3f345b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90.mov
deleted file mode 100644
index 2cb6758..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.H150.90.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,aac.mov
deleted file mode 100644
index 388e2e8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,ac-3.mov
deleted file mode 100644
index b72fc24..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,alac.mov
deleted file mode 100644
index 56706e4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,ec-3.mov
deleted file mode 100644
index a4ec394..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp3.mov
deleted file mode 100644
index 16c28ad..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.2.mov
deleted file mode 100644
index d8a552a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.29.mov
deleted file mode 100644
index 5a30926..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.34.mov
deleted file mode 100644
index 163212c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.5.mov
deleted file mode 100644
index 94c5ebc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,speex.mov
deleted file mode 100644
index f3ca4ab..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,vorbis.mov
deleted file mode 100644
index 66c4753..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90.mov
deleted file mode 100644
index f439e43..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.1.6.L60.90.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,aac.mov
deleted file mode 100644
index f9eb0d8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,ac-3.mov
deleted file mode 100644
index 2483796..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,alac.mov
deleted file mode 100644
index d457c23..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,ec-3.mov
deleted file mode 100644
index 637ee70..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp3.mov
deleted file mode 100644
index 6f2ecee..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.2.mov
deleted file mode 100644
index 732d65f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.29.mov
deleted file mode 100644
index 3216fe4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.34.mov
deleted file mode 100644
index 76983d4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.5.mov
deleted file mode 100644
index 25e2ee9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,speex.mov
deleted file mode 100644
index 527175f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,vorbis.mov
deleted file mode 100644
index 90a7f0b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8.mov
deleted file mode 100644
index 7e81e2a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hev1.4.10.H120.9c.8.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,aac.mov
deleted file mode 100644
index 8e65d0e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,ac-3.mov
deleted file mode 100644
index 11a14c7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,alac.mov
deleted file mode 100644
index 0cf0876..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,ec-3.mov
deleted file mode 100644
index 326b8ca..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp3.mov
deleted file mode 100644
index cd8679a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.2.mov
deleted file mode 100644
index 97af4db..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.29.mov
deleted file mode 100644
index 8de01d2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.34.mov
deleted file mode 100644
index b1cfd68..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.5.mov
deleted file mode 100644
index e8b4d9e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,speex.mov
deleted file mode 100644
index f19150a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,vorbis.mov
deleted file mode 100644
index 77c36c2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90.mov
deleted file mode 100644
index 92ca284..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/hvc1.1.6.H120.90.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp3.mov
deleted file mode 100644
index e7e4be5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.2.mov
deleted file mode 100644
index 3622df1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.29.mov
deleted file mode 100644
index 0003a30..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.34.mov
deleted file mode 100644
index 4f92bec..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.5.mov
deleted file mode 100644
index bc50c89..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,aac.mov
deleted file mode 100644
index d12ea74..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,ac-3.mov
deleted file mode 100644
index 29346c0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,alac.mov
deleted file mode 100644
index d0b1e8d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,ec-3.mov
deleted file mode 100644
index 69d8cf5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp3.mov
deleted file mode 100644
index 80b0a40..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.2.mov
deleted file mode 100644
index 71e6974..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.29.mov
deleted file mode 100644
index 311202e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.34.mov
deleted file mode 100644
index e581858..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.5.mov
deleted file mode 100644
index 9ebad60..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,speex.mov
deleted file mode 100644
index 970b608..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,vorbis.mov
deleted file mode 100644
index d008294..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240.mov
deleted file mode 100644
index 24368d1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.240.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,aac.mov
deleted file mode 100644
index 126d2e6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,ac-3.mov
deleted file mode 100644
index 879463e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,alac.mov
deleted file mode 100644
index 16a0ad3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,ec-3.mov
deleted file mode 100644
index bb81387..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp3.mov
deleted file mode 100644
index 89bca50..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.2.mov
deleted file mode 100644
index 6d8de75..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.29.mov
deleted file mode 100644
index 7f64e91..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.34.mov
deleted file mode 100644
index 296fc08..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.5.mov
deleted file mode 100644
index c72000a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,speex.mov
deleted file mode 100644
index 0eb4959..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,vorbis.mov
deleted file mode 100644
index 07d84c1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9.mov
deleted file mode 100644
index c0a8051..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/mp4v.20.9.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/speex.mov
deleted file mode 100644
index fb7af3b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,aac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,aac.mov
deleted file mode 100644
index 54a838c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,aac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,ac-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,ac-3.mov
deleted file mode 100644
index 59f473e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,ac-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,alac.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,alac.mov
deleted file mode 100644
index 91a92bc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,alac.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,ec-3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,ec-3.mov
deleted file mode 100644
index 6ca71cd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,ec-3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp3.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp3.mov
deleted file mode 100644
index 4d0225f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp3.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.2.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.2.mov
deleted file mode 100644
index d669632..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.2.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.29.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.29.mov
deleted file mode 100644
index 6342ed7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.29.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.34.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.34.mov
deleted file mode 100644
index 7de2d52..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.34.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.5.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.5.mov
deleted file mode 100644
index 1929aca..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,mp4a.40.5.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,speex.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,speex.mov
deleted file mode 100644
index 5d5d69e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,speex.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,vorbis.mov
deleted file mode 100644
index 6b038e6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora,vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora.mov
deleted file mode 100644
index 5a028f6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/theora.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/vorbis.mov b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/vorbis.mov
deleted file mode 100644
index 29821a0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mov/vorbis.mov and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp3/mp3.mp3 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp3/mp3.mp3
deleted file mode 100644
index 4cd329f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp3/mp3.mp3 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/aac.mp4
deleted file mode 100644
index 9d98de6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/ac-3.mp4
deleted file mode 100644
index 6f486eb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,aac.mp4
deleted file mode 100644
index 062d8a3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,ac-3.mp4
deleted file mode 100644
index 49ea24e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,ec-3.mp4
deleted file mode 100644
index fd91f71..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp3.mp4
deleted file mode 100644
index 14d04ec..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.2.mp4
deleted file mode 100644
index e1da7dc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.29.mp4
deleted file mode 100644
index d6c6f3b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.34.mp4
deleted file mode 100644
index 6631f73..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.5.mp4
deleted file mode 100644
index addc621..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,vorbis.mp4
deleted file mode 100644
index 7f1009c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110.mp4
deleted file mode 100644
index 80c25e9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/av01.0.00M.08.0.110.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,aac.mp4
deleted file mode 100644
index 8279e1d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,ac-3.mp4
deleted file mode 100644
index 4250bb4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,ec-3.mp4
deleted file mode 100644
index fa3232a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp3.mp4
deleted file mode 100644
index 19b028d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.2.mp4
deleted file mode 100644
index 2540e75..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.29.mp4
deleted file mode 100644
index 7fe4505..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.34.mp4
deleted file mode 100644
index a2e8721..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.5.mp4
deleted file mode 100644
index e293ff3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,vorbis.mp4
deleted file mode 100644
index dbee69a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d.mp4
deleted file mode 100644
index 9684a6e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.42c00d.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,aac.mp4
deleted file mode 100644
index dfdd5b6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,ac-3.mp4
deleted file mode 100644
index 3986746..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,ec-3.mp4
deleted file mode 100644
index f6030f6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp3.mp4
deleted file mode 100644
index 10fb78e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.2.mp4
deleted file mode 100644
index 47636e0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.29.mp4
deleted file mode 100644
index 72f20a1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.34.mp4
deleted file mode 100644
index 16497b1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.5.mp4
deleted file mode 100644
index 396ca34..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,vorbis.mp4
deleted file mode 100644
index 366e1ef..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e.mp4
deleted file mode 100644
index f8bfde5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.4d401e.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,aac.mp4
deleted file mode 100644
index 3c47662..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,ac-3.mp4
deleted file mode 100644
index b003a21..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,ec-3.mp4
deleted file mode 100644
index 36b6572..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp3.mp4
deleted file mode 100644
index e184fe2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.2.mp4
deleted file mode 100644
index 8005a54..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.29.mp4
deleted file mode 100644
index 7cd1ca9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.34.mp4
deleted file mode 100644
index 10d5bde..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.5.mp4
deleted file mode 100644
index 5a8f9d1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,vorbis.mp4
deleted file mode 100644
index c605f3a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028.mp4
deleted file mode 100644
index e04376a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/avc1.640028.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/ec-3.mp4
deleted file mode 100644
index 17ef4ad..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,aac.mp4
deleted file mode 100644
index 01b7d7b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,ac-3.mp4
deleted file mode 100644
index 5636671..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,ec-3.mp4
deleted file mode 100644
index 2697f41..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp3.mp4
deleted file mode 100644
index f6506af..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.2.mp4
deleted file mode 100644
index 7b8cb7b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.29.mp4
deleted file mode 100644
index 455bc01..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.34.mp4
deleted file mode 100644
index 846e089..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.5.mp4
deleted file mode 100644
index 4305418..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,vorbis.mp4
deleted file mode 100644
index 0b544f6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90.mp4
deleted file mode 100644
index 552ff1e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H120.90.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,aac.mp4
deleted file mode 100644
index 8538261..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,ac-3.mp4
deleted file mode 100644
index d22d988..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,ec-3.mp4
deleted file mode 100644
index f7c33b4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp3.mp4
deleted file mode 100644
index eecba3f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.2.mp4
deleted file mode 100644
index 2845399..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.29.mp4
deleted file mode 100644
index 50c1767..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.34.mp4
deleted file mode 100644
index f5ff59d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.5.mp4
deleted file mode 100644
index a470ddd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,vorbis.mp4
deleted file mode 100644
index cc311c5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90.mp4
deleted file mode 100644
index 3341d7f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.H150.90.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,aac.mp4
deleted file mode 100644
index fb5bc56..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,ac-3.mp4
deleted file mode 100644
index c2f6818..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,ec-3.mp4
deleted file mode 100644
index 5c6eb01..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp3.mp4
deleted file mode 100644
index 47aca13..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.2.mp4
deleted file mode 100644
index 39e73f9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.29.mp4
deleted file mode 100644
index 55aacd8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.34.mp4
deleted file mode 100644
index 43e902c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.5.mp4
deleted file mode 100644
index db5a9f7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,vorbis.mp4
deleted file mode 100644
index 2663973..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90.mp4
deleted file mode 100644
index 40e9bd8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.1.6.L60.90.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,aac.mp4
deleted file mode 100644
index 3ba03a0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,ac-3.mp4
deleted file mode 100644
index 9cc79b5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,ec-3.mp4
deleted file mode 100644
index 538b603..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp3.mp4
deleted file mode 100644
index faf477b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.2.mp4
deleted file mode 100644
index 9709051..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.29.mp4
deleted file mode 100644
index 0d2bf22..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.34.mp4
deleted file mode 100644
index 7c828bd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.5.mp4
deleted file mode 100644
index 0775571..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,vorbis.mp4
deleted file mode 100644
index e1a45fc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8.mp4
deleted file mode 100644
index 26b0860..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hev1.4.10.H120.9c.8.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,aac.mp4
deleted file mode 100644
index aea34d7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,ac-3.mp4
deleted file mode 100644
index e211f35..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,ec-3.mp4
deleted file mode 100644
index ae7f68a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp3.mp4
deleted file mode 100644
index 09870ae..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.2.mp4
deleted file mode 100644
index 17f4ab9..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.29.mp4
deleted file mode 100644
index 533a853..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.34.mp4
deleted file mode 100644
index 504fa97..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.5.mp4
deleted file mode 100644
index 4cd9c6a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,vorbis.mp4
deleted file mode 100644
index 6eaa579..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90.mp4
deleted file mode 100644
index fbffeb3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/hvc1.1.6.H120.90.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp3.mp4
deleted file mode 100644
index 0cb4e2c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.2.mp4
deleted file mode 100644
index a943882..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.29.mp4
deleted file mode 100644
index bc3d0a2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.34.mp4
deleted file mode 100644
index 4e88863..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.5.mp4
deleted file mode 100644
index 2155a15..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,aac.mp4
deleted file mode 100644
index bec9ce2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,ac-3.mp4
deleted file mode 100644
index 08850a4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,ec-3.mp4
deleted file mode 100644
index 15c0117..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp3.mp4
deleted file mode 100644
index 03fdcb7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.2.mp4
deleted file mode 100644
index 80267ee..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.29.mp4
deleted file mode 100644
index c9e662b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.34.mp4
deleted file mode 100644
index 88fa3ea..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.5.mp4
deleted file mode 100644
index 84ecb92..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,vorbis.mp4
deleted file mode 100644
index 13d5c82..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240.mp4
deleted file mode 100644
index 6069793..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.240.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,aac.mp4
deleted file mode 100644
index 23777ac..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,ac-3.mp4
deleted file mode 100644
index abf7e8b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,ec-3.mp4
deleted file mode 100644
index 8651ced..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp3.mp4
deleted file mode 100644
index d55b2bc..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.2.mp4
deleted file mode 100644
index c73605a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.29.mp4
deleted file mode 100644
index e9d41cb..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.34.mp4
deleted file mode 100644
index 1558463..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.5.mp4
deleted file mode 100644
index beecc39..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,vorbis.mp4
deleted file mode 100644
index 25d249c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9.mp4
deleted file mode 100644
index 28ecb23..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/mp4v.20.9.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vorbis.mp4
deleted file mode 100644
index 6110a88..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,aac.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,aac.mp4
deleted file mode 100644
index c05f050..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,aac.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,ac-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,ac-3.mp4
deleted file mode 100644
index a425440..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,ac-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,ec-3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,ec-3.mp4
deleted file mode 100644
index 6cc2116..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,ec-3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp3.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp3.mp4
deleted file mode 100644
index 7c2344c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp3.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.2.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.2.mp4
deleted file mode 100644
index b3f08ee..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.2.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.29.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.29.mp4
deleted file mode 100644
index f72e284..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.29.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.34.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.34.mp4
deleted file mode 100644
index 7a2107f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.34.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.5.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.5.mp4
deleted file mode 100644
index 8ebf010..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,mp4a.40.5.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,vorbis.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,vorbis.mp4
deleted file mode 100644
index d1c480a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00,vorbis.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00.mp4 b/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00.mp4
deleted file mode 100644
index ed2e5c6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/mp4/vp09.01.00.00.00.00.00.20.00.mp4 and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/flac.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/flac.ogg
deleted file mode 100644
index ee91eb6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/flac.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/opus.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/opus.ogg
deleted file mode 100644
index c529813..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/opus.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/speex.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/speex.ogg
deleted file mode 100644
index 21853af..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/speex.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,flac.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,flac.ogg
deleted file mode 100644
index 3ada65b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,flac.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,opus.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,opus.ogg
deleted file mode 100644
index 142f9b5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,opus.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,speex.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,speex.ogg
deleted file mode 100644
index 5b0343f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,speex.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,vorbis.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,vorbis.ogg
deleted file mode 100644
index 0068dab..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora,vorbis.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora.ogg
deleted file mode 100644
index e8503f1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/theora.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vorbis.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vorbis.ogg
deleted file mode 100644
index 6fd59c1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vorbis.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,flac.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,flac.ogg
deleted file mode 100644
index f1f52ce..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,flac.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,opus.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,opus.ogg
deleted file mode 100644
index 6288248..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,opus.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,speex.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,speex.ogg
deleted file mode 100644
index e1f5ce7..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,speex.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,vorbis.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,vorbis.ogg
deleted file mode 100644
index 30e9e33..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8,vorbis.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8.ogg b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8.ogg
deleted file mode 100644
index 2c5069a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ogg/vp8.ogg and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/aac.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/aac.ts
deleted file mode 100644
index 6b59e12..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/aac.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/ac-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/ac-3.ts
deleted file mode 100644
index 550fc17..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/ac-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,aac.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,aac.ts
deleted file mode 100644
index c0a2922..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,aac.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,ac-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,ac-3.ts
deleted file mode 100644
index 8a1da14..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,ac-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,ec-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,ec-3.ts
deleted file mode 100644
index 6c5bea3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,ec-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,mp3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,mp3.ts
deleted file mode 100644
index dfb9b5f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,mp3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,mp4a.40.2.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,mp4a.40.2.ts
deleted file mode 100644
index 78f5996..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,mp4a.40.2.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,mp4a.40.34.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,mp4a.40.34.ts
deleted file mode 100644
index 89ce256..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,mp4a.40.34.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,opus.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,opus.ts
deleted file mode 100644
index 25a39d8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d,opus.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d.ts
deleted file mode 100644
index a574be4..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.42c00d.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,aac.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,aac.ts
deleted file mode 100644
index 9678801..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,aac.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,ac-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,ac-3.ts
deleted file mode 100644
index 56288e6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,ac-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,ec-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,ec-3.ts
deleted file mode 100644
index 3c07267..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,ec-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,mp3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,mp3.ts
deleted file mode 100644
index ef31fd5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,mp3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,mp4a.40.2.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,mp4a.40.2.ts
deleted file mode 100644
index a7fd9fe..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,mp4a.40.2.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,mp4a.40.34.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,mp4a.40.34.ts
deleted file mode 100644
index 2f103a8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,mp4a.40.34.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,opus.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,opus.ts
deleted file mode 100644
index ec697c6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e,opus.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e.ts
deleted file mode 100644
index afc51c0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.4d401e.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,aac.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,aac.ts
deleted file mode 100644
index 05de94f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,aac.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,ac-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,ac-3.ts
deleted file mode 100644
index 020ddb3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,ac-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,ec-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,ec-3.ts
deleted file mode 100644
index 2d64a6a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,ec-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,mp3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,mp3.ts
deleted file mode 100644
index 058ffe1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,mp3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,mp4a.40.2.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,mp4a.40.2.ts
deleted file mode 100644
index 881da13..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,mp4a.40.2.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,mp4a.40.34.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,mp4a.40.34.ts
deleted file mode 100644
index a53ec6d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,mp4a.40.34.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,opus.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,opus.ts
deleted file mode 100644
index 0e51e4f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028,opus.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028.ts
deleted file mode 100644
index bac5a36..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/avc1.640028.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/ec-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/ec-3.ts
deleted file mode 100644
index c2e24ae..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/ec-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,aac.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,aac.ts
deleted file mode 100644
index 31e3cf8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,aac.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,ac-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,ac-3.ts
deleted file mode 100644
index 5823056..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,ac-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,ec-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,ec-3.ts
deleted file mode 100644
index 9322f72..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,ec-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,mp3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,mp3.ts
deleted file mode 100644
index 34b534e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,mp3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,mp4a.40.2.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,mp4a.40.2.ts
deleted file mode 100644
index 1d651f8..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,mp4a.40.2.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,mp4a.40.34.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,mp4a.40.34.ts
deleted file mode 100644
index 98e7fda..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,mp4a.40.34.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,opus.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,opus.ts
deleted file mode 100644
index 0fdb695..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90,opus.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90.ts
deleted file mode 100644
index 7cab747..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H120.90.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,aac.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,aac.ts
deleted file mode 100644
index e256157..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,aac.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,ac-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,ac-3.ts
deleted file mode 100644
index fc2ae0b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,ac-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,ec-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,ec-3.ts
deleted file mode 100644
index ae320bd..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,ec-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,mp3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,mp3.ts
deleted file mode 100644
index 2844184..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,mp3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,mp4a.40.2.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,mp4a.40.2.ts
deleted file mode 100644
index 6461237..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,mp4a.40.2.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,mp4a.40.34.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,mp4a.40.34.ts
deleted file mode 100644
index db60431..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,mp4a.40.34.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,opus.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,opus.ts
deleted file mode 100644
index 3bfe317..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90,opus.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90.ts
deleted file mode 100644
index 9ce0e25..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.H150.90.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,aac.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,aac.ts
deleted file mode 100644
index c48f7db..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,aac.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,ac-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,ac-3.ts
deleted file mode 100644
index 6f0d850..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,ac-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,ec-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,ec-3.ts
deleted file mode 100644
index 571352c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,ec-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,mp3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,mp3.ts
deleted file mode 100644
index 84d877a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,mp3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,mp4a.40.2.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,mp4a.40.2.ts
deleted file mode 100644
index 969ed1e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,mp4a.40.2.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,mp4a.40.34.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,mp4a.40.34.ts
deleted file mode 100644
index 65652e2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,mp4a.40.34.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,opus.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,opus.ts
deleted file mode 100644
index e2f46f6..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90,opus.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90.ts
deleted file mode 100644
index bb5bb20..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.1.6.L60.90.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,aac.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,aac.ts
deleted file mode 100644
index cf66d90..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,aac.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,ac-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,ac-3.ts
deleted file mode 100644
index 043e75f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,ac-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,ec-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,ec-3.ts
deleted file mode 100644
index 155be5a..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,ec-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,mp3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,mp3.ts
deleted file mode 100644
index c04ea74..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,mp3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,mp4a.40.2.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,mp4a.40.2.ts
deleted file mode 100644
index 70085d0..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,mp4a.40.2.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,mp4a.40.34.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,mp4a.40.34.ts
deleted file mode 100644
index 9639d18..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,mp4a.40.34.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,opus.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,opus.ts
deleted file mode 100644
index bbe0f33..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8,opus.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8.ts
deleted file mode 100644
index 9502f20..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/hev1.4.10.H120.9c.8.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp3.ts
deleted file mode 100644
index 089f35d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4a.40.2.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4a.40.2.ts
deleted file mode 100644
index 139682b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4a.40.2.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4a.40.34.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4a.40.34.ts
deleted file mode 100644
index 9673370..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4a.40.34.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,aac.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,aac.ts
deleted file mode 100644
index ebd9dda..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,aac.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,ac-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,ac-3.ts
deleted file mode 100644
index e2a3834..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,ac-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,ec-3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,ec-3.ts
deleted file mode 100644
index 960a19f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,ec-3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,mp3.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,mp3.ts
deleted file mode 100644
index 48bd9b5..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,mp3.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,mp4a.40.2.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,mp4a.40.2.ts
deleted file mode 100644
index ac92b8c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,mp4a.40.2.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,mp4a.40.34.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,mp4a.40.34.ts
deleted file mode 100644
index 65a5c1f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,mp4a.40.34.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,opus.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,opus.ts
deleted file mode 100644
index c5f038b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20,opus.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20.ts
deleted file mode 100644
index 3ad6a03..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/mp4v.20.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/opus.ts b/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/opus.ts
deleted file mode 100644
index 3da26c1..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/ts/opus.ts and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/aac.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/aac.wav
deleted file mode 100644
index 2c3ebbf..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/aac.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/ac-3.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/ac-3.wav
deleted file mode 100644
index 82297d2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/ac-3.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/ec-3.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/ec-3.wav
deleted file mode 100644
index 1faa4ee..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/ec-3.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/flac.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/flac.wav
deleted file mode 100644
index 3831175..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/flac.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp3.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp3.wav
deleted file mode 100644
index 940fe81..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp3.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.2.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.2.wav
deleted file mode 100644
index cf0c355..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.2.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.29.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.29.wav
deleted file mode 100644
index 6fb6e90..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.29.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.34.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.34.wav
deleted file mode 100644
index 166ae59..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.34.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.5.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.5.wav
deleted file mode 100644
index 0ac807b..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/mp4a.40.5.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/speex.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/speex.wav
deleted file mode 100644
index 70a75b2..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/speex.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/vorbis.wav b/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/vorbis.wav
deleted file mode 100644
index 1ccec6f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/wav/vorbis.wav and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/av01.0.00M.08.0.110,opus.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/av01.0.00M.08.0.110,opus.webm
deleted file mode 100644
index 25abf06..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/av01.0.00M.08.0.110,opus.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/av01.0.00M.08.0.110,vorbis.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/av01.0.00M.08.0.110,vorbis.webm
deleted file mode 100644
index dfe8f32..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/av01.0.00M.08.0.110,vorbis.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/av01.0.00M.08.0.110.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/av01.0.00M.08.0.110.webm
deleted file mode 100644
index 509d826..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/av01.0.00M.08.0.110.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/opus.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/opus.webm
deleted file mode 100644
index 34bb047..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/opus.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vorbis.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vorbis.webm
deleted file mode 100644
index 49a9d71..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vorbis.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp8,opus.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp8,opus.webm
deleted file mode 100644
index b180c4f..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp8,opus.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp8,vorbis.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp8,vorbis.webm
deleted file mode 100644
index 1d0153e..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp8,vorbis.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp8.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp8.webm
deleted file mode 100644
index bc87542..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp8.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp9,opus.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp9,opus.webm
deleted file mode 100644
index ce4f64d..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp9,opus.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp9,vorbis.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp9,vorbis.webm
deleted file mode 100644
index c2a3f36..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp9,vorbis.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp9.webm b/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp9.webm
deleted file mode 100644
index 2981d53..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/formats/webm/vp9.webm and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/parsing/mkv/fixed-lacing.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/parsing/mkv/fixed-lacing.mkv
deleted file mode 100644
index acf0bc3..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/parsing/mkv/fixed-lacing.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/parsing/mkv/live.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/parsing/mkv/live.mkv
deleted file mode 100644
index 4b7ec7c..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/parsing/mkv/live.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/fixtures/parsing/mkv/xiph-ebml-lacing.mkv b/node_modules/@videojs/vhs-utils/test/fixtures/parsing/mkv/xiph-ebml-lacing.mkv
deleted file mode 100644
index 65a7a83..0000000
Binary files a/node_modules/@videojs/vhs-utils/test/fixtures/parsing/mkv/xiph-ebml-lacing.mkv and /dev/null differ
diff --git a/node_modules/@videojs/vhs-utils/test/format-parser.test.js b/node_modules/@videojs/vhs-utils/test/format-parser.test.js
deleted file mode 100644
index 5058085..0000000
--- a/node_modules/@videojs/vhs-utils/test/format-parser.test.js
+++ /dev/null
@@ -1,33 +0,0 @@
-import QUnit from 'qunit';
-import formatFiles from 'create-test-data!formats';
-import {parseFormatForBytes} from '../src/format-parser.js';
-import {doesCodecMatch, codecsFromFile} from './test-helpers.js';
-
-const modules = {};
-
-// seperate files into modules by extension
-Object.keys(formatFiles).forEach((file) => {
- const extension = file.split('.').pop();
-
- modules[extension] = modules[extension] || [];
- modules[extension].push(file);
-});
-
-QUnit.module('parseFormatForBytes', () => Object.keys(modules).forEach(function(module) {
- const files = modules[module];
-
- QUnit.module(module);
-
- files.forEach((file) => QUnit.test(`${file} can be identified`, function(assert) {
- const {codecs, container} = parseFormatForBytes(formatFiles[file]());
- const expectedCodecs = codecsFromFile(file);
-
- assert.equal(container, module, module);
- Object.keys(expectedCodecs).forEach(function(type) {
- const expectedCodec = expectedCodecs[type];
- const codec = codecs[type];
-
- assert.ok(doesCodecMatch(codec, expectedCodec), `${codec} is ${expectedCodec}`);
- });
- }));
-}));
diff --git a/node_modules/@videojs/vhs-utils/test/media-groups.test.js b/node_modules/@videojs/vhs-utils/test/media-groups.test.js
deleted file mode 100644
index 4d16b86..0000000
--- a/node_modules/@videojs/vhs-utils/test/media-groups.test.js
+++ /dev/null
@@ -1,171 +0,0 @@
-import QUnit from 'qunit';
-import { forEachMediaGroup } from '../src/media-groups';
-
-QUnit.module('forEachMediaGroup');
-
-QUnit.test('runs callback for each audio media group', function(assert) {
- const master = {
- mediaGroups: {
- AUDIO: {
- au1: {
- en: { en: 'en' },
- es: { es: 'es' }
- },
- au2: {
- de: { de: 'de' },
- fr: { fr: 'fr' }
- }
- },
- OTHER: {
- other1: {
- other11: { other11: 'other11' },
- other12: { other12: 'other12' }
- },
- other2: {
- other21: { other21: 'other21' },
- other22: { other22: 'other22' }
- }
- }
- }
- };
- const iteratedMediaGroups = [];
-
- forEachMediaGroup(
- master,
- ['AUDIO'],
- (mediaGroup) => iteratedMediaGroups.push(mediaGroup)
- );
-
- assert.deepEqual(
- iteratedMediaGroups,
- [
- { en: 'en' },
- { es: 'es' },
- { de: 'de' },
- { fr: 'fr' }
- ],
- 'iterated audio media groups'
- );
-});
-
-QUnit.test('runs callback for each subtitle media group', function(assert) {
- const master = {
- mediaGroups: {
- SUBTITLES: {
- sub1: {
- en: { en: 'en' },
- es: { es: 'es' }
- },
- sub2: {
- de: { de: 'de' },
- fr: { fr: 'fr' }
- }
- },
- OTHER: {
- other1: {
- other11: { other11: 'other11' },
- other12: { other12: 'other12' }
- },
- other2: {
- other21: { other21: 'other21' },
- other22: { other22: 'other22' }
- }
- }
- }
- };
- const iteratedMediaGroups = [];
-
- forEachMediaGroup(
- master,
- ['SUBTITLES'],
- (mediaGroup) => iteratedMediaGroups.push(mediaGroup)
- );
-
- assert.deepEqual(
- iteratedMediaGroups,
- [
- { en: 'en' },
- { es: 'es' },
- { de: 'de' },
- { fr: 'fr' }
- ],
- 'iterated subtitles media groups'
- );
-});
-
-QUnit.test('runs callback for each audio and subtitles media group', function(assert) {
- const master = {
- mediaGroups: {
- AUDIO: {
- au1: {
- en: { en: 'en' },
- es: { es: 'es' }
- },
- au2: {
- de: { de: 'de' },
- fr: { fr: 'fr' }
- }
- },
- SUBTITLES: {
- sub1: {
- enS: { enS: 'enS' },
- esS: { esS: 'esS' }
- },
- sub2: {
- deS: { deS: 'deS' },
- frS: { frS: 'frS' }
- }
- },
- OTHER: {
- other1: {
- other11: { other11: 'other11' },
- other12: { other12: 'other12' }
- },
- other2: {
- other21: { other21: 'other21' },
- other22: { other22: 'other22' }
- }
- }
- }
- };
- const iteratedMediaGroups = [];
-
- forEachMediaGroup(
- master,
- ['AUDIO', 'SUBTITLES'],
- (mediaGroup) => iteratedMediaGroups.push(mediaGroup)
- );
-
- assert.deepEqual(
- iteratedMediaGroups,
- [
- { en: 'en' },
- { es: 'es' },
- { de: 'de' },
- { fr: 'fr' },
- { enS: 'enS' },
- { esS: 'esS' },
- { deS: 'deS' },
- { frS: 'frS' }
- ],
- 'iterated audio and subtitles media groups'
- );
-});
-
-QUnit.test('does not run callback for non specified media groups', function(assert) {
- const master = {
- mediaGroups: {
- 'VIDEO': { v1: { en: { en: 'en' } } },
- 'CLOSED-CAPTIONS': { cc1: { en: { en: 'en' } } }
- }
- };
- const iteratedMediaGroups = [];
-
- forEachMediaGroup(
- master,
- ['AUDIO', 'SUBTITLES'],
- (mediaGroup) => iteratedMediaGroups.push(mediaGroup)
- );
-
- assert.deepEqual(iteratedMediaGroups, [], 'did not iterate non specified media groups');
-});
diff --git a/node_modules/@videojs/vhs-utils/test/media-types.test.js b/node_modules/@videojs/vhs-utils/test/media-types.test.js
deleted file mode 100644
index 9997d5d..0000000
--- a/node_modules/@videojs/vhs-utils/test/media-types.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-import QUnit from 'qunit';
-import { simpleTypeFromSourceType } from '../src/media-types';
-
-QUnit.module('simpleTypeFromSourceType');
-
-QUnit.test('simpleTypeFromSourceType converts HLS mime types to hls', function(assert) {
- assert.equal(
- simpleTypeFromSourceType('aPplicatiOn/x-MPegUrl'),
- 'hls',
- 'supports application/x-mpegurl'
- );
- assert.equal(
- simpleTypeFromSourceType('aPplicatiOn/VnD.aPPle.MpEgUrL'),
- 'hls',
- 'supports application/vnd.apple.mpegurl'
- );
-});
-
-QUnit.test('simpleTypeFromSourceType converts DASH mime type to dash', function(assert) {
- assert.equal(
- simpleTypeFromSourceType('aPplication/dAsh+xMl'),
- 'dash',
- 'supports application/dash+xml'
- );
-});
-
-QUnit.test(
- 'simpleTypeFromSourceType does not convert non HLS/DASH mime types',
- function(assert) {
- assert.notOk(simpleTypeFromSourceType('video/mp4'), 'does not support video/mp4');
- assert.notOk(simpleTypeFromSourceType('video/x-flv'), 'does not support video/x-flv');
- }
-);
-
-QUnit.test('simpleTypeFromSourceType converts VHS media type to vhs-json', function(assert) {
- assert.equal(
- simpleTypeFromSourceType('application/vnd.videojs.vhs+json'),
- 'vhs-json',
- 'supports application/vnd.videojs.vhs+json'
- );
-});
diff --git a/node_modules/@videojs/vhs-utils/test/resolve-url.test.js b/node_modules/@videojs/vhs-utils/test/resolve-url.test.js
deleted file mode 100644
index 7a1f8a0..0000000
--- a/node_modules/@videojs/vhs-utils/test/resolve-url.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-import QUnit from 'qunit';
-import window from 'global/window';
-import resolveUrl from '../src/resolve-url';
-
-// A modified subset of tests from https://github.com/tjenkinson/url-toolkit
-
-QUnit.module('URL resolver');
-
-QUnit.test('works with a selection of valid urls', function(assert) {
- let currentLocation = '';
- let currentPath = '';
-
- if (window.location && window.location.protocol) {
- currentLocation = window.location.protocol + '//' + window.location.host;
- currentPath = window.location.pathname.split('/').slice(0, -1).join('/');
- }
-
- assert.equal(
- resolveUrl('http://a.com/b/cd/e.m3u8', 'https://example.com/z.ts'),
- 'https://example.com/z.ts'
- );
- assert.equal(resolveUrl('http://a.com/b/cd/e.m3u8', 'z.ts'), 'http://a.com/b/cd/z.ts');
- assert.equal(resolveUrl('//a.com/b/cd/e.m3u8', 'z.ts'), '//a.com/b/cd/z.ts');
- assert.equal(
- resolveUrl('/a/b/cd/e.m3u8', 'https://example.com:8080/z.ts'),
- 'https://example.com:8080/z.ts'
- );
- assert.equal(resolveUrl('/a/b/cd/e.m3u8', 'z.ts'), currentLocation + '/a/b/cd/z.ts');
- assert.equal(resolveUrl('/a/b/cd/e.m3u8', '../../../z.ts'), currentLocation + '/z.ts');
-
- assert.equal(
- resolveUrl('data:application/dash+xml;charset=utf-8,http%3A%2F%2Fexample.com', 'hello.m3u8'),
- // we need to add the currentPath because we're actually working relative to window.location
- currentLocation + currentPath + '/hello.m3u8',
- 'resolves urls relative to window when given a data base url'
- );
-
- assert.equal(
- resolveUrl('data:application/dash+xml;charset=utf-8,http%3A%2F%2Fexample.com', 'http://example.com/hello.m3u8'),
- 'http://example.com/hello.m3u8',
- 'absolute urls should still be absolute even with a data uri'
- );
-
- assert.equal(
- resolveUrl('http://example.com', 'data:application/dash+xml;charset=utf-8,http%3A%2F%2Fexample.com'),
- 'data:application/dash+xml;charset=utf-8,http%3A%2F%2Fexample.com',
- 'data uri is treated as an absolute url'
- );
-});
diff --git a/node_modules/@videojs/vhs-utils/test/stream.test.js b/node_modules/@videojs/vhs-utils/test/stream.test.js
deleted file mode 100644
index ed38dc7..0000000
--- a/node_modules/@videojs/vhs-utils/test/stream.test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import QUnit from 'qunit';
-import Stream from '../src/stream';
-
-QUnit.module('stream', {
-
- beforeEach() {
- this.stream = new Stream();
- },
-
- afterEach() {
- this.stream.dispose();
- }
-});
-
-QUnit.test('trigger calls listeners', function(assert) {
- const args = [];
-
- this.stream.on('test', function(data) {
- args.push(data);
- });
-
- this.stream.trigger('test', 1);
- this.stream.trigger('test', 2);
-
- assert.deepEqual(args, [1, 2]);
-});
-
-QUnit.test('callbacks can remove themselves', function(assert) {
- const args1 = [];
- const args2 = [];
- const args3 = [];
- const arg2Fn = (event) => {
- args2.push(event);
- this.stream.off('test', arg2Fn);
- };
-
- this.stream.on('test', (event) => {
- args1.push(event);
- });
- this.stream.on('test', arg2Fn);
- this.stream.on('test', (event) => {
- args3.push(event);
- });
-
- this.stream.trigger('test', 1);
- this.stream.trigger('test', 2);
-
- assert.deepEqual(args1, [1, 2], 'first callback ran all times');
- assert.deepEqual(args2, [1], 'second callback removed after first run');
- assert.deepEqual(args3, [1, 2], 'third callback ran all times');
-});
diff --git a/node_modules/@videojs/vhs-utils/test/test-helpers.js b/node_modules/@videojs/vhs-utils/test/test-helpers.js
deleted file mode 100644
index 4b35865..0000000
--- a/node_modules/@videojs/vhs-utils/test/test-helpers.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import {isVideoCodec, isAudioCodec} from '../src/codecs.js';
-
-const codecAliasMap = {
- mp3: ['mp3', 'mp4a.40.34', 'mp4a.6b'],
- aac: ['aac', 'mp4a.40.2', 'mp4a.40.5', 'mp4a.40.29']
-};
-
-Object.keys(codecAliasMap).forEach((alias) => {
- // map aliases as keys so that everything is linked to each other
- codecAliasMap[alias].forEach((subalias) => {
- codecAliasMap[subalias] = codecAliasMap[alias];
- });
-});
-
-export const doesCodecMatch = function(a, b) {
- if (!a) {
- return false;
- }
- if (codecAliasMap[b]) {
- return codecAliasMap[a].indexOf(b) !== -1;
- }
-
- return a === b;
-};
-
-export const codecsFromFile = function(file) {
- const codecs = {};
- const extension = file.split('.').pop();
- const codecStr = file.replace(`.${extension}`, '');
-
- codecStr.split(',').forEach((codec) => {
- if (isVideoCodec(codec)) {
- codecs.video = codec;
- } else if (isAudioCodec(codec)) {
- codecs.audio = codec;
- } else {
- throw new Error(`${codec} is not detected as audio or video`);
- }
- });
-
- return codecs;
-};
diff --git a/node_modules/@videojs/xhr/CONTRIBUTING.md b/node_modules/@videojs/xhr/CONTRIBUTING.md
deleted file mode 100644
index 3d4053b..0000000
--- a/node_modules/@videojs/xhr/CONTRIBUTING.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# XHR is an OPEN Open Source Project
-
------------------------------------------
-
-## What?
-
-Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
-
-## Rules
-
-There are a few basic ground-rules for contributors:
-
-1. **No `--force` pushes** or modifying the Git history in any way.
-1. **Non-master branches** ought to be used for ongoing work.
-1. **External API changes and significant modifications** ought to be subject to an **internal pull-request** to solicit feedback from other contributors.
-1. Internal pull-requests to solicit feedback are *encouraged* for any other non-trivial contribution but left to the discretion of the contributor.
-1. Contributors should attempt to adhere to the prevailing code-style.
-
-## Releases
-
-Declaring formal releases remains the prerogative of the project maintainer.
-
-## Changes to this arrangement
-
-This is an experiment and feedback is welcome! This document may also be subject to pull-requests or changes by contributors where you believe you have something valuable to add or change.
-
------------------------------------------
diff --git a/node_modules/@videojs/xhr/LICENCE b/node_modules/@videojs/xhr/LICENCE
deleted file mode 100644
index a23e08a..0000000
--- a/node_modules/@videojs/xhr/LICENCE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) 2012 Raynos.
-
-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.
\ No newline at end of file
diff --git a/node_modules/@videojs/xhr/README.md b/node_modules/@videojs/xhr/README.md
deleted file mode 100644
index 19fe36a..0000000
--- a/node_modules/@videojs/xhr/README.md
+++ /dev/null
@@ -1,255 +0,0 @@
-# xhr
-
-[](https://gitter.im/naugtur-xhr/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-
-[](https://greenkeeper.io/)
-
-A small XMLHttpRequest wrapper. Designed for use with [browserify](http://browserify.org/), [webpack](https://webpack.github.io/) etc.
-
-API is a subset of [request](https://github.com/request/request) so you can write code that works in both node.js and the browser by using `require('request')` in your code and telling your browser bundler to load `xhr` instead of `request`.
-
-For browserify, add a [browser](https://github.com/substack/node-browserify#browser-field) field to your `package.json`:
-
-```
-"browser": {
- "request": "@videojs/xhr"
-}
-```
-
-For webpack, add a [resolve.alias](http://webpack.github.io/docs/configuration.html#resolve-alias) field to your configuration:
-
-```
-"resolve": {
- "alias": {
- "request$": "@videojs/xhr"
- }
-}
-```
-
-Browser support: IE8+ and everything else.
-
-## Installation
-
-```
-npm install @videojs/xhr
-```
-
-## Example
-
-```js
-var xhr = require("@videojs/xhr")
-
-xhr({
- method: "post",
- body: someJSONString,
- uri: "/foo",
- headers: {
- "Content-Type": "application/json"
- }
-}, function (err, resp, body) {
- // check resp.statusCode
-})
-```
-
-## `var req = xhr(options, callback)`
-
-```js
-type XhrOptions = String | {
- useXDR: Boolean?,
- sync: Boolean?,
- uri: String,
- url: String,
- method: String?,
- timeout: Number?,
- headers: Object?,
- body: String? | Object?,
- json: Boolean? | Object?,
- username: String?,
- password: String?,
- withCredentials: Boolean?,
- responseType: String?,
- beforeSend: Function?
-}
-xhr := (XhrOptions, Callback) => Request
-```
-the returned object is either an [`XMLHttpRequest`][3] instance
- or an [`XDomainRequest`][4] instance (if on IE8/IE9 &&
- `options.useXDR` is set to `true`)
-
-Your callback will be called once with the arguments
- ( [`Error`][5], `response` , `body` ) where the response is an object:
-```js
-{
- body: Object||String,
- statusCode: Number,
- method: String,
- headers: {},
- url: String,
- rawRequest: xhr
-}
-```
- - `body`: HTTP response body - [`XMLHttpRequest.response`][6], [`XMLHttpRequest.responseText`][7] or
- [`XMLHttpRequest.responseXML`][8] depending on the request type.
- - `rawRequest`: Original [`XMLHttpRequest`][3] instance
- or [`XDomainRequest`][4] instance (if on IE8/IE9 &&
- `options.useXDR` is set to `true`)
- - `headers`: A collection of headers where keys are header names converted to lowercase
-
-
-Your callback will be called with an [`Error`][5] if there is an error in the browser that prevents sending the request.
-A HTTP 500 response is not going to cause an error to be returned.
-
-## Other signatures
-
-* `var req = xhr(url, callback)` -
-a simple string instead of the options. In this case, a GET request will be made to that url.
-
-* `var req = xhr(url, options, callback)` -
-the above may also be called with the standard set of options.
-
-### Convience methods
-* `var req = xhr.{post, put, patch, del, head, get}(url, callback)`
-* `var req = xhr.{post, put, patch, del, head, get}(options, callback)`
-* `var req = xhr.{post, put, patch, del, head, get}(url, options, callback)`
-
-The `xhr` module has convience functions attached that will make requests with the given method.
-Each function is named after its method, with the exception of `DELETE` which is called `xhr.del` for compatibility.
-
-The method shorthands may be combined with the url-first form of `xhr` for succinct and descriptive requests. For example,
-
-```js
-xhr.post('/post-to-me', function(err, resp) {
- console.log(resp.body)
-})
-```
-
-or
-
-```js
-xhr.del('/delete-me', { headers: { my: 'auth' } }, function (err, resp) {
- console.log(resp.statusCode);
-})
-```
-
-## Options
-
-### `options.method`
-
-Specify the method the [`XMLHttpRequest`][3] should be opened
- with. Passed to [`XMLHttpRequest.open`][2]. Defaults to "GET"
-
-### `options.useXDR`
-
-Specify whether this is a cross origin (CORS) request for IE<10.
- Switches IE to use [`XDomainRequest`][4] instead of `XMLHttpRequest`.
- Ignored in other browsers.
-
-Note that headers cannot be set on an XDomainRequest instance.
-
-### `options.sync`
-
-Specify whether this is a synchrounous request. Note that when
- this is true the callback will be called synchronously. In
- most cases this option should not be used. Only use if you
- know what you are doing!
-
-### `options.body`
-
-Pass in body to be send across the [`XMLHttpRequest`][3].
- Generally should be a string. But anything that's valid as
- a parameter to [`XMLHttpRequest.send`][1] should work (Buffer for file, etc.).
-
-If `options.json` is `true`, then this must be a JSON-serializable object. `options.body` is passed to `JSON.stringify` and sent.
-
-### `options.uri` or `options.url`
-
-The uri to send a request to. Passed to [`XMLHttpRequest.open`][2]. `options.url` and `options.uri` are aliases for each other.
-
-### `options.headers`
-
-An object of headers that should be set on the request. The
- key, value pair is passed to [`XMLHttpRequest.setRequestHeader`][9]
-
-### `options.timeout`
-
-Number of miliseconds to wait for response. Defaults to 0 (no timeout). Ignored when `options.sync` is true.
-
-### `options.json`
-
-Set to `true` to send request as `application/json` (see `options.body`) and parse response from JSON.
-
-For backwards compatibility `options.json` can also be a valid JSON-serializable value to be sent to the server. Additionally the response body is still parsed as JSON
-
-For sending booleans as JSON body see FAQ
-
-### `options.withCredentials`
-
-Specify whether user credentials are to be included in a cross-origin
- request. Sets [`XMLHttpRequest.withCredentials`][10]. Defaults to false.
-
-A wildcard `*` cannot be used in the `Access-Control-Allow-Origin` header when `withCredentials` is true.
- The header needs to specify your origin explicitly or browser will abort the request.
-
-### `options.responseType`
-
-Determines the data type of the `response`. Sets [`XMLHttpRequest.responseType`][11]. For example, a `responseType` of `document` will return a parsed `Document` object as the `response.body` for an XML resource.
-
-### `options.beforeSend`
-
-A function being called right before the `send` method of the `XMLHttpRequest` or `XDomainRequest` instance is called. The `XMLHttpRequest` or `XDomainRequest` instance is passed as an argument.
-
-### `options.xhr`
-
-Pass an `XMLHttpRequest` object (or something that acts like one) to use instead of constructing a new one using the `XMLHttpRequest` or `XDomainRequest` constructors. Useful for testing.
-
-## FAQ
-
-- Why is my server's JSON response not parsed? I returned the right content-type.
- - See `options.json` - you can set it to `true` on a GET request to tell `xhr` to parse the response body.
- - Without `options.json` body is returned as-is (a string or when `responseType` is set and the browser supports it - a result of parsing JSON or XML)
-- How do I send an object or array as POST body?
- - `options.body` should be a string. You need to serialize your object before passing to `xhr` for sending.
- - To serialize to JSON you can use
- `options.json:true` with `options.body` for convenience - then `xhr` will do the serialization and set content-type accordingly.
-- Where's stream API? `.pipe()` etc.
- - Not implemented. You can't reasonably have that in the browser.
-- Why can't I send `"true"` as body by passing it as `options.json` anymore?
- - Accepting `true` as a value was a bug. Despite what `JSON.stringify` does, the string `"true"` is not valid JSON. If you're sending booleans as JSON, please consider wrapping them in an object or array to save yourself from more trouble in the future. To bring back the old behavior, hardcode `options.json` to `true` and set `options.body` to your boolean value.
-- How do I add an `onprogress` listener?
- - use `beforeSend` function for non-standard things that are browser specific. In this case:
- ```js
- xhr({
- ...
- beforeSend: function(xhrObject){
- xhrObject.onprogress = function(){}
- }
- })
- ```
-
-## Mocking Requests
-You can override the constructor used to create new requests for testing. When you're making a new request:
-
-```js
-xhr({ xhr: new MockXMLHttpRequest() })
-```
-
-or you can override the constructors used to create requests at the module level:
-
-```js
-xhr.XMLHttpRequest = MockXMLHttpRequest
-xhr.XDomainRequest = MockXDomainRequest
-```
-
-## MIT Licenced
-
- [1]: http://xhr.spec.whatwg.org/#the-send()-method
- [2]: http://xhr.spec.whatwg.org/#the-open()-method
- [3]: http://xhr.spec.whatwg.org/#interface-xmlhttprequest
- [4]: http://msdn.microsoft.com/en-us/library/ie/cc288060(v=vs.85).aspx
- [5]: http://es5.github.com/#x15.11
- [6]: http://xhr.spec.whatwg.org/#the-response-attribute
- [7]: http://xhr.spec.whatwg.org/#the-responsetext-attribute
- [8]: http://xhr.spec.whatwg.org/#the-responsexml-attribute
- [9]: http://xhr.spec.whatwg.org/#the-setrequestheader()-method
- [10]: http://xhr.spec.whatwg.org/#the-withcredentials-attribute
- [11]: https://xhr.spec.whatwg.org/#the-responsetype-attribute
diff --git a/node_modules/@videojs/xhr/index.d.ts b/node_modules/@videojs/xhr/index.d.ts
deleted file mode 100644
index 3dbd5ba..0000000
--- a/node_modules/@videojs/xhr/index.d.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-export type XhrCallback = (
- error: Error,
- response: XhrResponse,
- body: any
-) => void;
-
-export interface XhrResponse {
- body: Object | string;
- statusCode: number;
- method: string;
- headers: XhrHeaders;
- url: string;
- rawRequest: XMLHttpRequest;
-}
-
-export interface XhrHeaders {
- [key: string]: string;
-}
-
-export interface XhrBaseConfig {
- useXDR?: boolean;
- sync?: boolean;
- method?: 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT';
- timeout?: number;
- headers?: XhrHeaders;
- body?: string | any;
- json?: boolean;
- username?: string;
- password?: string;
- withCredentials?: boolean;
- responseType?: '' | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text';
- beforeSend?: (xhrObject: XMLHttpRequest) => void;
- xhr?: XMLHttpRequest;
-}
-
-export interface XhrUriConfig extends XhrBaseConfig {
- uri: string;
-}
-
-export interface XhrUrlConfig extends XhrBaseConfig {
- url: string;
-}
-
-export interface XhrInstance {
- (options: XhrUriConfig | XhrUrlConfig, callback: XhrCallback): any;
- (url: string, callback: XhrCallback): any;
- (url: string, options: XhrBaseConfig, callback: XhrCallback): any;
-}
-
-export interface XhrStatic extends XhrInstance {
- del: XhrInstance;
- get: XhrInstance;
- head: XhrInstance;
- patch: XhrInstance;
- post: XhrInstance;
- put: XhrInstance;
-}
-
-declare const Xhr: XhrStatic;
-
-export default Xhr;
diff --git a/node_modules/@videojs/xhr/index.js b/node_modules/@videojs/xhr/index.js
deleted file mode 100644
index e2ca108..0000000
--- a/node_modules/@videojs/xhr/index.js
+++ /dev/null
@@ -1,278 +0,0 @@
-"use strict";
-var window = require("global/window")
-var _extends = require("@babel/runtime/helpers/extends");
-var isFunction = require('is-function');
-
-/**
- * @license
- * slighly modified parse-headers 2.0.2
- * Copyright (c) 2014 David Björklund
- * Available under the MIT license
- *
- */
-
-var parseHeaders = function(headers) {
- var result = {};
-
- if (!headers) {
- return result;
- }
-
- headers.trim().split('\n').forEach(function(row) {
- var index = row.indexOf(':');
- var key = row.slice(0, index).trim().toLowerCase();
- var value = row.slice(index + 1).trim();
-
- if (typeof(result[key]) === 'undefined') {
- result[key] = value
- } else if (Array.isArray(result[key])) {
- result[key].push(value)
- } else {
- result[key] = [ result[key], value ]
- }
- });
-
- return result;
-};
-
-module.exports = createXHR
-// Allow use of default import syntax in TypeScript
-module.exports.default = createXHR;
-createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
-createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
-
-forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
- createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
- options = initParams(uri, options, callback)
- options.method = method.toUpperCase()
- return _createXHR(options)
- }
-})
-
-function forEachArray(array, iterator) {
- for (var i = 0; i < array.length; i++) {
- iterator(array[i])
- }
-}
-
-function isEmpty(obj){
- for(var i in obj){
- if(obj.hasOwnProperty(i)) return false
- }
- return true
-}
-
-function initParams(uri, options, callback) {
- var params = uri
-
- if (isFunction(options)) {
- callback = options
- if (typeof uri === "string") {
- params = {uri:uri}
- }
- } else {
- params = _extends({}, options, {uri: uri})
- }
-
- params.callback = callback
- return params
-}
-
-function createXHR(uri, options, callback) {
- options = initParams(uri, options, callback)
- return _createXHR(options)
-}
-
-function _createXHR(options) {
- if(typeof options.callback === "undefined"){
- throw new Error("callback argument missing")
- }
-
- var called = false
- var callback = function cbOnce(err, response, body){
- if(!called){
- called = true
- options.callback(err, response, body)
- }
- }
-
- function readystatechange() {
- if (xhr.readyState === 4) {
- setTimeout(loadFunc, 0)
- }
- }
-
- function getBody() {
- // Chrome with requestType=blob throws errors arround when even testing access to responseText
- var body = undefined
-
- if (xhr.response) {
- body = xhr.response
- } else {
- body = xhr.responseText || getXml(xhr)
- }
-
- if (isJson) {
- try {
- body = JSON.parse(body)
- } catch (e) {}
- }
-
- return body
- }
-
- function errorFunc(evt) {
- clearTimeout(timeoutTimer)
- if(!(evt instanceof Error)){
- evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
- }
- evt.statusCode = 0
- return callback(evt, failureResponse)
- }
-
- // will load the data & process the response in a special response object
- function loadFunc() {
- if (aborted) return
- var status
- clearTimeout(timeoutTimer)
- if(options.useXDR && xhr.status===undefined) {
- //IE8 CORS GET successful response doesn't have a status field, but body is fine
- status = 200
- } else {
- status = (xhr.status === 1223 ? 204 : xhr.status)
- }
- var response = failureResponse
- var err = null
-
- if (status !== 0){
- response = {
- body: getBody(),
- statusCode: status,
- method: method,
- headers: {},
- url: uri,
- rawRequest: xhr
- }
- if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
- response.headers = parseHeaders(xhr.getAllResponseHeaders())
- }
- } else {
- err = new Error("Internal XMLHttpRequest Error")
- }
- return callback(err, response, response.body)
- }
-
- var xhr = options.xhr || null
-
- if (!xhr) {
- if (options.cors || options.useXDR) {
- xhr = new createXHR.XDomainRequest()
- }else{
- xhr = new createXHR.XMLHttpRequest()
- }
- }
-
- var key
- var aborted
- var uri = xhr.url = options.uri || options.url
- var method = xhr.method = options.method || "GET"
- var body = options.body || options.data
- var headers = xhr.headers = options.headers || {}
- var sync = !!options.sync
- var isJson = false
- var timeoutTimer
- var failureResponse = {
- body: undefined,
- headers: {},
- statusCode: 0,
- method: method,
- url: uri,
- rawRequest: xhr
- }
-
- if ("json" in options && options.json !== false) {
- isJson = true
- headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
- if (method !== "GET" && method !== "HEAD") {
- headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
- body = JSON.stringify(options.json === true ? body : options.json)
- }
- }
-
- xhr.onreadystatechange = readystatechange
- xhr.onload = loadFunc
- xhr.onerror = errorFunc
- // IE9 must have onprogress be set to a unique function.
- xhr.onprogress = function () {
- // IE must die
- }
- xhr.onabort = function(){
- aborted = true;
- }
- xhr.ontimeout = errorFunc
- xhr.open(method, uri, !sync, options.username, options.password)
- //has to be after open
- if(!sync) {
- xhr.withCredentials = !!options.withCredentials
- }
- // Cannot set timeout with sync request
- // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
- // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
- if (!sync && options.timeout > 0 ) {
- timeoutTimer = setTimeout(function(){
- if (aborted) return
- aborted = true//IE9 may still call readystatechange
- xhr.abort("timeout")
- var e = new Error("XMLHttpRequest timeout")
- e.code = "ETIMEDOUT"
- errorFunc(e)
- }, options.timeout )
- }
-
- if (xhr.setRequestHeader) {
- for(key in headers){
- if(headers.hasOwnProperty(key)){
- xhr.setRequestHeader(key, headers[key])
- }
- }
- } else if (options.headers && !isEmpty(options.headers)) {
- throw new Error("Headers cannot be set on an XDomainRequest object")
- }
-
- if ("responseType" in options) {
- xhr.responseType = options.responseType
- }
-
- if ("beforeSend" in options &&
- typeof options.beforeSend === "function"
- ) {
- options.beforeSend(xhr)
- }
-
- // Microsoft Edge browser sends "undefined" when send is called with undefined value.
- // XMLHttpRequest spec says to pass null as body to indicate no body
- // See https://github.com/naugtur/xhr/issues/100.
- xhr.send(body || null)
-
- return xhr
-
-
-}
-
-function getXml(xhr) {
- // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
- // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
- try {
- if (xhr.responseType === "document") {
- return xhr.responseXML
- }
- var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
- if (xhr.responseType === "" && !firefoxBugTakenEffect) {
- return xhr.responseXML
- }
- } catch (e) {}
-
- return null
-}
-
-function noop() {}
diff --git a/node_modules/@videojs/xhr/package.json b/node_modules/@videojs/xhr/package.json
deleted file mode 100644
index 1428519..0000000
--- a/node_modules/@videojs/xhr/package.json
+++ /dev/null
@@ -1,79 +0,0 @@
-{
- "_from": "@videojs/xhr@2.5.1",
- "_id": "@videojs/xhr@2.5.1",
- "_inBundle": false,
- "_integrity": "sha512-wV9nGESHseSK+S9ePEru2+OJZ1jq/ZbbzniGQ4weAmTIepuBMSYPx5zrxxQA0E786T5ykpO8ts+LayV+3/oI2w==",
- "_location": "/@videojs/xhr",
- "_phantomChildren": {},
- "_requested": {
- "type": "version",
- "registry": true,
- "raw": "@videojs/xhr@2.5.1",
- "name": "@videojs/xhr",
- "escapedName": "@videojs%2fxhr",
- "scope": "@videojs",
- "rawSpec": "2.5.1",
- "saveSpec": null,
- "fetchSpec": "2.5.1"
- },
- "_requiredBy": [
- "/video.js"
- ],
- "_resolved": "https://registry.npmjs.org/@videojs/xhr/-/xhr-2.5.1.tgz",
- "_shasum": "26bc5a79dbb3b03bfb13742c6ce559f89e90719e",
- "_spec": "@videojs/xhr@2.5.1",
- "_where": "F:\\Documents\\websites\\BMM\\node_modules\\video.js",
- "author": {
- "name": "Raynos",
- "email": "raynos2@gmail.com"
- },
- "bugs": {
- "url": "https://github.com/naugtur/xhr/issues",
- "email": "naugtur@gmail.com"
- },
- "bundleDependencies": false,
- "contributors": [
- {
- "name": "Jake Verbaten"
- },
- {
- "name": "Zbyszek Tenerowicz",
- "email": "naugtur@gmail.com"
- }
- ],
- "dependencies": {
- "@babel/runtime": "^7.5.5",
- "global": "~4.4.0",
- "is-function": "^1.0.1"
- },
- "deprecated": false,
- "description": "small xhr abstraction",
- "devDependencies": {
- "for-each": "^0.3.2",
- "pre-commit": "1.2.2",
- "run-browser": "github:naugtur/run-browser",
- "tap-spec": "^4.0.2",
- "tape": "^4.0.0"
- },
- "homepage": "https://github.com/naugtur/xhr",
- "keywords": [
- "xhr",
- "http",
- "xmlhttprequest",
- "xhr2",
- "browserify"
- ],
- "license": "MIT",
- "main": "index",
- "name": "@videojs/xhr",
- "repository": {
- "type": "git",
- "url": "git://github.com/naugtur/xhr.git"
- },
- "scripts": {
- "browser": "run-browser -m test/mock-server.js test/index.js",
- "test": "run-browser test/index.js -b -m test/mock-server.js | tap-spec"
- },
- "typings": "./index.d.ts",
- "version": "2.5.1"
-}
diff --git a/node_modules/aes-decrypter/CHANGELOG.md b/node_modules/aes-decrypter/CHANGELOG.md
deleted file mode 100644
index 969c26c..0000000
--- a/node_modules/aes-decrypter/CHANGELOG.md
+++ /dev/null
@@ -1,76 +0,0 @@
-
-## [3.1.2](https://github.com/videojs/aes-decrypter/compare/v3.1.1...v3.1.2) (2021-01-12)
-
-### Bug Fixes
-
-* cjs dist should only import cjs ([#83](https://github.com/videojs/aes-decrypter/issues/83)) ([a8a5fbf](https://github.com/videojs/aes-decrypter/commit/a8a5fbf))
-
-
-## [3.1.1](https://github.com/videojs/aes-decrypter/compare/v3.1.0...v3.1.1) (2021-01-11)
-
-### Chores
-
-* update to use vhs-utils 3 ([#81](https://github.com/videojs/aes-decrypter/issues/81)) ([8ead5d9](https://github.com/videojs/aes-decrypter/commit/8ead5d9))
-
-
-# [3.1.0](https://github.com/videojs/aes-decrypter/compare/v3.0.2...v3.1.0) (2020-11-03)
-
-### Chores
-
-* **package:** update to vhs-utils[@2](https://github.com/2) ([#80](https://github.com/videojs/aes-decrypter/issues/80)) ([63b9cb9](https://github.com/videojs/aes-decrypter/commit/63b9cb9))
-
-
-## [3.0.2](https://github.com/videojs/aes-decrypter/compare/v3.0.1...v3.0.2) (2020-09-09)
-
-### Chores
-
-* **package:** update pkcs7 to remove engine check ([062c952](https://github.com/videojs/aes-decrypter/commit/062c952))
-
-
-## [3.0.1](https://github.com/videojs/aes-decrypter/compare/v3.0.0...v3.0.1) (2019-08-21)
-
-### Chores
-
-* **package:** update rollup to version 0.66.0 ([#38](https://github.com/videojs/aes-decrypter/issues/38)) ([634556b](https://github.com/videojs/aes-decrypter/commit/634556b))
-* bump videojs-generate-karma-config version ([#51](https://github.com/videojs/aes-decrypter/issues/51)) ([195b923](https://github.com/videojs/aes-decrypter/commit/195b923))
-* **package:** update videojs-generate-karma-config to version 5.0.2 ([#57](https://github.com/videojs/aes-decrypter/issues/57)) ([be8bd81](https://github.com/videojs/aes-decrypter/commit/be8bd81))
-* update generator version and use [@videojs](https://github.com/videojs)/vhs-utils ([#68](https://github.com/videojs/aes-decrypter/issues/68)) ([9a6ab2f](https://github.com/videojs/aes-decrypter/commit/9a6ab2f))
-* Update to generator v7 standards ([#37](https://github.com/videojs/aes-decrypter/issues/37)) ([fcf96c4](https://github.com/videojs/aes-decrypter/commit/fcf96c4))
-* Update videojs-generate-karma-config to the latest version 🚀 ([#42](https://github.com/videojs/aes-decrypter/issues/42)) ([2b16de3](https://github.com/videojs/aes-decrypter/commit/2b16de3))
-* Update videojs-generate-karma-config to the latest version 🚀 ([#43](https://github.com/videojs/aes-decrypter/issues/43)) ([cb63ccd](https://github.com/videojs/aes-decrypter/commit/cb63ccd))
-
-
-# [3.0.0](https://github.com/videojs/aes-decrypter/compare/v2.0.0...v3.0.0) (2017-07-24)
-
-### Features
-
-* Use Rollup for packaging ([bda57ab](https://github.com/videojs/aes-decrypter/commit/bda57ab))
-
-### Chores
-
-* prepare CHANGELOG for new process ([1a5175c](https://github.com/videojs/aes-decrypter/commit/1a5175c))
-
-
-### BREAKING CHANGES
-
-* revert to 1.x and stop using web crypto.
-
-## 2.0.0 (2016-11-15)
-* Use webcrypto for aes-cbc segment decryption when supported (#4)
-* Lock the linter to a specific version
-
-## 1.1.1 (2016-11-17)
-* version to revert 1.1.0
-
-## 1.0.3 (2016-06-16)
-* dont do browserify-shim globally since we only use it in tests (#1)
-
-## 1.0.2 (2016-06-16)
-* specify browserify transform globally
-
-## 1.0.1 (2016-06-16)
-* fixing the build pipeline
-
-## 1.0.0 (2016-06-16)
-* initial
-
diff --git a/node_modules/aes-decrypter/CONTRIBUTING.md b/node_modules/aes-decrypter/CONTRIBUTING.md
deleted file mode 100644
index 7840f8c..0000000
--- a/node_modules/aes-decrypter/CONTRIBUTING.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# CONTRIBUTING
-
-We welcome contributions from everyone!
-
-## Getting Started
-
-Make sure you have Node.js 4.8 or higher and npm installed.
-
-1. Fork this repository and clone your fork
-1. Install dependencies: `npm install`
-1. Run a development server: `npm start`
-
-### Making Changes
-
-Refer to the [video.js plugin conventions][conventions] for more detail on best practices and tooling for video.js plugin authorship.
-
-When you've made your changes, push your commit(s) to your fork and issue a pull request against the original repository.
-
-### Running Tests
-
-Testing is a crucial part of any software project. For all but the most trivial changes (typos, etc) test cases are expected. Tests are run in actual browsers using [Karma][karma].
-
-- In all available and supported browsers: `npm test`
-- In a specific browser: `npm run test:chrome`, `npm run test:firefox`, etc.
-- While development server is running (`npm start`), navigate to [`http://localhost:9999/test/`][local]
-
-
-[karma]: http://karma-runner.github.io/
-[local]: http://localhost:9999/test/
-[conventions]: https://github.com/videojs/generator-videojs-plugin/blob/master/docs/conventions.md
diff --git a/node_modules/aes-decrypter/LICENSE b/node_modules/aes-decrypter/LICENSE
deleted file mode 100644
index 50c17f4..0000000
--- a/node_modules/aes-decrypter/LICENSE
+++ /dev/null
@@ -1,13 +0,0 @@
-Copyright Brightcove, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
diff --git a/node_modules/aes-decrypter/README.md b/node_modules/aes-decrypter/README.md
deleted file mode 100644
index 843f4c0..0000000
--- a/node_modules/aes-decrypter/README.md
+++ /dev/null
@@ -1,72 +0,0 @@
-# aes-decrypter
-
-[](https://travis-ci.org/videojs/aes-decrypter)
-[](https://greenkeeper.io/)
-[](http://slack.videojs.com)
-
-[](https://nodei.co/npm/aes-decrypter/)
-
-
-
-
-
-- [Installation](#installation)
-- [Usage](#usage)
-- [License](#license)
-
-
-## Installation
-
-```sh
-npm install --save aes-decrypter
-```
-
-Also available to install globally:
-
-```sh
-npm install --global aes-decrypter
-```
-
-The npm installation is preferred, but Bower works, too.
-
-```sh
-bower install --save aes-decrypter
-```
-
-## Usage
-
-To include decrypter on your website or npm application, use any of the following methods.
-```js
-var Decrypter = require('aes-decrypter').Decrypter;
-var fs = require('fs');
-var keyContent = fs.readFileSync('something.key');
-var encryptedBytes = fs.readFileSync('somithing.txt');
-
-// keyContent is a string of the aes-keys content
-var keyContent = fs.readFileSync(keyFile);
-
-var view = new DataView(keyContent.buffer);
-var key.bytes = new Uint32Array([
- view.getUint32(0),
- view.getUint32(4),
- view.getUint32(8),
- view.getUint32(12)
-]);
-
-key.iv = new Uint32Array([
- 0, 0, 0, 0
-]);
-
-var d = new Decrypter(
- encryptedBytes,
- key.bytes,
- key.iv,
- function(err, decryptedBytes) {
- // err always null
-});
-```
-
-## [License](LICENSE)
-
-Apache-2.0. Copyright (c) Brightcove, Inc.
-
diff --git a/node_modules/aes-decrypter/dist/aes-decrypter.cjs.js b/node_modules/aes-decrypter/dist/aes-decrypter.cjs.js
deleted file mode 100644
index 081f5d3..0000000
--- a/node_modules/aes-decrypter/dist/aes-decrypter.cjs.js
+++ /dev/null
@@ -1,442 +0,0 @@
-/*! @name aes-decrypter @version 3.1.2 @license Apache-2.0 */
-'use strict';
-
-Object.defineProperty(exports, '__esModule', { value: true });
-
-var _createClass = require('@babel/runtime/helpers/createClass');
-var _inheritsLoose = require('@babel/runtime/helpers/inheritsLoose');
-var Stream = require('@videojs/vhs-utils/cjs/stream.js');
-var pkcs7 = require('pkcs7');
-
-function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
-
-var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
-var _inheritsLoose__default = /*#__PURE__*/_interopDefaultLegacy(_inheritsLoose);
-var Stream__default = /*#__PURE__*/_interopDefaultLegacy(Stream);
-
-/**
- * @file aes.js
- *
- * This file contains an adaptation of the AES decryption algorithm
- * from the Standford Javascript Cryptography Library. That work is
- * covered by the following copyright and permissions notice:
- *
- * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. 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 AUTHORS ``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 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.
- *
- * The views and conclusions contained in the software and documentation
- * are those of the authors and should not be interpreted as representing
- * official policies, either expressed or implied, of the authors.
- */
-
-/**
- * Expand the S-box tables.
- *
- * @private
- */
-var precompute = function precompute() {
- var tables = [[[], [], [], [], []], [[], [], [], [], []]];
- var encTable = tables[0];
- var decTable = tables[1];
- var sbox = encTable[4];
- var sboxInv = decTable[4];
- var i;
- var x;
- var xInv;
- var d = [];
- var th = [];
- var x2;
- var x4;
- var x8;
- var s;
- var tEnc;
- var tDec; // Compute double and third tables
-
- for (i = 0; i < 256; i++) {
- th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
- }
-
- for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
- // Compute sbox
- s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
- s = s >> 8 ^ s & 255 ^ 99;
- sbox[x] = s;
- sboxInv[s] = x; // Compute MixColumns
-
- x8 = d[x4 = d[x2 = d[x]]];
- tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- tEnc = d[s] * 0x101 ^ s * 0x1010100;
-
- for (i = 0; i < 4; i++) {
- encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
- decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
- }
- } // Compactify. Considerable speedup on Firefox.
-
-
- for (i = 0; i < 5; i++) {
- encTable[i] = encTable[i].slice(0);
- decTable[i] = decTable[i].slice(0);
- }
-
- return tables;
-};
-
-var aesTables = null;
-/**
- * Schedule out an AES key for both encryption and decryption. This
- * is a low-level class. Use a cipher mode to do bulk encryption.
- *
- * @class AES
- * @param key {Array} The key as an array of 4, 6 or 8 words.
- */
-
-var AES = /*#__PURE__*/function () {
- function AES(key) {
- /**
- * The expanded S-box and inverse S-box tables. These will be computed
- * on the client so that we don't have to send them down the wire.
- *
- * There are two tables, _tables[0] is for encryption and
- * _tables[1] is for decryption.
- *
- * The first 4 sub-tables are the expanded S-box with MixColumns. The
- * last (_tables[01][4]) is the S-box itself.
- *
- * @private
- */
- // if we have yet to precompute the S-box tables
- // do so now
- if (!aesTables) {
- aesTables = precompute();
- } // then make a copy of that object for use
-
-
- this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
- var i;
- var j;
- var tmp;
- var sbox = this._tables[0][4];
- var decTable = this._tables[1];
- var keyLen = key.length;
- var rcon = 1;
-
- if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
- throw new Error('Invalid aes key size');
- }
-
- var encKey = key.slice(0);
- var decKey = [];
- this._key = [encKey, decKey]; // schedule encryption keys
-
- for (i = keyLen; i < 4 * keyLen + 28; i++) {
- tmp = encKey[i - 1]; // apply sbox
-
- if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
- tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
-
- if (i % keyLen === 0) {
- tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
- rcon = rcon << 1 ^ (rcon >> 7) * 283;
- }
- }
-
- encKey[i] = encKey[i - keyLen] ^ tmp;
- } // schedule decryption keys
-
-
- for (j = 0; i; j++, i--) {
- tmp = encKey[j & 3 ? i : i - 4];
-
- if (i <= 4 || j < 4) {
- decKey[j] = tmp;
- } else {
- decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
- }
- }
- }
- /**
- * Decrypt 16 bytes, specified as four 32-bit words.
- *
- * @param {number} encrypted0 the first word to decrypt
- * @param {number} encrypted1 the second word to decrypt
- * @param {number} encrypted2 the third word to decrypt
- * @param {number} encrypted3 the fourth word to decrypt
- * @param {Int32Array} out the array to write the decrypted words
- * into
- * @param {number} offset the offset into the output array to start
- * writing results
- * @return {Array} The plaintext.
- */
-
-
- var _proto = AES.prototype;
-
- _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
- var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
-
- var a = encrypted0 ^ key[0];
- var b = encrypted3 ^ key[1];
- var c = encrypted2 ^ key[2];
- var d = encrypted1 ^ key[3];
- var a2;
- var b2;
- var c2; // key.length === 2 ?
-
- var nInnerRounds = key.length / 4 - 2;
- var i;
- var kIndex = 4;
- var table = this._tables[1]; // load up the tables
-
- var table0 = table[0];
- var table1 = table[1];
- var table2 = table[2];
- var table3 = table[3];
- var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
-
- for (i = 0; i < nInnerRounds; i++) {
- a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
- b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
- c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
- d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
- kIndex += 4;
- a = a2;
- b = b2;
- c = c2;
- } // Last round.
-
-
- for (i = 0; i < 4; i++) {
- out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
- a2 = a;
- a = b;
- b = c;
- c = d;
- d = a2;
- }
- };
-
- return AES;
-}();
-
-/**
- * A wrapper around the Stream class to use setTimeout
- * and run stream "jobs" Asynchronously
- *
- * @class AsyncStream
- * @extends Stream
- */
-
-var AsyncStream = /*#__PURE__*/function (_Stream) {
- _inheritsLoose__default['default'](AsyncStream, _Stream);
-
- function AsyncStream() {
- var _this;
-
- _this = _Stream.call(this, Stream__default['default']) || this;
- _this.jobs = [];
- _this.delay = 1;
- _this.timeout_ = null;
- return _this;
- }
- /**
- * process an async job
- *
- * @private
- */
-
-
- var _proto = AsyncStream.prototype;
-
- _proto.processJob_ = function processJob_() {
- this.jobs.shift()();
-
- if (this.jobs.length) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- } else {
- this.timeout_ = null;
- }
- }
- /**
- * push a job into the stream
- *
- * @param {Function} job the job to push into the stream
- */
- ;
-
- _proto.push = function push(job) {
- this.jobs.push(job);
-
- if (!this.timeout_) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- }
- };
-
- return AsyncStream;
-}(Stream__default['default']);
-
-/**
- * Convert network-order (big-endian) bytes into their little-endian
- * representation.
- */
-
-var ntoh = function ntoh(word) {
- return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
-};
-/**
- * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * use for the first round of CBC.
- * @return {Uint8Array} the decrypted bytes
- *
- * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
- * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
- * @see https://tools.ietf.org/html/rfc2315
- */
-
-
-var decrypt = function decrypt(encrypted, key, initVector) {
- // word-level access to the encrypted bytes
- var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
- var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
-
- var decrypted = new Uint8Array(encrypted.byteLength);
- var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
- // decrypted data
-
- var init0;
- var init1;
- var init2;
- var init3;
- var encrypted0;
- var encrypted1;
- var encrypted2;
- var encrypted3; // iteration variable
-
- var wordIx; // pull out the words of the IV to ensure we don't modify the
- // passed-in reference and easier access
-
- init0 = initVector[0];
- init1 = initVector[1];
- init2 = initVector[2];
- init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
- // to each decrypted block
-
- for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
- // convert big-endian (network order) words into little-endian
- // (javascript order)
- encrypted0 = ntoh(encrypted32[wordIx]);
- encrypted1 = ntoh(encrypted32[wordIx + 1]);
- encrypted2 = ntoh(encrypted32[wordIx + 2]);
- encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
-
- decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
- // plaintext
-
- decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
- decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
- decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
- decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
-
- init0 = encrypted0;
- init1 = encrypted1;
- init2 = encrypted2;
- init3 = encrypted3;
- }
-
- return decrypted;
-};
-/**
- * The `Decrypter` class that manages decryption of AES
- * data through `AsyncStream` objects and the `decrypt`
- * function
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * @param {Function} done the function to run when done
- * @class Decrypter
- */
-
-
-var Decrypter = /*#__PURE__*/function () {
- function Decrypter(encrypted, key, initVector, done) {
- var step = Decrypter.STEP;
- var encrypted32 = new Int32Array(encrypted.buffer);
- var decrypted = new Uint8Array(encrypted.byteLength);
- var i = 0;
- this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
-
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
-
- for (i = step; i < encrypted32.length; i += step) {
- initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
- } // invoke the done() callback when everything is finished
-
-
- this.asyncStream_.push(function () {
- // remove pkcs#7 padding from the decrypted bytes
- done(null, pkcs7.unpad(decrypted));
- });
- }
- /**
- * a getter for step the maximum number of bytes to process at one time
- *
- * @return {number} the value of step 32000
- */
-
-
- var _proto = Decrypter.prototype;
-
- /**
- * @private
- */
- _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
- return function () {
- var bytes = decrypt(encrypted, key, initVector);
- decrypted.set(bytes, encrypted.byteOffset);
- };
- };
-
- _createClass__default['default'](Decrypter, null, [{
- key: "STEP",
- get: function get() {
- // 4 * 8000;
- return 32000;
- }
- }]);
-
- return Decrypter;
-}();
-
-exports.AsyncStream = AsyncStream;
-exports.Decrypter = Decrypter;
-exports.decrypt = decrypt;
diff --git a/node_modules/aes-decrypter/dist/aes-decrypter.es.js b/node_modules/aes-decrypter/dist/aes-decrypter.es.js
deleted file mode 100644
index 622e8a3..0000000
--- a/node_modules/aes-decrypter/dist/aes-decrypter.es.js
+++ /dev/null
@@ -1,430 +0,0 @@
-/*! @name aes-decrypter @version 3.1.2 @license Apache-2.0 */
-import _createClass from '@babel/runtime/helpers/createClass';
-import _inheritsLoose from '@babel/runtime/helpers/inheritsLoose';
-import Stream from '@videojs/vhs-utils/es/stream.js';
-import { unpad } from 'pkcs7';
-
-/**
- * @file aes.js
- *
- * This file contains an adaptation of the AES decryption algorithm
- * from the Standford Javascript Cryptography Library. That work is
- * covered by the following copyright and permissions notice:
- *
- * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. 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 AUTHORS ``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 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.
- *
- * The views and conclusions contained in the software and documentation
- * are those of the authors and should not be interpreted as representing
- * official policies, either expressed or implied, of the authors.
- */
-
-/**
- * Expand the S-box tables.
- *
- * @private
- */
-var precompute = function precompute() {
- var tables = [[[], [], [], [], []], [[], [], [], [], []]];
- var encTable = tables[0];
- var decTable = tables[1];
- var sbox = encTable[4];
- var sboxInv = decTable[4];
- var i;
- var x;
- var xInv;
- var d = [];
- var th = [];
- var x2;
- var x4;
- var x8;
- var s;
- var tEnc;
- var tDec; // Compute double and third tables
-
- for (i = 0; i < 256; i++) {
- th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
- }
-
- for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
- // Compute sbox
- s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
- s = s >> 8 ^ s & 255 ^ 99;
- sbox[x] = s;
- sboxInv[s] = x; // Compute MixColumns
-
- x8 = d[x4 = d[x2 = d[x]]];
- tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- tEnc = d[s] * 0x101 ^ s * 0x1010100;
-
- for (i = 0; i < 4; i++) {
- encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
- decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
- }
- } // Compactify. Considerable speedup on Firefox.
-
-
- for (i = 0; i < 5; i++) {
- encTable[i] = encTable[i].slice(0);
- decTable[i] = decTable[i].slice(0);
- }
-
- return tables;
-};
-
-var aesTables = null;
-/**
- * Schedule out an AES key for both encryption and decryption. This
- * is a low-level class. Use a cipher mode to do bulk encryption.
- *
- * @class AES
- * @param key {Array} The key as an array of 4, 6 or 8 words.
- */
-
-var AES = /*#__PURE__*/function () {
- function AES(key) {
- /**
- * The expanded S-box and inverse S-box tables. These will be computed
- * on the client so that we don't have to send them down the wire.
- *
- * There are two tables, _tables[0] is for encryption and
- * _tables[1] is for decryption.
- *
- * The first 4 sub-tables are the expanded S-box with MixColumns. The
- * last (_tables[01][4]) is the S-box itself.
- *
- * @private
- */
- // if we have yet to precompute the S-box tables
- // do so now
- if (!aesTables) {
- aesTables = precompute();
- } // then make a copy of that object for use
-
-
- this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
- var i;
- var j;
- var tmp;
- var sbox = this._tables[0][4];
- var decTable = this._tables[1];
- var keyLen = key.length;
- var rcon = 1;
-
- if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
- throw new Error('Invalid aes key size');
- }
-
- var encKey = key.slice(0);
- var decKey = [];
- this._key = [encKey, decKey]; // schedule encryption keys
-
- for (i = keyLen; i < 4 * keyLen + 28; i++) {
- tmp = encKey[i - 1]; // apply sbox
-
- if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
- tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
-
- if (i % keyLen === 0) {
- tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
- rcon = rcon << 1 ^ (rcon >> 7) * 283;
- }
- }
-
- encKey[i] = encKey[i - keyLen] ^ tmp;
- } // schedule decryption keys
-
-
- for (j = 0; i; j++, i--) {
- tmp = encKey[j & 3 ? i : i - 4];
-
- if (i <= 4 || j < 4) {
- decKey[j] = tmp;
- } else {
- decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
- }
- }
- }
- /**
- * Decrypt 16 bytes, specified as four 32-bit words.
- *
- * @param {number} encrypted0 the first word to decrypt
- * @param {number} encrypted1 the second word to decrypt
- * @param {number} encrypted2 the third word to decrypt
- * @param {number} encrypted3 the fourth word to decrypt
- * @param {Int32Array} out the array to write the decrypted words
- * into
- * @param {number} offset the offset into the output array to start
- * writing results
- * @return {Array} The plaintext.
- */
-
-
- var _proto = AES.prototype;
-
- _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
- var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
-
- var a = encrypted0 ^ key[0];
- var b = encrypted3 ^ key[1];
- var c = encrypted2 ^ key[2];
- var d = encrypted1 ^ key[3];
- var a2;
- var b2;
- var c2; // key.length === 2 ?
-
- var nInnerRounds = key.length / 4 - 2;
- var i;
- var kIndex = 4;
- var table = this._tables[1]; // load up the tables
-
- var table0 = table[0];
- var table1 = table[1];
- var table2 = table[2];
- var table3 = table[3];
- var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
-
- for (i = 0; i < nInnerRounds; i++) {
- a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
- b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
- c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
- d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
- kIndex += 4;
- a = a2;
- b = b2;
- c = c2;
- } // Last round.
-
-
- for (i = 0; i < 4; i++) {
- out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
- a2 = a;
- a = b;
- b = c;
- c = d;
- d = a2;
- }
- };
-
- return AES;
-}();
-
-/**
- * A wrapper around the Stream class to use setTimeout
- * and run stream "jobs" Asynchronously
- *
- * @class AsyncStream
- * @extends Stream
- */
-
-var AsyncStream = /*#__PURE__*/function (_Stream) {
- _inheritsLoose(AsyncStream, _Stream);
-
- function AsyncStream() {
- var _this;
-
- _this = _Stream.call(this, Stream) || this;
- _this.jobs = [];
- _this.delay = 1;
- _this.timeout_ = null;
- return _this;
- }
- /**
- * process an async job
- *
- * @private
- */
-
-
- var _proto = AsyncStream.prototype;
-
- _proto.processJob_ = function processJob_() {
- this.jobs.shift()();
-
- if (this.jobs.length) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- } else {
- this.timeout_ = null;
- }
- }
- /**
- * push a job into the stream
- *
- * @param {Function} job the job to push into the stream
- */
- ;
-
- _proto.push = function push(job) {
- this.jobs.push(job);
-
- if (!this.timeout_) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- }
- };
-
- return AsyncStream;
-}(Stream);
-
-/**
- * Convert network-order (big-endian) bytes into their little-endian
- * representation.
- */
-
-var ntoh = function ntoh(word) {
- return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
-};
-/**
- * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * use for the first round of CBC.
- * @return {Uint8Array} the decrypted bytes
- *
- * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
- * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
- * @see https://tools.ietf.org/html/rfc2315
- */
-
-
-var decrypt = function decrypt(encrypted, key, initVector) {
- // word-level access to the encrypted bytes
- var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
- var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
-
- var decrypted = new Uint8Array(encrypted.byteLength);
- var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
- // decrypted data
-
- var init0;
- var init1;
- var init2;
- var init3;
- var encrypted0;
- var encrypted1;
- var encrypted2;
- var encrypted3; // iteration variable
-
- var wordIx; // pull out the words of the IV to ensure we don't modify the
- // passed-in reference and easier access
-
- init0 = initVector[0];
- init1 = initVector[1];
- init2 = initVector[2];
- init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
- // to each decrypted block
-
- for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
- // convert big-endian (network order) words into little-endian
- // (javascript order)
- encrypted0 = ntoh(encrypted32[wordIx]);
- encrypted1 = ntoh(encrypted32[wordIx + 1]);
- encrypted2 = ntoh(encrypted32[wordIx + 2]);
- encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
-
- decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
- // plaintext
-
- decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
- decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
- decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
- decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
-
- init0 = encrypted0;
- init1 = encrypted1;
- init2 = encrypted2;
- init3 = encrypted3;
- }
-
- return decrypted;
-};
-/**
- * The `Decrypter` class that manages decryption of AES
- * data through `AsyncStream` objects and the `decrypt`
- * function
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * @param {Function} done the function to run when done
- * @class Decrypter
- */
-
-
-var Decrypter = /*#__PURE__*/function () {
- function Decrypter(encrypted, key, initVector, done) {
- var step = Decrypter.STEP;
- var encrypted32 = new Int32Array(encrypted.buffer);
- var decrypted = new Uint8Array(encrypted.byteLength);
- var i = 0;
- this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
-
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
-
- for (i = step; i < encrypted32.length; i += step) {
- initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
- } // invoke the done() callback when everything is finished
-
-
- this.asyncStream_.push(function () {
- // remove pkcs#7 padding from the decrypted bytes
- done(null, unpad(decrypted));
- });
- }
- /**
- * a getter for step the maximum number of bytes to process at one time
- *
- * @return {number} the value of step 32000
- */
-
-
- var _proto = Decrypter.prototype;
-
- /**
- * @private
- */
- _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
- return function () {
- var bytes = decrypt(encrypted, key, initVector);
- decrypted.set(bytes, encrypted.byteOffset);
- };
- };
-
- _createClass(Decrypter, null, [{
- key: "STEP",
- get: function get() {
- // 4 * 8000;
- return 32000;
- }
- }]);
-
- return Decrypter;
-}();
-
-export { AsyncStream, Decrypter, decrypt };
diff --git a/node_modules/aes-decrypter/dist/aes-decrypter.js b/node_modules/aes-decrypter/dist/aes-decrypter.js
deleted file mode 100644
index 39213b8..0000000
--- a/node_modules/aes-decrypter/dist/aes-decrypter.js
+++ /dev/null
@@ -1,596 +0,0 @@
-/*! @name aes-decrypter @version 3.1.2 @license Apache-2.0 */
-(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.aesDecrypter = {}));
-}(this, (function (exports) { 'use strict';
-
- 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);
- }
- }
-
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
-
- var createClass = _createClass;
-
- /**
- * @file aes.js
- *
- * This file contains an adaptation of the AES decryption algorithm
- * from the Standford Javascript Cryptography Library. That work is
- * covered by the following copyright and permissions notice:
- *
- * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. 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 AUTHORS ``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 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.
- *
- * The views and conclusions contained in the software and documentation
- * are those of the authors and should not be interpreted as representing
- * official policies, either expressed or implied, of the authors.
- */
-
- /**
- * Expand the S-box tables.
- *
- * @private
- */
- var precompute = function precompute() {
- var tables = [[[], [], [], [], []], [[], [], [], [], []]];
- var encTable = tables[0];
- var decTable = tables[1];
- var sbox = encTable[4];
- var sboxInv = decTable[4];
- var i;
- var x;
- var xInv;
- var d = [];
- var th = [];
- var x2;
- var x4;
- var x8;
- var s;
- var tEnc;
- var tDec; // Compute double and third tables
-
- for (i = 0; i < 256; i++) {
- th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
- }
-
- for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
- // Compute sbox
- s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
- s = s >> 8 ^ s & 255 ^ 99;
- sbox[x] = s;
- sboxInv[s] = x; // Compute MixColumns
-
- x8 = d[x4 = d[x2 = d[x]]];
- tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- tEnc = d[s] * 0x101 ^ s * 0x1010100;
-
- for (i = 0; i < 4; i++) {
- encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
- decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
- }
- } // Compactify. Considerable speedup on Firefox.
-
-
- for (i = 0; i < 5; i++) {
- encTable[i] = encTable[i].slice(0);
- decTable[i] = decTable[i].slice(0);
- }
-
- return tables;
- };
-
- var aesTables = null;
- /**
- * Schedule out an AES key for both encryption and decryption. This
- * is a low-level class. Use a cipher mode to do bulk encryption.
- *
- * @class AES
- * @param key {Array} The key as an array of 4, 6 or 8 words.
- */
-
- var AES = /*#__PURE__*/function () {
- function AES(key) {
- /**
- * The expanded S-box and inverse S-box tables. These will be computed
- * on the client so that we don't have to send them down the wire.
- *
- * There are two tables, _tables[0] is for encryption and
- * _tables[1] is for decryption.
- *
- * The first 4 sub-tables are the expanded S-box with MixColumns. The
- * last (_tables[01][4]) is the S-box itself.
- *
- * @private
- */
- // if we have yet to precompute the S-box tables
- // do so now
- if (!aesTables) {
- aesTables = precompute();
- } // then make a copy of that object for use
-
-
- this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
- var i;
- var j;
- var tmp;
- var sbox = this._tables[0][4];
- var decTable = this._tables[1];
- var keyLen = key.length;
- var rcon = 1;
-
- if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
- throw new Error('Invalid aes key size');
- }
-
- var encKey = key.slice(0);
- var decKey = [];
- this._key = [encKey, decKey]; // schedule encryption keys
-
- for (i = keyLen; i < 4 * keyLen + 28; i++) {
- tmp = encKey[i - 1]; // apply sbox
-
- if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
- tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
-
- if (i % keyLen === 0) {
- tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
- rcon = rcon << 1 ^ (rcon >> 7) * 283;
- }
- }
-
- encKey[i] = encKey[i - keyLen] ^ tmp;
- } // schedule decryption keys
-
-
- for (j = 0; i; j++, i--) {
- tmp = encKey[j & 3 ? i : i - 4];
-
- if (i <= 4 || j < 4) {
- decKey[j] = tmp;
- } else {
- decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
- }
- }
- }
- /**
- * Decrypt 16 bytes, specified as four 32-bit words.
- *
- * @param {number} encrypted0 the first word to decrypt
- * @param {number} encrypted1 the second word to decrypt
- * @param {number} encrypted2 the third word to decrypt
- * @param {number} encrypted3 the fourth word to decrypt
- * @param {Int32Array} out the array to write the decrypted words
- * into
- * @param {number} offset the offset into the output array to start
- * writing results
- * @return {Array} The plaintext.
- */
-
-
- var _proto = AES.prototype;
-
- _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
- var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
-
- var a = encrypted0 ^ key[0];
- var b = encrypted3 ^ key[1];
- var c = encrypted2 ^ key[2];
- var d = encrypted1 ^ key[3];
- var a2;
- var b2;
- var c2; // key.length === 2 ?
-
- var nInnerRounds = key.length / 4 - 2;
- var i;
- var kIndex = 4;
- var table = this._tables[1]; // load up the tables
-
- var table0 = table[0];
- var table1 = table[1];
- var table2 = table[2];
- var table3 = table[3];
- var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
-
- for (i = 0; i < nInnerRounds; i++) {
- a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
- b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
- c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
- d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
- kIndex += 4;
- a = a2;
- b = b2;
- c = c2;
- } // Last round.
-
-
- for (i = 0; i < 4; i++) {
- out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
- a2 = a;
- a = b;
- b = c;
- c = d;
- d = a2;
- }
- };
-
- return AES;
- }();
-
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- subClass.__proto__ = superClass;
- }
-
- var inheritsLoose = _inheritsLoose;
-
- /**
- * @file stream.js
- */
-
- /**
- * A lightweight readable stream implemention that handles event dispatching.
- *
- * @class Stream
- */
- var Stream = /*#__PURE__*/function () {
- function Stream() {
- this.listeners = {};
- }
- /**
- * Add a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener the callback to be invoked when an event of
- * the specified type occurs
- */
-
-
- var _proto = Stream.prototype;
-
- _proto.on = function on(type, listener) {
- if (!this.listeners[type]) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push(listener);
- }
- /**
- * Remove a listener for a specified event type.
- *
- * @param {string} type the event name
- * @param {Function} listener a function previously registered for this
- * type of event through `on`
- * @return {boolean} if we could turn it off or not
- */
- ;
-
- _proto.off = function off(type, listener) {
- if (!this.listeners[type]) {
- return false;
- }
-
- var index = this.listeners[type].indexOf(listener); // TODO: which is better?
- // In Video.js we slice listener functions
- // on trigger so that it does not mess up the order
- // while we loop through.
- //
- // Here we slice on off so that the loop in trigger
- // can continue using it's old reference to loop without
- // messing up the order.
-
- this.listeners[type] = this.listeners[type].slice(0);
- this.listeners[type].splice(index, 1);
- return index > -1;
- }
- /**
- * Trigger an event of the specified type on this stream. Any additional
- * arguments to this function are passed as parameters to event listeners.
- *
- * @param {string} type the event name
- */
- ;
-
- _proto.trigger = function trigger(type) {
- var callbacks = this.listeners[type];
-
- if (!callbacks) {
- return;
- } // Slicing the arguments on every invocation of this method
- // can add a significant amount of overhead. Avoid the
- // intermediate object creation for the common case of a
- // single callback argument
-
-
- if (arguments.length === 2) {
- var length = callbacks.length;
-
- for (var i = 0; i < length; ++i) {
- callbacks[i].call(this, arguments[1]);
- }
- } else {
- var args = Array.prototype.slice.call(arguments, 1);
- var _length = callbacks.length;
-
- for (var _i = 0; _i < _length; ++_i) {
- callbacks[_i].apply(this, args);
- }
- }
- }
- /**
- * Destroys the stream and cleans up.
- */
- ;
-
- _proto.dispose = function dispose() {
- this.listeners = {};
- }
- /**
- * Forwards all `data` events on this stream to the destination stream. The
- * destination stream should provide a method `push` to receive the data
- * events as they arrive.
- *
- * @param {Stream} destination the stream that will receive all `data` events
- * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
- */
- ;
-
- _proto.pipe = function pipe(destination) {
- this.on('data', function (data) {
- destination.push(data);
- });
- };
-
- return Stream;
- }();
-
- /**
- * A wrapper around the Stream class to use setTimeout
- * and run stream "jobs" Asynchronously
- *
- * @class AsyncStream
- * @extends Stream
- */
-
- var AsyncStream = /*#__PURE__*/function (_Stream) {
- inheritsLoose(AsyncStream, _Stream);
-
- function AsyncStream() {
- var _this;
-
- _this = _Stream.call(this, Stream) || this;
- _this.jobs = [];
- _this.delay = 1;
- _this.timeout_ = null;
- return _this;
- }
- /**
- * process an async job
- *
- * @private
- */
-
-
- var _proto = AsyncStream.prototype;
-
- _proto.processJob_ = function processJob_() {
- this.jobs.shift()();
-
- if (this.jobs.length) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- } else {
- this.timeout_ = null;
- }
- }
- /**
- * push a job into the stream
- *
- * @param {Function} job the job to push into the stream
- */
- ;
-
- _proto.push = function push(job) {
- this.jobs.push(job);
-
- if (!this.timeout_) {
- this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
- }
- };
-
- return AsyncStream;
- }(Stream);
-
- /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
- /**
- * Returns the subarray of a Uint8Array without PKCS#7 padding.
- *
- * @param padded {Uint8Array} unencrypted bytes that have been padded
- * @return {Uint8Array} the unpadded bytes
- * @see http://tools.ietf.org/html/rfc5652
- */
-
- function unpad(padded) {
- return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
- }
-
- /**
- * Convert network-order (big-endian) bytes into their little-endian
- * representation.
- */
-
- var ntoh = function ntoh(word) {
- return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
- };
- /**
- * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * use for the first round of CBC.
- * @return {Uint8Array} the decrypted bytes
- *
- * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
- * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
- * @see https://tools.ietf.org/html/rfc2315
- */
-
-
- var decrypt = function decrypt(encrypted, key, initVector) {
- // word-level access to the encrypted bytes
- var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
- var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
-
- var decrypted = new Uint8Array(encrypted.byteLength);
- var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
- // decrypted data
-
- var init0;
- var init1;
- var init2;
- var init3;
- var encrypted0;
- var encrypted1;
- var encrypted2;
- var encrypted3; // iteration variable
-
- var wordIx; // pull out the words of the IV to ensure we don't modify the
- // passed-in reference and easier access
-
- init0 = initVector[0];
- init1 = initVector[1];
- init2 = initVector[2];
- init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
- // to each decrypted block
-
- for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
- // convert big-endian (network order) words into little-endian
- // (javascript order)
- encrypted0 = ntoh(encrypted32[wordIx]);
- encrypted1 = ntoh(encrypted32[wordIx + 1]);
- encrypted2 = ntoh(encrypted32[wordIx + 2]);
- encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
-
- decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
- // plaintext
-
- decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
- decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
- decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
- decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
-
- init0 = encrypted0;
- init1 = encrypted1;
- init2 = encrypted2;
- init3 = encrypted3;
- }
-
- return decrypted;
- };
- /**
- * The `Decrypter` class that manages decryption of AES
- * data through `AsyncStream` objects and the `decrypt`
- * function
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * @param {Function} done the function to run when done
- * @class Decrypter
- */
-
-
- var Decrypter = /*#__PURE__*/function () {
- function Decrypter(encrypted, key, initVector, done) {
- var step = Decrypter.STEP;
- var encrypted32 = new Int32Array(encrypted.buffer);
- var decrypted = new Uint8Array(encrypted.byteLength);
- var i = 0;
- this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
-
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
-
- for (i = step; i < encrypted32.length; i += step) {
- initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
- this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
- } // invoke the done() callback when everything is finished
-
-
- this.asyncStream_.push(function () {
- // remove pkcs#7 padding from the decrypted bytes
- done(null, unpad(decrypted));
- });
- }
- /**
- * a getter for step the maximum number of bytes to process at one time
- *
- * @return {number} the value of step 32000
- */
-
-
- var _proto = Decrypter.prototype;
-
- /**
- * @private
- */
- _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
- return function () {
- var bytes = decrypt(encrypted, key, initVector);
- decrypted.set(bytes, encrypted.byteOffset);
- };
- };
-
- createClass(Decrypter, null, [{
- key: "STEP",
- get: function get() {
- // 4 * 8000;
- return 32000;
- }
- }]);
-
- return Decrypter;
- }();
-
- exports.AsyncStream = AsyncStream;
- exports.Decrypter = Decrypter;
- exports.decrypt = decrypt;
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
-})));
diff --git a/node_modules/aes-decrypter/dist/aes-decrypter.min.js b/node_modules/aes-decrypter/dist/aes-decrypter.min.js
deleted file mode 100644
index 55d207b..0000000
--- a/node_modules/aes-decrypter/dist/aes-decrypter.min.js
+++ /dev/null
@@ -1,4 +0,0 @@
-/*! @name aes-decrypter @version 3.1.2 @license Apache-2.0 */
-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).aesDecrypter={})}(this,(function(t){"use strict";function e(t,e){for(var n=0;n>7))^t]=t;for(e=n=0;!a[e];e^=r||1,n=p[n]||1)for(s=(s=n^n<<1^n<<2^n<<3^n<<4)>>8^255&s^99,a[e]=s,h[s]=e,u=16843009*y[i=y[r=y[e]]]^65537*i^257*r^16843008*e,o=257*y[s]^16843008*s,t=0;t<4;t++)c[t][e]=o=o<<24^o>>>8,f[t][s]=u=u<<24^u>>>8;for(t=0;t<5;t++)c[t]=c[t].slice(0),f[t]=f[t].slice(0);return l}()),this._tables=[[r[0][0].slice(),r[0][1].slice(),r[0][2].slice(),r[0][3].slice(),r[0][4].slice()],[r[1][0].slice(),r[1][1].slice(),r[1][2].slice(),r[1][3].slice(),r[1][4].slice()]];var s=this._tables[0][4],o=this._tables[1],u=t.length,l=1;if(4!==u&&6!==u&&8!==u)throw new Error("Invalid aes key size");var c=t.slice(0),f=[];for(this._key=[c,f],e=u;e<4*u+28;e++)i=c[e-1],(e%u==0||8===u&&e%u==4)&&(i=s[i>>>24]<<24^s[i>>16&255]<<16^s[i>>8&255]<<8^s[255&i],e%u==0&&(i=i<<8^i>>>24^l<<24,l=l<<1^283*(l>>7))),c[e]=c[e-u]^i;for(n=0;e;n++,e--)i=c[3&n?e:e-4],f[n]=e<=4||n<4?i:o[0][s[i>>>24]]^o[1][s[i>>16&255]]^o[2][s[i>>8&255]]^o[3][s[255&i]]}return t.prototype.decrypt=function(t,e,n,r,i,s){var o,u,l,c,f=this._key[1],a=t^f[0],h=r^f[1],y=n^f[2],p=e^f[3],b=f.length/4-2,d=4,_=this._tables[1],v=_[0],g=_[1],m=_[2],w=_[3],A=_[4];for(c=0;c>>24]^g[h>>16&255]^m[y>>8&255]^w[255&p]^f[d],u=v[h>>>24]^g[y>>16&255]^m[p>>8&255]^w[255&a]^f[d+1],l=v[y>>>24]^g[p>>16&255]^m[a>>8&255]^w[255&h]^f[d+2],p=v[p>>>24]^g[a>>16&255]^m[h>>8&255]^w[255&y]^f[d+3],d+=4,a=o,h=u,y=l;for(c=0;c<4;c++)i[(3&-c)+s]=A[a>>>24]<<24^A[h>>16&255]<<16^A[y>>8&255]<<8^A[255&p]^f[d++],o=a,a=h,h=y,y=p,p=o},t}();var s=function(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e},o=function(){function t(){this.listeners={}}var e=t.prototype;return e.on=function(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)},e.off=function(t,e){if(!this.listeners[t])return!1;var n=this.listeners[t].indexOf(e);return this.listeners[t]=this.listeners[t].slice(0),this.listeners[t].splice(n,1),n>-1},e.trigger=function(t){var e=this.listeners[t];if(e)if(2===arguments.length)for(var n=e.length,r=0;r>8|t>>>24},c=function(t,e,n){var r,s,o,u,c,f,a,h,y,p=new Int32Array(t.buffer,t.byteOffset,t.byteLength>>2),b=new i(Array.prototype.slice.call(e)),d=new Uint8Array(t.byteLength),_=new Int32Array(d.buffer);for(r=n[0],s=n[1],o=n[2],u=n[3],y=0;y
-
-
-
- aes-decrypter Demo
-
-
-
- To test this out, open up your developer console.
-
-
-
diff --git a/node_modules/aes-decrypter/package.json b/node_modules/aes-decrypter/package.json
deleted file mode 100644
index 2ea438f..0000000
--- a/node_modules/aes-decrypter/package.json
+++ /dev/null
@@ -1,133 +0,0 @@
-{
- "_from": "aes-decrypter@3.1.2",
- "_id": "aes-decrypter@3.1.2",
- "_inBundle": false,
- "_integrity": "sha512-42nRwfQuPRj9R1zqZBdoxnaAmnIFyDi0MNyTVhjdFOd8fifXKKRfwIHIZ6AMn1or4x5WONzjwRTbTWcsIQ0O4A==",
- "_location": "/aes-decrypter",
- "_phantomChildren": {},
- "_requested": {
- "type": "version",
- "registry": true,
- "raw": "aes-decrypter@3.1.2",
- "name": "aes-decrypter",
- "escapedName": "aes-decrypter",
- "rawSpec": "3.1.2",
- "saveSpec": null,
- "fetchSpec": "3.1.2"
- },
- "_requiredBy": [
- "/@videojs/http-streaming",
- "/video.js"
- ],
- "_resolved": "https://registry.npmjs.org/aes-decrypter/-/aes-decrypter-3.1.2.tgz",
- "_shasum": "3545546f8e9f6b878640339a242efe221ba7a7cb",
- "_spec": "aes-decrypter@3.1.2",
- "_where": "F:\\Documents\\websites\\BMM\\node_modules\\video.js",
- "author": {
- "name": "Brightcove, Inc."
- },
- "browserslist": [
- "defaults",
- "ie 11"
- ],
- "bugs": {
- "url": "https://github.com/videojs/aes-decrypter/issues"
- },
- "bundleDependencies": false,
- "contributors": [
- {
- "name": "gkatsev"
- },
- {
- "name": "imbcmdth"
- },
- {
- "name": "dmlap"
- },
- {
- "name": "bcasey"
- }
- ],
- "dependencies": {
- "@babel/runtime": "^7.12.5",
- "@videojs/vhs-utils": "^3.0.0",
- "global": "^4.4.0",
- "pkcs7": "^1.0.4"
- },
- "deprecated": false,
- "description": "decrypt aes-128 content using a key",
- "devDependencies": {
- "@rollup/plugin-replace": "^2.3.4",
- "@videojs/generator-helpers": "~2.0.1",
- "karma": "^5.2.3",
- "rollup": "^2.36.1",
- "sinon": "^9.2.3",
- "videojs-generate-karma-config": "~7.0.0",
- "videojs-generate-rollup-config": "~6.1.0",
- "videojs-generator-verify": "~3.0.1",
- "videojs-standard": "^8.0.4"
- },
- "directories": {
- "test": "test"
- },
- "files": [
- "CONTRIBUTING.md",
- "dist/",
- "docs/",
- "index.html",
- "scripts/",
- "src/",
- "test/"
- ],
- "generator-videojs-plugin": {
- "version": "7.7.3"
- },
- "homepage": "https://github.com/videojs/aes-decrypter#readme",
- "husky": {
- "hooks": {
- "pre-commit": "lint-staged"
- }
- },
- "keywords": [
- "videojs",
- "videojs-plugin"
- ],
- "license": "Apache-2.0",
- "lint-staged": {
- "*.js": "vjsstandard --fix",
- "README.md": "doctoc --notitle"
- },
- "main": "dist/aes-decrypter.cjs.js",
- "module": "dist/aes-decrypter.es.js",
- "name": "aes-decrypter",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/videojs/aes-decrypter.git"
- },
- "scripts": {
- "build": "npm-run-all -s clean -p build:*",
- "build-prod": "cross-env-shell NO_TEST_BUNDLE=1 'npm run build'",
- "build-test": "cross-env-shell TEST_BUNDLE_ONLY=1 'npm run build'",
- "build:js": "rollup -c scripts/rollup.config.js",
- "clean": "shx rm -rf ./dist ./test/dist && shx mkdir -p ./dist ./test/dist",
- "lint": "vjsstandard",
- "posttest": "shx cat test/dist/coverage/text.txt",
- "prepublishOnly": "npm-run-all build-prod && vjsverify --verbose",
- "preversion": "npm test",
- "server": "karma start scripts/karma.conf.js --singleRun=false --auto-watch",
- "start": "npm-run-all -p server watch",
- "test": "npm-run-all lint build-test && karma start scripts/karma.conf.js",
- "update-changelog": "conventional-changelog -p videojs -i CHANGELOG.md -s",
- "version": "is-prerelease || npm run update-changelog && git add CHANGELOG.md",
- "watch": "npm-run-all -p watch:*",
- "watch:js": "npm run build:js -- -w"
- },
- "version": "3.1.2",
- "vjsstandard": {
- "ignore": [
- "dist",
- "docs",
- "test/dist"
- ]
- }
-}
diff --git a/node_modules/aes-decrypter/scripts/karma.conf.js b/node_modules/aes-decrypter/scripts/karma.conf.js
deleted file mode 100644
index ac53a18..0000000
--- a/node_modules/aes-decrypter/scripts/karma.conf.js
+++ /dev/null
@@ -1,12 +0,0 @@
-const generate = require('videojs-generate-karma-config');
-
-module.exports = function(config) {
-
- // see https://github.com/videojs/videojs-generate-karma-config
- // for options
- const options = {};
-
- config = generate(config, options);
-
- // any other custom stuff not supported by options here!
-};
diff --git a/node_modules/aes-decrypter/scripts/rollup.config.js b/node_modules/aes-decrypter/scripts/rollup.config.js
deleted file mode 100644
index 8641ab2..0000000
--- a/node_modules/aes-decrypter/scripts/rollup.config.js
+++ /dev/null
@@ -1,36 +0,0 @@
-const generate = require('videojs-generate-rollup-config');
-const replace = require('@rollup/plugin-replace');
-
-// see https://github.com/videojs/videojs-generate-rollup-config
-// for options
-const options = {
- input: 'src/index.js',
- externals(defaults) {
- defaults.module.push('pkcs7');
- defaults.module.push('@videojs/vhs-utils');
- return defaults;
- },
- primedPlugins(defaults) {
- // when using "require" rather than import
- // require cjs module
- defaults.replace = replace({
- // single quote replace
- "require('@videojs/vhs-utils/es": "require('@videojs/vhs-utils/cjs",
- // double quote replace
- 'require("@videojs/vhs-utils/es': 'require("@videojs/vhs-utils/cjs'
- });
-
- return defaults;
- },
- plugins(defaults) {
- defaults.module.unshift('replace');
-
- return defaults;
- }
-};
-const config = generate(options);
-
-// Add additonal builds/customization here!
-
-// export the builds to rollup
-export default Object.values(config.builds);
diff --git a/node_modules/aes-decrypter/src/aes.js b/node_modules/aes-decrypter/src/aes.js
deleted file mode 100644
index 5ca850e..0000000
--- a/node_modules/aes-decrypter/src/aes.js
+++ /dev/null
@@ -1,258 +0,0 @@
-/**
- * @file aes.js
- *
- * This file contains an adaptation of the AES decryption algorithm
- * from the Standford Javascript Cryptography Library. That work is
- * covered by the following copyright and permissions notice:
- *
- * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. 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 AUTHORS ``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 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.
- *
- * The views and conclusions contained in the software and documentation
- * are those of the authors and should not be interpreted as representing
- * official policies, either expressed or implied, of the authors.
- */
-
-/**
- * Expand the S-box tables.
- *
- * @private
- */
-const precompute = function() {
- const tables = [[[], [], [], [], []], [[], [], [], [], []]];
- const encTable = tables[0];
- const decTable = tables[1];
- const sbox = encTable[4];
- const sboxInv = decTable[4];
- let i;
- let x;
- let xInv;
- const d = [];
- const th = [];
- let x2;
- let x4;
- let x8;
- let s;
- let tEnc;
- let tDec;
-
- // Compute double and third tables
- for (i = 0; i < 256; i++) {
- th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
- }
-
- for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
- // Compute sbox
- s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
- s = s >> 8 ^ s & 255 ^ 99;
- sbox[x] = s;
- sboxInv[s] = x;
-
- // Compute MixColumns
- x8 = d[x4 = d[x2 = d[x]]];
- tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
- tEnc = d[s] * 0x101 ^ s * 0x1010100;
-
- for (i = 0; i < 4; i++) {
- encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
- decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
- }
- }
-
- // Compactify. Considerable speedup on Firefox.
- for (i = 0; i < 5; i++) {
- encTable[i] = encTable[i].slice(0);
- decTable[i] = decTable[i].slice(0);
- }
- return tables;
-};
-let aesTables = null;
-
-/**
- * Schedule out an AES key for both encryption and decryption. This
- * is a low-level class. Use a cipher mode to do bulk encryption.
- *
- * @class AES
- * @param key {Array} The key as an array of 4, 6 or 8 words.
- */
-export default class AES {
- constructor(key) {
- /**
- * The expanded S-box and inverse S-box tables. These will be computed
- * on the client so that we don't have to send them down the wire.
- *
- * There are two tables, _tables[0] is for encryption and
- * _tables[1] is for decryption.
- *
- * The first 4 sub-tables are the expanded S-box with MixColumns. The
- * last (_tables[01][4]) is the S-box itself.
- *
- * @private
- */
- // if we have yet to precompute the S-box tables
- // do so now
- if (!aesTables) {
- aesTables = precompute();
- }
- // then make a copy of that object for use
- this._tables = [[aesTables[0][0].slice(),
- aesTables[0][1].slice(),
- aesTables[0][2].slice(),
- aesTables[0][3].slice(),
- aesTables[0][4].slice()],
- [aesTables[1][0].slice(),
- aesTables[1][1].slice(),
- aesTables[1][2].slice(),
- aesTables[1][3].slice(),
- aesTables[1][4].slice()]];
- let i;
- let j;
- let tmp;
- const sbox = this._tables[0][4];
- const decTable = this._tables[1];
- const keyLen = key.length;
- let rcon = 1;
-
- if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
- throw new Error('Invalid aes key size');
- }
-
- const encKey = key.slice(0);
- const decKey = [];
-
- this._key = [encKey, decKey];
-
- // schedule encryption keys
- for (i = keyLen; i < 4 * keyLen + 28; i++) {
- tmp = encKey[i - 1];
-
- // apply sbox
- if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {
- tmp = sbox[tmp >>> 24] << 24 ^
- sbox[tmp >> 16 & 255] << 16 ^
- sbox[tmp >> 8 & 255] << 8 ^
- sbox[tmp & 255];
-
- // shift rows and add rcon
- if (i % keyLen === 0) {
- tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
- rcon = rcon << 1 ^ (rcon >> 7) * 283;
- }
- }
-
- encKey[i] = encKey[i - keyLen] ^ tmp;
- }
-
- // schedule decryption keys
- for (j = 0; i; j++, i--) {
- tmp = encKey[j & 3 ? i : i - 4];
- if (i <= 4 || j < 4) {
- decKey[j] = tmp;
- } else {
- decKey[j] = decTable[0][sbox[tmp >>> 24 ]] ^
- decTable[1][sbox[tmp >> 16 & 255]] ^
- decTable[2][sbox[tmp >> 8 & 255]] ^
- decTable[3][sbox[tmp & 255]];
- }
- }
- }
-
- /**
- * Decrypt 16 bytes, specified as four 32-bit words.
- *
- * @param {number} encrypted0 the first word to decrypt
- * @param {number} encrypted1 the second word to decrypt
- * @param {number} encrypted2 the third word to decrypt
- * @param {number} encrypted3 the fourth word to decrypt
- * @param {Int32Array} out the array to write the decrypted words
- * into
- * @param {number} offset the offset into the output array to start
- * writing results
- * @return {Array} The plaintext.
- */
- decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
- const key = this._key[1];
- // state variables a,b,c,d are loaded with pre-whitened data
- let a = encrypted0 ^ key[0];
- let b = encrypted3 ^ key[1];
- let c = encrypted2 ^ key[2];
- let d = encrypted1 ^ key[3];
- let a2;
- let b2;
- let c2;
-
- // key.length === 2 ?
- const nInnerRounds = key.length / 4 - 2;
- let i;
- let kIndex = 4;
- const table = this._tables[1];
-
- // load up the tables
- const table0 = table[0];
- const table1 = table[1];
- const table2 = table[2];
- const table3 = table[3];
- const sbox = table[4];
-
- // Inner rounds. Cribbed from OpenSSL.
- for (i = 0; i < nInnerRounds; i++) {
- a2 = table0[a >>> 24] ^
- table1[b >> 16 & 255] ^
- table2[c >> 8 & 255] ^
- table3[d & 255] ^
- key[kIndex];
- b2 = table0[b >>> 24] ^
- table1[c >> 16 & 255] ^
- table2[d >> 8 & 255] ^
- table3[a & 255] ^
- key[kIndex + 1];
- c2 = table0[c >>> 24] ^
- table1[d >> 16 & 255] ^
- table2[a >> 8 & 255] ^
- table3[b & 255] ^
- key[kIndex + 2];
- d = table0[d >>> 24] ^
- table1[a >> 16 & 255] ^
- table2[b >> 8 & 255] ^
- table3[c & 255] ^
- key[kIndex + 3];
- kIndex += 4;
- a = a2; b = b2; c = c2;
- }
-
- // Last round.
- for (i = 0; i < 4; i++) {
- out[(3 & -i) + offset] =
- sbox[a >>> 24] << 24 ^
- sbox[b >> 16 & 255] << 16 ^
- sbox[c >> 8 & 255] << 8 ^
- sbox[d & 255] ^
- key[kIndex++];
- a2 = a; a = b; b = c; c = d; d = a2;
- }
- }
-}
diff --git a/node_modules/aes-decrypter/src/async-stream.js b/node_modules/aes-decrypter/src/async-stream.js
deleted file mode 100644
index b8acf08..0000000
--- a/node_modules/aes-decrypter/src/async-stream.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * @file async-stream.js
- */
-import Stream from '@videojs/vhs-utils/es/stream.js';
-
-/**
- * A wrapper around the Stream class to use setTimeout
- * and run stream "jobs" Asynchronously
- *
- * @class AsyncStream
- * @extends Stream
- */
-export default class AsyncStream extends Stream {
- constructor() {
- super(Stream);
- this.jobs = [];
- this.delay = 1;
- this.timeout_ = null;
- }
-
- /**
- * process an async job
- *
- * @private
- */
- processJob_() {
- this.jobs.shift()();
- if (this.jobs.length) {
- this.timeout_ = setTimeout(
- this.processJob_.bind(this),
- this.delay
- );
- } else {
- this.timeout_ = null;
- }
- }
-
- /**
- * push a job into the stream
- *
- * @param {Function} job the job to push into the stream
- */
- push(job) {
- this.jobs.push(job);
- if (!this.timeout_) {
- this.timeout_ = setTimeout(
- this.processJob_.bind(this),
- this.delay
- );
- }
- }
-}
-
diff --git a/node_modules/aes-decrypter/src/decrypter.js b/node_modules/aes-decrypter/src/decrypter.js
deleted file mode 100644
index d887d62..0000000
--- a/node_modules/aes-decrypter/src/decrypter.js
+++ /dev/null
@@ -1,179 +0,0 @@
-/**
- * @file decrypter.js
- *
- * An asynchronous implementation of AES-128 CBC decryption with
- * PKCS#7 padding.
- */
-
-import AES from './aes';
-import AsyncStream from './async-stream';
-import {unpad} from 'pkcs7';
-
-/**
- * Convert network-order (big-endian) bytes into their little-endian
- * representation.
- */
-const ntoh = function(word) {
- return (word << 24) |
- ((word & 0xff00) << 8) |
- ((word & 0xff0000) >> 8) |
- (word >>> 24);
-};
-
-/**
- * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * use for the first round of CBC.
- * @return {Uint8Array} the decrypted bytes
- *
- * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
- * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
- * @see https://tools.ietf.org/html/rfc2315
- */
-const decrypt = function(encrypted, key, initVector) {
- // word-level access to the encrypted bytes
- const encrypted32 = new Int32Array(
- encrypted.buffer,
- encrypted.byteOffset,
- encrypted.byteLength >> 2
- );
-
- const decipher = new AES(Array.prototype.slice.call(key));
-
- // byte and word-level access for the decrypted output
- const decrypted = new Uint8Array(encrypted.byteLength);
- const decrypted32 = new Int32Array(decrypted.buffer);
-
- // temporary variables for working with the IV, encrypted, and
- // decrypted data
- let init0;
- let init1;
- let init2;
- let init3;
- let encrypted0;
- let encrypted1;
- let encrypted2;
- let encrypted3;
-
- // iteration variable
- let wordIx;
-
- // pull out the words of the IV to ensure we don't modify the
- // passed-in reference and easier access
- init0 = initVector[0];
- init1 = initVector[1];
- init2 = initVector[2];
- init3 = initVector[3];
-
- // decrypt four word sequences, applying cipher-block chaining (CBC)
- // to each decrypted block
- for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
- // convert big-endian (network order) words into little-endian
- // (javascript order)
- encrypted0 = ntoh(encrypted32[wordIx]);
- encrypted1 = ntoh(encrypted32[wordIx + 1]);
- encrypted2 = ntoh(encrypted32[wordIx + 2]);
- encrypted3 = ntoh(encrypted32[wordIx + 3]);
-
- // decrypt the block
- decipher.decrypt(
- encrypted0,
- encrypted1,
- encrypted2,
- encrypted3,
- decrypted32,
- wordIx
- );
-
- // XOR with the IV, and restore network byte-order to obtain the
- // plaintext
- decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
- decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
- decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
- decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3);
-
- // setup the IV for the next round
- init0 = encrypted0;
- init1 = encrypted1;
- init2 = encrypted2;
- init3 = encrypted3;
- }
-
- return decrypted;
-};
-
-/**
- * The `Decrypter` class that manages decryption of AES
- * data through `AsyncStream` objects and the `decrypt`
- * function
- *
- * @param {Uint8Array} encrypted the encrypted bytes
- * @param {Uint32Array} key the bytes of the decryption key
- * @param {Uint32Array} initVector the initialization vector (IV) to
- * @param {Function} done the function to run when done
- * @class Decrypter
- */
-class Decrypter {
- constructor(encrypted, key, initVector, done) {
- const step = Decrypter.STEP;
- const encrypted32 = new Int32Array(encrypted.buffer);
- const decrypted = new Uint8Array(encrypted.byteLength);
- let i = 0;
-
- this.asyncStream_ = new AsyncStream();
-
- // split up the encryption job and do the individual chunks asynchronously
- this.asyncStream_.push(this.decryptChunk_(
- encrypted32.subarray(i, i + step),
- key,
- initVector,
- decrypted
- ));
- for (i = step; i < encrypted32.length; i += step) {
- initVector = new Uint32Array([ntoh(encrypted32[i - 4]),
- ntoh(encrypted32[i - 3]),
- ntoh(encrypted32[i - 2]),
- ntoh(encrypted32[i - 1])]);
- this.asyncStream_.push(this.decryptChunk_(
- encrypted32.subarray(i, i + step),
- key,
- initVector,
- decrypted
- ));
- }
- // invoke the done() callback when everything is finished
- this.asyncStream_.push(function() {
- // remove pkcs#7 padding from the decrypted bytes
- done(null, unpad(decrypted));
- });
- }
-
- /**
- * a getter for step the maximum number of bytes to process at one time
- *
- * @return {number} the value of step 32000
- */
- static get STEP() {
- // 4 * 8000;
- return 32000;
- }
-
- /**
- * @private
- */
- decryptChunk_(encrypted, key, initVector, decrypted) {
- return function() {
- const bytes = decrypt(encrypted, key, initVector);
-
- decrypted.set(bytes, encrypted.byteOffset);
- };
- }
-}
-
-export {
- Decrypter,
- decrypt
-};
diff --git a/node_modules/aes-decrypter/src/index.js b/node_modules/aes-decrypter/src/index.js
deleted file mode 100644
index dd75764..0000000
--- a/node_modules/aes-decrypter/src/index.js
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * @file index.js
- *
- * Index module to easily import the primary components of AES-128
- * decryption. Like this:
- *
- * ```js
- * import {Decrypter, decrypt, AsyncStream} from 'aes-decrypter';
- * ```
- */
-import {decrypt, Decrypter} from './decrypter';
-import AsyncStream from './async-stream';
-
-export {
- decrypt,
- Decrypter,
- AsyncStream
-};
diff --git a/node_modules/aes-decrypter/test/decrypter.test.js b/node_modules/aes-decrypter/test/decrypter.test.js
deleted file mode 100644
index b050ebd..0000000
--- a/node_modules/aes-decrypter/test/decrypter.test.js
+++ /dev/null
@@ -1,198 +0,0 @@
-// see docs/hlse.md for instructions on how test data was generated
-import QUnit from 'qunit';
-import {unpad} from 'pkcs7';
-import sinon from 'sinon';
-import {decrypt, Decrypter, AsyncStream} from '../src';
-
-// see docs/hlse.md for instructions on how test data was generated
-const stringFromBytes = function(bytes) {
- let result = '';
-
- for (let i = 0; i < bytes.length; i++) {
- result += String.fromCharCode(bytes[i]);
- }
- return result;
-};
-
-QUnit.module('Decryption');
-QUnit.test('decrypts a single AES-128 with PKCS7 block', function(assert) {
- const key = new Uint32Array([0, 0, 0, 0]);
- const initVector = key;
- // the string "howdy folks" encrypted
- const encrypted = new Uint8Array([
- 0xce, 0x90, 0x97, 0xd0,
- 0x08, 0x46, 0x4d, 0x18,
- 0x4f, 0xae, 0x01, 0x1c,
- 0x82, 0xa8, 0xf0, 0x67
- ]);
-
- assert.deepEqual(
- 'howdy folks',
- stringFromBytes(unpad(decrypt(encrypted, key, initVector))),
- 'decrypted with a byte array key'
- );
-});
-
-QUnit.test('decrypts multiple AES-128 blocks with CBC', function(assert) {
- const key = new Uint32Array([0, 0, 0, 0]);
- const initVector = key;
- // the string "0123456789abcdef01234" encrypted
- const encrypted = new Uint8Array([
- 0x14, 0xf5, 0xfe, 0x74,
- 0x69, 0x66, 0xf2, 0x92,
- 0x65, 0x1c, 0x22, 0x88,
- 0xbb, 0xff, 0x46, 0x09,
-
- 0x0b, 0xde, 0x5e, 0x71,
- 0x77, 0x87, 0xeb, 0x84,
- 0xa9, 0x54, 0xc2, 0x45,
- 0xe9, 0x4e, 0x29, 0xb3
- ]);
-
- assert.deepEqual(
- '0123456789abcdef01234',
- stringFromBytes(unpad(decrypt(encrypted, key, initVector))),
- 'decrypted multiple blocks'
- );
-});
-
-QUnit.test(
- 'verify that the deepcopy works by doing two decrypts in the same test',
- function(assert) {
- const key = new Uint32Array([0, 0, 0, 0]);
- const initVector = key;
- // the string "howdy folks" encrypted
- const pkcs7Block = new Uint8Array([
- 0xce, 0x90, 0x97, 0xd0,
- 0x08, 0x46, 0x4d, 0x18,
- 0x4f, 0xae, 0x01, 0x1c,
- 0x82, 0xa8, 0xf0, 0x67
- ]);
-
- assert.deepEqual(
- 'howdy folks',
- stringFromBytes(unpad(decrypt(pkcs7Block, key, initVector))),
- 'decrypted with a byte array key'
- );
-
- // the string "0123456789abcdef01234" encrypted
- const cbcBlocks = new Uint8Array([
- 0x14, 0xf5, 0xfe, 0x74,
- 0x69, 0x66, 0xf2, 0x92,
- 0x65, 0x1c, 0x22, 0x88,
- 0xbb, 0xff, 0x46, 0x09,
-
- 0x0b, 0xde, 0x5e, 0x71,
- 0x77, 0x87, 0xeb, 0x84,
- 0xa9, 0x54, 0xc2, 0x45,
- 0xe9, 0x4e, 0x29, 0xb3
- ]);
-
- assert.deepEqual(
- '0123456789abcdef01234',
- stringFromBytes(unpad(decrypt(cbcBlocks, key, initVector))),
- 'decrypted multiple blocks'
- );
-
- }
-);
-
-QUnit.module('Incremental Processing', {
- beforeEach() {
- this.clock = sinon.useFakeTimers();
- },
- afterEach() {
- this.clock.restore();
- }
-});
-
-QUnit.test('executes a callback after a timeout', function(assert) {
- const asyncStream = new AsyncStream();
- let calls = '';
-
- asyncStream.push(function() {
- calls += 'a';
- });
-
- this.clock.tick(asyncStream.delay);
- assert.equal(calls, 'a', 'invoked the callback once');
- this.clock.tick(asyncStream.delay);
- assert.equal(calls, 'a', 'only invoked the callback once');
-});
-
-QUnit.test('executes callback in series', function(assert) {
- const asyncStream = new AsyncStream();
- let calls = '';
-
- asyncStream.push(function() {
- calls += 'a';
- });
- asyncStream.push(function() {
- calls += 'b';
- });
-
- this.clock.tick(asyncStream.delay);
- assert.equal(calls, 'a', 'invoked the first callback');
- this.clock.tick(asyncStream.delay);
- assert.equal(calls, 'ab', 'invoked the second');
-});
-
-QUnit.module('Incremental Decryption', {
- beforeEach() {
- this.clock = sinon.useFakeTimers();
- },
- afterEach() {
- this.clock.restore();
- }
-});
-
-QUnit.test('asynchronously decrypts a 4-word block', function(assert) {
- const key = new Uint32Array([0, 0, 0, 0]);
- const initVector = key;
- // the string "howdy folks" encrypted
- const encrypted = new Uint8Array([0xce, 0x90, 0x97, 0xd0,
- 0x08, 0x46, 0x4d, 0x18,
- 0x4f, 0xae, 0x01, 0x1c,
- 0x82, 0xa8, 0xf0, 0x67]);
- let decrypted;
- const decrypter = new Decrypter(
- encrypted,
- key,
- initVector,
- function(error, result) {
- if (error) {
- throw new Error(error);
- }
- decrypted = result;
- }
- );
-
- assert.ok(!decrypted, 'asynchronously decrypts');
- this.clock.tick(decrypter.asyncStream_.delay * 2);
-
- assert.ok(decrypted, 'completed decryption');
- assert.deepEqual(
- 'howdy folks',
- stringFromBytes(decrypted),
- 'decrypts and unpads the result'
- );
-});
-
-QUnit.test('breaks up input greater than the step value', function(assert) {
- const encrypted = new Int32Array(Decrypter.STEP + 4);
- let done = false;
- const decrypter = new Decrypter(
- encrypted,
- new Uint32Array(4),
- new Uint32Array(4),
- function() {
- done = true;
- }
- );
-
- this.clock.tick(decrypter.asyncStream_.delay * 2);
- assert.ok(!done, 'not finished after two ticks');
-
- this.clock.tick(decrypter.asyncStream_.delay);
- assert.ok(done, 'finished after the last chunk is decrypted');
-});
diff --git a/node_modules/cssgram/.npmignore b/node_modules/cssgram/.npmignore
deleted file mode 100644
index d444c16..0000000
--- a/node_modules/cssgram/.npmignore
+++ /dev/null
@@ -1,2 +0,0 @@
-node_modules/
-assets/
\ No newline at end of file
diff --git a/node_modules/cssgram/LICENSE b/node_modules/cssgram/LICENSE
deleted file mode 100644
index fb81747..0000000
--- a/node_modules/cssgram/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2015 Una Kravets
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/node_modules/cssgram/README.md b/node_modules/cssgram/README.md
deleted file mode 100644
index 484a6d7..0000000
--- a/node_modules/cssgram/README.md
+++ /dev/null
@@ -1,149 +0,0 @@
-
-
-# CSSgram
-
-Instagram filter library in Sass and CSS.
-
-## What is This?
-
-Simply put, CSSgram is a library for editing your images with Instagram-like filters directly in CSS. What we’re doing here is adding filters to the images as well as applying color and/or gradient overlays via various blending techniques to mimic these effects. This means *less manual image processing* and more fun filter effects on the web!
-
-We are using pseudo-elements (i.e. `::before` and `::after`) to create the filter effects, so you must apply these filters on a containing element (i.e. not a *replaced element* like ` `). The recommendation is to wrap your images in a `` tag. More about the tag [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure).
-
-## Browser Support
-
-This library uses [CSS Filters](https://developer.mozilla.org/en-US/docs/Web/CSS/filter) and [CSS Blend Modes](https://css-tricks.com/basics-css-blend-modes/). These features are supported in the following browsers:
-
-| | | | | |
-|:---:|:---:|:---:|:---:|:---:|
-| 43+ ✔ | 38+ ✔ | Nope ✘ | 32+ ✔ | 8+ ✔ |
-
-For more information, check on [Can I Use](http://caniuse.com/).
-
-## Usage
-
-**There are currently 2 ways to consume this library:**
-
-### Use CSS classes
-
-When using CSS classes, you can simply add the class with the filter name to the element containing your image.
-
- 1. Include the CDN link in your `` tag: ` `
- * Alternatively, you can [download the CSSgram library](https://raw.githubusercontent.com/una/CSSgram/master/source/css/cssgram.min.css) locally and link to the it within your project: ` `
- * Add a class to your image element with the name of the filter you would like to use
-
-For example:
-
-```
-
-
-
-
-```
-
-Alternatively, you can just download and link to any individual css file (e.g. ` `), if you’re just using one of the styles.
-
-### Available Classes
-
-_For use in HTML markup:_
-
-* Aden: `class="aden"`
-* Reyes: `class="reyes"`
-* Perpetua: `class="perpetua"`
-* Inkwell: `class="inkwell"`
-* Toaster: `class="toaster"`
-* Walden: `class="walden"`
-* Hudson: `class="hudson"`
-* Gingham: `class="gingham"`
-* Mayfair: `class="mayfair"`
-* Lo-fi: `class="lofi"`
-* X-Pro II: `class="xpro2"`
-* 1977: `class="_1977"`
-* Brooklyn: `class="brooklyn"`
-* Nashville: `class="nashville"`
-
-* * *
-
-### Use Sass `@extend`
-
-If you use custom naming in your CSS architecture, you can add the `.scss` files for the provided styles within your project and then `@extend` the filter effects within your style definitions. If you think extends are stupid, I will fight you 😊.
-
-1. [Download the `scss/` folder contents](https://github.com/una/CSSgram/tree/master/source/scss)
-* Include a link to `scss/cssgram.scss` via an `@import` statement in your Sass manifest file (i.e. `main.scss`). It may look like: `@import 'vendor/cssgram'`
-* Extend the placeholder selector (e.g. `@extend %aden`) in your element.
-
-For example:
-
-```
-
-
-
-
-```
-
-```
-// Sass
-.viz--beautiful {
- @extend %aden;
-}
-```
-
-Alternatively, you can just download and link any individual `.scss` file in your Sass manifest (i.e. `scss/aden.scss`), if you're just using one of the styles.
-
-### Available Placeholders
-
-_For use in Sass stylesheets:_
-
-* Aden: `@extend %aden`
-* Reyes: `@extend %reyes`
-* Perpetua: `@extend %perpetua`
-* Inkwell: `@extend %inkwell`
-* Toaster: `@extend %toaster`
-* Walden: `@extend %walden`
-* Hudson: `@extend %hudson`
-* Gingham: `@extend %gingham`
-* Mayfair: `@extend %mayfair`
-* Lo-fi: `@extend %lofi`
-* X-Pro II: `@extend %xpro2`
-* 1977: `@extend %_1977`
-* Brooklyn: `@extend %brooklyn`
-* Nashville: `@extend %nashville`
-
-## Contributing
-
-Either:
-
-1. Create an [issue](https://github.com/una/CSSgram/issues)
-
-Or:
-
-1. Fork this repository
-2. Clone the fork onto your system
-3. `npm install` dependencies (must have Node installed)
-4. Run `gulp` to compile CSS and the test site
-5. Make changes and check the test site with your changes (see file structure outline below)
-6. Submit a PR referencing the issue with a smile :smile:
-
-If you’d like to contribute, the following filters are yet to be added:
-
-- [ ] [Charmes](https://github.com/una/CSSgram/issues/22)
-- [ ] [Stinsen](https://github.com/una/CSSgram/issues/21)
-- [ ] [Kelvin](https://github.com/una/CSSgram/issues/20)
-- [ ] [Sutro](https://github.com/una/CSSgram/issues/19)
-- [ ] [Hefe](https://github.com/una/CSSgram/issues/17)
-- [ ] [Valencia](https://github.com/una/CSSgram/issues/16)
-- [ ] [Rise](https://github.com/una/CSSgram/issues/15)
-- [ ] [Sierra](https://github.com/una/CSSgram/issues/14)
-- [ ] [Amaro](https://github.com/una/CSSgram/issues/13)
-- [ ] [Crema](https://github.com/una/CSSgram/issues/12)
-
-Filters are really fun to create! Reference photos created by [Miles Croxford](https://twitter.com/milescroxford) can be found [here](https://instagram.com/cssgram/).
-
-## File Structure Outline
-
-- `source/css/cssgram.css` contains each of the CSS classes you can apply to your ` ` to give it the filter. You should use `source/css/cssgram.min.css` for production if you want access to all of the library
-- `source/scss/` contains the source files for individual classes and placeholder selectors you can use to extend CSS classes in Sass
-- `site/` is the public facing website
-- `site/test` is how you test filters if you're developing, remember to change `is_done` for the filter you're creating in `site/test/index.twig` whilst gulp is running.
-
-Note: this will also have mixin options and a PostCSS Component.
diff --git a/node_modules/cssgram/bower.json b/node_modules/cssgram/bower.json
deleted file mode 100644
index da11277..0000000
--- a/node_modules/cssgram/bower.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "name": "cssgram",
- "description": "Instagram filter library in Sass and CSS.",
- "main": [
- "source/css/cssgram.min.css",
- "source/scss/cssgram.scss"
- ],
- "authors": [
- "Una Kravets"
- ],
- "license": "MIT",
- "keywords": [
- "cssgram",
- "filters",
- "CSS",
- "library",
- "photo",
- "effects"
- ],
- "homepage": "http://una.im/CSSgram/",
- "moduleType": [],
- "ignore": [
- "**/.*",
- "node_modules",
- "bower_components",
- "test",
- "tests",
- "site"
- ]
-}
diff --git a/node_modules/cssgram/gulpfile.js b/node_modules/cssgram/gulpfile.js
deleted file mode 100644
index 6ab6b95..0000000
--- a/node_modules/cssgram/gulpfile.js
+++ /dev/null
@@ -1,111 +0,0 @@
-var gulp = require('gulp'),
- sass = require('gulp-sass'),
- rename = require('gulp-rename'),
- cssmin = require('gulp-minify-css'),
- concat = require('gulp-concat'),
- uglify = require('gulp-uglify'),
- cache = require('gulp-cached'),
- prefix = require('gulp-autoprefixer'),
- browserSync = require('browser-sync'),
- reload = browserSync.reload,
- size = require('gulp-size'),
- imagemin = require('gulp-imagemin'),
- minifyHTML = require('gulp-minify-html'),
- pngquant = require('imagemin-pngquant'),
- plumber = require('gulp-plumber'),
- deploy = require('gulp-gh-pages'),
- notify = require('gulp-notify'),
- sassLint = require('gulp-sass-lint'),
- twig = require('gulp-twig');
-
-
-gulp.task('lib-scss', function() {
- var onError = function(err) {
- notify.onError({
- title: "Gulp",
- subtitle: "Failure!",
- message: "Error: <%= error.message %>",
- sound: "Beep"
- })(err);
- this.emit('end');
- };
-
- return gulp.src('source/scss/**/*.scss')
- .pipe(plumber({errorHandler: onError}))
- .pipe(sass())
- .pipe(size({ gzip: true, showFiles: true }))
- .pipe(prefix())
- .pipe(gulp.dest('source/css'))
- .pipe(reload({stream:true}))
- .pipe(cssmin())
- .pipe(size({ gzip: true, showFiles: true }))
- .pipe(rename({ suffix: '.min' }))
- .pipe(gulp.dest('source/css'))
- .pipe(gulp.dest('site/css'));
-});
-
-gulp.task('site-scss', function() {
- var onError = function(err) {
- notify.onError({
- title: "Gulp",
- subtitle: "Failure!",
- message: "Error: <%= error.message %>",
- sound: "Beep"
- })(err);
- this.emit('end');
- };
-
- return gulp.src('site/scss/**/*.scss')
- .pipe(plumber({errorHandler: onError}))
- .pipe(sass())
- .pipe(size({ gzip: true, showFiles: true }))
- .pipe(prefix())
- .pipe(gulp.dest('site/css'))
- .pipe(reload({stream:true}))
- .pipe(cssmin())
- .pipe(size({ gzip: true, showFiles: true }))
- .pipe(rename({ suffix: '.min' }))
- .pipe(gulp.dest('site/css'));
-});
-
-gulp.task('browser-sync', function() {
- browserSync({
- server: {
- baseDir: "site"
- }
- });
-});
-
-gulp.task('deploy', function () {
- return gulp.src('site/**/*')
- .pipe(deploy());
-});
-
-gulp.task('sass-lint', function () {
- gulp.src('scss/**/*.scss')
- .pipe(sassLint())
- .pipe(sassLint.format())
- .pipe(sassLint.failOnError());
-});
-
-gulp.task('twig', function () {
- gulp.src('site/**/*.twig', {base: './'})
- .pipe(twig())
- .pipe(gulp.dest('./'));
-});
-
-
-gulp.task('watch', function() {
- gulp.watch('source/scss/**/*.scss', ['lib-scss', 'site-scss', 'sass-lint']);
- gulp.watch('source/scss/**/*.html', ['minify-html']);
- gulp.watch('site/**/*.twig', ['twig']);
-});
-
-
-gulp.task('jshint', function() {
- gulp.src('js/*.js')
- .pipe(jshint())
- .pipe(jshint.reporter('default'));
-});
-
-gulp.task('default', ['browser-sync', 'twig', 'lib-scss', 'site-scss', 'watch']);
diff --git a/node_modules/cssgram/package.json b/node_modules/cssgram/package.json
deleted file mode 100644
index d42e05a..0000000
--- a/node_modules/cssgram/package.json
+++ /dev/null
@@ -1,77 +0,0 @@
-{
- "_args": [
- [
- "cssgram@0.1.3",
- "F:\\Documents\\websites\\BMM"
- ]
- ],
- "_from": "cssgram@0.1.3",
- "_id": "cssgram@0.1.3",
- "_inBundle": false,
- "_integrity": "sha1-zIBiLOrqyhjUoqqFz4U8RCA0ol4=",
- "_location": "/cssgram",
- "_phantomChildren": {},
- "_requested": {
- "type": "version",
- "registry": true,
- "raw": "cssgram@0.1.3",
- "name": "cssgram",
- "escapedName": "cssgram",
- "rawSpec": "0.1.3",
- "saveSpec": null,
- "fetchSpec": "0.1.3"
- },
- "_requiredBy": [
- "/"
- ],
- "_resolved": "https://registry.npmjs.org/cssgram/-/cssgram-0.1.3.tgz",
- "_spec": "0.1.3",
- "_where": "F:\\Documents\\websites\\BMM",
- "author": {
- "name": "Una Kravets",
- "email": "una.kravets@gmail.com",
- "url": "http://una.im"
- },
- "bugs": {
- "url": "https://github.com/una/CSSgram/issues"
- },
- "dependencies": {},
- "description": "",
- "devDependencies": {
- "browser-sync": "^2.0.0-rc4",
- "gulp": "^3.8.10",
- "gulp-autoprefixer": "^2.1.0",
- "gulp-cached": "^1.0.2",
- "gulp-concat": "^2.4.3",
- "gulp-gh-pages": "^0.4.0",
- "gulp-imagemin": "^2.1.0",
- "gulp-minify-css": "^0.3.12",
- "gulp-minify-html": "^0.1.8",
- "gulp-notify": "^2.2.0",
- "gulp-plumber": "^0.6.6",
- "gulp-rename": "^1.2.0",
- "gulp-sass": "^1.3.2",
- "gulp-sass-lint": "0.1.0-beta.2",
- "gulp-size": "^1.2.0",
- "gulp-twig": "~0.4.0",
- "gulp-uglify": "^1.0.2",
- "imagemin-pngquant": "^4.0.0"
- },
- "homepage": "https://github.com/una/CSSgram#readme",
- "keywords": [
- "cssgram",
- "filters",
- "CSS",
- "library",
- "photo",
- "effects"
- ],
- "license": "MIT",
- "name": "cssgram",
- "repository": {
- "type": "git",
- "url": "git+ssh://git@github.com/una/CSSgram.git"
- },
- "style": "source/css/cssgram.css",
- "version": "0.1.3"
-}
diff --git a/node_modules/cssgram/sass-lint.yml b/node_modules/cssgram/sass-lint.yml
deleted file mode 100644
index fb64bba..0000000
--- a/node_modules/cssgram/sass-lint.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-files:
- include: '**/*.s+(a|c)ss'
- ignore:
-rules:
- # Consistency Rules
- extends-before-mixins: 1
- extends-before-declarations: 1
- mixins-before-declarations: 1
- # Require an empty line between blocks
- empty-line-between-blocks: 1
- no-empty-rulesets: 1
- no-extends: 0
- final-newline: 1
- no-ids: 1
- indentation: 1
- no-important: 1
- leading-zero: 1
- nesting-depth: 1
- placeholder-in-extend: 1
- property-sort-order: 1
- one-declaration-per-line: 1
- single-line-per-selector: 1
- space-after-comma: 1
- # Space surrounding colons
- space-before-colon: 1
- space-after-colon: 1
-
- space-before-brace: 1
-
- space-before-bang: 1
- space-after-bang: 1
-
- space-between-parens: 1
- trailing-semicolon: 1
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/1977.min.css b/node_modules/cssgram/site/css/1977.min.css
deleted file mode 100644
index ee34123..0000000
--- a/node_modules/cssgram/site/css/1977.min.css
+++ /dev/null
@@ -1 +0,0 @@
-._1977:after,._1977:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}._1977{position:relative}._1977 img{width:100%;z-index:1}._1977:before{z-index:2}._1977:after{z-index:3}._1977{-webkit-filter:contrast(1.1) brightness(1.1) saturate(1.3);filter:contrast(1.1) brightness(1.1) saturate(1.3)}._1977:after{background:rgba(243,106,188,.3);mix-blend-mode:screen}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/aden.min.css b/node_modules/cssgram/site/css/aden.min.css
deleted file mode 100644
index 9cb969e..0000000
--- a/node_modules/cssgram/site/css/aden.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.aden:after,.aden:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.aden{position:relative}.aden img{width:100%;z-index:1}.aden:before{z-index:2}.aden:after{z-index:3}.aden{-webkit-filter:hue-rotate(-20deg) contrast(.9) saturate(.85) brightness(1.2);filter:hue-rotate(-20deg) contrast(.9) saturate(.85) brightness(1.2)}.aden:after{background:-webkit-linear-gradient(left,rgba(66,10,14,.2),transparent);background:linear-gradient(to right,rgba(66,10,14,.2),transparent);mix-blend-mode:darken}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/brooklyn.min.css b/node_modules/cssgram/site/css/brooklyn.min.css
deleted file mode 100644
index d7adc6b..0000000
--- a/node_modules/cssgram/site/css/brooklyn.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.brooklyn:after,.brooklyn:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.brooklyn{position:relative}.brooklyn img{width:100%;z-index:1}.brooklyn:before{z-index:2}.brooklyn:after{z-index:3}.brooklyn{-webkit-filter:contrast(.9) brightness(1.1);filter:contrast(.9) brightness(1.1)}.brooklyn:after{background:-webkit-radial-gradient(circle,rgba(168,223,193,.4) 70%,#c4b7c8);background:radial-gradient(circle,rgba(168,223,193,.4) 70%,#c4b7c8);mix-blend-mode:overlay}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/cssgram.min.css b/node_modules/cssgram/site/css/cssgram.min.css
deleted file mode 100644
index 90f673d..0000000
--- a/node_modules/cssgram/site/css/cssgram.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.aden{-webkit-filter:hue-rotate(-20deg) contrast(.9) saturate(.85) brightness(1.2);filter:hue-rotate(-20deg) contrast(.9) saturate(.85) brightness(1.2)}.aden:after{background:-webkit-linear-gradient(left,rgba(66,10,14,.2),transparent);background:linear-gradient(to right,rgba(66,10,14,.2),transparent);mix-blend-mode:darken}.inkwell{-webkit-filter:sepia(.3) contrast(1.1) brightness(1.1) grayscale(1);filter:sepia(.3) contrast(1.1) brightness(1.1) grayscale(1)}.perpetua:after{background:-webkit-linear-gradient(top,#005b9a,#e6c13d);background:linear-gradient(to bottom,#005b9a,#e6c13d);mix-blend-mode:soft-light;opacity:.5}.reyes{-webkit-filter:sepia(.22) brightness(1.1) contrast(.85) saturate(.75);filter:sepia(.22) brightness(1.1) contrast(.85) saturate(.75)}.reyes:after{background:#efcdad;mix-blend-mode:soft-light;opacity:.5}.gingham{-webkit-filter:brightness(1.05) hue-rotate(-10deg);filter:brightness(1.05) hue-rotate(-10deg)}.gingham:after{background:-webkit-linear-gradient(left,rgba(66,10,14,.2),transparent);background:linear-gradient(to right,rgba(66,10,14,.2),transparent);mix-blend-mode:darken}.toaster{-webkit-filter:contrast(1.5) brightness(.9);filter:contrast(1.5) brightness(.9)}.toaster:after{background:-webkit-radial-gradient(circle,#804e0f,#3b003b);background:radial-gradient(circle,#804e0f,#3b003b);mix-blend-mode:screen}.walden{-webkit-filter:brightness(1.1) hue-rotate(-10deg) sepia(.3) saturate(1.6);filter:brightness(1.1) hue-rotate(-10deg) sepia(.3) saturate(1.6)}.walden:after{background:#04c;mix-blend-mode:screen;opacity:.3}.hudson{-webkit-filter:brightness(1.2) contrast(.9) saturate(1.1);filter:brightness(1.2) contrast(.9) saturate(1.1)}.hudson:after{background:-webkit-radial-gradient(circle,#a6b1ff 50%,#342134);background:radial-gradient(circle,#a6b1ff 50%,#342134);mix-blend-mode:multiply;opacity:.5}.earlybird{-webkit-filter:contrast(.9) sepia(.2);filter:contrast(.9) sepia(.2)}.earlybird:after{background:-webkit-radial-gradient(circle,#d0ba8e 20%,#360309 85%,#1d0210 100%);background:radial-gradient(circle,#d0ba8e 20%,#360309 85%,#1d0210 100%);mix-blend-mode:overlay}.mayfair{-webkit-filter:contrast(1.1) saturate(1.1);filter:contrast(1.1) saturate(1.1)}.mayfair:after{background:-webkit-radial-gradient(40% 40%,circle,rgba(255,255,255,.8),rgba(255,200,200,.6),#111 60%);background:radial-gradient(circle at 40% 40%,rgba(255,255,255,.8),rgba(255,200,200,.6),#111 60%);mix-blend-mode:overlay;opacity:.4}.lofi{-webkit-filter:saturate(1.1) contrast(1.5);filter:saturate(1.1) contrast(1.5)}.lofi:after{background:-webkit-radial-gradient(circle,transparent 70%,#222 150%);background:radial-gradient(circle,transparent 70%,#222 150%);mix-blend-mode:multiply}._1977{-webkit-filter:contrast(1.1) brightness(1.1) saturate(1.3);filter:contrast(1.1) brightness(1.1) saturate(1.3)}._1977:after{background:rgba(243,106,188,.3);mix-blend-mode:screen}.brooklyn{-webkit-filter:contrast(.9) brightness(1.1);filter:contrast(.9) brightness(1.1)}.brooklyn:after{background:-webkit-radial-gradient(circle,rgba(168,223,193,.4) 70%,#c4b7c8);background:radial-gradient(circle,rgba(168,223,193,.4) 70%,#c4b7c8);mix-blend-mode:overlay}.xpro2{-webkit-filter:sepia(.3);filter:sepia(.3)}.xpro2:after{background:-webkit-radial-gradient(circle,#E6E7E0 40%,rgba(43,42,161,.6) 110%);background:radial-gradient(circle,#E6E7E0 40%,rgba(43,42,161,.6) 110%);mix-blend-mode:color-burn}._1977:after,._1977:before,.aden:after,.aden:before,.brooklyn:after,.brooklyn:before,.earlybird:after,.earlybird:before,.gingham:after,.gingham:before,.hudson:after,.hudson:before,.inkwell:after,.inkwell:before,.lofi:after,.lofi:before,.mayfair:after,.mayfair:before,.nashville:after,.nashville:before,.perpetua:after,.perpetua:before,.reyes:after,.reyes:before,.toaster:after,.toaster:before,.walden:after,.walden:before,.xpro2:after,.xpro2:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}._1977,.aden,.brooklyn,.earlybird,.gingham,.hudson,.inkwell,.lofi,.mayfair,.nashville,.perpetua,.reyes,.toaster,.walden,.xpro2{position:relative}._1977 img,.aden img,.brooklyn img,.earlybird img,.gingham img,.hudson img,.inkwell img,.lofi img,.mayfair img,.nashville img,.perpetua img,.reyes img,.toaster img,.walden img,.xpro2 img{width:100%;z-index:1}._1977:before,.aden:before,.brooklyn:before,.earlybird:before,.gingham:before,.hudson:before,.inkwell:before,.lofi:before,.mayfair:before,.nashville:before,.perpetua:before,.reyes:before,.toaster:before,.walden:before,.xpro2:before{z-index:2}._1977:after,.aden:after,.brooklyn:after,.earlybird:after,.gingham:after,.hudson:after,.inkwell:after,.lofi:after,.mayfair:after,.nashville:after,.perpetua:after,.reyes:after,.toaster:after,.walden:after,.xpro2:after{z-index:3}.nashville{-webkit-filter:sepia(.2) contrast(1.2) brightness(1.05) saturate(1.2);filter:sepia(.2) contrast(1.2) brightness(1.05) saturate(1.2)}.nashville::after{background:rgba(0,70,150,.4);mix-blend-mode:lighten}.nashville::before{background:rgba(247,176,153,.56);mix-blend-mode:darken}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/demo-site.css b/node_modules/cssgram/site/css/demo-site.css
deleted file mode 100644
index 5489a80..0000000
--- a/node_modules/cssgram/site/css/demo-site.css
+++ /dev/null
@@ -1,746 +0,0 @@
-@charset "UTF-8";
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-/*
- *
- * Aden
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.aden {
- -webkit-filter: hue-rotate(-20deg) contrast(.9) saturate(0.85) brightness(1.2);
- filter: hue-rotate(-20deg) contrast(.9) saturate(0.85) brightness(1.2); }
- .aden:after {
- background: -webkit-linear-gradient(left, rgba(66, 10, 14, 0.2), transparent);
- background: linear-gradient(to right, rgba(66, 10, 14, 0.2), transparent);
- mix-blend-mode: darken; }
-
-/*
- *
- * Inkwell
- *
- */
-.inkwell {
- -webkit-filter: sepia(.3) contrast(1.1) brightness(1.1) grayscale(1);
- filter: sepia(.3) contrast(1.1) brightness(1.1) grayscale(1); }
-
-/*
- *
- * Perpetua
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.perpetua:after {
- background: -webkit-linear-gradient(top, #005b9a, #e6c13d);
- background: linear-gradient(to bottom, #005b9a, #e6c13d);
- mix-blend-mode: soft-light;
- opacity: .5; }
-
-/*
- *
- * Reyes
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.reyes {
- -webkit-filter: sepia(.22) brightness(1.1) contrast(.85) saturate(0.75);
- filter: sepia(.22) brightness(1.1) contrast(.85) saturate(0.75); }
- .reyes:after {
- background: #efcdad;
- mix-blend-mode: soft-light;
- opacity: .5; }
-
-/*
- *
- * Gingham
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.gingham {
- -webkit-filter: brightness(1.05) hue-rotate(-10deg);
- filter: brightness(1.05) hue-rotate(-10deg); }
- .gingham:after {
- background: -webkit-linear-gradient(left, rgba(66, 10, 14, 0.2), transparent);
- background: linear-gradient(to right, rgba(66, 10, 14, 0.2), transparent);
- mix-blend-mode: darken; }
-
-/*
- *
- * Toaster
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.toaster {
- -webkit-filter: contrast(1.5) brightness(.9);
- filter: contrast(1.5) brightness(.9); }
- .toaster:after {
- background: -webkit-radial-gradient(circle, #804e0f, #3b003b);
- background: radial-gradient(circle, #804e0f, #3b003b);
- mix-blend-mode: screen; }
-
-/*
- *
- * Walden
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.walden {
- -webkit-filter: brightness(1.1) hue-rotate(-10deg) sepia(.3) saturate(1.6);
- filter: brightness(1.1) hue-rotate(-10deg) sepia(.3) saturate(1.6); }
- .walden:after {
- background: #04c;
- mix-blend-mode: screen;
- opacity: .3; }
-
-/*
- *
- * Hudson
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.hudson {
- -webkit-filter: brightness(1.2) contrast(.9) saturate(1.1);
- filter: brightness(1.2) contrast(.9) saturate(1.1); }
- .hudson:after {
- background: -webkit-radial-gradient(circle, #a6b1ff 50%, #342134);
- background: radial-gradient(circle, #a6b1ff 50%, #342134);
- mix-blend-mode: multiply;
- opacity: .5; }
-
-/*
- *
- * Earlybird
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.earlybird {
- -webkit-filter: contrast(.9) sepia(.2);
- filter: contrast(.9) sepia(.2); }
- .earlybird:after {
- background: -webkit-radial-gradient(circle, #d0ba8e 20%, #360309 85%, #1d0210 100%);
- background: radial-gradient(circle, #d0ba8e 20%, #360309 85%, #1d0210 100%);
- mix-blend-mode: overlay; }
-
-/*
- *
- * Mayfair
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.mayfair {
- -webkit-filter: contrast(1.1) saturate(1.1);
- filter: contrast(1.1) saturate(1.1); }
- .mayfair:after {
- background: -webkit-radial-gradient(40% 40%, circle, rgba(255, 255, 255, 0.8), rgba(255, 200, 200, 0.6), #111 60%);
- background: radial-gradient(circle at 40% 40%, rgba(255, 255, 255, 0.8), rgba(255, 200, 200, 0.6), #111 60%);
- mix-blend-mode: overlay;
- opacity: .4; }
-
-/*
- * Lo-fi
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.lofi {
- -webkit-filter: saturate(1.1) contrast(1.5);
- filter: saturate(1.1) contrast(1.5); }
- .lofi:after {
- background: -webkit-radial-gradient(circle, transparent 70%, #222 150%);
- background: radial-gradient(circle, transparent 70%, #222 150%);
- mix-blend-mode: multiply; }
-
-/*
- * 1977
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-._1977 {
- -webkit-filter: contrast(1.1) brightness(1.1) saturate(1.3);
- filter: contrast(1.1) brightness(1.1) saturate(1.3); }
- ._1977:after {
- background: rgba(243, 106, 188, 0.3);
- mix-blend-mode: screen; }
-
-/*
- *
- * Brooklyn
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.brooklyn {
- -webkit-filter: contrast(.9) brightness(1.1);
- filter: contrast(.9) brightness(1.1); }
- .brooklyn:after {
- background: -webkit-radial-gradient(circle, rgba(168, 223, 193, 0.4) 70%, #c4b7c8);
- background: radial-gradient(circle, rgba(168, 223, 193, 0.4) 70%, #c4b7c8);
- mix-blend-mode: overlay; }
-
-/*
- *
- * X-Pro II
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.xpro2 {
- -webkit-filter: sepia(.3);
- filter: sepia(.3); }
- .xpro2:after {
- background: -webkit-radial-gradient(circle, #E6E7E0 40%, rgba(43, 42, 161, 0.6) 110%);
- background: radial-gradient(circle, #E6E7E0 40%, rgba(43, 42, 161, 0.6) 110%);
- mix-blend-mode: color-burn; }
-
-/*
- *
- * Nashville
- *
- */
-.aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before, .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- content: '';
- display: block;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- position: absolute;
- pointer-events: none; }
-
-.aden, .inkwell, .perpetua, .reyes, .gingham, .toaster, .walden, .hudson, .earlybird, .mayfair, .lofi, ._1977, .brooklyn, .xpro2, .nashville {
- position: relative; }
- .aden img, .inkwell img, .perpetua img, .reyes img, .gingham img, .toaster img, .walden img, .hudson img, .earlybird img, .mayfair img, .lofi img, ._1977 img, .brooklyn img, .xpro2 img, .nashville img {
- width: 100%;
- z-index: 1; }
- .aden:before, .inkwell:before, .perpetua:before, .reyes:before, .gingham:before, .toaster:before, .walden:before, .hudson:before, .earlybird:before, .mayfair:before, .lofi:before, ._1977:before, .brooklyn:before, .xpro2:before, .nashville:before {
- z-index: 2; }
- .aden:after, .inkwell:after, .perpetua:after, .reyes:after, .gingham:after, .toaster:after, .walden:after, .hudson:after, .earlybird:after, .mayfair:after, .lofi:after, ._1977:after, .brooklyn:after, .xpro2:after, .nashville:after {
- z-index: 3; }
-
-.nashville {
- -webkit-filter: sepia(.2) contrast(1.2) brightness(1.05) saturate(1.2);
- filter: sepia(.2) contrast(1.2) brightness(1.05) saturate(1.2); }
- .nashville::after {
- background: rgba(0, 70, 150, 0.4);
- mix-blend-mode: lighten; }
- .nashville::before {
- background: rgba(247, 176, 153, 0.56);
- mix-blend-mode: darken; }
-
-::-moz-selection {
- background: #9b1c9b;
- color: white; }
-
-::selection {
- background: #9b1c9b;
- color: white; }
-
-body {
- font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
- margin: 0 auto;
- padding: 0 2em;
- max-width: 1200px;
- line-height: 1.5;
- font-size: 1.1em;
- overflow-x: hidden; }
- @media (max-width: 500px) {
- body {
- font-size: .9em; } }
-
-section {
- overflow-x: hidden; }
-
-h1, h2 {
- color: #9b1c9b; }
- @media (max-width: 500px) {
- h1, h2 {
- text-align: center; } }
-
-h3, em {
- color: #c63082; }
-
-pre, code {
- background: #eff1ef; }
- pre code, code code {
- border: none;
- background: none; }
-
-code {
- font-family: monospace;
- padding: 0;
- padding: .25em .5em; }
-
-.highlight {
- color: #c63082;
- font-weight: 800; }
-
-.comment {
- color: #abb1ad; }
-
-ul {
- width: 100%;
- margin: 0;
- padding: 0; }
-
-ul, ol {
- line-height: 1.8; }
-
-a {
- text-decoration: none;
- color: #9b1c9b;
- -webkit-transition-duration: .35s;
- transition-duration: .35s;
- border-bottom: 1px solid #c63082;
- padding-bottom: .05em; }
- a:hover, a:focus {
- color: #e297c0;
- border-color: #e297c0; }
-
-figure {
- max-width: 350px;
- max-height: 350px;
- overflow: hidden;
- position: relative;
- margin: 0;
- padding: 0;
- -webkit-transition-duration: .35s;
- transition-duration: .35s; }
- @media (max-width: 1240px) {
- figure {
- max-width: 300px;
- max-height: 300px; } }
- @media (max-width: 992px) {
- figure {
- max-width: 250px;
- max-height: 250px; } }
- @media (max-width: 768px) {
- figure {
- max-width: 300px;
- max-height: 300px; } }
- @media (max-width: 500px) {
- figure {
- max-width: 400px;
- max-height: 400px; } }
- figure:hover, figure:focus {
- -webkit-filter: none !important;
- filter: none !important; }
- figure:hover::after, figure:focus::after, figure:hover::before, figure:focus::before {
- opacity: 0 !important; }
-
-figcaption {
- position: absolute;
- bottom: 1em;
- right: 0;
- padding: .25em 1em .25em .25em;
- background: #000;
- color: white;
- font-weight: 200; }
-
-hr {
- clear: both;
- float: none;
- border: 1px solid #eff1ef;
- margin: 2em auto;
- display: block; }
-
-img {
- display: block;
- margin: auto;
- height: auto;
- max-height: 100%;
- width: auto;
- max-width: 100%; }
-
-.demo__section {
- font-weight: 300;
- font-size: 1.2em; }
-.demo__subtitle {
- font-size: 2em;
- text-align: center; }
-.demo__note {
- font-style: italic;
- text-align: center;
- display: block;
- margin: 2em auto 0; }
-.demo__input-area {
- display: block;
- font-size: 1em;
- text-align: center;
- font-weight: 300;
- margin: 1em auto;
- padding: 1em 0; }
- @media (max-width: 500px) {
- .demo__input-area {
- margin: 0;
- font-size: .8em; } }
-.demo__input-label {
- text-align: center;
- color: #9b1c9b; }
-.demo__input-img {
- max-width: 16em;
- font-size: 1em;
- padding: .5em;
- border: 2px solid #9b1c9b;
- outline: none;
- margin: .5em;
- font-weight: 200;
- -webkit-transition-duration: .35s;
- transition-duration: .35s; }
- .demo__input-img:hover {
- background: #f5e8f5; }
- .demo__input-img:focus {
- background: #e6c6e6; }
-.demo__option-field {
- color: #9b1c9b;
- border: 1px solid #cad1cc;
- min-width: 200px; }
-.demo__option-img {
- max-width: 150px;
- height: 150px;
- display: inline-block;
- cursor: pointer; }
- @media (max-width: 768px) {
- .demo__option-img {
- height: 100px; } }
- @media (max-width: 500px) {
- .demo__option-img {
- height: 60px; } }
-.demo__list {
- width: 100%;
- display: -webkit-box;
- display: -webkit-flex;
- display: -ms-flexbox;
- display: flex;
- -webkit-box-pack: center;
- -webkit-justify-content: center;
- -ms-flex-pack: center;
- justify-content: center;
- -webkit-flex-wrap: wrap;
- -ms-flex-wrap: wrap;
- flex-wrap: wrap; }
-.demo__item {
- margin: .75em;
- list-style: none; }
- @media (max-width: 992px) {
- .demo__item {
- margin: .5em; } }
- @media (max-width: 500px) {
- .demo__item {
- margin: .5em 0; } }
-
-.title-section {
- width: 100%;
- text-align: center; }
-.title--logo {
- max-width: 400px; }
-.title--top-sub {
- font-weight: 200;
- margin: 0 auto;
- text-align: center;
- max-width: 26em; }
- @media (max-width: 500px) {
- .title--top-sub {
- font-size: 1.2em; } }
-
-.how-to-section, .explanation-section {
- font-size: 1.2em;
- font-weight: 300;
- max-width: 40em;
- margin: 0 auto;
- display: block; }
-
-.attribution {
- padding: 1em 0 4em;
- text-align: center; }
-
-.callout {
- max-width: 14em;
- background: #eff1ef;
- padding: 2em;
- margin: -.5em 2em 0;
- display: block;
- font-weight: 200;
- float: right; }
- @media (max-width: 768px) {
- .callout {
- max-width: 28em;
- margin: 1em auto;
- float: none;
- font-size: .8em; } }
-
-.available-classes, .available-extends, .supported-browsers {
- -webkit-columns: 15em 2;
- -moz-columns: 15em 2;
- columns: 15em 2; }
-
-.supported:after {
- content: '✔';
- color: #62B859;
- margin-left: .5em; }
-
-.not-supported:after {
- content: '✘';
- color: #c63082;
- margin-left: .5em; }
diff --git a/node_modules/cssgram/site/css/demo-site.min.css b/node_modules/cssgram/site/css/demo-site.min.css
deleted file mode 100644
index 9a0a6f5..0000000
--- a/node_modules/cssgram/site/css/demo-site.min.css
+++ /dev/null
@@ -1 +0,0 @@
-@charset "UTF-8";.aden{-webkit-filter:hue-rotate(-20deg) contrast(.9) saturate(.85) brightness(1.2);filter:hue-rotate(-20deg) contrast(.9) saturate(.85) brightness(1.2)}.aden:after{background:-webkit-linear-gradient(left,rgba(66,10,14,.2),transparent);background:linear-gradient(to right,rgba(66,10,14,.2),transparent);mix-blend-mode:darken}.inkwell{-webkit-filter:sepia(.3) contrast(1.1) brightness(1.1) grayscale(1);filter:sepia(.3) contrast(1.1) brightness(1.1) grayscale(1)}.perpetua:after{background:-webkit-linear-gradient(top,#005b9a,#e6c13d);background:linear-gradient(to bottom,#005b9a,#e6c13d);mix-blend-mode:soft-light;opacity:.5}.reyes{-webkit-filter:sepia(.22) brightness(1.1) contrast(.85) saturate(.75);filter:sepia(.22) brightness(1.1) contrast(.85) saturate(.75)}.reyes:after{background:#efcdad;mix-blend-mode:soft-light;opacity:.5}.gingham{-webkit-filter:brightness(1.05) hue-rotate(-10deg);filter:brightness(1.05) hue-rotate(-10deg)}.gingham:after{background:-webkit-linear-gradient(left,rgba(66,10,14,.2),transparent);background:linear-gradient(to right,rgba(66,10,14,.2),transparent);mix-blend-mode:darken}.toaster{-webkit-filter:contrast(1.5) brightness(.9);filter:contrast(1.5) brightness(.9)}.toaster:after{background:-webkit-radial-gradient(circle,#804e0f,#3b003b);background:radial-gradient(circle,#804e0f,#3b003b);mix-blend-mode:screen}.walden{-webkit-filter:brightness(1.1) hue-rotate(-10deg) sepia(.3) saturate(1.6);filter:brightness(1.1) hue-rotate(-10deg) sepia(.3) saturate(1.6)}.walden:after{background:#04c;mix-blend-mode:screen;opacity:.3}.hudson{-webkit-filter:brightness(1.2) contrast(.9) saturate(1.1);filter:brightness(1.2) contrast(.9) saturate(1.1)}.hudson:after{background:-webkit-radial-gradient(circle,#a6b1ff 50%,#342134);background:radial-gradient(circle,#a6b1ff 50%,#342134);mix-blend-mode:multiply;opacity:.5}.earlybird{-webkit-filter:contrast(.9) sepia(.2);filter:contrast(.9) sepia(.2)}.earlybird:after{background:-webkit-radial-gradient(circle,#d0ba8e 20%,#360309 85%,#1d0210 100%);background:radial-gradient(circle,#d0ba8e 20%,#360309 85%,#1d0210 100%);mix-blend-mode:overlay}.mayfair{-webkit-filter:contrast(1.1) saturate(1.1);filter:contrast(1.1) saturate(1.1)}.mayfair:after{background:-webkit-radial-gradient(40% 40%,circle,rgba(255,255,255,.8),rgba(255,200,200,.6),#111 60%);background:radial-gradient(circle at 40% 40%,rgba(255,255,255,.8),rgba(255,200,200,.6),#111 60%);mix-blend-mode:overlay;opacity:.4}.lofi{-webkit-filter:saturate(1.1) contrast(1.5);filter:saturate(1.1) contrast(1.5)}.lofi:after{background:-webkit-radial-gradient(circle,transparent 70%,#222 150%);background:radial-gradient(circle,transparent 70%,#222 150%);mix-blend-mode:multiply}._1977{-webkit-filter:contrast(1.1) brightness(1.1) saturate(1.3);filter:contrast(1.1) brightness(1.1) saturate(1.3)}._1977:after{background:rgba(243,106,188,.3);mix-blend-mode:screen}.brooklyn{-webkit-filter:contrast(.9) brightness(1.1);filter:contrast(.9) brightness(1.1)}.brooklyn:after{background:-webkit-radial-gradient(circle,rgba(168,223,193,.4) 70%,#c4b7c8);background:radial-gradient(circle,rgba(168,223,193,.4) 70%,#c4b7c8);mix-blend-mode:overlay}.xpro2{-webkit-filter:sepia(.3);filter:sepia(.3)}.xpro2:after{background:-webkit-radial-gradient(circle,#E6E7E0 40%,rgba(43,42,161,.6) 110%);background:radial-gradient(circle,#E6E7E0 40%,rgba(43,42,161,.6) 110%);mix-blend-mode:color-burn}._1977:after,._1977:before,.aden:after,.aden:before,.brooklyn:after,.brooklyn:before,.earlybird:after,.earlybird:before,.gingham:after,.gingham:before,.hudson:after,.hudson:before,.inkwell:after,.inkwell:before,.lofi:after,.lofi:before,.mayfair:after,.mayfair:before,.nashville:after,.nashville:before,.perpetua:after,.perpetua:before,.reyes:after,.reyes:before,.toaster:after,.toaster:before,.walden:after,.walden:before,.xpro2:after,.xpro2:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}._1977,.aden,.brooklyn,.earlybird,.gingham,.hudson,.inkwell,.lofi,.mayfair,.nashville,.perpetua,.reyes,.toaster,.walden,.xpro2{position:relative}._1977 img,.aden img,.brooklyn img,.earlybird img,.gingham img,.hudson img,.inkwell img,.lofi img,.mayfair img,.nashville img,.perpetua img,.reyes img,.toaster img,.walden img,.xpro2 img{width:100%;z-index:1}._1977:before,.aden:before,.brooklyn:before,.earlybird:before,.gingham:before,.hudson:before,.inkwell:before,.lofi:before,.mayfair:before,.nashville:before,.perpetua:before,.reyes:before,.toaster:before,.walden:before,.xpro2:before{z-index:2}._1977:after,.aden:after,.brooklyn:after,.earlybird:after,.gingham:after,.hudson:after,.inkwell:after,.lofi:after,.mayfair:after,.nashville:after,.perpetua:after,.reyes:after,.toaster:after,.walden:after,.xpro2:after{z-index:3}.nashville{-webkit-filter:sepia(.2) contrast(1.2) brightness(1.05) saturate(1.2);filter:sepia(.2) contrast(1.2) brightness(1.05) saturate(1.2)}.nashville::after{background:rgba(0,70,150,.4);mix-blend-mode:lighten}.nashville::before{background:rgba(247,176,153,.56);mix-blend-mode:darken}::-moz-selection{background:#9b1c9b;color:#fff}::selection{background:#9b1c9b;color:#fff}body{font-family:'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif;margin:0 auto;padding:0 2em;max-width:1200px;line-height:1.5;font-size:1.1em;overflow-x:hidden}@media (max-width:500px){body{font-size:.9em}}section{overflow-x:hidden}h1,h2{color:#9b1c9b}@media (max-width:500px){h1,h2{text-align:center}}em,h3{color:#c63082}code,pre{background:#eff1ef}code code,pre code{border:none;background:0 0}code{font-family:monospace;padding:.25em .5em}.highlight{color:#c63082;font-weight:800}.comment{color:#abb1ad}ul{width:100%;margin:0;padding:0}ol,ul{line-height:1.8}a{text-decoration:none;color:#9b1c9b;-webkit-transition-duration:.35s;transition-duration:.35s;border-bottom:1px solid #c63082;padding-bottom:.05em}a:focus,a:hover{color:#e297c0;border-color:#e297c0}figure{max-width:350px;max-height:350px;overflow:hidden;position:relative;margin:0;padding:0;-webkit-transition-duration:.35s;transition-duration:.35s}@media (max-width:1240px){figure{max-width:300px;max-height:300px}}@media (max-width:992px){figure{max-width:250px;max-height:250px}}@media (max-width:768px){figure{max-width:300px;max-height:300px}}@media (max-width:500px){figure{max-width:400px;max-height:400px}}figure:focus,figure:hover{-webkit-filter:none!important;filter:none!important}figure:focus::after,figure:focus::before,figure:hover::after,figure:hover::before{opacity:0!important}figcaption{position:absolute;bottom:1em;right:0;padding:.25em 1em .25em .25em;background:#000;color:#fff;font-weight:200}hr{clear:both;float:none;border:1px solid #eff1ef;margin:2em auto;display:block}img{display:block;margin:auto;height:auto;max-height:100%;width:auto;max-width:100%}.demo__section{font-weight:300;font-size:1.2em}.demo__subtitle{font-size:2em;text-align:center}.demo__note{font-style:italic;text-align:center;display:block;margin:2em auto 0}.demo__input-area{display:block;font-size:1em;text-align:center;font-weight:300;margin:1em auto;padding:1em 0}@media (max-width:500px){.demo__input-area{margin:0;font-size:.8em}}.demo__input-label{text-align:center;color:#9b1c9b}.demo__input-img{max-width:16em;font-size:1em;padding:.5em;border:2px solid #9b1c9b;outline:0;margin:.5em;font-weight:200;-webkit-transition-duration:.35s;transition-duration:.35s}.demo__input-img:hover{background:#f5e8f5}.demo__input-img:focus{background:#e6c6e6}.demo__option-field{color:#9b1c9b;border:1px solid #cad1cc;min-width:200px}.demo__option-img{max-width:150px;height:150px;display:inline-block;cursor:pointer}@media (max-width:768px){.demo__option-img{height:100px}}@media (max-width:500px){.demo__option-img{height:60px}}.demo__list{width:100%;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-flex-wrap:wrap;-ms-flex-wrap:wrap;flex-wrap:wrap}.demo__item{margin:.75em;list-style:none}@media (max-width:992px){.demo__item{margin:.5em}}@media (max-width:500px){.demo__item{margin:.5em 0}}.title-section{width:100%;text-align:center}.title--logo{max-width:400px}.title--top-sub{font-weight:200;margin:0 auto;text-align:center;max-width:26em}@media (max-width:500px){.title--top-sub{font-size:1.2em}}.explanation-section,.how-to-section{font-size:1.2em;font-weight:300;max-width:40em;margin:0 auto;display:block}.attribution{padding:1em 0 4em;text-align:center}.callout{max-width:14em;background:#eff1ef;padding:2em;margin:-.5em 2em 0;display:block;font-weight:200;float:right}@media (max-width:768px){.callout{max-width:28em;margin:1em auto;float:none;font-size:.8em}}.available-classes,.available-extends,.supported-browsers{-webkit-columns:15em 2;-moz-columns:15em 2;columns:15em 2}.supported:after{content:'✔';color:#62B859;margin-left:.5em}.not-supported:after{content:'✘';color:#c63082;margin-left:.5em}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/earlybird.min.css b/node_modules/cssgram/site/css/earlybird.min.css
deleted file mode 100644
index 3abe93a..0000000
--- a/node_modules/cssgram/site/css/earlybird.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.earlybird:after,.earlybird:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.earlybird{position:relative}.earlybird img{width:100%;z-index:1}.earlybird:before{z-index:2}.earlybird:after{z-index:3}.earlybird{-webkit-filter:contrast(.9) sepia(.2);filter:contrast(.9) sepia(.2)}.earlybird:after{background:-webkit-radial-gradient(circle,#d0ba8e 20%,#360309 85%,#1d0210 100%);background:radial-gradient(circle,#d0ba8e 20%,#360309 85%,#1d0210 100%);mix-blend-mode:overlay}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/gingham.min.css b/node_modules/cssgram/site/css/gingham.min.css
deleted file mode 100644
index 4a1572a..0000000
--- a/node_modules/cssgram/site/css/gingham.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.gingham:after,.gingham:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.gingham{position:relative}.gingham img{width:100%;z-index:1}.gingham:before{z-index:2}.gingham:after{z-index:3}.gingham{-webkit-filter:brightness(1.05) hue-rotate(-10deg);filter:brightness(1.05) hue-rotate(-10deg)}.gingham:after{background:-webkit-linear-gradient(left,rgba(66,10,14,.2),transparent);background:linear-gradient(to right,rgba(66,10,14,.2),transparent);mix-blend-mode:darken}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/hudson.min.css b/node_modules/cssgram/site/css/hudson.min.css
deleted file mode 100644
index 99dbd08..0000000
--- a/node_modules/cssgram/site/css/hudson.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.hudson:after,.hudson:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.hudson{position:relative}.hudson img{width:100%;z-index:1}.hudson:before{z-index:2}.hudson:after{z-index:3}.hudson{-webkit-filter:brightness(1.2) contrast(.9) saturate(1.1);filter:brightness(1.2) contrast(.9) saturate(1.1)}.hudson:after{background:-webkit-radial-gradient(circle,#a6b1ff 50%,#342134);background:radial-gradient(circle,#a6b1ff 50%,#342134);mix-blend-mode:multiply;opacity:.5}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/inkwell.min.css b/node_modules/cssgram/site/css/inkwell.min.css
deleted file mode 100644
index 97b3451..0000000
--- a/node_modules/cssgram/site/css/inkwell.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.inkwell{-webkit-filter:sepia(.3) contrast(1.1) brightness(1.1) grayscale(1);filter:sepia(.3) contrast(1.1) brightness(1.1) grayscale(1)}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/lofi.min.css b/node_modules/cssgram/site/css/lofi.min.css
deleted file mode 100644
index c5a3534..0000000
--- a/node_modules/cssgram/site/css/lofi.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.lofi:after,.lofi:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.lofi{position:relative}.lofi img{width:100%;z-index:1}.lofi:before{z-index:2}.lofi:after{z-index:3}.lofi{-webkit-filter:saturate(1.1) contrast(1.5);filter:saturate(1.1) contrast(1.5)}.lofi:after{background:-webkit-radial-gradient(circle,transparent 70%,#222 150%);background:radial-gradient(circle,transparent 70%,#222 150%);mix-blend-mode:multiply}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/mayfair.min.css b/node_modules/cssgram/site/css/mayfair.min.css
deleted file mode 100644
index 9d19697..0000000
--- a/node_modules/cssgram/site/css/mayfair.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.mayfair:after,.mayfair:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.mayfair{position:relative}.mayfair img{width:100%;z-index:1}.mayfair:before{z-index:2}.mayfair:after{z-index:3}.mayfair{-webkit-filter:contrast(1.1) saturate(1.1);filter:contrast(1.1) saturate(1.1)}.mayfair:after{background:-webkit-radial-gradient(40% 40%,circle,rgba(255,255,255,.8),rgba(255,200,200,.6),#111 60%);background:radial-gradient(circle at 40% 40%,rgba(255,255,255,.8),rgba(255,200,200,.6),#111 60%);mix-blend-mode:overlay;opacity:.4}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/nashville.min.css b/node_modules/cssgram/site/css/nashville.min.css
deleted file mode 100644
index 8fae499..0000000
--- a/node_modules/cssgram/site/css/nashville.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.nashville:after,.nashville:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.nashville{position:relative}.nashville img{width:100%;z-index:1}.nashville:before{z-index:2}.nashville:after{z-index:3}.nashville{-webkit-filter:sepia(.2) contrast(1.2) brightness(1.05) saturate(1.2);filter:sepia(.2) contrast(1.2) brightness(1.05) saturate(1.2)}.nashville::after{background:rgba(0,70,150,.4);mix-blend-mode:lighten}.nashville::before{background:rgba(247,176,153,.56);mix-blend-mode:darken}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/perpetua.min.css b/node_modules/cssgram/site/css/perpetua.min.css
deleted file mode 100644
index 8c4341b..0000000
--- a/node_modules/cssgram/site/css/perpetua.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.perpetua:after,.perpetua:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.perpetua{position:relative}.perpetua img{width:100%;z-index:1}.perpetua:before{z-index:2}.perpetua:after{z-index:3;background:-webkit-linear-gradient(top,#005b9a,#e6c13d);background:linear-gradient(to bottom,#005b9a,#e6c13d);mix-blend-mode:soft-light;opacity:.5}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/reyes.min.css b/node_modules/cssgram/site/css/reyes.min.css
deleted file mode 100644
index 8a7ad26..0000000
--- a/node_modules/cssgram/site/css/reyes.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.reyes:after,.reyes:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.reyes{position:relative}.reyes img{width:100%;z-index:1}.reyes:before{z-index:2}.reyes:after{z-index:3}.reyes{-webkit-filter:sepia(.22) brightness(1.1) contrast(.85) saturate(.75);filter:sepia(.22) brightness(1.1) contrast(.85) saturate(.75)}.reyes:after{background:#efcdad;mix-blend-mode:soft-light;opacity:.5}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/toaster.min.css b/node_modules/cssgram/site/css/toaster.min.css
deleted file mode 100644
index 9c35195..0000000
--- a/node_modules/cssgram/site/css/toaster.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.toaster:after,.toaster:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.toaster{position:relative}.toaster img{width:100%;z-index:1}.toaster:before{z-index:2}.toaster:after{z-index:3}.toaster{-webkit-filter:contrast(1.5) brightness(.9);filter:contrast(1.5) brightness(.9)}.toaster:after{background:-webkit-radial-gradient(circle,#804e0f,#3b003b);background:radial-gradient(circle,#804e0f,#3b003b);mix-blend-mode:screen}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/walden.min.css b/node_modules/cssgram/site/css/walden.min.css
deleted file mode 100644
index 0c7e769..0000000
--- a/node_modules/cssgram/site/css/walden.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.walden:after,.walden:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.walden{position:relative}.walden img{width:100%;z-index:1}.walden:before{z-index:2}.walden:after{z-index:3}.walden{-webkit-filter:brightness(1.1) hue-rotate(-10deg) sepia(.3) saturate(1.6);filter:brightness(1.1) hue-rotate(-10deg) sepia(.3) saturate(1.6)}.walden:after{background:#04c;mix-blend-mode:screen;opacity:.3}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/css/xpro2.min.css b/node_modules/cssgram/site/css/xpro2.min.css
deleted file mode 100644
index ac56684..0000000
--- a/node_modules/cssgram/site/css/xpro2.min.css
+++ /dev/null
@@ -1 +0,0 @@
-.xpro2:after,.xpro2:before{content:'';display:block;height:100%;width:100%;top:0;left:0;position:absolute;pointer-events:none}.xpro2{position:relative}.xpro2 img{width:100%;z-index:1}.xpro2:before{z-index:2}.xpro2:after{z-index:3}.xpro2{-webkit-filter:sepia(.3);filter:sepia(.3)}.xpro2:after{background:-webkit-radial-gradient(circle,#E6E7E0 40%,rgba(43,42,161,.6) 110%);background:radial-gradient(circle,#E6E7E0 40%,rgba(43,42,161,.6) 110%);mix-blend-mode:color-burn}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/img/atx.jpg b/node_modules/cssgram/site/img/atx.jpg
deleted file mode 100644
index 0c71453..0000000
Binary files a/node_modules/cssgram/site/img/atx.jpg and /dev/null differ
diff --git a/node_modules/cssgram/site/img/bike.jpg b/node_modules/cssgram/site/img/bike.jpg
deleted file mode 100644
index 5c072b9..0000000
Binary files a/node_modules/cssgram/site/img/bike.jpg and /dev/null differ
diff --git a/node_modules/cssgram/site/img/cacti.jpg b/node_modules/cssgram/site/img/cacti.jpg
deleted file mode 100644
index ff909fe..0000000
Binary files a/node_modules/cssgram/site/img/cacti.jpg and /dev/null differ
diff --git a/node_modules/cssgram/site/img/cssgram-logo.png b/node_modules/cssgram/site/img/cssgram-logo.png
deleted file mode 100644
index a12cfdf..0000000
Binary files a/node_modules/cssgram/site/img/cssgram-logo.png and /dev/null differ
diff --git a/node_modules/cssgram/site/img/cssgram-logo.svg b/node_modules/cssgram/site/img/cssgram-logo.svg
deleted file mode 100644
index 9691b24..0000000
--- a/node_modules/cssgram/site/img/cssgram-logo.svg
+++ /dev/null
@@ -1,121 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- C SS
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/node_modules/cssgram/site/img/lakegeneva.jpg b/node_modules/cssgram/site/img/lakegeneva.jpg
deleted file mode 100644
index d288621..0000000
Binary files a/node_modules/cssgram/site/img/lakegeneva.jpg and /dev/null differ
diff --git a/node_modules/cssgram/site/img/logo-temp.png b/node_modules/cssgram/site/img/logo-temp.png
deleted file mode 100644
index 0064f8e..0000000
Binary files a/node_modules/cssgram/site/img/logo-temp.png and /dev/null differ
diff --git a/node_modules/cssgram/site/img/tahoe.jpg b/node_modules/cssgram/site/img/tahoe.jpg
deleted file mode 100644
index b75fd30..0000000
Binary files a/node_modules/cssgram/site/img/tahoe.jpg and /dev/null differ
diff --git a/node_modules/cssgram/site/index.html b/node_modules/cssgram/site/index.html
deleted file mode 100644
index 3bd2118..0000000
--- a/node_modules/cssgram/site/index.html
+++ /dev/null
@@ -1,300 +0,0 @@
-
-
-
-
- CSSGram
-
-
-
-
-
-
-
-
- A tiny (<1kb gzipped!) library for recreating Instagram filters with CSS filters and blend modes.
-
-
-
-
-
-
-
-
-
- #nofilter
-
-
-
-
-
- Aden
-
-
-
-
-
- Reyes
-
-
-
-
-
- Perpetua
-
-
-
-
-
- Inkwell
-
-
-
-
-
- Earlybird
-
-
-
-
-
- Toaster
-
-
-
-
-
- Walden
-
-
-
-
-
- Hudson
-
-
-
-
-
- Gingham
-
-
-
-
-
- Mayfair
-
-
-
-
-
- Lo-fi
-
-
-
-
-
- X-Pro II
-
-
-
-
-
- 1977
-
-
-
-
-
- Brooklyn
-
-
-
-
-
- Nashville
-
-
-
-
-
-
- What is This?
-
- For more background on CSS Image Effects, you can check out my blog series here , or watch my video from CSS Conf EU, which gives a baseline on blend modes and filters.
-
- Simply put, CSSgram is a library for editing your images with Instagram-like filters directly in CSS. What we're doing here is adding filters to the images as well as applying color and/or gradient overlays via various blending techniques to mimic these effects. This means less manual image processing and more fun filter effects on the web!
-
- We are using pseudo-elements (i.e. :before
and :after
) to create the filter effects, so you must apply these filters on a containing element (i.e. not a content-block like <img>
. The recommendation is to wrap your images in a <figure>
tag. More about the tag here.
-
- Browser Support
-
- This library uses CSS Filters and CSS Blend Modes . This features are supported in the following browsers:
-
-
- Google Chrome: 43+
- Mozilla Firefox: 38+
- Internet Explorer: Nope
- Opera: 32+
- Safari: 8+
-
-
- For more information, check on Can I Use .
-
-
-
-
- Usage
-
- There are currently 2 ways to consume this library:
-
- Use CSS classes
-
- When using CSS classes, you can simply add the class with the filter name to the element containing your image.
-
- The quickest way to do this is to link to our CDN in your <head>
tag: <link rel="stylesheet" href="https://cssgram-cssgram.netdna-ssl.com/cssgram.min.css">
. Then, add a class to your figure element with the name of the filter you would like to use (shown below)
-
- If you want to work locally, do the following:
-
-
- Download the CSSgram Library
- Link to the CSSgram library within your project: <link rel="stylesheet" href="css/vendor/cssgram.min.css">
- Add a class to your figure element with the name of the filter you would like to use
-
-
- For example:
-
-
-
- <figure class="aden" >
- <img src="../img.png">
- </figure>
-
-
- Alternatively, you can just download and link to any individual css file: <link rel="stylesheet" href="css/vendor/aden.min.css">
, if you're just using one of the styles.
-
- Available Classes
- For use in HTML markup:
-
- Aden: class="aden"
- Reyes: class="reyes"
- Perpetua: class="perpetua"
- Inkwell: class="inkwell"
- Toaster: class="toaster"
- Walden: class="walden"
- Hudson: class="hudson"
- Gingham: class="gingham"
- Mayfair: class="mayfair"
- Lo-fi: class="lofi"
- X-Pro II: class="xpro2"
- 1977: class="_1977"
- Brooklyn: class="brooklyn"
- Nashville: class="nashville"
-
-
-
-
- Use Sass @extends
-
- If you use custom naming in your CSS architecture, you can add the .scss files for the provided styles within your project and then @extend
the filter effects within your style definitions. If you think extends are stupid, I will fight you 😊.
-
-
- Download the /scss folder contents
- Include a link to scss/cssgram.scss
via an import statement in your Sass manifest file (i.e. main.scss
). It may look like: @import 'vendor/cssgram';
- Extend the silent placeholder selector @extend %aden;
in your element.
-
-
- For example:
-
-
-
- <figure class="viz--beautiful" >
- <img src="../img.png">
- </figure>
-
-
-
-
- .viz--beautiful {
- @extend %aden;
- }
-
-
- Alternatively, you can just download and link any individual .scss file in your Sass manifest: (i.e. scss/aden.scss
), if you're just using one of the styles.
-
- Available Extends
- For use in Sass elements:
-
- Aden: @extend %aden;
- Reyes: @extend %reyes;
- Perpetua: @extend %perpetua;
- Inkwell: @extend %inkwell;
- Toaster: @extend %toaster;
- Walden: @extend %walden;
- Hudson: @extend %hudson;
- Gingham: @extend %gingham;
- Mayfair: @extend %mayfair;
- Lo-fi: @extend %lofi;
- X-Pro II: @extend %xpro2;
- 1977: @extend %_1977;
- Brooklyn: @extend %brooklyn;
- Nashville: @extend %nashville;
-
-
-
-
-
-
-
-
-
diff --git a/node_modules/cssgram/site/index.twig b/node_modules/cssgram/site/index.twig
deleted file mode 100644
index 24a826f..0000000
--- a/node_modules/cssgram/site/index.twig
+++ /dev/null
@@ -1,299 +0,0 @@
-
-
-
-
- CSSGram
-
-
-
-
-
-
-
-
- A tiny (<1kb gzipped!) library for recreating Instagram filters with CSS filters and blend modes.
-
-
- {% set images = ['atx', 'bike', 'cacti', 'lakegeneva', 'tahoe'] %}
-
-
-
-
-
-
-
- #nofilter
-
-
-
-
-
- Aden
-
-
-
-
-
- Reyes
-
-
-
-
-
- Perpetua
-
-
-
-
-
- Inkwell
-
-
-
-
-
- Earlybird
-
-
-
-
-
- Toaster
-
-
-
-
-
- Walden
-
-
-
-
-
- Hudson
-
-
-
-
-
- Gingham
-
-
-
-
-
- Mayfair
-
-
-
-
-
- Lo-fi
-
-
-
-
-
- X-Pro II
-
-
-
-
-
- 1977
-
-
-
-
-
- Brooklyn
-
-
-
-
-
- Nashville
-
-
-
-
-
-
- What is This?
-
- For more background on CSS Image Effects, you can check out my blog series here , or watch my video from CSS Conf EU, which gives a baseline on blend modes and filters.
-
- Simply put, CSSgram is a library for editing your images with Instagram-like filters directly in CSS. What we're doing here is adding filters to the images as well as applying color and/or gradient overlays via various blending techniques to mimic these effects. This means less manual image processing and more fun filter effects on the web!
-
- We are using pseudo-elements (i.e. :before
and :after
) to create the filter effects, so you must apply these filters on a containing element (i.e. not a content-block like <img>
. The recommendation is to wrap your images in a <figure>
tag. More about the tag here.
-
- Browser Support
-
- This library uses CSS Filters and CSS Blend Modes . This features are supported in the following browsers:
-
-
- Google Chrome: 43+
- Mozilla Firefox: 38+
- Internet Explorer: Nope
- Opera: 32+
- Safari: 8+
-
-
- For more information, check on Can I Use .
-
-
-
-
- Usage
-
- There are currently 2 ways to consume this library:
-
- Use CSS classes
-
- When using CSS classes, you can simply add the class with the filter name to the element containing your image.
-
- The quickest way to do this is to link to our CDN in your <head>
tag: <link rel="stylesheet" href="https://cssgram-cssgram.netdna-ssl.com/cssgram.min.css">
. Then, add a class to your figure element with the name of the filter you would like to use (shown below)
-
- If you want to work locally, do the following:
-
-
- Download the CSSgram Library
- Link to the CSSgram library within your project: <link rel="stylesheet" href="css/vendor/cssgram.min.css">
- Add a class to your figure element with the name of the filter you would like to use
-
-
- For example:
-
-
-
- <figure class="aden" >
- <img src="../img.png">
- </figure>
-
-
- Alternatively, you can just download and link to any individual css file: <link rel="stylesheet" href="css/vendor/aden.min.css">
, if you're just using one of the styles.
-
- Available Classes
- For use in HTML markup:
-
- Aden: class="aden"
- Reyes: class="reyes"
- Perpetua: class="perpetua"
- Inkwell: class="inkwell"
- Toaster: class="toaster"
- Walden: class="walden"
- Hudson: class="hudson"
- Gingham: class="gingham"
- Mayfair: class="mayfair"
- Lo-fi: class="lofi"
- X-Pro II: class="xpro2"
- 1977: class="_1977"
- Brooklyn: class="brooklyn"
- Nashville: class="nashville"
-
-
-
-
- Use Sass @extends
-
- If you use custom naming in your CSS architecture, you can add the .scss files for the provided styles within your project and then @extend
the filter effects within your style definitions. If you think extends are stupid, I will fight you 😊.
-
-
- Download the /scss folder contents
- Include a link to scss/cssgram.scss
via an import statement in your Sass manifest file (i.e. main.scss
). It may look like: @import 'vendor/cssgram';
- Extend the silent placeholder selector @extend %aden;
in your element.
-
-
- For example:
-
-
-
- <figure class="viz--beautiful" >
- <img src="../img.png">
- </figure>
-
-
-
-
- .viz--beautiful {
- @extend %aden;
- }
-
-
- Alternatively, you can just download and link any individual .scss file in your Sass manifest: (i.e. scss/aden.scss
), if you're just using one of the styles.
-
- Available Extends
- For use in Sass elements:
-
- Aden: @extend %aden;
- Reyes: @extend %reyes;
- Perpetua: @extend %perpetua;
- Inkwell: @extend %inkwell;
- Toaster: @extend %toaster;
- Walden: @extend %walden;
- Hudson: @extend %hudson;
- Gingham: @extend %gingham;
- Mayfair: @extend %mayfair;
- Lo-fi: @extend %lofi;
- X-Pro II: @extend %xpro2;
- 1977: @extend %_1977;
- Brooklyn: @extend %brooklyn;
- Nashville: @extend %nashville;
-
-
-
-
-
-
-
-
-
diff --git a/node_modules/cssgram/site/scss/_home.scss b/node_modules/cssgram/site/scss/_home.scss
deleted file mode 100644
index 7df0077..0000000
--- a/node_modules/cssgram/site/scss/_home.scss
+++ /dev/null
@@ -1,329 +0,0 @@
-&::selection {
- background: $accent;
- color: white;
-}
-
-body {
- font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
- margin: 0 auto;
- padding: 0 2em;
- max-width: 1200px;
- line-height: 1.5;
- font-size: 1.1em;
- overflow-x: hidden;
-
- @include breakpoint(xs) {
- font-size: .9em;
- }
-}
-
-section {
- overflow-x: hidden;
-}
-
-h1,
-h2 {
- color: $accent;
-
- @include breakpoint(xs) {
- text-align: center;
- }
-}
-
-h3,
-em {
- color: $secondary;
-}
-
-pre, code {
- background: $lightergrey;
-
- code {
- border: none;
- background: none;
- }
-}
-
-code {
- font-family: monospace;
- padding: 0;
- padding: .25em .5em;
-}
-
-.highlight {
- color: $secondary;
- font-weight: 800;
-}
-
-.comment {
- color: $midgrey;
-}
-
-ul {
- width: 100%;
- margin: 0;
- padding: 0;
-}
-
-ul,
-ol {
- line-height: 1.8;
-}
-
-a {
- text-decoration: none;
- color: $accent;
- transition-duration: .35s;
- border-bottom: 1px solid $secondary;
- padding-bottom: .05em;
-
- &:hover,
- &:focus {
- color: mix(white, $secondary, 50%);
- border-color: mix(white, $secondary, 50%);
- }
-}
-
-figure {
- max-width: 350px;
- max-height: 350px;
- overflow: hidden;
- position: relative;
- margin: 0;
- padding: 0;
- transition-duration: .35s;
-
- @include breakpoint(lg) {
- max-width: 300px;
- max-height: 300px;
- }
-
- @include breakpoint(md) {
- max-width: 250px;
- max-height: 250px;
- }
-
- @include breakpoint(sm) {
- max-width: 300px;
- max-height: 300px;
- }
-
- @include breakpoint(xs) {
- max-width: 400px;
- max-height: 400px;
- }
-
- &:hover,
- &:focus {
- filter: none !important;
- }
-
- &:hover::after,
- &:focus::after,
- &:hover::before,
- &:focus::before {
- opacity: 0 !important;
- }
-}
-
-figcaption {
- position: absolute;
- bottom: 1em;
- right: 0;
- padding: .25em 1em .25em .25em;
- background: $black;
- color: white;
- font-weight: 200;
-}
-
-hr {
- clear: both;
- float: none;
- border: 1px solid $lightergrey;
- margin: 2em auto;
- display: block;
-}
-
-img {
- display: block;
- margin: auto;
-
- height: auto;
- max-height: 100%;
-
- width: auto;
- max-width: 100%;
-}
-
-.demo {
- &__section {
- font-weight: 300;
- font-size: 1.2em;
- }
-
- &__subtitle {
- font-size: 2em;
- text-align: center;
- }
-
- &__note {
- font-style: italic;
- text-align: center;
- display: block;
- margin: 2em auto 0;
- }
-
- &__input-area {
- display: block;
- font-size: 1em;
- text-align: center;
- font-weight: 300;
- margin: 1em auto;
- padding: 1em 0;
-
- @include breakpoint(xs) {
- margin: 0;
- font-size: .8em;
- }
- }
-
- &__input-label {
- text-align: center;
- color: $accent;
- }
-
- &__input-img {
- max-width: 16em;
- font-size: 1em;
- padding: .5em;
- border: 2px solid $accent;
- outline: none;
- margin: .5em;
- font-weight: 200;
- transition-duration: .35s;
-
- &:hover {
- background: mix(white, $accent, 90%);
- }
-
- &:focus {
- background: mix(white, $accent, 75%);
- }
- }
-
- &__option-field {
- color: $accent;
- border: 1px solid $lightgrey;
- min-width: 200px;
- }
-
- &__option-img {
- max-width: 150px;
- height: 150px;
- display: inline-block;
- cursor: pointer;
-
- @include breakpoint(sm) {
- height: 100px;
- }
-
- @include breakpoint(xs) {
- height: 60px;
- }
- }
-
- &__list {
- width: 100%;
- display: flex;
- justify-content: center;
- flex-wrap: wrap;
- }
-
- &__item {
- margin: .75em;
- list-style: none;
-
- @include breakpoint(md) {
- margin: .5em;
- }
-
- @include breakpoint(xs) {
- margin: .5em 0;
- }
- }
-}
-
-.title {
- &-section {
- width: 100%;
- text-align: center;
- }
-
- &--logo {
- max-width: 400px;
- }
-
- &--top-sub {
- font-weight: 200;
- margin: 0 auto;
- text-align: center;
- max-width: 26em;
-
- @include breakpoint(xs) {
- font-size: 1.2em;
- }
- }
-}
-
-.how-to-section,
-.explanation-section {
- font-size: 1.2em;
- font-weight: 300;
- max-width: 40em;
- margin: 0 auto;
- display: block;
-}
-
-.attribution {
- padding: 1em 0 4em;
- text-align: center;
-}
-
-.callout {
- max-width: 14em;
- background: $lightergrey;
- padding: 2em;
- margin: -.5em 2em 0;
- display: block;
- font-weight: 200;
- float: right;
-
- @include breakpoint(sm) {
- max-width: 28em;
- margin: 1em auto;
- float: none;
- font-size: .8em;
- }
-}
-
-.available-classes,
-.available-extends,
-.supported-browsers {
- columns: 15em 2;
-}
-
-.supported {
- &:after {
- content: '✔';
- color: $green;
- margin-left: .5em;
- }
-}
-
-.not-supported {
- &:after {
- content: '✘';
- color: $maroon;
- margin-left: .5em;
- }
-}
diff --git a/node_modules/cssgram/site/scss/_mixins.scss b/node_modules/cssgram/site/scss/_mixins.scss
deleted file mode 100644
index 5c29c64..0000000
--- a/node_modules/cssgram/site/scss/_mixins.scss
+++ /dev/null
@@ -1,23 +0,0 @@
-// Grid Mixin
-
-@mixin breakpoint($class) {
- @if $class == xs {
- @media (max-width: 500px) { @content; }
- }
-
- @else if $class == sm {
- @media (max-width: 768px) { @content; }
- }
-
- @else if $class == md {
- @media (max-width: 992px) { @content; }
- }
-
- @else if $class == lg {
- @media (max-width: 1240px) { @content; }
- }
-
- @else {
- @warn "Breakpoint mixin supports: xs, sm, md, lg";
- }
-}
\ No newline at end of file
diff --git a/node_modules/cssgram/site/scss/_vars.scss b/node_modules/cssgram/site/scss/_vars.scss
deleted file mode 100644
index 2adffbb..0000000
--- a/node_modules/cssgram/site/scss/_vars.scss
+++ /dev/null
@@ -1,11 +0,0 @@
-$dusky-blue: #649CA7;
-$maroon: #c63082;
-$purple: #9b1c9b;
-$lightgrey: #cad1cc;
-$black: #000;
-$green: #62B859;
-$midgrey: mix($black, $lightgrey, 15%);
-$lightergrey: mix(white, $lightgrey, 70%);
-
-$accent: $purple;
-$secondary: $maroon;
\ No newline at end of file
diff --git a/node_modules/cssgram/site/scss/demo-site.scss b/node_modules/cssgram/site/scss/demo-site.scss
deleted file mode 100644
index cbf5dcf..0000000
--- a/node_modules/cssgram/site/scss/demo-site.scss
+++ /dev/null
@@ -1,4 +0,0 @@
-@import 'source/scss/cssgram';
-@import 'vars';
-@import 'mixins';
-@import 'home';
\ No newline at end of file
diff --git a/node_modules/cssgram/site/test/css/test-site.css b/node_modules/cssgram/site/test/css/test-site.css
deleted file mode 100644
index 50aab46..0000000
--- a/node_modules/cssgram/site/test/css/test-site.css
+++ /dev/null
@@ -1,64 +0,0 @@
-.test-page {
- max-width: 650px;
- line-height: 1.5;
- font-size: 1.1em;
- text-align: center;
-}
-
-.test-page a {
- border-bottom: none;
-}
-
-.test-page .logo {
- display: block;
- float: left;
- height: 100px;
- width: auto;
-}
-
-.test-page .blurb {
- display: block;
- float: left;
-
-}
-
-.test-page section {
- display: block;
- margin-bottom: 10px;
- overflow: hidden;
- width: 100%;
-}
-
-.filter-header a {
- color: #9b1c9b;
- text-decoration: none;
-}
-
-.filter-header .done.done--yep{
- color: #62B859;
-}
-
-.filter-header .done.done--nope{
- color: #c63082;
-}
-
-.headers h3{
- float: left;
- width: 50%;
-}
-
-.test-images>div {
- float: left;
- width: 50%;
-}
-
-.test-images figure {
- margin: 10px;
- padding: 0;
-}
-
-.test-images img {
- display: block;
- height: auto;
- width: 100%;
-}
diff --git a/node_modules/cssgram/site/test/index.html b/node_modules/cssgram/site/test/index.html
deleted file mode 100644
index eead659..0000000
--- a/node_modules/cssgram/site/test/index.html
+++ /dev/null
@@ -1,2116 +0,0 @@
-
-
-
-
-
-
-
-
-
- CSSgram test sheet
-
-
-
-
-
-
-
-
- – Test sheet
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-