{"version":3,"file":"video-BVmBZcCY.mjs","sources":["../../../node_modules/.pnpm/@babel+runtime@7.28.4/node_modules/@babel/runtime/helpers/esm/extends.js","../../../node_modules/.pnpm/@babel+runtime@7.28.4/node_modules/@babel/runtime/helpers/extends.js","../../../node_modules/.pnpm/global@4.4.0/node_modules/global/window.js","../__vite-browser-external","../../../node_modules/.pnpm/global@4.4.0/node_modules/global/document.js","../../../node_modules/.pnpm/is-function@1.0.2/node_modules/is-function/index.js","../../../node_modules/.pnpm/@videojs+xhr@2.7.0/node_modules/@videojs/xhr/lib/interceptors.js","../../../node_modules/.pnpm/@videojs+xhr@2.7.0/node_modules/@videojs/xhr/lib/retry.js","../../../node_modules/.pnpm/@videojs+xhr@2.7.0/node_modules/@videojs/xhr/lib/http-handler.js","../../../node_modules/.pnpm/@videojs+xhr@2.7.0/node_modules/@videojs/xhr/lib/index.js","../../../node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/vtt.js","../../../node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/vttcue.js","../../../node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/vttregion.js","../../../node_modules/.pnpm/videojs-vtt.js@0.15.5/node_modules/videojs-vtt.js/lib/browser-index.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/resolve-url.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/codecs.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/media-types.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/byte-helpers.js","../../../node_modules/.pnpm/mux.js@7.1.0/node_modules/mux.js/lib/utils/numbers.js","../../../node_modules/.pnpm/mux.js@7.1.0/node_modules/mux.js/lib/tools/parse-sidx.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/id3-helpers.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/mp4-helpers.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/ebml-helpers.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/nal-helpers.js","../../../node_modules/.pnpm/@videojs+vhs-utils@4.1.1/node_modules/@videojs/vhs-utils/es/containers.js","../../../node_modules/.pnpm/mux.js@7.1.0/node_modules/mux.js/lib/utils/clock.js","../../../node_modules/.pnpm/video.js@8.23.4/node_modules/video.js/dist/video.es.js"],"sourcesContent":["function _extends() {\n  return _extends = Object.assign ? Object.assign.bind() : function (n) {\n    for (var e = 1; e < arguments.length; e++) {\n      var t = arguments[e];\n      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n    }\n    return n;\n  }, _extends.apply(null, arguments);\n}\nexport { _extends as default };","function _extends() {\n  return module.exports = _extends = Object.assign ? Object.assign.bind() : function (n) {\n    for (var e = 1; e < arguments.length; e++) {\n      var t = arguments[e];\n      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n    }\n    return n;\n  }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports, _extends.apply(null, arguments);\n}\nmodule.exports = _extends, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var win;\n\nif (typeof window !== \"undefined\") {\n    win = window;\n} else if (typeof global !== \"undefined\") {\n    win = global;\n} else if (typeof self !== \"undefined\"){\n    win = self;\n} else {\n    win = {};\n}\n\nmodule.exports = win;\n","export default {}","var topLevel = typeof global !== 'undefined' ? global :\n    typeof window !== 'undefined' ? window : {}\nvar minDoc = require('min-document');\n\nvar doccy;\n\nif (typeof document !== 'undefined') {\n    doccy = document;\n} else {\n    doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];\n\n    if (!doccy) {\n        doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;\n    }\n}\n\nmodule.exports = doccy;\n","module.exports = isFunction\n\nvar toString = Object.prototype.toString\n\nfunction isFunction (fn) {\n  if (!fn) {\n    return false\n  }\n  var string = toString.call(fn)\n  return string === '[object Function]' ||\n    (typeof fn === 'function' && string !== '[object RegExp]') ||\n    (typeof window !== 'undefined' &&\n     // IE8 and below\n     (fn === window.setTimeout ||\n      fn === window.alert ||\n      fn === window.confirm ||\n      fn === window.prompt))\n};\n","\"use strict\";\n\nfunction _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.\"); }\n\nfunction _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); }\n\nfunction _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; }\n\nvar InterceptorsStorage = /*#__PURE__*/function () {\n  function InterceptorsStorage() {\n    this.typeToInterceptorsMap_ = new Map();\n    this.enabled_ = false;\n  }\n\n  var _proto = InterceptorsStorage.prototype;\n\n  _proto.getIsEnabled = function getIsEnabled() {\n    return this.enabled_;\n  };\n\n  _proto.enable = function enable() {\n    this.enabled_ = true;\n  };\n\n  _proto.disable = function disable() {\n    this.enabled_ = false;\n  };\n\n  _proto.reset = function reset() {\n    this.typeToInterceptorsMap_ = new Map();\n    this.enabled_ = false;\n  };\n\n  _proto.addInterceptor = function addInterceptor(type, interceptor) {\n    if (!this.typeToInterceptorsMap_.has(type)) {\n      this.typeToInterceptorsMap_.set(type, new Set());\n    }\n\n    var interceptorsSet = this.typeToInterceptorsMap_.get(type);\n\n    if (interceptorsSet.has(interceptor)) {\n      // already have this interceptor\n      return false;\n    }\n\n    interceptorsSet.add(interceptor);\n    return true;\n  };\n\n  _proto.removeInterceptor = function removeInterceptor(type, interceptor) {\n    var interceptorsSet = this.typeToInterceptorsMap_.get(type);\n\n    if (interceptorsSet && interceptorsSet.has(interceptor)) {\n      interceptorsSet.delete(interceptor);\n      return true;\n    }\n\n    return false;\n  };\n\n  _proto.clearInterceptorsByType = function clearInterceptorsByType(type) {\n    var interceptorsSet = this.typeToInterceptorsMap_.get(type);\n\n    if (!interceptorsSet) {\n      return false;\n    }\n\n    this.typeToInterceptorsMap_.delete(type);\n    this.typeToInterceptorsMap_.set(type, new Set());\n    return true;\n  };\n\n  _proto.clear = function clear() {\n    if (!this.typeToInterceptorsMap_.size) {\n      return false;\n    }\n\n    this.typeToInterceptorsMap_ = new Map();\n    return true;\n  };\n\n  _proto.getForType = function getForType(type) {\n    return this.typeToInterceptorsMap_.get(type) || new Set();\n  };\n\n  _proto.execute = function execute(type, payload) {\n    var interceptors = this.getForType(type);\n\n    for (var _iterator = _createForOfIteratorHelperLoose(interceptors), _step; !(_step = _iterator()).done;) {\n      var interceptor = _step.value;\n\n      try {\n        payload = interceptor(payload);\n      } catch (e) {//ignore\n      }\n    }\n\n    return payload;\n  };\n\n  return InterceptorsStorage;\n}();\n\nmodule.exports = InterceptorsStorage;","\"use strict\";\n\nvar RetryManager = /*#__PURE__*/function () {\n  function RetryManager() {\n    this.maxAttempts_ = 1;\n    this.delayFactor_ = 0.1;\n    this.fuzzFactor_ = 0.1;\n    this.initialDelay_ = 1000;\n    this.enabled_ = false;\n  }\n\n  var _proto = RetryManager.prototype;\n\n  _proto.getIsEnabled = function getIsEnabled() {\n    return this.enabled_;\n  };\n\n  _proto.enable = function enable() {\n    this.enabled_ = true;\n  };\n\n  _proto.disable = function disable() {\n    this.enabled_ = false;\n  };\n\n  _proto.reset = function reset() {\n    this.maxAttempts_ = 1;\n    this.delayFactor_ = 0.1;\n    this.fuzzFactor_ = 0.1;\n    this.initialDelay_ = 1000;\n    this.enabled_ = false;\n  };\n\n  _proto.getMaxAttempts = function getMaxAttempts() {\n    return this.maxAttempts_;\n  };\n\n  _proto.setMaxAttempts = function setMaxAttempts(maxAttempts) {\n    this.maxAttempts_ = maxAttempts;\n  };\n\n  _proto.getDelayFactor = function getDelayFactor() {\n    return this.delayFactor_;\n  };\n\n  _proto.setDelayFactor = function setDelayFactor(delayFactor) {\n    this.delayFactor_ = delayFactor;\n  };\n\n  _proto.getFuzzFactor = function getFuzzFactor() {\n    return this.fuzzFactor_;\n  };\n\n  _proto.setFuzzFactor = function setFuzzFactor(fuzzFactor) {\n    this.fuzzFactor_ = fuzzFactor;\n  };\n\n  _proto.getInitialDelay = function getInitialDelay() {\n    return this.initialDelay_;\n  };\n\n  _proto.setInitialDelay = function setInitialDelay(initialDelay) {\n    this.initialDelay_ = initialDelay;\n  };\n\n  _proto.createRetry = function createRetry(_temp) {\n    var _ref = _temp === void 0 ? {} : _temp,\n        maxAttempts = _ref.maxAttempts,\n        delayFactor = _ref.delayFactor,\n        fuzzFactor = _ref.fuzzFactor,\n        initialDelay = _ref.initialDelay;\n\n    return new Retry({\n      maxAttempts: maxAttempts || this.maxAttempts_,\n      delayFactor: delayFactor || this.delayFactor_,\n      fuzzFactor: fuzzFactor || this.fuzzFactor_,\n      initialDelay: initialDelay || this.initialDelay_\n    });\n  };\n\n  return RetryManager;\n}();\n\nvar Retry = /*#__PURE__*/function () {\n  function Retry(options) {\n    this.maxAttempts_ = options.maxAttempts;\n    this.delayFactor_ = options.delayFactor;\n    this.fuzzFactor_ = options.fuzzFactor;\n    this.currentDelay_ = options.initialDelay;\n    this.currentAttempt_ = 1;\n  }\n\n  var _proto2 = Retry.prototype;\n\n  _proto2.moveToNextAttempt = function moveToNextAttempt() {\n    this.currentAttempt_++;\n    var delayDelta = this.currentDelay_ * this.delayFactor_;\n    this.currentDelay_ = this.currentDelay_ + delayDelta;\n  };\n\n  _proto2.shouldRetry = function shouldRetry() {\n    return this.currentAttempt_ < this.maxAttempts_;\n  };\n\n  _proto2.getCurrentDelay = function getCurrentDelay() {\n    return this.currentDelay_;\n  };\n\n  _proto2.getCurrentMinPossibleDelay = function getCurrentMinPossibleDelay() {\n    return (1 - this.fuzzFactor_) * this.currentDelay_;\n  };\n\n  _proto2.getCurrentMaxPossibleDelay = function getCurrentMaxPossibleDelay() {\n    return (1 + this.fuzzFactor_) * this.currentDelay_;\n  }\n  /**\n   * For example fuzzFactor is 0.1\n   * This means ±10% deviation\n   * So if we have delay as 1000\n   * This function can generate any value from 900 to 1100\n   */\n  ;\n\n  _proto2.getCurrentFuzzedDelay = function getCurrentFuzzedDelay() {\n    var lowValue = this.getCurrentMinPossibleDelay();\n    var highValue = this.getCurrentMaxPossibleDelay();\n    return lowValue + Math.random() * (highValue - lowValue);\n  };\n\n  return Retry;\n}();\n\nmodule.exports = RetryManager;","\"use strict\";\n\nvar window = require('global/window');\n\nvar httpResponseHandler = function httpResponseHandler(callback, decodeResponseBody) {\n  if (decodeResponseBody === void 0) {\n    decodeResponseBody = false;\n  }\n\n  return function (err, response, responseBody) {\n    // if the XHR failed, return that error\n    if (err) {\n      callback(err);\n      return;\n    } // if the HTTP status code is 4xx or 5xx, the request also failed\n\n\n    if (response.statusCode >= 400 && response.statusCode <= 599) {\n      var cause = responseBody;\n\n      if (decodeResponseBody) {\n        if (window.TextDecoder) {\n          var charset = getCharset(response.headers && response.headers['content-type']);\n\n          try {\n            cause = new TextDecoder(charset).decode(responseBody);\n          } catch (e) {}\n        } else {\n          cause = String.fromCharCode.apply(null, new Uint8Array(responseBody));\n        }\n      }\n\n      callback({\n        cause: cause\n      });\n      return;\n    } // otherwise, request succeeded\n\n\n    callback(null, responseBody);\n  };\n};\n\nfunction getCharset(contentTypeHeader) {\n  if (contentTypeHeader === void 0) {\n    contentTypeHeader = '';\n  }\n\n  return contentTypeHeader.toLowerCase().split(';').reduce(function (charset, contentType) {\n    var _contentType$split = contentType.split('='),\n        type = _contentType$split[0],\n        value = _contentType$split[1];\n\n    if (type.trim() === 'charset') {\n      return value.trim();\n    }\n\n    return charset;\n  }, 'utf-8');\n}\n\nmodule.exports = httpResponseHandler;","\"use strict\";\n\nvar window = require(\"global/window\");\n\nvar _extends = require(\"@babel/runtime/helpers/extends\");\n\nvar isFunction = require('is-function');\n\nvar InterceptorsStorage = require('./interceptors.js');\n\nvar RetryManager = require(\"./retry.js\");\n\ncreateXHR.httpHandler = require('./http-handler.js');\ncreateXHR.requestInterceptorsStorage = new InterceptorsStorage();\ncreateXHR.responseInterceptorsStorage = new InterceptorsStorage();\ncreateXHR.retryManager = new RetryManager();\n/**\n * @license\n * slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>\n * Copyright (c) 2014 David Björklund\n * Available under the MIT license\n * <https://github.com/kesla/parse-headers/blob/master/LICENCE>\n */\n\nvar parseHeaders = function parseHeaders(headers) {\n  var result = {};\n\n  if (!headers) {\n    return result;\n  }\n\n  headers.trim().split('\\n').forEach(function (row) {\n    var index = row.indexOf(':');\n    var key = row.slice(0, index).trim().toLowerCase();\n    var value = row.slice(index + 1).trim();\n\n    if (typeof result[key] === 'undefined') {\n      result[key] = value;\n    } else if (Array.isArray(result[key])) {\n      result[key].push(value);\n    } else {\n      result[key] = [result[key], value];\n    }\n  });\n  return result;\n};\n\nmodule.exports = createXHR; // Allow use of default import syntax in TypeScript\n\nmodule.exports.default = createXHR;\ncreateXHR.XMLHttpRequest = window.XMLHttpRequest || noop;\ncreateXHR.XDomainRequest = \"withCredentials\" in new createXHR.XMLHttpRequest() ? createXHR.XMLHttpRequest : window.XDomainRequest;\nforEachArray([\"get\", \"put\", \"post\", \"patch\", \"head\", \"delete\"], function (method) {\n  createXHR[method === \"delete\" ? \"del\" : method] = function (uri, options, callback) {\n    options = initParams(uri, options, callback);\n    options.method = method.toUpperCase();\n    return _createXHR(options);\n  };\n});\n\nfunction forEachArray(array, iterator) {\n  for (var i = 0; i < array.length; i++) {\n    iterator(array[i]);\n  }\n}\n\nfunction isEmpty(obj) {\n  for (var i in obj) {\n    if (obj.hasOwnProperty(i)) return false;\n  }\n\n  return true;\n}\n\nfunction initParams(uri, options, callback) {\n  var params = uri;\n\n  if (isFunction(options)) {\n    callback = options;\n\n    if (typeof uri === \"string\") {\n      params = {\n        uri: uri\n      };\n    }\n  } else {\n    params = _extends({}, options, {\n      uri: uri\n    });\n  }\n\n  params.callback = callback;\n  return params;\n}\n\nfunction createXHR(uri, options, callback) {\n  options = initParams(uri, options, callback);\n  return _createXHR(options);\n}\n\nfunction _createXHR(options) {\n  if (typeof options.callback === \"undefined\") {\n    throw new Error(\"callback argument missing\");\n  } // call all registered request interceptors for a given request type:\n\n\n  if (options.requestType && createXHR.requestInterceptorsStorage.getIsEnabled()) {\n    var requestInterceptorPayload = {\n      uri: options.uri || options.url,\n      headers: options.headers || {},\n      body: options.body,\n      metadata: options.metadata || {},\n      retry: options.retry,\n      timeout: options.timeout\n    };\n    var updatedPayload = createXHR.requestInterceptorsStorage.execute(options.requestType, requestInterceptorPayload);\n    options.uri = updatedPayload.uri;\n    options.headers = updatedPayload.headers;\n    options.body = updatedPayload.body;\n    options.metadata = updatedPayload.metadata;\n    options.retry = updatedPayload.retry;\n    options.timeout = updatedPayload.timeout;\n  }\n\n  var called = false;\n\n  var callback = function cbOnce(err, response, body) {\n    if (!called) {\n      called = true;\n      options.callback(err, response, body);\n    }\n  };\n\n  function readystatechange() {\n    // do not call load 2 times when response interceptors are enabled\n    // why do we even need this 2nd load?\n    if (xhr.readyState === 4 && !createXHR.responseInterceptorsStorage.getIsEnabled()) {\n      setTimeout(loadFunc, 0);\n    }\n  }\n\n  function getBody() {\n    // Chrome with requestType=blob throws errors arround when even testing access to responseText\n    var body = undefined;\n\n    if (xhr.response) {\n      body = xhr.response;\n    } else {\n      body = xhr.responseText || getXml(xhr);\n    }\n\n    if (isJson) {\n      try {\n        body = JSON.parse(body);\n      } catch (e) {}\n    }\n\n    return body;\n  }\n\n  function errorFunc(evt) {\n    clearTimeout(timeoutTimer);\n    clearTimeout(options.retryTimeout);\n\n    if (!(evt instanceof Error)) {\n      evt = new Error(\"\" + (evt || \"Unknown XMLHttpRequest Error\"));\n    }\n\n    evt.statusCode = 0; // we would like to retry on error:\n\n    if (!aborted && createXHR.retryManager.getIsEnabled() && options.retry && options.retry.shouldRetry()) {\n      options.retryTimeout = setTimeout(function () {\n        options.retry.moveToNextAttempt(); // we want to re-use the same options and the same xhr object:\n\n        options.xhr = xhr;\n\n        _createXHR(options);\n      }, options.retry.getCurrentFuzzedDelay());\n      return;\n    } // call all registered response interceptors for a given request type:\n\n\n    if (options.requestType && createXHR.responseInterceptorsStorage.getIsEnabled()) {\n      var responseInterceptorPayload = {\n        headers: failureResponse.headers || {},\n        body: failureResponse.body,\n        responseUrl: xhr.responseURL,\n        responseType: xhr.responseType\n      };\n\n      var _updatedPayload = createXHR.responseInterceptorsStorage.execute(options.requestType, responseInterceptorPayload);\n\n      failureResponse.body = _updatedPayload.body;\n      failureResponse.headers = _updatedPayload.headers;\n    }\n\n    return callback(evt, failureResponse);\n  } // will load the data & process the response in a special response object\n\n\n  function loadFunc() {\n    if (aborted) return;\n    var status;\n    clearTimeout(timeoutTimer);\n    clearTimeout(options.retryTimeout);\n\n    if (options.useXDR && xhr.status === undefined) {\n      //IE8 CORS GET successful response doesn't have a status field, but body is fine\n      status = 200;\n    } else {\n      status = xhr.status === 1223 ? 204 : xhr.status;\n    }\n\n    var response = failureResponse;\n    var err = null;\n\n    if (status !== 0) {\n      response = {\n        body: getBody(),\n        statusCode: status,\n        method: method,\n        headers: {},\n        url: uri,\n        rawRequest: xhr\n      };\n\n      if (xhr.getAllResponseHeaders) {\n        //remember xhr can in fact be XDR for CORS in IE\n        response.headers = parseHeaders(xhr.getAllResponseHeaders());\n      }\n    } else {\n      err = new Error(\"Internal XMLHttpRequest Error\");\n    } // call all registered response interceptors for a given request type:\n\n\n    if (options.requestType && createXHR.responseInterceptorsStorage.getIsEnabled()) {\n      var responseInterceptorPayload = {\n        headers: response.headers || {},\n        body: response.body,\n        responseUrl: xhr.responseURL,\n        responseType: xhr.responseType\n      };\n\n      var _updatedPayload2 = createXHR.responseInterceptorsStorage.execute(options.requestType, responseInterceptorPayload);\n\n      response.body = _updatedPayload2.body;\n      response.headers = _updatedPayload2.headers;\n    }\n\n    return callback(err, response, response.body);\n  }\n\n  var xhr = options.xhr || null;\n\n  if (!xhr) {\n    if (options.cors || options.useXDR) {\n      xhr = new createXHR.XDomainRequest();\n    } else {\n      xhr = new createXHR.XMLHttpRequest();\n    }\n  }\n\n  var key;\n  var aborted;\n  var uri = xhr.url = options.uri || options.url;\n  var method = xhr.method = options.method || \"GET\";\n  var body = options.body || options.data;\n  var headers = xhr.headers = options.headers || {};\n  var sync = !!options.sync;\n  var isJson = false;\n  var timeoutTimer;\n  var failureResponse = {\n    body: undefined,\n    headers: {},\n    statusCode: 0,\n    method: method,\n    url: uri,\n    rawRequest: xhr\n  };\n\n  if (\"json\" in options && options.json !== false) {\n    isJson = true;\n    headers[\"accept\"] || headers[\"Accept\"] || (headers[\"Accept\"] = \"application/json\"); //Don't override existing accept header declared by user\n\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      headers[\"content-type\"] || headers[\"Content-Type\"] || (headers[\"Content-Type\"] = \"application/json\"); //Don't override existing accept header declared by user\n\n      body = JSON.stringify(options.json === true ? body : options.json);\n    }\n  }\n\n  xhr.onreadystatechange = readystatechange;\n  xhr.onload = loadFunc;\n  xhr.onerror = errorFunc; // IE9 must have onprogress be set to a unique function.\n\n  xhr.onprogress = function () {// IE must die\n  };\n\n  xhr.onabort = function () {\n    aborted = true;\n    clearTimeout(options.retryTimeout);\n  };\n\n  xhr.ontimeout = errorFunc;\n  xhr.open(method, uri, !sync, options.username, options.password); //has to be after open\n\n  if (!sync) {\n    xhr.withCredentials = !!options.withCredentials;\n  } // Cannot set timeout with sync request\n  // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly\n  // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent\n\n\n  if (!sync && options.timeout > 0) {\n    timeoutTimer = setTimeout(function () {\n      if (aborted) return;\n      aborted = true; //IE9 may still call readystatechange\n\n      xhr.abort(\"timeout\");\n      var e = new Error(\"XMLHttpRequest timeout\");\n      e.code = \"ETIMEDOUT\";\n      errorFunc(e);\n    }, options.timeout);\n  }\n\n  if (xhr.setRequestHeader) {\n    for (key in headers) {\n      if (headers.hasOwnProperty(key)) {\n        xhr.setRequestHeader(key, headers[key]);\n      }\n    }\n  } else if (options.headers && !isEmpty(options.headers)) {\n    throw new Error(\"Headers cannot be set on an XDomainRequest object\");\n  }\n\n  if (\"responseType\" in options) {\n    xhr.responseType = options.responseType;\n  }\n\n  if (\"beforeSend\" in options && typeof options.beforeSend === \"function\") {\n    options.beforeSend(xhr);\n  } // Microsoft Edge browser sends \"undefined\" when send is called with undefined value.\n  // XMLHttpRequest spec says to pass null as body to indicate no body\n  // See https://github.com/naugtur/xhr/issues/100.\n\n\n  xhr.send(body || null);\n  return xhr;\n}\n\nfunction getXml(xhr) {\n  // xhr.responseXML will throw Exception \"InvalidStateError\" or \"DOMException\"\n  // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.\n  try {\n    if (xhr.responseType === \"document\") {\n      return xhr.responseXML;\n    }\n\n    var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === \"parsererror\";\n\n    if (xhr.responseType === \"\" && !firefoxBugTakenEffect) {\n      return xhr.responseXML;\n    }\n  } catch (e) {}\n\n  return null;\n}\n\nfunction noop() {}","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */\nvar document = require('global/document');\n\nvar _objCreate = Object.create || (function() {\n  function F() {}\n  return function(o) {\n    if (arguments.length !== 1) {\n      throw new Error('Object.create shim only accepts one parameter.');\n    }\n    F.prototype = o;\n    return new F();\n  };\n})();\n\n// Creates a new ParserError object from an errorData object. The errorData\n// object should have default code and message properties. The default message\n// property can be overriden by passing in a message parameter.\n// See ParsingError.Errors below for acceptable errors.\nfunction ParsingError(errorData, message) {\n  this.name = \"ParsingError\";\n  this.code = errorData.code;\n  this.message = message || errorData.message;\n}\nParsingError.prototype = _objCreate(Error.prototype);\nParsingError.prototype.constructor = ParsingError;\n\n// ParsingError metadata for acceptable ParsingErrors.\nParsingError.Errors = {\n  BadSignature: {\n    code: 0,\n    message: \"Malformed WebVTT signature.\"\n  },\n  BadTimeStamp: {\n    code: 1,\n    message: \"Malformed time stamp.\"\n  }\n};\n\n// Try to parse input as a time stamp.\nfunction parseTimeStamp(input) {\n\n  function computeSeconds(h, m, s, f) {\n    return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;\n  }\n\n  var m = input.match(/^(\\d+):(\\d{1,2})(:\\d{1,2})?\\.(\\d{3})/);\n  if (!m) {\n    return null;\n  }\n\n  if (m[3]) {\n    // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]\n    return computeSeconds(m[1], m[2], m[3].replace(\":\", \"\"), m[4]);\n  } else if (m[1] > 59) {\n    // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n    // First position is hours as it's over 59.\n    return computeSeconds(m[1], m[2], 0,  m[4]);\n  } else {\n    // Timestamp takes the form of [minutes]:[seconds].[milliseconds]\n    return computeSeconds(0, m[1], m[2], m[4]);\n  }\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nfunction Settings() {\n  this.values = _objCreate(null);\n}\n\nSettings.prototype = {\n  // Only accept the first assignment to any key.\n  set: function(k, v) {\n    if (!this.get(k) && v !== \"\") {\n      this.values[k] = v;\n    }\n  },\n  // Return the value for a key, or a default value.\n  // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n  // a number of possible default values as properties where 'defaultKey' is\n  // the key of the property that will be chosen; otherwise it's assumed to be\n  // a single value.\n  get: function(k, dflt, defaultKey) {\n    if (defaultKey) {\n      return this.has(k) ? this.values[k] : dflt[defaultKey];\n    }\n    return this.has(k) ? this.values[k] : dflt;\n  },\n  // Check whether we have a value for a key.\n  has: function(k) {\n    return k in this.values;\n  },\n  // Accept a setting if its one of the given alternatives.\n  alt: function(k, v, a) {\n    for (var n = 0; n < a.length; ++n) {\n      if (v === a[n]) {\n        this.set(k, v);\n        break;\n      }\n    }\n  },\n  // Accept a setting if its a valid (signed) integer.\n  integer: function(k, v) {\n    if (/^-?\\d+$/.test(v)) { // integer\n      this.set(k, parseInt(v, 10));\n    }\n  },\n  // Accept a setting if its a valid percentage.\n  percent: function(k, v) {\n    var m;\n    if ((m = v.match(/^([\\d]{1,3})(\\.[\\d]*)?%$/))) {\n      v = parseFloat(v);\n      if (v >= 0 && v <= 100) {\n        this.set(k, v);\n        return true;\n      }\n    }\n    return false;\n  }\n};\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interprete each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions(input, callback, keyValueDelim, groupDelim) {\n  var groups = groupDelim ? input.split(groupDelim) : [input];\n  for (var i in groups) {\n    if (typeof groups[i] !== \"string\") {\n      continue;\n    }\n    var kv = groups[i].split(keyValueDelim);\n    if (kv.length !== 2) {\n      continue;\n    }\n    var k = kv[0].trim();\n    var v = kv[1].trim();\n    callback(k, v);\n  }\n}\n\nfunction parseCue(input, cue, regionList) {\n  // Remember the original input if we need to throw an error.\n  var oInput = input;\n  // 4.1 WebVTT timestamp\n  function consumeTimeStamp() {\n    var ts = parseTimeStamp(input);\n    if (ts === null) {\n      throw new ParsingError(ParsingError.Errors.BadTimeStamp,\n                            \"Malformed timestamp: \" + oInput);\n    }\n    // Remove time stamp from input.\n    input = input.replace(/^[^\\sa-zA-Z-]+/, \"\");\n    return ts;\n  }\n\n  // 4.4.2 WebVTT cue settings\n  function consumeCueSettings(input, cue) {\n    var settings = new Settings();\n\n    parseOptions(input, function (k, v) {\n      switch (k) {\n      case \"region\":\n        // Find the last region we parsed with the same region id.\n        for (var i = regionList.length - 1; i >= 0; i--) {\n          if (regionList[i].id === v) {\n            settings.set(k, regionList[i].region);\n            break;\n          }\n        }\n        break;\n      case \"vertical\":\n        settings.alt(k, v, [\"rl\", \"lr\"]);\n        break;\n      case \"line\":\n        var vals = v.split(\",\"),\n            vals0 = vals[0];\n        settings.integer(k, vals0);\n        settings.percent(k, vals0) ? settings.set(\"snapToLines\", false) : null;\n        settings.alt(k, vals0, [\"auto\"]);\n        if (vals.length === 2) {\n          settings.alt(\"lineAlign\", vals[1], [\"start\", \"center\", \"end\"]);\n        }\n        break;\n      case \"position\":\n        vals = v.split(\",\");\n        settings.percent(k, vals[0]);\n        if (vals.length === 2) {\n          settings.alt(\"positionAlign\", vals[1], [\"start\", \"center\", \"end\"]);\n        }\n        break;\n      case \"size\":\n        settings.percent(k, v);\n        break;\n      case \"align\":\n        settings.alt(k, v, [\"start\", \"center\", \"end\", \"left\", \"right\"]);\n        break;\n      }\n    }, /:/, /\\s/);\n\n    // Apply default values for any missing fields.\n    cue.region = settings.get(\"region\", null);\n    cue.vertical = settings.get(\"vertical\", \"\");\n    try {\n      cue.line = settings.get(\"line\", \"auto\");\n    } catch (e) {}\n    cue.lineAlign = settings.get(\"lineAlign\", \"start\");\n    cue.snapToLines = settings.get(\"snapToLines\", true);\n    cue.size = settings.get(\"size\", 100);\n    // Safari still uses the old middle value and won't accept center\n    try {\n      cue.align = settings.get(\"align\", \"center\");\n    } catch (e) {\n      cue.align = settings.get(\"align\", \"middle\");\n    }\n    try {\n      cue.position = settings.get(\"position\", \"auto\");\n    } catch (e) {\n      cue.position = settings.get(\"position\", {\n        start: 0,\n        left: 0,\n        center: 50,\n        middle: 50,\n        end: 100,\n        right: 100\n      }, cue.align);\n    }\n\n\n    cue.positionAlign = settings.get(\"positionAlign\", {\n      start: \"start\",\n      left: \"start\",\n      center: \"center\",\n      middle: \"center\",\n      end: \"end\",\n      right: \"end\"\n    }, cue.align);\n  }\n\n  function skipWhitespace() {\n    input = input.replace(/^\\s+/, \"\");\n  }\n\n  // 4.1 WebVTT cue timings.\n  skipWhitespace();\n  cue.startTime = consumeTimeStamp();   // (1) collect cue start time\n  skipWhitespace();\n  if (input.substr(0, 3) !== \"-->\") {     // (3) next characters must match \"-->\"\n    throw new ParsingError(ParsingError.Errors.BadTimeStamp,\n                           \"Malformed time stamp (time stamps must be separated by '-->'): \" +\n                           oInput);\n  }\n  input = input.substr(3);\n  skipWhitespace();\n  cue.endTime = consumeTimeStamp();     // (5) collect cue end time\n\n  // 4.1 WebVTT cue settings list.\n  skipWhitespace();\n  consumeCueSettings(input, cue);\n}\n\n// When evaluating this file as part of a Webpack bundle for server\n// side rendering, `document` is an empty object.\nvar TEXTAREA_ELEMENT = document.createElement && document.createElement(\"textarea\");\n\nvar TAG_NAME = {\n  c: \"span\",\n  i: \"i\",\n  b: \"b\",\n  u: \"u\",\n  ruby: \"ruby\",\n  rt: \"rt\",\n  v: \"span\",\n  lang: \"span\"\n};\n\n// 5.1 default text color\n// 5.2 default text background color is equivalent to text color with bg_ prefix\nvar DEFAULT_COLOR_CLASS = {\n  white: 'rgba(255,255,255,1)',\n  lime: 'rgba(0,255,0,1)',\n  cyan: 'rgba(0,255,255,1)',\n  red: 'rgba(255,0,0,1)',\n  yellow: 'rgba(255,255,0,1)',\n  magenta: 'rgba(255,0,255,1)',\n  blue: 'rgba(0,0,255,1)',\n  black: 'rgba(0,0,0,1)'\n};\n\nvar TAG_ANNOTATION = {\n  v: \"title\",\n  lang: \"lang\"\n};\n\nvar NEEDS_PARENT = {\n  rt: \"ruby\"\n};\n\n// Parse content into a document fragment.\nfunction parseContent(window, input) {\n  function nextToken() {\n    // Check for end-of-string.\n    if (!input) {\n      return null;\n    }\n\n    // Consume 'n' characters from the input.\n    function consume(result) {\n      input = input.substr(result.length);\n      return result;\n    }\n\n    var m = input.match(/^([^<]*)(<[^>]*>?)?/);\n    // If there is some text before the next tag, return it, otherwise return\n    // the tag.\n    return consume(m[1] ? m[1] : m[2]);\n  }\n\n  function unescape(s) {\n    TEXTAREA_ELEMENT.innerHTML = s;\n    s = TEXTAREA_ELEMENT.textContent;\n    TEXTAREA_ELEMENT.textContent = \"\";\n    return s;\n  }\n\n  function shouldAdd(current, element) {\n    return !NEEDS_PARENT[element.localName] ||\n           NEEDS_PARENT[element.localName] === current.localName;\n  }\n\n  // Create an element for this tag.\n  function createElement(type, annotation) {\n    var tagName = TAG_NAME[type];\n    if (!tagName) {\n      return null;\n    }\n    var element = window.document.createElement(tagName);\n    var name = TAG_ANNOTATION[type];\n    if (name && annotation) {\n      element[name] = annotation.trim();\n    }\n    return element;\n  }\n\n  var rootDiv = window.document.createElement(\"div\"),\n      current = rootDiv,\n      t,\n      tagStack = [];\n\n  while ((t = nextToken()) !== null) {\n    if (t[0] === '<') {\n      if (t[1] === \"/\") {\n        // If the closing tag matches, move back up to the parent node.\n        if (tagStack.length &&\n            tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n          tagStack.pop();\n          current = current.parentNode;\n        }\n        // Otherwise just ignore the end tag.\n        continue;\n      }\n      var ts = parseTimeStamp(t.substr(1, t.length - 2));\n      var node;\n      if (ts) {\n        // Timestamps are lead nodes as well.\n        node = window.document.createProcessingInstruction(\"timestamp\", ts);\n        current.appendChild(node);\n        continue;\n      }\n      var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n      // If we can't parse the tag, skip to the next tag.\n      if (!m) {\n        continue;\n      }\n      // Try to construct an element, and ignore the tag if we couldn't.\n      node = createElement(m[1], m[3]);\n      if (!node) {\n        continue;\n      }\n      // Determine if the tag should be added based on the context of where it\n      // is placed in the cuetext.\n      if (!shouldAdd(current, node)) {\n        continue;\n      }\n      // Set the class list (as a list of classes, separated by space).\n      if (m[2]) {\n        var classes = m[2].split('.');\n\n        classes.forEach(function(cl) {\n          var bgColor = /^bg_/.test(cl);\n          // slice out `bg_` if it's a background color\n          var colorName = bgColor ? cl.slice(3) : cl;\n\n          if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {\n            var propName = bgColor ? 'background-color' : 'color';\n            var propValue = DEFAULT_COLOR_CLASS[colorName];\n\n            node.style[propName] = propValue;\n          }\n        });\n\n        node.className = classes.join(' ');\n      }\n      // Append the node to the current node, and enter the scope of the new\n      // node.\n      tagStack.push(m[1]);\n      current.appendChild(node);\n      current = node;\n      continue;\n    }\n\n    // Text nodes are leaf nodes.\n    current.appendChild(window.document.createTextNode(unescape(t)));\n  }\n\n  return rootDiv;\n}\n\n// This is a list of all the Unicode characters that have a strong\n// right-to-left category. What this means is that these characters are\n// written right-to-left for sure. It was generated by pulling all the strong\n// right-to-left characters out of the Unicode data table. That table can\n// found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt\nvar strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6],\n [0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d],\n [0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6],\n [0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5],\n [0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815],\n [0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858],\n [0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f],\n [0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c],\n [0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1],\n [0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc],\n [0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808],\n [0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855],\n [0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f],\n [0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13],\n [0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58],\n [0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72],\n [0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f],\n [0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32],\n [0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42],\n [0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f],\n [0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59],\n [0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62],\n [0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77],\n [0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b],\n [0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]];\n\nfunction isStrongRTLChar(charCode) {\n  for (var i = 0; i < strongRTLRanges.length; i++) {\n    var currentRange = strongRTLRanges[i];\n    if (charCode >= currentRange[0] && charCode <= currentRange[1]) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nfunction determineBidi(cueDiv) {\n  var nodeStack = [],\n      text = \"\",\n      charCode;\n\n  if (!cueDiv || !cueDiv.childNodes) {\n    return \"ltr\";\n  }\n\n  function pushNodes(nodeStack, node) {\n    for (var i = node.childNodes.length - 1; i >= 0; i--) {\n      nodeStack.push(node.childNodes[i]);\n    }\n  }\n\n  function nextTextNode(nodeStack) {\n    if (!nodeStack || !nodeStack.length) {\n      return null;\n    }\n\n    var node = nodeStack.pop(),\n        text = node.textContent || node.innerText;\n    if (text) {\n      // TODO: This should match all unicode type B characters (paragraph\n      // separator characters). See issue #115.\n      var m = text.match(/^.*(\\n|\\r)/);\n      if (m) {\n        nodeStack.length = 0;\n        return m[0];\n      }\n      return text;\n    }\n    if (node.tagName === \"ruby\") {\n      return nextTextNode(nodeStack);\n    }\n    if (node.childNodes) {\n      pushNodes(nodeStack, node);\n      return nextTextNode(nodeStack);\n    }\n  }\n\n  pushNodes(nodeStack, cueDiv);\n  while ((text = nextTextNode(nodeStack))) {\n    for (var i = 0; i < text.length; i++) {\n      charCode = text.charCodeAt(i);\n      if (isStrongRTLChar(charCode)) {\n        return \"rtl\";\n      }\n    }\n  }\n  return \"ltr\";\n}\n\nfunction computeLinePos(cue) {\n  if (typeof cue.line === \"number\" &&\n      (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) {\n    return cue.line;\n  }\n  if (!cue.track || !cue.track.textTrackList ||\n      !cue.track.textTrackList.mediaElement) {\n    return -1;\n  }\n  var track = cue.track,\n      trackList = track.textTrackList,\n      count = 0;\n  for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {\n    if (trackList[i].mode === \"showing\") {\n      count++;\n    }\n  }\n  return ++count * -1;\n}\n\nfunction StyleBox() {\n}\n\n// Apply styles to a div. If there is no div passed then it defaults to the\n// div on 'this'.\nStyleBox.prototype.applyStyles = function(styles, div) {\n  div = div || this.div;\n  for (var prop in styles) {\n    if (styles.hasOwnProperty(prop)) {\n      div.style[prop] = styles[prop];\n    }\n  }\n};\n\nStyleBox.prototype.formatStyle = function(val, unit) {\n  return val === 0 ? 0 : val + unit;\n};\n\n// Constructs the computed display state of the cue (a div). Places the div\n// into the overlay which should be a block level element (usually a div).\nfunction CueStyleBox(window, cue, styleOptions) {\n  StyleBox.call(this);\n  this.cue = cue;\n\n  // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will\n  // have inline positioning and will function as the cue background box.\n  this.cueDiv = parseContent(window, cue.text);\n  var styles = {\n    color: \"rgba(255, 255, 255, 1)\",\n    backgroundColor:  \"rgba(0, 0, 0, 0.8)\",\n    position: \"relative\",\n    left: 0,\n    right: 0,\n    top: 0,\n    bottom: 0,\n    display: \"inline\",\n    writingMode: cue.vertical === \"\" ? \"horizontal-tb\"\n                                     : cue.vertical === \"lr\" ? \"vertical-lr\"\n                                                             : \"vertical-rl\",\n    unicodeBidi: \"plaintext\"\n  };\n\n  this.applyStyles(styles, this.cueDiv);\n\n  // Create an absolutely positioned div that will be used to position the cue\n  // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS\n  // mirrors of them except middle instead of center on Safari.\n  this.div = window.document.createElement(\"div\");\n  styles = {\n    direction: determineBidi(this.cueDiv),\n    writingMode: cue.vertical === \"\" ? \"horizontal-tb\"\n                                     : cue.vertical === \"lr\" ? \"vertical-lr\"\n                                                             : \"vertical-rl\",\n    unicodeBidi: \"plaintext\",\n    textAlign: cue.align === \"middle\" ? \"center\" : cue.align,\n    font: styleOptions.font,\n    whiteSpace: \"pre-line\",\n    position: \"absolute\"\n  };\n\n  this.applyStyles(styles);\n  this.div.appendChild(this.cueDiv);\n\n  // Calculate the distance from the reference edge of the viewport to the text\n  // position of the cue box. The reference edge will be resolved later when\n  // the box orientation styles are applied.\n  var textPos = 0;\n  switch (cue.positionAlign) {\n  case \"start\":\n  case \"line-left\":\n    textPos = cue.position;\n    break;\n  case \"center\":\n    textPos = cue.position - (cue.size / 2);\n    break;\n  case \"end\":\n  case \"line-right\":\n    textPos = cue.position - cue.size;\n    break;\n  }\n\n  // Horizontal box orientation; textPos is the distance from the left edge of the\n  // area to the left edge of the box and cue.size is the distance extending to\n  // the right from there.\n  if (cue.vertical === \"\") {\n    this.applyStyles({\n      left:  this.formatStyle(textPos, \"%\"),\n      width: this.formatStyle(cue.size, \"%\")\n    });\n  // Vertical box orientation; textPos is the distance from the top edge of the\n  // area to the top edge of the box and cue.size is the height extending\n  // downwards from there.\n  } else {\n    this.applyStyles({\n      top: this.formatStyle(textPos, \"%\"),\n      height: this.formatStyle(cue.size, \"%\")\n    });\n  }\n\n  this.move = function(box) {\n    this.applyStyles({\n      top: this.formatStyle(box.top, \"px\"),\n      bottom: this.formatStyle(box.bottom, \"px\"),\n      left: this.formatStyle(box.left, \"px\"),\n      right: this.formatStyle(box.right, \"px\"),\n      height: this.formatStyle(box.height, \"px\"),\n      width: this.formatStyle(box.width, \"px\")\n    });\n  };\n}\nCueStyleBox.prototype = _objCreate(StyleBox.prototype);\nCueStyleBox.prototype.constructor = CueStyleBox;\n\n// Represents the co-ordinates of an Element in a way that we can easily\n// compute things with such as if it overlaps or intersects with another Element.\n// Can initialize it with either a StyleBox or another BoxPosition.\nfunction BoxPosition(obj) {\n  // Either a BoxPosition was passed in and we need to copy it, or a StyleBox\n  // was passed in and we need to copy the results of 'getBoundingClientRect'\n  // as the object returned is readonly. All co-ordinate values are in reference\n  // to the viewport origin (top left).\n  var lh, height, width, top;\n  if (obj.div) {\n    height = obj.div.offsetHeight;\n    width = obj.div.offsetWidth;\n    top = obj.div.offsetTop;\n\n    var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&\n                rects.getClientRects && rects.getClientRects();\n    obj = obj.div.getBoundingClientRect();\n    // In certain cases the outter div will be slightly larger then the sum of\n    // the inner div's lines. This could be due to bold text, etc, on some platforms.\n    // In this case we should get the average line height and use that. This will\n    // result in the desired behaviour.\n    lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)\n               : 0;\n\n  }\n  this.left = obj.left;\n  this.right = obj.right;\n  this.top = obj.top || top;\n  this.height = obj.height || height;\n  this.bottom = obj.bottom || (top + (obj.height || height));\n  this.width = obj.width || width;\n  this.lineHeight = lh !== undefined ? lh : obj.lineHeight;\n}\n\n// Move the box along a particular axis. Optionally pass in an amount to move\n// the box. If no amount is passed then the default is the line height of the\n// box.\nBoxPosition.prototype.move = function(axis, toMove) {\n  toMove = toMove !== undefined ? toMove : this.lineHeight;\n  switch (axis) {\n  case \"+x\":\n    this.left += toMove;\n    this.right += toMove;\n    break;\n  case \"-x\":\n    this.left -= toMove;\n    this.right -= toMove;\n    break;\n  case \"+y\":\n    this.top += toMove;\n    this.bottom += toMove;\n    break;\n  case \"-y\":\n    this.top -= toMove;\n    this.bottom -= toMove;\n    break;\n  }\n};\n\n// Check if this box overlaps another box, b2.\nBoxPosition.prototype.overlaps = function(b2) {\n  return this.left < b2.right &&\n         this.right > b2.left &&\n         this.top < b2.bottom &&\n         this.bottom > b2.top;\n};\n\n// Check if this box overlaps any other boxes in boxes.\nBoxPosition.prototype.overlapsAny = function(boxes) {\n  for (var i = 0; i < boxes.length; i++) {\n    if (this.overlaps(boxes[i])) {\n      return true;\n    }\n  }\n  return false;\n};\n\n// Check if this box is within another box.\nBoxPosition.prototype.within = function(container) {\n  return this.top >= container.top &&\n         this.bottom <= container.bottom &&\n         this.left >= container.left &&\n         this.right <= container.right;\n};\n\n// Check if this box is entirely within the container or it is overlapping\n// on the edge opposite of the axis direction passed. For example, if \"+x\" is\n// passed and the box is overlapping on the left edge of the container, then\n// return true.\nBoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {\n  switch (axis) {\n  case \"+x\":\n    return this.left < container.left;\n  case \"-x\":\n    return this.right > container.right;\n  case \"+y\":\n    return this.top < container.top;\n  case \"-y\":\n    return this.bottom > container.bottom;\n  }\n};\n\n// Find the percentage of the area that this box is overlapping with another\n// box.\nBoxPosition.prototype.intersectPercentage = function(b2) {\n  var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),\n      y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),\n      intersectArea = x * y;\n  return intersectArea / (this.height * this.width);\n};\n\n// Convert the positions from this box to CSS compatible positions using\n// the reference container's positions. This has to be done because this\n// box's positions are in reference to the viewport origin, whereas, CSS\n// values are in referecne to their respective edges.\nBoxPosition.prototype.toCSSCompatValues = function(reference) {\n  return {\n    top: this.top - reference.top,\n    bottom: reference.bottom - this.bottom,\n    left: this.left - reference.left,\n    right: reference.right - this.right,\n    height: this.height,\n    width: this.width\n  };\n};\n\n// Get an object that represents the box's position without anything extra.\n// Can pass a StyleBox, HTMLElement, or another BoxPositon.\nBoxPosition.getSimpleBoxPosition = function(obj) {\n  var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;\n  var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;\n  var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;\n\n  obj = obj.div ? obj.div.getBoundingClientRect() :\n                obj.tagName ? obj.getBoundingClientRect() : obj;\n  var ret = {\n    left: obj.left,\n    right: obj.right,\n    top: obj.top || top,\n    height: obj.height || height,\n    bottom: obj.bottom || (top + (obj.height || height)),\n    width: obj.width || width\n  };\n  return ret;\n};\n\n// Move a StyleBox to its specified, or next best, position. The containerBox\n// is the box that contains the StyleBox, such as a div. boxPositions are\n// a list of other boxes that the styleBox can't overlap with.\nfunction moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {\n\n  // Find the best position for a cue box, b, on the video. The axis parameter\n  // is a list of axis, the order of which, it will move the box along. For example:\n  // Passing [\"+x\", \"-x\"] will move the box first along the x axis in the positive\n  // direction. If it doesn't find a good position for it there it will then move\n  // it along the x axis in the negative direction.\n  function findBestPosition(b, axis) {\n    var bestPosition,\n        specifiedPosition = new BoxPosition(b),\n        percentage = 1; // Highest possible so the first thing we get is better.\n\n    for (var i = 0; i < axis.length; i++) {\n      while (b.overlapsOppositeAxis(containerBox, axis[i]) ||\n             (b.within(containerBox) && b.overlapsAny(boxPositions))) {\n        b.move(axis[i]);\n      }\n      // We found a spot where we aren't overlapping anything. This is our\n      // best position.\n      if (b.within(containerBox)) {\n        return b;\n      }\n      var p = b.intersectPercentage(containerBox);\n      // If we're outside the container box less then we were on our last try\n      // then remember this position as the best position.\n      if (percentage > p) {\n        bestPosition = new BoxPosition(b);\n        percentage = p;\n      }\n      // Reset the box position to the specified position.\n      b = new BoxPosition(specifiedPosition);\n    }\n    return bestPosition || specifiedPosition;\n  }\n\n  var boxPosition = new BoxPosition(styleBox),\n      cue = styleBox.cue,\n      linePos = computeLinePos(cue),\n      axis = [];\n\n  // If we have a line number to align the cue to.\n  if (cue.snapToLines) {\n    var size;\n    switch (cue.vertical) {\n    case \"\":\n      axis = [ \"+y\", \"-y\" ];\n      size = \"height\";\n      break;\n    case \"rl\":\n      axis = [ \"+x\", \"-x\" ];\n      size = \"width\";\n      break;\n    case \"lr\":\n      axis = [ \"-x\", \"+x\" ];\n      size = \"width\";\n      break;\n    }\n\n    var step = boxPosition.lineHeight,\n        position = step * Math.round(linePos),\n        maxPosition = containerBox[size] + step,\n        initialAxis = axis[0];\n\n    // If the specified intial position is greater then the max position then\n    // clamp the box to the amount of steps it would take for the box to\n    // reach the max position.\n    if (Math.abs(position) > maxPosition) {\n      position = position < 0 ? -1 : 1;\n      position *= Math.ceil(maxPosition / step) * step;\n    }\n\n    // If computed line position returns negative then line numbers are\n    // relative to the bottom of the video instead of the top. Therefore, we\n    // need to increase our initial position by the length or width of the\n    // video, depending on the writing direction, and reverse our axis directions.\n    if (linePos < 0) {\n      position += cue.vertical === \"\" ? containerBox.height : containerBox.width;\n      axis = axis.reverse();\n    }\n\n    // Move the box to the specified position. This may not be its best\n    // position.\n    boxPosition.move(initialAxis, position);\n\n  } else {\n    // If we have a percentage line value for the cue.\n    var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;\n\n    switch (cue.lineAlign) {\n    case \"center\":\n      linePos -= (calculatedPercentage / 2);\n      break;\n    case \"end\":\n      linePos -= calculatedPercentage;\n      break;\n    }\n\n    // Apply initial line position to the cue box.\n    switch (cue.vertical) {\n    case \"\":\n      styleBox.applyStyles({\n        top: styleBox.formatStyle(linePos, \"%\")\n      });\n      break;\n    case \"rl\":\n      styleBox.applyStyles({\n        left: styleBox.formatStyle(linePos, \"%\")\n      });\n      break;\n    case \"lr\":\n      styleBox.applyStyles({\n        right: styleBox.formatStyle(linePos, \"%\")\n      });\n      break;\n    }\n\n    axis = [ \"+y\", \"-x\", \"+x\", \"-y\" ];\n\n    // Get the box position again after we've applied the specified positioning\n    // to it.\n    boxPosition = new BoxPosition(styleBox);\n  }\n\n  var bestPosition = findBestPosition(boxPosition, axis);\n  styleBox.move(bestPosition.toCSSCompatValues(containerBox));\n}\n\nfunction WebVTT() {\n  // Nothing\n}\n\n// Helper to allow strings to be decoded instead of the default binary utf8 data.\nWebVTT.StringDecoder = function() {\n  return {\n    decode: function(data) {\n      if (!data) {\n        return \"\";\n      }\n      if (typeof data !== \"string\") {\n        throw new Error(\"Error - expected string data.\");\n      }\n      return decodeURIComponent(encodeURIComponent(data));\n    }\n  };\n};\n\nWebVTT.convertCueToDOMTree = function(window, cuetext) {\n  if (!window || !cuetext) {\n    return null;\n  }\n  return parseContent(window, cuetext);\n};\n\nvar FONT_SIZE_PERCENT = 0.05;\nvar FONT_STYLE = \"sans-serif\";\nvar CUE_BACKGROUND_PADDING = \"1.5%\";\n\n// Runs the processing model over the cues and regions passed to it.\n// @param overlay A block level element (usually a div) that the computed cues\n//                and regions will be placed into.\nWebVTT.processCues = function(window, cues, overlay) {\n  if (!window || !cues || !overlay) {\n    return null;\n  }\n\n  // Remove all previous children.\n  while (overlay.firstChild) {\n    overlay.removeChild(overlay.firstChild);\n  }\n\n  var paddedOverlay = window.document.createElement(\"div\");\n  paddedOverlay.style.position = \"absolute\";\n  paddedOverlay.style.left = \"0\";\n  paddedOverlay.style.right = \"0\";\n  paddedOverlay.style.top = \"0\";\n  paddedOverlay.style.bottom = \"0\";\n  paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;\n  overlay.appendChild(paddedOverlay);\n\n  // Determine if we need to compute the display states of the cues. This could\n  // be the case if a cue's state has been changed since the last computation or\n  // if it has not been computed yet.\n  function shouldCompute(cues) {\n    for (var i = 0; i < cues.length; i++) {\n      if (cues[i].hasBeenReset || !cues[i].displayState) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  // We don't need to recompute the cues' display states. Just reuse them.\n  if (!shouldCompute(cues)) {\n    for (var i = 0; i < cues.length; i++) {\n      paddedOverlay.appendChild(cues[i].displayState);\n    }\n    return;\n  }\n\n  var boxPositions = [],\n      containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),\n      fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;\n  var styleOptions = {\n    font: fontSize + \"px \" + FONT_STYLE\n  };\n\n  (function() {\n    var styleBox, cue;\n\n    for (var i = 0; i < cues.length; i++) {\n      cue = cues[i];\n\n      // Compute the intial position and styles of the cue div.\n      styleBox = new CueStyleBox(window, cue, styleOptions);\n      paddedOverlay.appendChild(styleBox.div);\n\n      // Move the cue div to it's correct line position.\n      moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);\n\n      // Remember the computed div so that we don't have to recompute it later\n      // if we don't have too.\n      cue.displayState = styleBox.div;\n\n      boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));\n    }\n  })();\n};\n\nWebVTT.Parser = function(window, vttjs, decoder) {\n  if (!decoder) {\n    decoder = vttjs;\n    vttjs = {};\n  }\n  if (!vttjs) {\n    vttjs = {};\n  }\n\n  this.window = window;\n  this.vttjs = vttjs;\n  this.state = \"INITIAL\";\n  this.buffer = \"\";\n  this.decoder = decoder || new TextDecoder(\"utf8\");\n  this.regionList = [];\n};\n\nWebVTT.Parser.prototype = {\n  // If the error is a ParsingError then report it to the consumer if\n  // possible. If it's not a ParsingError then throw it like normal.\n  reportOrThrowError: function(e) {\n    if (e instanceof ParsingError) {\n      this.onparsingerror && this.onparsingerror(e);\n    } else {\n      throw e;\n    }\n  },\n  parse: function (data) {\n    var self = this;\n\n    // If there is no data then we won't decode it, but will just try to parse\n    // whatever is in buffer already. This may occur in circumstances, for\n    // example when flush() is called.\n    if (data) {\n      // Try to decode the data that we received.\n      self.buffer += self.decoder.decode(data, {stream: true});\n    }\n\n    function collectNextLine() {\n      var buffer = self.buffer;\n      var pos = 0;\n      while (pos < buffer.length && buffer[pos] !== '\\r' && buffer[pos] !== '\\n') {\n        ++pos;\n      }\n      var line = buffer.substr(0, pos);\n      // Advance the buffer early in case we fail below.\n      if (buffer[pos] === '\\r') {\n        ++pos;\n      }\n      if (buffer[pos] === '\\n') {\n        ++pos;\n      }\n      self.buffer = buffer.substr(pos);\n      return line;\n    }\n\n    // 3.4 WebVTT region and WebVTT region settings syntax\n    function parseRegion(input) {\n      var settings = new Settings();\n\n      parseOptions(input, function (k, v) {\n        switch (k) {\n        case \"id\":\n          settings.set(k, v);\n          break;\n        case \"width\":\n          settings.percent(k, v);\n          break;\n        case \"lines\":\n          settings.integer(k, v);\n          break;\n        case \"regionanchor\":\n        case \"viewportanchor\":\n          var xy = v.split(',');\n          if (xy.length !== 2) {\n            break;\n          }\n          // We have to make sure both x and y parse, so use a temporary\n          // settings object here.\n          var anchor = new Settings();\n          anchor.percent(\"x\", xy[0]);\n          anchor.percent(\"y\", xy[1]);\n          if (!anchor.has(\"x\") || !anchor.has(\"y\")) {\n            break;\n          }\n          settings.set(k + \"X\", anchor.get(\"x\"));\n          settings.set(k + \"Y\", anchor.get(\"y\"));\n          break;\n        case \"scroll\":\n          settings.alt(k, v, [\"up\"]);\n          break;\n        }\n      }, /=/, /\\s/);\n\n      // Create the region, using default values for any values that were not\n      // specified.\n      if (settings.has(\"id\")) {\n        var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();\n        region.width = settings.get(\"width\", 100);\n        region.lines = settings.get(\"lines\", 3);\n        region.regionAnchorX = settings.get(\"regionanchorX\", 0);\n        region.regionAnchorY = settings.get(\"regionanchorY\", 100);\n        region.viewportAnchorX = settings.get(\"viewportanchorX\", 0);\n        region.viewportAnchorY = settings.get(\"viewportanchorY\", 100);\n        region.scroll = settings.get(\"scroll\", \"\");\n        // Register the region.\n        self.onregion && self.onregion(region);\n        // Remember the VTTRegion for later in case we parse any VTTCues that\n        // reference it.\n        self.regionList.push({\n          id: settings.get(\"id\"),\n          region: region\n        });\n      }\n    }\n\n    // draft-pantos-http-live-streaming-20\n    // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5\n    // 3.5 WebVTT\n    function parseTimestampMap(input) {\n      var settings = new Settings();\n\n      parseOptions(input, function(k, v) {\n        switch(k) {\n        case \"MPEGT\":\n          settings.integer(k + 'S', v);\n          break;\n        case \"LOCA\":\n          settings.set(k + 'L', parseTimeStamp(v));\n          break;\n        }\n      }, /[^\\d]:/, /,/);\n\n      self.ontimestampmap && self.ontimestampmap({\n        \"MPEGTS\": settings.get(\"MPEGTS\"),\n        \"LOCAL\": settings.get(\"LOCAL\")\n      });\n    }\n\n    // 3.2 WebVTT metadata header syntax\n    function parseHeader(input) {\n      if (input.match(/X-TIMESTAMP-MAP/)) {\n        // This line contains HLS X-TIMESTAMP-MAP metadata\n        parseOptions(input, function(k, v) {\n          switch(k) {\n          case \"X-TIMESTAMP-MAP\":\n            parseTimestampMap(v);\n            break;\n          }\n        }, /=/);\n      } else {\n        parseOptions(input, function (k, v) {\n          switch (k) {\n          case \"Region\":\n            // 3.3 WebVTT region metadata header syntax\n            parseRegion(v);\n            break;\n          }\n        }, /:/);\n      }\n\n    }\n\n    // 5.1 WebVTT file parsing.\n    try {\n      var line;\n      if (self.state === \"INITIAL\") {\n        // We can't start parsing until we have the first line.\n        if (!/\\r\\n|\\n/.test(self.buffer)) {\n          return this;\n        }\n\n        line = collectNextLine();\n\n        var m = line.match(/^WEBVTT([ \\t].*)?$/);\n        if (!m || !m[0]) {\n          throw new ParsingError(ParsingError.Errors.BadSignature);\n        }\n\n        self.state = \"HEADER\";\n      }\n\n      var alreadyCollectedLine = false;\n      while (self.buffer) {\n        // We can't parse a line until we have the full line.\n        if (!/\\r\\n|\\n/.test(self.buffer)) {\n          return this;\n        }\n\n        if (!alreadyCollectedLine) {\n          line = collectNextLine();\n        } else {\n          alreadyCollectedLine = false;\n        }\n\n        switch (self.state) {\n        case \"HEADER\":\n          // 13-18 - Allow a header (metadata) under the WEBVTT line.\n          if (/:/.test(line)) {\n            parseHeader(line);\n          } else if (!line) {\n            // An empty line terminates the header and starts the body (cues).\n            self.state = \"ID\";\n          }\n          continue;\n        case \"NOTE\":\n          // Ignore NOTE blocks.\n          if (!line) {\n            self.state = \"ID\";\n          }\n          continue;\n        case \"ID\":\n          // Check for the start of NOTE blocks.\n          if (/^NOTE($|[ \\t])/.test(line)) {\n            self.state = \"NOTE\";\n            break;\n          }\n          // 19-29 - Allow any number of line terminators, then initialize new cue values.\n          if (!line) {\n            continue;\n          }\n          self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, \"\");\n          // Safari still uses the old middle value and won't accept center\n          try {\n            self.cue.align = \"center\";\n          } catch (e) {\n            self.cue.align = \"middle\";\n          }\n          self.state = \"CUE\";\n          // 30-39 - Check if self line contains an optional identifier or timing data.\n          if (line.indexOf(\"-->\") === -1) {\n            self.cue.id = line;\n            continue;\n          }\n          // Process line as start of a cue.\n          /*falls through*/\n        case \"CUE\":\n          // 40 - Collect cue timings and settings.\n          try {\n            parseCue(line, self.cue, self.regionList);\n          } catch (e) {\n            self.reportOrThrowError(e);\n            // In case of an error ignore rest of the cue.\n            self.cue = null;\n            self.state = \"BADCUE\";\n            continue;\n          }\n          self.state = \"CUETEXT\";\n          continue;\n        case \"CUETEXT\":\n          var hasSubstring = line.indexOf(\"-->\") !== -1;\n          // 34 - If we have an empty line then report the cue.\n          // 35 - If we have the special substring '-->' then report the cue,\n          // but do not collect the line as we need to process the current\n          // one as a new cue.\n          if (!line || hasSubstring && (alreadyCollectedLine = true)) {\n            // We are done parsing self cue.\n            self.oncue && self.oncue(self.cue);\n            self.cue = null;\n            self.state = \"ID\";\n            continue;\n          }\n          if (self.cue.text) {\n            self.cue.text += \"\\n\";\n          }\n          self.cue.text += line.replace(/\\u2028/g, '\\n').replace(/u2029/g, '\\n');\n          continue;\n        case \"BADCUE\": // BADCUE\n          // 54-62 - Collect and discard the remaining cue.\n          if (!line) {\n            self.state = \"ID\";\n          }\n          continue;\n        }\n      }\n    } catch (e) {\n      self.reportOrThrowError(e);\n\n      // If we are currently parsing a cue, report what we have.\n      if (self.state === \"CUETEXT\" && self.cue && self.oncue) {\n        self.oncue(self.cue);\n      }\n      self.cue = null;\n      // Enter BADWEBVTT state if header was not parsed correctly otherwise\n      // another exception occurred so enter BADCUE state.\n      self.state = self.state === \"INITIAL\" ? \"BADWEBVTT\" : \"BADCUE\";\n    }\n    return this;\n  },\n  flush: function () {\n    var self = this;\n    try {\n      // Finish decoding the stream.\n      self.buffer += self.decoder.decode();\n      // Synthesize the end of the current cue or region.\n      if (self.cue || self.state === \"HEADER\") {\n        self.buffer += \"\\n\\n\";\n        self.parse();\n      }\n      // If we've flushed, parsed, and we're still on the INITIAL state then\n      // that means we don't have enough of the stream to parse the first\n      // line.\n      if (self.state === \"INITIAL\") {\n        throw new ParsingError(ParsingError.Errors.BadSignature);\n      }\n    } catch(e) {\n      self.reportOrThrowError(e);\n    }\n    self.onflush && self.onflush();\n    return this;\n  }\n};\n\nmodule.exports = WebVTT;\n","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nvar autoKeyword = \"auto\";\nvar directionSetting = {\n  \"\": 1,\n  \"lr\": 1,\n  \"rl\": 1\n};\nvar alignSetting = {\n  \"start\": 1,\n  \"center\": 1,\n  \"end\": 1,\n  \"left\": 1,\n  \"right\": 1,\n  \"auto\": 1,\n  \"line-left\": 1,\n  \"line-right\": 1\n};\n\nfunction findDirectionSetting(value) {\n  if (typeof value !== \"string\") {\n    return false;\n  }\n  var dir = directionSetting[value.toLowerCase()];\n  return dir ? value.toLowerCase() : false;\n}\n\nfunction findAlignSetting(value) {\n  if (typeof value !== \"string\") {\n    return false;\n  }\n  var align = alignSetting[value.toLowerCase()];\n  return align ? value.toLowerCase() : false;\n}\n\nfunction VTTCue(startTime, endTime, text) {\n  /**\n   * Shim implementation specific properties. These properties are not in\n   * the spec.\n   */\n\n  // Lets us know when the VTTCue's data has changed in such a way that we need\n  // to recompute its display state. This lets us compute its display state\n  // lazily.\n  this.hasBeenReset = false;\n\n  /**\n   * VTTCue and TextTrackCue properties\n   * http://dev.w3.org/html5/webvtt/#vttcue-interface\n   */\n\n  var _id = \"\";\n  var _pauseOnExit = false;\n  var _startTime = startTime;\n  var _endTime = endTime;\n  var _text = text;\n  var _region = null;\n  var _vertical = \"\";\n  var _snapToLines = true;\n  var _line = \"auto\";\n  var _lineAlign = \"start\";\n  var _position = \"auto\";\n  var _positionAlign = \"auto\";\n  var _size = 100;\n  var _align = \"center\";\n\n  Object.defineProperties(this, {\n    \"id\": {\n      enumerable: true,\n      get: function() {\n        return _id;\n      },\n      set: function(value) {\n        _id = \"\" + value;\n      }\n    },\n\n    \"pauseOnExit\": {\n      enumerable: true,\n      get: function() {\n        return _pauseOnExit;\n      },\n      set: function(value) {\n        _pauseOnExit = !!value;\n      }\n    },\n\n    \"startTime\": {\n      enumerable: true,\n      get: function() {\n        return _startTime;\n      },\n      set: function(value) {\n        if (typeof value !== \"number\") {\n          throw new TypeError(\"Start time must be set to a number.\");\n        }\n        _startTime = value;\n        this.hasBeenReset = true;\n      }\n    },\n\n    \"endTime\": {\n      enumerable: true,\n      get: function() {\n        return _endTime;\n      },\n      set: function(value) {\n        if (typeof value !== \"number\") {\n          throw new TypeError(\"End time must be set to a number.\");\n        }\n        _endTime = value;\n        this.hasBeenReset = true;\n      }\n    },\n\n    \"text\": {\n      enumerable: true,\n      get: function() {\n        return _text;\n      },\n      set: function(value) {\n        _text = \"\" + value;\n        this.hasBeenReset = true;\n      }\n    },\n\n    \"region\": {\n      enumerable: true,\n      get: function() {\n        return _region;\n      },\n      set: function(value) {\n        _region = value;\n        this.hasBeenReset = true;\n      }\n    },\n\n    \"vertical\": {\n      enumerable: true,\n      get: function() {\n        return _vertical;\n      },\n      set: function(value) {\n        var setting = findDirectionSetting(value);\n        // Have to check for false because the setting an be an empty string.\n        if (setting === false) {\n          throw new SyntaxError(\"Vertical: an invalid or illegal direction string was specified.\");\n        }\n        _vertical = setting;\n        this.hasBeenReset = true;\n      }\n    },\n\n    \"snapToLines\": {\n      enumerable: true,\n      get: function() {\n        return _snapToLines;\n      },\n      set: function(value) {\n        _snapToLines = !!value;\n        this.hasBeenReset = true;\n      }\n    },\n\n    \"line\": {\n      enumerable: true,\n      get: function() {\n        return _line;\n      },\n      set: function(value) {\n        if (typeof value !== \"number\" && value !== autoKeyword) {\n          throw new SyntaxError(\"Line: an invalid number or illegal string was specified.\");\n        }\n        _line = value;\n        this.hasBeenReset = true;\n      }\n    },\n\n    \"lineAlign\": {\n      enumerable: true,\n      get: function() {\n        return _lineAlign;\n      },\n      set: function(value) {\n        var setting = findAlignSetting(value);\n        if (!setting) {\n          console.warn(\"lineAlign: an invalid or illegal string was specified.\");\n        } else {\n          _lineAlign = setting;\n          this.hasBeenReset = true;\n        }\n      }\n    },\n\n    \"position\": {\n      enumerable: true,\n      get: function() {\n        return _position;\n      },\n      set: function(value) {\n        if (value < 0 || value > 100) {\n          throw new Error(\"Position must be between 0 and 100.\");\n        }\n        _position = value;\n        this.hasBeenReset = true;\n      }\n    },\n\n    \"positionAlign\": {\n      enumerable: true,\n      get: function() {\n        return _positionAlign;\n      },\n      set: function(value) {\n        var setting = findAlignSetting(value);\n        if (!setting) {\n          console.warn(\"positionAlign: an invalid or illegal string was specified.\");\n        } else {\n          _positionAlign = setting;\n          this.hasBeenReset = true;\n        }\n      }\n    },\n\n    \"size\": {\n      enumerable: true,\n      get: function() {\n        return _size;\n      },\n      set: function(value) {\n        if (value < 0 || value > 100) {\n          throw new Error(\"Size must be between 0 and 100.\");\n        }\n        _size = value;\n        this.hasBeenReset = true;\n      }\n    },\n\n    \"align\": {\n      enumerable: true,\n      get: function() {\n        return _align;\n      },\n      set: function(value) {\n        var setting = findAlignSetting(value);\n        if (!setting) {\n          throw new SyntaxError(\"align: an invalid or illegal alignment string was specified.\");\n        }\n        _align = setting;\n        this.hasBeenReset = true;\n      }\n    }\n  });\n\n  /**\n   * Other <track> spec defined properties\n   */\n\n  // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n  this.displayState = undefined;\n}\n\n/**\n * VTTCue methods\n */\n\nVTTCue.prototype.getCueAsHTML = function() {\n  // Assume WebVTT.convertCueToDOMTree is on the global.\n  return WebVTT.convertCueToDOMTree(window, this.text);\n};\n\nmodule.exports = VTTCue;\n","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nvar scrollSetting = {\n  \"\": true,\n  \"up\": true\n};\n\nfunction findScrollSetting(value) {\n  if (typeof value !== \"string\") {\n    return false;\n  }\n  var scroll = scrollSetting[value.toLowerCase()];\n  return scroll ? value.toLowerCase() : false;\n}\n\nfunction isValidPercentValue(value) {\n  return typeof value === \"number\" && (value >= 0 && value <= 100);\n}\n\n// VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface\nfunction VTTRegion() {\n  var _width = 100;\n  var _lines = 3;\n  var _regionAnchorX = 0;\n  var _regionAnchorY = 100;\n  var _viewportAnchorX = 0;\n  var _viewportAnchorY = 100;\n  var _scroll = \"\";\n\n  Object.defineProperties(this, {\n    \"width\": {\n      enumerable: true,\n      get: function() {\n        return _width;\n      },\n      set: function(value) {\n        if (!isValidPercentValue(value)) {\n          throw new Error(\"Width must be between 0 and 100.\");\n        }\n        _width = value;\n      }\n    },\n    \"lines\": {\n      enumerable: true,\n      get: function() {\n        return _lines;\n      },\n      set: function(value) {\n        if (typeof value !== \"number\") {\n          throw new TypeError(\"Lines must be set to a number.\");\n        }\n        _lines = value;\n      }\n    },\n    \"regionAnchorY\": {\n      enumerable: true,\n      get: function() {\n        return _regionAnchorY;\n      },\n      set: function(value) {\n        if (!isValidPercentValue(value)) {\n          throw new Error(\"RegionAnchorX must be between 0 and 100.\");\n        }\n        _regionAnchorY = value;\n      }\n    },\n    \"regionAnchorX\": {\n      enumerable: true,\n      get: function() {\n        return _regionAnchorX;\n      },\n      set: function(value) {\n        if(!isValidPercentValue(value)) {\n          throw new Error(\"RegionAnchorY must be between 0 and 100.\");\n        }\n        _regionAnchorX = value;\n      }\n    },\n    \"viewportAnchorY\": {\n      enumerable: true,\n      get: function() {\n        return _viewportAnchorY;\n      },\n      set: function(value) {\n        if (!isValidPercentValue(value)) {\n          throw new Error(\"ViewportAnchorY must be between 0 and 100.\");\n        }\n        _viewportAnchorY = value;\n      }\n    },\n    \"viewportAnchorX\": {\n      enumerable: true,\n      get: function() {\n        return _viewportAnchorX;\n      },\n      set: function(value) {\n        if (!isValidPercentValue(value)) {\n          throw new Error(\"ViewportAnchorX must be between 0 and 100.\");\n        }\n        _viewportAnchorX = value;\n      }\n    },\n    \"scroll\": {\n      enumerable: true,\n      get: function() {\n        return _scroll;\n      },\n      set: function(value) {\n        var setting = findScrollSetting(value);\n        // Have to check for false as an empty string is a legal value.\n        if (setting === false) {\n          console.warn(\"Scroll: an invalid or illegal string was specified.\");\n        } else {\n          _scroll = setting;\n        }\n      }\n    }\n  });\n}\n\nmodule.exports = VTTRegion;\n","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Default exports for Node. Export the extended versions of VTTCue and\n// VTTRegion in Node since we likely want the capability to convert back and\n// forth between JSON. If we don't then it's not that big of a deal since we're\n// off browser.\n\nvar window = require('global/window');\n\nvar vttjs = module.exports = {\n  WebVTT: require(\"./vtt.js\"),\n  VTTCue: require(\"./vttcue.js\"),\n  VTTRegion: require(\"./vttregion.js\")\n};\n\nwindow.vttjs = vttjs;\nwindow.WebVTT = vttjs.WebVTT;\n\nvar cueShim = vttjs.VTTCue;\nvar regionShim = vttjs.VTTRegion;\nvar nativeVTTCue = window.VTTCue;\nvar nativeVTTRegion = window.VTTRegion;\n\nvttjs.shim = function() {\n  window.VTTCue = cueShim;\n  window.VTTRegion = regionShim;\n};\n\nvttjs.restore = function() {\n  window.VTTCue = nativeVTTCue;\n  window.VTTRegion = nativeVTTRegion;\n};\n\nif (!window.VTTCue) {\n  vttjs.shim();\n}\n","import window from 'global/window';\nvar DEFAULT_LOCATION = 'https://example.com';\n\nvar resolveUrl = function resolveUrl(baseUrl, relativeUrl) {\n  // return early if we don't need to resolve\n  if (/^[a-z]+:/i.test(relativeUrl)) {\n    return relativeUrl;\n  } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location\n\n\n  if (/^data:/.test(baseUrl)) {\n    baseUrl = window.location && window.location.href || '';\n  }\n\n  var protocolLess = /^\\/\\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)\n  // and if baseUrl isn't an absolute url\n\n  var removeLocation = !window.location && !/\\/\\//i.test(baseUrl); // if the base URL is relative then combine with the current location\n\n  baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);\n  var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol\n  // and if we're location-less, remove the location\n  // otherwise, return the url unmodified\n\n  if (removeLocation) {\n    return newUrl.href.slice(DEFAULT_LOCATION.length);\n  } else if (protocolLess) {\n    return newUrl.href.slice(newUrl.protocol.length);\n  }\n\n  return newUrl.href;\n};\n\nexport default resolveUrl;","import window from 'global/window';\nvar regexs = {\n  // to determine mime types\n  mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,\n  webm: /^(vp0?[89]|av0?1|opus|vorbis)/,\n  ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,\n  // to determine if a codec is audio or video\n  video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,\n  audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,\n  text: /^(stpp.ttml.im1t)/,\n  // mux.js support regex\n  muxerVideo: /^(avc0?1)/,\n  muxerAudio: /^(mp4a)/,\n  // match nothing as muxer does not support text right now.\n  // there cannot never be a character before the start of a string\n  // so this matches nothing.\n  muxerText: /a^/\n};\nvar mediaTypes = ['video', 'audio', 'text'];\nvar upperMediaTypes = ['Video', 'Audio', 'Text'];\n/**\n * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard\n * `avc1.<hhhhhh>`\n *\n * @param {string} codec\n *        Codec string to translate\n * @return {string}\n *         The translated codec string\n */\n\nexport var translateLegacyCodec = function translateLegacyCodec(codec) {\n  if (!codec) {\n    return codec;\n  }\n\n  return codec.replace(/avc1\\.(\\d+)\\.(\\d+)/i, function (orig, profile, avcLevel) {\n    var profileHex = ('00' + Number(profile).toString(16)).slice(-2);\n    var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);\n    return 'avc1.' + profileHex + '00' + avcLevelHex;\n  });\n};\n/**\n * Replace the old apple-style `avc1.<dd>.<dd>` codec strings with the standard\n * `avc1.<hhhhhh>`\n *\n * @param {string[]} codecs\n *        An array of codec strings to translate\n * @return {string[]}\n *         The translated array of codec strings\n */\n\nexport var translateLegacyCodecs = function translateLegacyCodecs(codecs) {\n  return codecs.map(translateLegacyCodec);\n};\n/**\n * Replace codecs in the codec string with the old apple-style `avc1.<dd>.<dd>` to the\n * standard `avc1.<hhhhhh>`.\n *\n * @param {string} codecString\n *        The codec string\n * @return {string}\n *         The codec string with old apple-style codecs replaced\n *\n * @private\n */\n\nexport var mapLegacyAvcCodecs = function mapLegacyAvcCodecs(codecString) {\n  return codecString.replace(/avc1\\.(\\d+)\\.(\\d+)/i, function (match) {\n    return translateLegacyCodecs([match])[0];\n  });\n};\n/**\n * @typedef {Object} ParsedCodecInfo\n * @property {number} codecCount\n *           Number of codecs parsed\n * @property {string} [videoCodec]\n *           Parsed video codec (if found)\n * @property {string} [videoObjectTypeIndicator]\n *           Video object type indicator (if found)\n * @property {string|null} audioProfile\n *           Audio profile\n */\n\n/**\n * Parses a codec string to retrieve the number of codecs specified, the video codec and\n * object type indicator, and the audio profile.\n *\n * @param {string} [codecString]\n *        The codec string to parse\n * @return {ParsedCodecInfo}\n *         Parsed codec info\n */\n\nexport var parseCodecs = function parseCodecs(codecString) {\n  if (codecString === void 0) {\n    codecString = '';\n  }\n\n  var codecs = codecString.split(',');\n  var result = [];\n  codecs.forEach(function (codec) {\n    codec = codec.trim();\n    var codecType;\n    mediaTypes.forEach(function (name) {\n      var match = regexs[name].exec(codec.toLowerCase());\n\n      if (!match || match.length <= 1) {\n        return;\n      }\n\n      codecType = name; // maintain codec case\n\n      var type = codec.substring(0, match[1].length);\n      var details = codec.replace(type, '');\n      result.push({\n        type: type,\n        details: details,\n        mediaType: name\n      });\n    });\n\n    if (!codecType) {\n      result.push({\n        type: codec,\n        details: '',\n        mediaType: 'unknown'\n      });\n    }\n  });\n  return result;\n};\n/**\n * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is\n * a default alternate audio playlist for the provided audio group.\n *\n * @param {Object} master\n *        The master playlist\n * @param {string} audioGroupId\n *        ID of the audio group for which to find the default codec info\n * @return {ParsedCodecInfo}\n *         Parsed codec info\n */\n\nexport var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {\n  if (!master.mediaGroups.AUDIO || !audioGroupId) {\n    return null;\n  }\n\n  var audioGroup = master.mediaGroups.AUDIO[audioGroupId];\n\n  if (!audioGroup) {\n    return null;\n  }\n\n  for (var name in audioGroup) {\n    var audioType = audioGroup[name];\n\n    if (audioType.default && audioType.playlists) {\n      // codec should be the same for all playlists within the audio type\n      return parseCodecs(audioType.playlists[0].attributes.CODECS);\n    }\n  }\n\n  return null;\n};\nexport var isVideoCodec = function isVideoCodec(codec) {\n  if (codec === void 0) {\n    codec = '';\n  }\n\n  return regexs.video.test(codec.trim().toLowerCase());\n};\nexport var isAudioCodec = function isAudioCodec(codec) {\n  if (codec === void 0) {\n    codec = '';\n  }\n\n  return regexs.audio.test(codec.trim().toLowerCase());\n};\nexport var isTextCodec = function isTextCodec(codec) {\n  if (codec === void 0) {\n    codec = '';\n  }\n\n  return regexs.text.test(codec.trim().toLowerCase());\n};\nexport var getMimeForCodec = function getMimeForCodec(codecString) {\n  if (!codecString || typeof codecString !== 'string') {\n    return;\n  }\n\n  var codecs = codecString.toLowerCase().split(',').map(function (c) {\n    return translateLegacyCodec(c.trim());\n  }); // default to video type\n\n  var type = 'video'; // only change to audio type if the only codec we have is\n  // audio\n\n  if (codecs.length === 1 && isAudioCodec(codecs[0])) {\n    type = 'audio';\n  } else if (codecs.length === 1 && isTextCodec(codecs[0])) {\n    // text uses application/<container> for now\n    type = 'application';\n  } // default the container to mp4\n\n\n  var container = 'mp4'; // every codec must be able to go into the container\n  // for that container to be the correct one\n\n  if (codecs.every(function (c) {\n    return regexs.mp4.test(c);\n  })) {\n    container = 'mp4';\n  } else if (codecs.every(function (c) {\n    return regexs.webm.test(c);\n  })) {\n    container = 'webm';\n  } else if (codecs.every(function (c) {\n    return regexs.ogg.test(c);\n  })) {\n    container = 'ogg';\n  }\n\n  return type + \"/\" + container + \";codecs=\\\"\" + codecString + \"\\\"\";\n};\n/**\n * Tests whether the codec is supported by MediaSource. Optionally also tests ManagedMediaSource.\n *\n * @param {string} codecString\n *        Codec to test\n * @param {boolean} [withMMS]\n *        Whether to check if ManagedMediaSource supports it\n * @return {boolean}\n *          Codec is supported\n */\n\nexport var browserSupportsCodec = function browserSupportsCodec(codecString, withMMS) {\n  if (codecString === void 0) {\n    codecString = '';\n  }\n\n  if (withMMS === void 0) {\n    withMMS = false;\n  }\n\n  return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || withMMS && window.ManagedMediaSource && window.ManagedMediaSource.isTypeSupported && window.ManagedMediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;\n};\nexport var muxerSupportsCodec = function muxerSupportsCodec(codecString) {\n  if (codecString === void 0) {\n    codecString = '';\n  }\n\n  return codecString.toLowerCase().split(',').every(function (codec) {\n    codec = codec.trim(); // any match is supported.\n\n    for (var i = 0; i < upperMediaTypes.length; i++) {\n      var type = upperMediaTypes[i];\n\n      if (regexs[\"muxer\" + type].test(codec)) {\n        return true;\n      }\n    }\n\n    return false;\n  });\n};\nexport var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';\nexport var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';","var MPEGURL_REGEX = /^(audio|video|application)\\/(x-|vnd\\.apple\\.)?mpegurl/i;\nvar DASH_REGEX = /^application\\/dash\\+xml/i;\n/**\n * Returns a string that describes the type of source based on a video source object's\n * media type.\n *\n * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}\n *\n * @param {string} type\n *        Video source object media type\n * @return {('hls'|'dash'|'vhs-json'|null)}\n *         VHS source type string\n */\n\nexport var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {\n  if (MPEGURL_REGEX.test(type)) {\n    return 'hls';\n  }\n\n  if (DASH_REGEX.test(type)) {\n    return 'dash';\n  } // Denotes the special case of a manifest object passed to http-streaming instead of a\n  // source URL.\n  //\n  // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.\n  //\n  // In this case, vnd stands for vendor, video.js for the organization, VHS for this\n  // project, and the +json suffix identifies the structure of the media type.\n\n\n  if (type === 'application/vnd.videojs.vhs+json') {\n    return 'vhs-json';\n  }\n\n  return null;\n};","import window from 'global/window'; // const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));\n\nvar repeat = function repeat(str, len) {\n  var acc = '';\n\n  while (len--) {\n    acc += str;\n  }\n\n  return acc;\n}; // count the number of bits it would take to represent a number\n// we used to do this with log2 but BigInt does not support builtin math\n// Math.ceil(log2(x));\n\n\nexport var countBits = function countBits(x) {\n  return x.toString(2).length;\n}; // count the number of whole bytes it would take to represent a number\n\nexport var countBytes = function countBytes(x) {\n  return Math.ceil(countBits(x) / 8);\n};\nexport var padStart = function padStart(b, len, str) {\n  if (str === void 0) {\n    str = ' ';\n  }\n\n  return (repeat(str, len) + b.toString()).slice(-len);\n};\nexport var isArrayBufferView = function isArrayBufferView(obj) {\n  if (ArrayBuffer.isView === 'function') {\n    return ArrayBuffer.isView(obj);\n  }\n\n  return obj && obj.buffer instanceof ArrayBuffer;\n};\nexport var isTypedArray = function isTypedArray(obj) {\n  return isArrayBufferView(obj);\n};\nexport var toUint8 = function toUint8(bytes) {\n  if (bytes instanceof Uint8Array) {\n    return bytes;\n  }\n\n  if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {\n    // any non-number or NaN leads to empty uint8array\n    // eslint-disable-next-line\n    if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {\n      bytes = 0;\n    } else {\n      bytes = [bytes];\n    }\n  }\n\n  return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);\n};\nexport var toHexString = function toHexString(bytes) {\n  bytes = toUint8(bytes);\n  var str = '';\n\n  for (var i = 0; i < bytes.length; i++) {\n    str += padStart(bytes[i].toString(16), 2, '0');\n  }\n\n  return str;\n};\nexport var toBinaryString = function toBinaryString(bytes) {\n  bytes = toUint8(bytes);\n  var str = '';\n\n  for (var i = 0; i < bytes.length; i++) {\n    str += padStart(bytes[i].toString(2), 8, '0');\n  }\n\n  return str;\n};\nvar BigInt = window.BigInt || Number;\nvar BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];\nexport var ENDIANNESS = function () {\n  var a = new Uint16Array([0xFFCC]);\n  var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n\n  if (b[0] === 0xFF) {\n    return 'big';\n  }\n\n  if (b[0] === 0xCC) {\n    return 'little';\n  }\n\n  return 'unknown';\n}();\nexport var IS_BIG_ENDIAN = ENDIANNESS === 'big';\nexport var IS_LITTLE_ENDIAN = ENDIANNESS === 'little';\nexport var bytesToNumber = function bytesToNumber(bytes, _temp) {\n  var _ref = _temp === void 0 ? {} : _temp,\n      _ref$signed = _ref.signed,\n      signed = _ref$signed === void 0 ? false : _ref$signed,\n      _ref$le = _ref.le,\n      le = _ref$le === void 0 ? false : _ref$le;\n\n  bytes = toUint8(bytes);\n  var fn = le ? 'reduce' : 'reduceRight';\n  var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];\n  var number = obj.call(bytes, function (total, byte, i) {\n    var exponent = le ? i : Math.abs(i + 1 - bytes.length);\n    return total + BigInt(byte) * BYTE_TABLE[exponent];\n  }, BigInt(0));\n\n  if (signed) {\n    var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);\n    number = BigInt(number);\n\n    if (number > max) {\n      number -= max;\n      number -= max;\n      number -= BigInt(2);\n    }\n  }\n\n  return Number(number);\n};\nexport var numberToBytes = function numberToBytes(number, _temp2) {\n  var _ref2 = _temp2 === void 0 ? {} : _temp2,\n      _ref2$le = _ref2.le,\n      le = _ref2$le === void 0 ? false : _ref2$le;\n\n  // eslint-disable-next-line\n  if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {\n    number = 0;\n  }\n\n  number = BigInt(number);\n  var byteCount = countBytes(number);\n  var bytes = new Uint8Array(new ArrayBuffer(byteCount));\n\n  for (var i = 0; i < byteCount; i++) {\n    var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);\n    bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));\n\n    if (number < 0) {\n      bytes[byteIndex] = Math.abs(~bytes[byteIndex]);\n      bytes[byteIndex] -= i === 0 ? 1 : 2;\n    }\n  }\n\n  return bytes;\n};\nexport var bytesToString = function bytesToString(bytes) {\n  if (!bytes) {\n    return '';\n  } // TODO: should toUint8 handle cases where we only have 8 bytes\n  // but report more since this is a Uint16+ Array?\n\n\n  bytes = Array.prototype.slice.call(bytes);\n  var string = String.fromCharCode.apply(null, toUint8(bytes));\n\n  try {\n    return decodeURIComponent(escape(string));\n  } catch (e) {// if decodeURIComponent/escape fails, we are dealing with partial\n    // or full non string data. Just return the potentially garbled string.\n  }\n\n  return string;\n};\nexport var stringToBytes = function stringToBytes(string, stringIsBytes) {\n  if (typeof string !== 'string' && string && typeof string.toString === 'function') {\n    string = string.toString();\n  }\n\n  if (typeof string !== 'string') {\n    return new Uint8Array();\n  } // If the string already is bytes, we don't have to do this\n  // otherwise we do this so that we split multi length characters\n  // into individual bytes\n\n\n  if (!stringIsBytes) {\n    string = unescape(encodeURIComponent(string));\n  }\n\n  var view = new Uint8Array(string.length);\n\n  for (var i = 0; i < string.length; i++) {\n    view[i] = string.charCodeAt(i);\n  }\n\n  return view;\n};\nexport var concatTypedArrays = function concatTypedArrays() {\n  for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {\n    buffers[_key] = arguments[_key];\n  }\n\n  buffers = buffers.filter(function (b) {\n    return b && (b.byteLength || b.length) && typeof b !== 'string';\n  });\n\n  if (buffers.length <= 1) {\n    // for 0 length we will return empty uint8\n    // for 1 length we return the first uint8\n    return toUint8(buffers[0]);\n  }\n\n  var totalLen = buffers.reduce(function (total, buf, i) {\n    return total + (buf.byteLength || buf.length);\n  }, 0);\n  var tempBuffer = new Uint8Array(totalLen);\n  var offset = 0;\n  buffers.forEach(function (buf) {\n    buf = toUint8(buf);\n    tempBuffer.set(buf, offset);\n    offset += buf.byteLength;\n  });\n  return tempBuffer;\n};\n/**\n * Check if the bytes \"b\" are contained within bytes \"a\".\n *\n * @param {Uint8Array|Array} a\n *        Bytes to check in\n *\n * @param {Uint8Array|Array} b\n *        Bytes to check for\n *\n * @param {Object} options\n *        options\n *\n * @param {Array|Uint8Array} [offset=0]\n *        offset to use when looking at bytes in a\n *\n * @param {Array|Uint8Array} [mask=[]]\n *        mask to use on bytes before comparison.\n *\n * @return {boolean}\n *         If all bytes in b are inside of a, taking into account\n *         bit masks.\n */\n\nexport var bytesMatch = function bytesMatch(a, b, _temp3) {\n  var _ref3 = _temp3 === void 0 ? {} : _temp3,\n      _ref3$offset = _ref3.offset,\n      offset = _ref3$offset === void 0 ? 0 : _ref3$offset,\n      _ref3$mask = _ref3.mask,\n      mask = _ref3$mask === void 0 ? [] : _ref3$mask;\n\n  a = toUint8(a);\n  b = toUint8(b); // ie 11 does not support uint8 every\n\n  var fn = b.every ? b.every : Array.prototype.every;\n  return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8\n  fn.call(b, function (bByte, i) {\n    var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];\n    return bByte === aByte;\n  });\n};\nexport var sliceBytes = function sliceBytes(src, start, end) {\n  if (Uint8Array.prototype.slice) {\n    return Uint8Array.prototype.slice.call(src, start, end);\n  }\n\n  return new Uint8Array(Array.prototype.slice.call(src, start, end));\n};\nexport var reverseBytes = function reverseBytes(src) {\n  if (src.reverse) {\n    return src.reverse();\n  }\n\n  return Array.prototype.reverse.call(src);\n};","var MAX_UINT32 = Math.pow(2, 32);\n\nvar getUint64 = function(uint8) {\n  var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);\n  var value;\n\n  if (dv.getBigUint64) {\n    value = dv.getBigUint64(0);\n\n    if (value < Number.MAX_SAFE_INTEGER) {\n      return Number(value);\n    }\n\n    return value;\n  }\n\n  return (dv.getUint32(0) * MAX_UINT32) + dv.getUint32(4);\n};\n\nmodule.exports = {\n  getUint64: getUint64,\n  MAX_UINT32: MAX_UINT32\n};\n","var getUint64 = require('../utils/numbers.js').getUint64;\n\nvar parseSidx = function(data) {\n  var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n      result = {\n        version: data[0],\n        flags: new Uint8Array(data.subarray(1, 4)),\n        references: [],\n        referenceId: view.getUint32(4),\n        timescale: view.getUint32(8)\n      },\n    i = 12;\n\n  if (result.version === 0) {\n    result.earliestPresentationTime = view.getUint32(i);\n    result.firstOffset = view.getUint32(i + 4);\n    i += 8;\n  } else {\n    // read 64 bits\n    result.earliestPresentationTime = getUint64(data.subarray(i));\n    result.firstOffset = getUint64(data.subarray(i + 8));\n    i += 16;\n  }\n\n  i += 2; // reserved\n\n  var referenceCount = view.getUint16(i);\n\n  i += 2; // start of references\n\n  for (; referenceCount > 0; i += 12, referenceCount--) {\n    result.references.push({\n      referenceType: (data[i] & 0x80) >>> 7,\n      referencedSize: view.getUint32(i) & 0x7FFFFFFF,\n      subsegmentDuration: view.getUint32(i + 4),\n      startsWithSap: !!(data[i + 8] & 0x80),\n      sapType: (data[i + 8] & 0x70) >>> 4,\n      sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF\n    });\n  }\n\n  return result;\n};\n\n\nmodule.exports = parseSidx;\n","import { toUint8, bytesMatch } from './byte-helpers.js';\nvar ID3 = toUint8([0x49, 0x44, 0x33]);\nexport var getId3Size = function getId3Size(bytes, offset) {\n  if (offset === void 0) {\n    offset = 0;\n  }\n\n  bytes = toUint8(bytes);\n  var flags = bytes[offset + 5];\n  var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];\n  var footerPresent = (flags & 16) >> 4;\n\n  if (footerPresent) {\n    return returnSize + 20;\n  }\n\n  return returnSize + 10;\n};\nexport var getId3Offset = function getId3Offset(bytes, offset) {\n  if (offset === void 0) {\n    offset = 0;\n  }\n\n  bytes = toUint8(bytes);\n\n  if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {\n    offset: offset\n  })) {\n    return offset;\n  }\n\n  offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files\n  // have multiple ID3 tag sections even though\n  // they should not.\n\n  return getId3Offset(bytes, offset);\n};","import { stringToBytes, toUint8, bytesMatch, bytesToString, toHexString, padStart, bytesToNumber } from './byte-helpers.js';\nimport { getAvcCodec, getHvcCodec, getAv1Codec } from './codec-helpers.js';\nimport { parseOpusHead } from './opus-helpers.js';\n\nvar normalizePath = function normalizePath(path) {\n  if (typeof path === 'string') {\n    return stringToBytes(path);\n  }\n\n  if (typeof path === 'number') {\n    return path;\n  }\n\n  return path;\n};\n\nvar normalizePaths = function normalizePaths(paths) {\n  if (!Array.isArray(paths)) {\n    return [normalizePath(paths)];\n  }\n\n  return paths.map(function (p) {\n    return normalizePath(p);\n  });\n};\n\nvar DESCRIPTORS;\nexport var parseDescriptors = function parseDescriptors(bytes) {\n  bytes = toUint8(bytes);\n  var results = [];\n  var i = 0;\n\n  while (bytes.length > i) {\n    var tag = bytes[i];\n    var size = 0;\n    var headerSize = 0; // tag\n\n    headerSize++;\n    var byte = bytes[headerSize]; // first byte\n\n    headerSize++;\n\n    while (byte & 0x80) {\n      size = (byte & 0x7F) << 7;\n      byte = bytes[headerSize];\n      headerSize++;\n    }\n\n    size += byte & 0x7F;\n\n    for (var z = 0; z < DESCRIPTORS.length; z++) {\n      var _DESCRIPTORS$z = DESCRIPTORS[z],\n          id = _DESCRIPTORS$z.id,\n          parser = _DESCRIPTORS$z.parser;\n\n      if (tag === id) {\n        results.push(parser(bytes.subarray(headerSize, headerSize + size)));\n        break;\n      }\n    }\n\n    i += size + headerSize;\n  }\n\n  return results;\n};\nDESCRIPTORS = [{\n  id: 0x03,\n  parser: function parser(bytes) {\n    var desc = {\n      tag: 0x03,\n      id: bytes[0] << 8 | bytes[1],\n      flags: bytes[2],\n      size: 3,\n      dependsOnEsId: 0,\n      ocrEsId: 0,\n      descriptors: [],\n      url: ''\n    }; // depends on es id\n\n    if (desc.flags & 0x80) {\n      desc.dependsOnEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];\n      desc.size += 2;\n    } // url\n\n\n    if (desc.flags & 0x40) {\n      var len = bytes[desc.size];\n      desc.url = bytesToString(bytes.subarray(desc.size + 1, desc.size + 1 + len));\n      desc.size += len;\n    } // ocr es id\n\n\n    if (desc.flags & 0x20) {\n      desc.ocrEsId = bytes[desc.size] << 8 | bytes[desc.size + 1];\n      desc.size += 2;\n    }\n\n    desc.descriptors = parseDescriptors(bytes.subarray(desc.size)) || [];\n    return desc;\n  }\n}, {\n  id: 0x04,\n  parser: function parser(bytes) {\n    // DecoderConfigDescriptor\n    var desc = {\n      tag: 0x04,\n      oti: bytes[0],\n      streamType: bytes[1],\n      bufferSize: bytes[2] << 16 | bytes[3] << 8 | bytes[4],\n      maxBitrate: bytes[5] << 24 | bytes[6] << 16 | bytes[7] << 8 | bytes[8],\n      avgBitrate: bytes[9] << 24 | bytes[10] << 16 | bytes[11] << 8 | bytes[12],\n      descriptors: parseDescriptors(bytes.subarray(13))\n    };\n    return desc;\n  }\n}, {\n  id: 0x05,\n  parser: function parser(bytes) {\n    // DecoderSpecificInfo\n    return {\n      tag: 0x05,\n      bytes: bytes\n    };\n  }\n}, {\n  id: 0x06,\n  parser: function parser(bytes) {\n    // SLConfigDescriptor\n    return {\n      tag: 0x06,\n      bytes: bytes\n    };\n  }\n}];\n/**\n * find any number of boxes by name given a path to it in an iso bmff\n * such as mp4.\n *\n * @param {TypedArray} bytes\n *        bytes for the iso bmff to search for boxes in\n *\n * @param {Uint8Array[]|string[]|string|Uint8Array} name\n *        An array of paths or a single path representing the name\n *        of boxes to search through in bytes. Paths may be\n *        uint8 (character codes) or strings.\n *\n * @param {boolean} [complete=false]\n *        Should we search only for complete boxes on the final path.\n *        This is very useful when you do not want to get back partial boxes\n *        in the case of streaming files.\n *\n * @return {Uint8Array[]}\n *         An array of the end paths that we found.\n */\n\nexport var findBox = function findBox(bytes, paths, complete) {\n  if (complete === void 0) {\n    complete = false;\n  }\n\n  paths = normalizePaths(paths);\n  bytes = toUint8(bytes);\n  var results = [];\n\n  if (!paths.length) {\n    // short-circuit the search for empty paths\n    return results;\n  }\n\n  var i = 0;\n\n  while (i < bytes.length) {\n    var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;\n    var type = bytes.subarray(i + 4, i + 8); // invalid box format.\n\n    if (size === 0) {\n      break;\n    }\n\n    var end = i + size;\n\n    if (end > bytes.length) {\n      // this box is bigger than the number of bytes we have\n      // and complete is set, we cannot find any more boxes.\n      if (complete) {\n        break;\n      }\n\n      end = bytes.length;\n    }\n\n    var data = bytes.subarray(i + 8, end);\n\n    if (bytesMatch(type, paths[0])) {\n      if (paths.length === 1) {\n        // this is the end of the path and we've found the box we were\n        // looking for\n        results.push(data);\n      } else {\n        // recursively search for the next box along the path\n        results.push.apply(results, findBox(data, paths.slice(1), complete));\n      }\n    }\n\n    i = end;\n  } // we've finished searching all of bytes\n\n\n  return results;\n};\n/**\n * Search for a single matching box by name in an iso bmff format like\n * mp4. This function is useful for finding codec boxes which\n * can be placed arbitrarily in sample descriptions depending\n * on the version of the file or file type.\n *\n * @param {TypedArray} bytes\n *        bytes for the iso bmff to search for boxes in\n *\n * @param {string|Uint8Array} name\n *        The name of the box to find.\n *\n * @return {Uint8Array[]}\n *         a subarray of bytes representing the name boxed we found.\n */\n\nexport var findNamedBox = function findNamedBox(bytes, name) {\n  name = normalizePath(name);\n\n  if (!name.length) {\n    // short-circuit the search for empty paths\n    return bytes.subarray(bytes.length);\n  }\n\n  var i = 0;\n\n  while (i < bytes.length) {\n    if (bytesMatch(bytes.subarray(i, i + name.length), name)) {\n      var size = (bytes[i - 4] << 24 | bytes[i - 3] << 16 | bytes[i - 2] << 8 | bytes[i - 1]) >>> 0;\n      var end = size > 1 ? i + size : bytes.byteLength;\n      return bytes.subarray(i + 4, end);\n    }\n\n    i++;\n  } // we've finished searching all of bytes\n\n\n  return bytes.subarray(bytes.length);\n};\n\nvar parseSamples = function parseSamples(data, entrySize, parseEntry) {\n  if (entrySize === void 0) {\n    entrySize = 4;\n  }\n\n  if (parseEntry === void 0) {\n    parseEntry = function parseEntry(d) {\n      return bytesToNumber(d);\n    };\n  }\n\n  var entries = [];\n\n  if (!data || !data.length) {\n    return entries;\n  }\n\n  var entryCount = bytesToNumber(data.subarray(4, 8));\n\n  for (var i = 8; entryCount; i += entrySize, entryCount--) {\n    entries.push(parseEntry(data.subarray(i, i + entrySize)));\n  }\n\n  return entries;\n};\n\nexport var buildFrameTable = function buildFrameTable(stbl, timescale) {\n  var keySamples = parseSamples(findBox(stbl, ['stss'])[0]);\n  var chunkOffsets = parseSamples(findBox(stbl, ['stco'])[0]);\n  var timeToSamples = parseSamples(findBox(stbl, ['stts'])[0], 8, function (entry) {\n    return {\n      sampleCount: bytesToNumber(entry.subarray(0, 4)),\n      sampleDelta: bytesToNumber(entry.subarray(4, 8))\n    };\n  });\n  var samplesToChunks = parseSamples(findBox(stbl, ['stsc'])[0], 12, function (entry) {\n    return {\n      firstChunk: bytesToNumber(entry.subarray(0, 4)),\n      samplesPerChunk: bytesToNumber(entry.subarray(4, 8)),\n      sampleDescriptionIndex: bytesToNumber(entry.subarray(8, 12))\n    };\n  });\n  var stsz = findBox(stbl, ['stsz'])[0]; // stsz starts with a 4 byte sampleSize which we don't need\n\n  var sampleSizes = parseSamples(stsz && stsz.length && stsz.subarray(4) || null);\n  var frames = [];\n\n  for (var chunkIndex = 0; chunkIndex < chunkOffsets.length; chunkIndex++) {\n    var samplesInChunk = void 0;\n\n    for (var i = 0; i < samplesToChunks.length; i++) {\n      var sampleToChunk = samplesToChunks[i];\n      var isThisOne = chunkIndex + 1 >= sampleToChunk.firstChunk && (i + 1 >= samplesToChunks.length || chunkIndex + 1 < samplesToChunks[i + 1].firstChunk);\n\n      if (isThisOne) {\n        samplesInChunk = sampleToChunk.samplesPerChunk;\n        break;\n      }\n    }\n\n    var chunkOffset = chunkOffsets[chunkIndex];\n\n    for (var _i = 0; _i < samplesInChunk; _i++) {\n      var frameEnd = sampleSizes[frames.length]; // if we don't have key samples every frame is a keyframe\n\n      var keyframe = !keySamples.length;\n\n      if (keySamples.length && keySamples.indexOf(frames.length + 1) !== -1) {\n        keyframe = true;\n      }\n\n      var frame = {\n        keyframe: keyframe,\n        start: chunkOffset,\n        end: chunkOffset + frameEnd\n      };\n\n      for (var k = 0; k < timeToSamples.length; k++) {\n        var _timeToSamples$k = timeToSamples[k],\n            sampleCount = _timeToSamples$k.sampleCount,\n            sampleDelta = _timeToSamples$k.sampleDelta;\n\n        if (frames.length <= sampleCount) {\n          // ms to ns\n          var lastTimestamp = frames.length ? frames[frames.length - 1].timestamp : 0;\n          frame.timestamp = lastTimestamp + sampleDelta / timescale * 1000;\n          frame.duration = sampleDelta;\n          break;\n        }\n      }\n\n      frames.push(frame);\n      chunkOffset += frameEnd;\n    }\n  }\n\n  return frames;\n};\nexport var addSampleDescription = function addSampleDescription(track, bytes) {\n  var codec = bytesToString(bytes.subarray(0, 4));\n\n  if (track.type === 'video') {\n    track.info = track.info || {};\n    track.info.width = bytes[28] << 8 | bytes[29];\n    track.info.height = bytes[30] << 8 | bytes[31];\n  } else if (track.type === 'audio') {\n    track.info = track.info || {};\n    track.info.channels = bytes[20] << 8 | bytes[21];\n    track.info.bitDepth = bytes[22] << 8 | bytes[23];\n    track.info.sampleRate = bytes[28] << 8 | bytes[29];\n  }\n\n  if (codec === 'avc1') {\n    var avcC = findNamedBox(bytes, 'avcC'); // AVCDecoderConfigurationRecord\n\n    codec += \".\" + getAvcCodec(avcC);\n    track.info.avcC = avcC; // TODO: do we need to parse all this?\n\n    /* {\n      configurationVersion: avcC[0],\n      profile: avcC[1],\n      profileCompatibility: avcC[2],\n      level: avcC[3],\n      lengthSizeMinusOne: avcC[4] & 0x3\n    };\n     let spsNalUnitCount = avcC[5] & 0x1F;\n    const spsNalUnits = track.info.avc.spsNalUnits = [];\n     // past spsNalUnitCount\n    let offset = 6;\n     while (spsNalUnitCount--) {\n      const nalLen = avcC[offset] << 8 | avcC[offset + 1];\n       spsNalUnits.push(avcC.subarray(offset + 2, offset + 2 + nalLen));\n       offset += nalLen + 2;\n    }\n    let ppsNalUnitCount = avcC[offset];\n    const ppsNalUnits = track.info.avc.ppsNalUnits = [];\n     // past ppsNalUnitCount\n    offset += 1;\n     while (ppsNalUnitCount--) {\n      const nalLen = avcC[offset] << 8 | avcC[offset + 1];\n       ppsNalUnits.push(avcC.subarray(offset + 2, offset + 2 + nalLen));\n       offset += nalLen + 2;\n    }*/\n    // HEVCDecoderConfigurationRecord\n  } else if (codec === 'hvc1' || codec === 'hev1') {\n    codec += \".\" + getHvcCodec(findNamedBox(bytes, 'hvcC'));\n  } else if (codec === 'mp4a' || codec === 'mp4v') {\n    var esds = findNamedBox(bytes, 'esds');\n    var esDescriptor = parseDescriptors(esds.subarray(4))[0];\n    var decoderConfig = esDescriptor && esDescriptor.descriptors.filter(function (_ref) {\n      var tag = _ref.tag;\n      return tag === 0x04;\n    })[0];\n\n    if (decoderConfig) {\n      // most codecs do not have a further '.'\n      // such as 0xa5 for ac-3 and 0xa6 for e-ac-3\n      codec += '.' + toHexString(decoderConfig.oti);\n\n      if (decoderConfig.oti === 0x40) {\n        codec += '.' + (decoderConfig.descriptors[0].bytes[0] >> 3).toString();\n      } else if (decoderConfig.oti === 0x20) {\n        codec += '.' + decoderConfig.descriptors[0].bytes[4].toString();\n      } else if (decoderConfig.oti === 0xdd) {\n        codec = 'vorbis';\n      }\n    } else if (track.type === 'audio') {\n      codec += '.40.2';\n    } else {\n      codec += '.20.9';\n    }\n  } else if (codec === 'av01') {\n    // AV1DecoderConfigurationRecord\n    codec += \".\" + getAv1Codec(findNamedBox(bytes, 'av1C'));\n  } else if (codec === 'vp09') {\n    // VPCodecConfigurationRecord\n    var vpcC = findNamedBox(bytes, 'vpcC'); // https://www.webmproject.org/vp9/mp4/\n\n    var profile = vpcC[0];\n    var level = vpcC[1];\n    var bitDepth = vpcC[2] >> 4;\n    var chromaSubsampling = (vpcC[2] & 0x0F) >> 1;\n    var videoFullRangeFlag = (vpcC[2] & 0x0F) >> 3;\n    var colourPrimaries = vpcC[3];\n    var transferCharacteristics = vpcC[4];\n    var matrixCoefficients = vpcC[5];\n    codec += \".\" + padStart(profile, 2, '0');\n    codec += \".\" + padStart(level, 2, '0');\n    codec += \".\" + padStart(bitDepth, 2, '0');\n    codec += \".\" + padStart(chromaSubsampling, 2, '0');\n    codec += \".\" + padStart(colourPrimaries, 2, '0');\n    codec += \".\" + padStart(transferCharacteristics, 2, '0');\n    codec += \".\" + padStart(matrixCoefficients, 2, '0');\n    codec += \".\" + padStart(videoFullRangeFlag, 2, '0');\n  } else if (codec === 'theo') {\n    codec = 'theora';\n  } else if (codec === 'spex') {\n    codec = 'speex';\n  } else if (codec === '.mp3') {\n    codec = 'mp4a.40.34';\n  } else if (codec === 'msVo') {\n    codec = 'vorbis';\n  } else if (codec === 'Opus') {\n    codec = 'opus';\n    var dOps = findNamedBox(bytes, 'dOps');\n    track.info.opus = parseOpusHead(dOps); // TODO: should this go into the webm code??\n    // Firefox requires a codecDelay for opus playback\n    // see https://bugzilla.mozilla.org/show_bug.cgi?id=1276238\n\n    track.info.codecDelay = 6500000;\n  } else {\n    codec = codec.toLowerCase();\n  }\n  /* eslint-enable */\n  // flac, ac-3, ec-3, opus\n\n\n  track.codec = codec;\n};\nexport var parseTracks = function parseTracks(bytes, frameTable) {\n  if (frameTable === void 0) {\n    frameTable = true;\n  }\n\n  bytes = toUint8(bytes);\n  var traks = findBox(bytes, ['moov', 'trak'], true);\n  var tracks = [];\n  traks.forEach(function (trak) {\n    var track = {\n      bytes: trak\n    };\n    var mdia = findBox(trak, ['mdia'])[0];\n    var hdlr = findBox(mdia, ['hdlr'])[0];\n    var trakType = bytesToString(hdlr.subarray(8, 12));\n\n    if (trakType === 'soun') {\n      track.type = 'audio';\n    } else if (trakType === 'vide') {\n      track.type = 'video';\n    } else {\n      track.type = trakType;\n    }\n\n    var tkhd = findBox(trak, ['tkhd'])[0];\n\n    if (tkhd) {\n      var view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);\n      var tkhdVersion = view.getUint8(0);\n      track.number = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);\n    }\n\n    var mdhd = findBox(mdia, ['mdhd'])[0];\n\n    if (mdhd) {\n      // mdhd is a FullBox, meaning it will have its own version as the first byte\n      var version = mdhd[0];\n      var index = version === 0 ? 12 : 20;\n      track.timescale = (mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]) >>> 0;\n    }\n\n    var stbl = findBox(mdia, ['minf', 'stbl'])[0];\n    var stsd = findBox(stbl, ['stsd'])[0];\n    var descriptionCount = bytesToNumber(stsd.subarray(4, 8));\n    var offset = 8; // add codec and codec info\n\n    while (descriptionCount--) {\n      var len = bytesToNumber(stsd.subarray(offset, offset + 4));\n      var sampleDescriptor = stsd.subarray(offset + 4, offset + 4 + len);\n      addSampleDescription(track, sampleDescriptor);\n      offset += 4 + len;\n    }\n\n    if (frameTable) {\n      track.frameTable = buildFrameTable(stbl, track.timescale);\n    } // codec has no sub parameters\n\n\n    tracks.push(track);\n  });\n  return tracks;\n};\nexport var parseMediaInfo = function parseMediaInfo(bytes) {\n  var mvhd = findBox(bytes, ['moov', 'mvhd'], true)[0];\n\n  if (!mvhd || !mvhd.length) {\n    return;\n  }\n\n  var info = {}; // ms to ns\n  // mvhd v1 has 8 byte duration and other fields too\n\n  if (mvhd[0] === 1) {\n    info.timestampScale = bytesToNumber(mvhd.subarray(20, 24));\n    info.duration = bytesToNumber(mvhd.subarray(24, 32));\n  } else {\n    info.timestampScale = bytesToNumber(mvhd.subarray(12, 16));\n    info.duration = bytesToNumber(mvhd.subarray(16, 20));\n  }\n\n  info.bytes = mvhd;\n  return info;\n};","import { toUint8, bytesToNumber, bytesMatch, bytesToString, numberToBytes, padStart } from './byte-helpers';\nimport { getAvcCodec, getHvcCodec, getAv1Codec } from './codec-helpers.js'; // relevant specs for this parser:\n// https://matroska-org.github.io/libebml/specs.html\n// https://www.matroska.org/technical/elements.html\n// https://www.webmproject.org/docs/container/\n\nexport var EBML_TAGS = {\n  EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),\n  DocType: toUint8([0x42, 0x82]),\n  Segment: toUint8([0x18, 0x53, 0x80, 0x67]),\n  SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),\n  Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),\n  Track: toUint8([0xAE]),\n  TrackNumber: toUint8([0xd7]),\n  DefaultDuration: toUint8([0x23, 0xe3, 0x83]),\n  TrackEntry: toUint8([0xAE]),\n  TrackType: toUint8([0x83]),\n  FlagDefault: toUint8([0x88]),\n  CodecID: toUint8([0x86]),\n  CodecPrivate: toUint8([0x63, 0xA2]),\n  VideoTrack: toUint8([0xe0]),\n  AudioTrack: toUint8([0xe1]),\n  // Not used yet, but will be used for live webm/mkv\n  // see https://www.matroska.org/technical/basics.html#block-structure\n  // see https://www.matroska.org/technical/basics.html#simpleblock-structure\n  Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),\n  Timestamp: toUint8([0xE7]),\n  TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),\n  BlockGroup: toUint8([0xA0]),\n  BlockDuration: toUint8([0x9B]),\n  Block: toUint8([0xA1]),\n  SimpleBlock: toUint8([0xA3])\n};\n/**\n * This is a simple table to determine the length\n * of things in ebml. The length is one based (starts at 1,\n * rather than zero) and for every zero bit before a one bit\n * we add one to length. We also need this table because in some\n * case we have to xor all the length bits from another value.\n */\n\nvar LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];\n\nvar getLength = function getLength(byte) {\n  var len = 1;\n\n  for (var i = 0; i < LENGTH_TABLE.length; i++) {\n    if (byte & LENGTH_TABLE[i]) {\n      break;\n    }\n\n    len++;\n  }\n\n  return len;\n}; // length in ebml is stored in the first 4 to 8 bits\n// of the first byte. 4 for the id length and 8 for the\n// data size length. Length is measured by converting the number to binary\n// then 1 + the number of zeros before a 1 is encountered starting\n// from the left.\n\n\nvar getvint = function getvint(bytes, offset, removeLength, signed) {\n  if (removeLength === void 0) {\n    removeLength = true;\n  }\n\n  if (signed === void 0) {\n    signed = false;\n  }\n\n  var length = getLength(bytes[offset]);\n  var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes\n  // as they will be modified below to remove the dataSizeLen bits and we do not\n  // want to modify the original data. normally we could just call slice on\n  // uint8array but ie 11 does not support that...\n\n  if (removeLength) {\n    valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);\n    valueBytes[0] ^= LENGTH_TABLE[length - 1];\n  }\n\n  return {\n    length: length,\n    value: bytesToNumber(valueBytes, {\n      signed: signed\n    }),\n    bytes: valueBytes\n  };\n};\n\nvar normalizePath = function normalizePath(path) {\n  if (typeof path === 'string') {\n    return path.match(/.{1,2}/g).map(function (p) {\n      return normalizePath(p);\n    });\n  }\n\n  if (typeof path === 'number') {\n    return numberToBytes(path);\n  }\n\n  return path;\n};\n\nvar normalizePaths = function normalizePaths(paths) {\n  if (!Array.isArray(paths)) {\n    return [normalizePath(paths)];\n  }\n\n  return paths.map(function (p) {\n    return normalizePath(p);\n  });\n};\n\nvar getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {\n  if (offset >= bytes.length) {\n    return bytes.length;\n  }\n\n  var innerid = getvint(bytes, offset, false);\n\n  if (bytesMatch(id.bytes, innerid.bytes)) {\n    return offset;\n  }\n\n  var dataHeader = getvint(bytes, offset + innerid.length);\n  return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);\n};\n/**\n * Notes on the EBLM format.\n *\n * EBLM uses \"vints\" tags. Every vint tag contains\n * two parts\n *\n * 1. The length from the first byte. You get this by\n *    converting the byte to binary and counting the zeros\n *    before a 1. Then you add 1 to that. Examples\n *    00011111 = length 4 because there are 3 zeros before a 1.\n *    00100000 = length 3 because there are 2 zeros before a 1.\n *    00000011 = length 7 because there are 6 zeros before a 1.\n *\n * 2. The bits used for length are removed from the first byte\n *    Then all the bytes are merged into a value. NOTE: this\n *    is not the case for id ebml tags as there id includes\n *    length bits.\n *\n */\n\n\nexport var findEbml = function findEbml(bytes, paths) {\n  paths = normalizePaths(paths);\n  bytes = toUint8(bytes);\n  var results = [];\n\n  if (!paths.length) {\n    return results;\n  }\n\n  var i = 0;\n\n  while (i < bytes.length) {\n    var id = getvint(bytes, i, false);\n    var dataHeader = getvint(bytes, i + id.length);\n    var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream\n\n    if (dataHeader.value === 0x7f) {\n      dataHeader.value = getInfinityDataSize(id, bytes, dataStart);\n\n      if (dataHeader.value !== bytes.length) {\n        dataHeader.value -= dataStart;\n      }\n    }\n\n    var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;\n    var data = bytes.subarray(dataStart, dataEnd);\n\n    if (bytesMatch(paths[0], id.bytes)) {\n      if (paths.length === 1) {\n        // this is the end of the paths and we've found the tag we were\n        // looking for\n        results.push(data);\n      } else {\n        // recursively search for the next tag inside of the data\n        // of this one\n        results = results.concat(findEbml(data, paths.slice(1)));\n      }\n    }\n\n    var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it\n\n    i += totalLength;\n  }\n\n  return results;\n}; // see https://www.matroska.org/technical/basics.html#block-structure\n\nexport var decodeBlock = function decodeBlock(block, type, timestampScale, clusterTimestamp) {\n  var duration;\n\n  if (type === 'group') {\n    duration = findEbml(block, [EBML_TAGS.BlockDuration])[0];\n\n    if (duration) {\n      duration = bytesToNumber(duration);\n      duration = 1 / timestampScale * duration * timestampScale / 1000;\n    }\n\n    block = findEbml(block, [EBML_TAGS.Block])[0];\n    type = 'block'; // treat data as a block after this point\n  }\n\n  var dv = new DataView(block.buffer, block.byteOffset, block.byteLength);\n  var trackNumber = getvint(block, 0);\n  var timestamp = dv.getInt16(trackNumber.length, false);\n  var flags = block[trackNumber.length + 2];\n  var data = block.subarray(trackNumber.length + 3); // pts/dts in seconds\n\n  var ptsdts = 1 / timestampScale * (clusterTimestamp + timestamp) * timestampScale / 1000; // return the frame\n\n  var parsed = {\n    duration: duration,\n    trackNumber: trackNumber.value,\n    keyframe: type === 'simple' && flags >> 7 === 1,\n    invisible: (flags & 0x08) >> 3 === 1,\n    lacing: (flags & 0x06) >> 1,\n    discardable: type === 'simple' && (flags & 0x01) === 1,\n    frames: [],\n    pts: ptsdts,\n    dts: ptsdts,\n    timestamp: timestamp\n  };\n\n  if (!parsed.lacing) {\n    parsed.frames.push(data);\n    return parsed;\n  }\n\n  var numberOfFrames = data[0] + 1;\n  var frameSizes = [];\n  var offset = 1; // Fixed\n\n  if (parsed.lacing === 2) {\n    var sizeOfFrame = (data.length - offset) / numberOfFrames;\n\n    for (var i = 0; i < numberOfFrames; i++) {\n      frameSizes.push(sizeOfFrame);\n    }\n  } // xiph\n\n\n  if (parsed.lacing === 1) {\n    for (var _i = 0; _i < numberOfFrames - 1; _i++) {\n      var size = 0;\n\n      do {\n        size += data[offset];\n        offset++;\n      } while (data[offset - 1] === 0xFF);\n\n      frameSizes.push(size);\n    }\n  } // ebml\n\n\n  if (parsed.lacing === 3) {\n    // first vint is unsinged\n    // after that vints are singed and\n    // based on a compounding size\n    var _size = 0;\n\n    for (var _i2 = 0; _i2 < numberOfFrames - 1; _i2++) {\n      var vint = _i2 === 0 ? getvint(data, offset) : getvint(data, offset, true, true);\n      _size += vint.value;\n      frameSizes.push(_size);\n      offset += vint.length;\n    }\n  }\n\n  frameSizes.forEach(function (size) {\n    parsed.frames.push(data.subarray(offset, offset + size));\n    offset += size;\n  });\n  return parsed;\n}; // VP9 Codec Feature Metadata (CodecPrivate)\n// https://www.webmproject.org/docs/container/\n\nvar parseVp9Private = function parseVp9Private(bytes) {\n  var i = 0;\n  var params = {};\n\n  while (i < bytes.length) {\n    var id = bytes[i] & 0x7f;\n    var len = bytes[i + 1];\n    var val = void 0;\n\n    if (len === 1) {\n      val = bytes[i + 2];\n    } else {\n      val = bytes.subarray(i + 2, i + 2 + len);\n    }\n\n    if (id === 1) {\n      params.profile = val;\n    } else if (id === 2) {\n      params.level = val;\n    } else if (id === 3) {\n      params.bitDepth = val;\n    } else if (id === 4) {\n      params.chromaSubsampling = val;\n    } else {\n      params[id] = val;\n    }\n\n    i += 2 + len;\n  }\n\n  return params;\n};\n\nexport var parseTracks = function parseTracks(bytes) {\n  bytes = toUint8(bytes);\n  var decodedTracks = [];\n  var tracks = findEbml(bytes, [EBML_TAGS.Segment, EBML_TAGS.Tracks, EBML_TAGS.Track]);\n\n  if (!tracks.length) {\n    tracks = findEbml(bytes, [EBML_TAGS.Tracks, EBML_TAGS.Track]);\n  }\n\n  if (!tracks.length) {\n    tracks = findEbml(bytes, [EBML_TAGS.Track]);\n  }\n\n  if (!tracks.length) {\n    return decodedTracks;\n  }\n\n  tracks.forEach(function (track) {\n    var trackType = findEbml(track, EBML_TAGS.TrackType)[0];\n\n    if (!trackType || !trackType.length) {\n      return;\n    } // 1 is video, 2 is audio, 17 is subtitle\n    // other values are unimportant in this context\n\n\n    if (trackType[0] === 1) {\n      trackType = 'video';\n    } else if (trackType[0] === 2) {\n      trackType = 'audio';\n    } else if (trackType[0] === 17) {\n      trackType = 'subtitle';\n    } else {\n      return;\n    } // todo parse language\n\n\n    var decodedTrack = {\n      rawCodec: bytesToString(findEbml(track, [EBML_TAGS.CodecID])[0]),\n      type: trackType,\n      codecPrivate: findEbml(track, [EBML_TAGS.CodecPrivate])[0],\n      number: bytesToNumber(findEbml(track, [EBML_TAGS.TrackNumber])[0]),\n      defaultDuration: bytesToNumber(findEbml(track, [EBML_TAGS.DefaultDuration])[0]),\n      default: findEbml(track, [EBML_TAGS.FlagDefault])[0],\n      rawData: track\n    };\n    var codec = '';\n\n    if (/V_MPEG4\\/ISO\\/AVC/.test(decodedTrack.rawCodec)) {\n      codec = \"avc1.\" + getAvcCodec(decodedTrack.codecPrivate);\n    } else if (/V_MPEGH\\/ISO\\/HEVC/.test(decodedTrack.rawCodec)) {\n      codec = \"hev1.\" + getHvcCodec(decodedTrack.codecPrivate);\n    } else if (/V_MPEG4\\/ISO\\/ASP/.test(decodedTrack.rawCodec)) {\n      if (decodedTrack.codecPrivate) {\n        codec = 'mp4v.20.' + decodedTrack.codecPrivate[4].toString();\n      } else {\n        codec = 'mp4v.20.9';\n      }\n    } else if (/^V_THEORA/.test(decodedTrack.rawCodec)) {\n      codec = 'theora';\n    } else if (/^V_VP8/.test(decodedTrack.rawCodec)) {\n      codec = 'vp8';\n    } else if (/^V_VP9/.test(decodedTrack.rawCodec)) {\n      if (decodedTrack.codecPrivate) {\n        var _parseVp9Private = parseVp9Private(decodedTrack.codecPrivate),\n            profile = _parseVp9Private.profile,\n            level = _parseVp9Private.level,\n            bitDepth = _parseVp9Private.bitDepth,\n            chromaSubsampling = _parseVp9Private.chromaSubsampling;\n\n        codec = 'vp09.';\n        codec += padStart(profile, 2, '0') + \".\";\n        codec += padStart(level, 2, '0') + \".\";\n        codec += padStart(bitDepth, 2, '0') + \".\";\n        codec += \"\" + padStart(chromaSubsampling, 2, '0'); // Video -> Colour -> Ebml name\n\n        var matrixCoefficients = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xB1]])[0] || [];\n        var videoFullRangeFlag = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xB9]])[0] || [];\n        var transferCharacteristics = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xBA]])[0] || [];\n        var colourPrimaries = findEbml(track, [0xE0, [0x55, 0xB0], [0x55, 0xBB]])[0] || []; // if we find any optional codec parameter specify them all.\n\n        if (matrixCoefficients.length || videoFullRangeFlag.length || transferCharacteristics.length || colourPrimaries.length) {\n          codec += \".\" + padStart(colourPrimaries[0], 2, '0');\n          codec += \".\" + padStart(transferCharacteristics[0], 2, '0');\n          codec += \".\" + padStart(matrixCoefficients[0], 2, '0');\n          codec += \".\" + padStart(videoFullRangeFlag[0], 2, '0');\n        }\n      } else {\n        codec = 'vp9';\n      }\n    } else if (/^V_AV1/.test(decodedTrack.rawCodec)) {\n      codec = \"av01.\" + getAv1Codec(decodedTrack.codecPrivate);\n    } else if (/A_ALAC/.test(decodedTrack.rawCodec)) {\n      codec = 'alac';\n    } else if (/A_MPEG\\/L2/.test(decodedTrack.rawCodec)) {\n      codec = 'mp2';\n    } else if (/A_MPEG\\/L3/.test(decodedTrack.rawCodec)) {\n      codec = 'mp3';\n    } else if (/^A_AAC/.test(decodedTrack.rawCodec)) {\n      if (decodedTrack.codecPrivate) {\n        codec = 'mp4a.40.' + (decodedTrack.codecPrivate[0] >>> 3).toString();\n      } else {\n        codec = 'mp4a.40.2';\n      }\n    } else if (/^A_AC3/.test(decodedTrack.rawCodec)) {\n      codec = 'ac-3';\n    } else if (/^A_PCM/.test(decodedTrack.rawCodec)) {\n      codec = 'pcm';\n    } else if (/^A_MS\\/ACM/.test(decodedTrack.rawCodec)) {\n      codec = 'speex';\n    } else if (/^A_EAC3/.test(decodedTrack.rawCodec)) {\n      codec = 'ec-3';\n    } else if (/^A_VORBIS/.test(decodedTrack.rawCodec)) {\n      codec = 'vorbis';\n    } else if (/^A_FLAC/.test(decodedTrack.rawCodec)) {\n      codec = 'flac';\n    } else if (/^A_OPUS/.test(decodedTrack.rawCodec)) {\n      codec = 'opus';\n    }\n\n    decodedTrack.codec = codec;\n    decodedTracks.push(decodedTrack);\n  });\n  return decodedTracks.sort(function (a, b) {\n    return a.number - b.number;\n  });\n};\nexport var parseData = function parseData(data, tracks) {\n  var allBlocks = [];\n  var segment = findEbml(data, [EBML_TAGS.Segment])[0];\n  var timestampScale = findEbml(segment, [EBML_TAGS.SegmentInfo, EBML_TAGS.TimestampScale])[0]; // in nanoseconds, defaults to 1ms\n\n  if (timestampScale && timestampScale.length) {\n    timestampScale = bytesToNumber(timestampScale);\n  } else {\n    timestampScale = 1000000;\n  }\n\n  var clusters = findEbml(segment, [EBML_TAGS.Cluster]);\n\n  if (!tracks) {\n    tracks = parseTracks(segment);\n  }\n\n  clusters.forEach(function (cluster, ci) {\n    var simpleBlocks = findEbml(cluster, [EBML_TAGS.SimpleBlock]).map(function (b) {\n      return {\n        type: 'simple',\n        data: b\n      };\n    });\n    var blockGroups = findEbml(cluster, [EBML_TAGS.BlockGroup]).map(function (b) {\n      return {\n        type: 'group',\n        data: b\n      };\n    });\n    var timestamp = findEbml(cluster, [EBML_TAGS.Timestamp])[0] || 0;\n\n    if (timestamp && timestamp.length) {\n      timestamp = bytesToNumber(timestamp);\n    } // get all blocks then sort them into the correct order\n\n\n    var blocks = simpleBlocks.concat(blockGroups).sort(function (a, b) {\n      return a.data.byteOffset - b.data.byteOffset;\n    });\n    blocks.forEach(function (block, bi) {\n      var decoded = decodeBlock(block.data, block.type, timestampScale, timestamp);\n      allBlocks.push(decoded);\n    });\n  });\n  return {\n    tracks: tracks,\n    blocks: allBlocks\n  };\n};","import { bytesMatch, toUint8 } from './byte-helpers.js';\nexport var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);\nexport var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);\nexport var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);\n/**\n * Expunge any \"Emulation Prevention\" bytes from a \"Raw Byte\n * Sequence Payload\"\n *\n * @param data {Uint8Array} the bytes of a RBSP from a NAL\n * unit\n * @return {Uint8Array} the RBSP without any Emulation\n * Prevention Bytes\n */\n\nexport var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {\n  var positions = [];\n  var i = 1; // Find all `Emulation Prevention Bytes`\n\n  while (i < bytes.length - 2) {\n    if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {\n      positions.push(i + 2);\n      i++;\n    }\n\n    i++;\n  } // If no Emulation Prevention Bytes were found just return the original\n  // array\n\n\n  if (positions.length === 0) {\n    return bytes;\n  } // Create a new array to hold the NAL unit data\n\n\n  var newLength = bytes.length - positions.length;\n  var newData = new Uint8Array(newLength);\n  var sourceIndex = 0;\n\n  for (i = 0; i < newLength; sourceIndex++, i++) {\n    if (sourceIndex === positions[0]) {\n      // Skip this byte\n      sourceIndex++; // Remove this position index\n\n      positions.shift();\n    }\n\n    newData[i] = bytes[sourceIndex];\n  }\n\n  return newData;\n};\nexport var findNal = function findNal(bytes, dataType, types, nalLimit) {\n  if (nalLimit === void 0) {\n    nalLimit = Infinity;\n  }\n\n  bytes = toUint8(bytes);\n  types = [].concat(types);\n  var i = 0;\n  var nalStart;\n  var nalsFound = 0; // keep searching until:\n  // we reach the end of bytes\n  // we reach the maximum number of nals they want to seach\n  // NOTE: that we disregard nalLimit when we have found the start\n  // of the nal we want so that we can find the end of the nal we want.\n\n  while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {\n    var nalOffset = void 0;\n\n    if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {\n      nalOffset = 4;\n    } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {\n      nalOffset = 3;\n    } // we are unsynced,\n    // find the next nal unit\n\n\n    if (!nalOffset) {\n      i++;\n      continue;\n    }\n\n    nalsFound++;\n\n    if (nalStart) {\n      return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));\n    }\n\n    var nalType = void 0;\n\n    if (dataType === 'h264') {\n      nalType = bytes[i + nalOffset] & 0x1f;\n    } else if (dataType === 'h265') {\n      nalType = bytes[i + nalOffset] >> 1 & 0x3f;\n    }\n\n    if (types.indexOf(nalType) !== -1) {\n      nalStart = i + nalOffset;\n    } // nal header is 1 length for h264, and 2 for h265\n\n\n    i += nalOffset + (dataType === 'h264' ? 1 : 2);\n  }\n\n  return bytes.subarray(0, 0);\n};\nexport var findH264Nal = function findH264Nal(bytes, type, nalLimit) {\n  return findNal(bytes, 'h264', type, nalLimit);\n};\nexport var findH265Nal = function findH265Nal(bytes, type, nalLimit) {\n  return findNal(bytes, 'h265', type, nalLimit);\n};","import { toUint8, bytesMatch } from './byte-helpers.js';\nimport { findBox } from './mp4-helpers.js';\nimport { findEbml, EBML_TAGS } from './ebml-helpers.js';\nimport { getId3Offset } from './id3-helpers.js';\nimport { findH264Nal, findH265Nal } from './nal-helpers.js';\nvar CONSTANTS = {\n  // \"webm\" string literal in hex\n  'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),\n  // \"matroska\" string literal in hex\n  'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),\n  // \"fLaC\" string literal in hex\n  'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),\n  // \"OggS\" string literal in hex\n  'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),\n  // ac-3 sync byte, also works for ec-3 as that is simply a codec\n  // of ac-3\n  'ac3': toUint8([0x0b, 0x77]),\n  // \"RIFF\" string literal in hex used for wav and avi\n  'riff': toUint8([0x52, 0x49, 0x46, 0x46]),\n  // \"AVI\" string literal in hex\n  'avi': toUint8([0x41, 0x56, 0x49]),\n  // \"WAVE\" string literal in hex\n  'wav': toUint8([0x57, 0x41, 0x56, 0x45]),\n  // \"ftyp3g\" string literal in hex\n  '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),\n  // \"ftyp\" string literal in hex\n  'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),\n  // \"styp\" string literal in hex\n  'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),\n  // \"ftypqt\" string literal in hex\n  'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74]),\n  // moov string literal in hex\n  'moov': toUint8([0x6D, 0x6F, 0x6F, 0x76]),\n  // moof string literal in hex\n  'moof': toUint8([0x6D, 0x6F, 0x6F, 0x66])\n};\nvar _isLikely = {\n  aac: function aac(bytes) {\n    var offset = getId3Offset(bytes);\n    return bytesMatch(bytes, [0xFF, 0x10], {\n      offset: offset,\n      mask: [0xFF, 0x16]\n    });\n  },\n  mp3: function mp3(bytes) {\n    var offset = getId3Offset(bytes);\n    return bytesMatch(bytes, [0xFF, 0x02], {\n      offset: offset,\n      mask: [0xFF, 0x06]\n    });\n  },\n  webm: function webm(bytes) {\n    var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm\n\n    return bytesMatch(docType, CONSTANTS.webm);\n  },\n  mkv: function mkv(bytes) {\n    var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska\n\n    return bytesMatch(docType, CONSTANTS.matroska);\n  },\n  mp4: function mp4(bytes) {\n    // if this file is another base media file format, it is not mp4\n    if (_isLikely['3gp'](bytes) || _isLikely.mov(bytes)) {\n      return false;\n    } // if this file starts with a ftyp or styp box its mp4\n\n\n    if (bytesMatch(bytes, CONSTANTS.mp4, {\n      offset: 4\n    }) || bytesMatch(bytes, CONSTANTS.fmp4, {\n      offset: 4\n    })) {\n      return true;\n    } // if this file starts with a moof/moov box its mp4\n\n\n    if (bytesMatch(bytes, CONSTANTS.moof, {\n      offset: 4\n    }) || bytesMatch(bytes, CONSTANTS.moov, {\n      offset: 4\n    })) {\n      return true;\n    }\n  },\n  mov: function mov(bytes) {\n    return bytesMatch(bytes, CONSTANTS.mov, {\n      offset: 4\n    });\n  },\n  '3gp': function gp(bytes) {\n    return bytesMatch(bytes, CONSTANTS['3gp'], {\n      offset: 4\n    });\n  },\n  ac3: function ac3(bytes) {\n    var offset = getId3Offset(bytes);\n    return bytesMatch(bytes, CONSTANTS.ac3, {\n      offset: offset\n    });\n  },\n  ts: function ts(bytes) {\n    if (bytes.length < 189 && bytes.length >= 1) {\n      return bytes[0] === 0x47;\n    }\n\n    var i = 0; // check the first 376 bytes for two matching sync bytes\n\n    while (i + 188 < bytes.length && i < 188) {\n      if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {\n        return true;\n      }\n\n      i += 1;\n    }\n\n    return false;\n  },\n  flac: function flac(bytes) {\n    var offset = getId3Offset(bytes);\n    return bytesMatch(bytes, CONSTANTS.flac, {\n      offset: offset\n    });\n  },\n  ogg: function ogg(bytes) {\n    return bytesMatch(bytes, CONSTANTS.ogg);\n  },\n  avi: function avi(bytes) {\n    return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {\n      offset: 8\n    });\n  },\n  wav: function wav(bytes) {\n    return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {\n      offset: 8\n    });\n  },\n  'h264': function h264(bytes) {\n    // find seq_parameter_set_rbsp\n    return findH264Nal(bytes, 7, 3).length;\n  },\n  'h265': function h265(bytes) {\n    // find video_parameter_set_rbsp or seq_parameter_set_rbsp\n    return findH265Nal(bytes, [32, 33], 3).length;\n  }\n}; // get all the isLikely functions\n// but make sure 'ts' is above h264 and h265\n// but below everything else as it is the least specific\n\nvar isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265\n.filter(function (t) {\n  return t !== 'ts' && t !== 'h264' && t !== 'h265';\n}) // add it back to the bottom\n.concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.\n\nisLikelyTypes.forEach(function (type) {\n  var isLikelyFn = _isLikely[type];\n\n  _isLikely[type] = function (bytes) {\n    return isLikelyFn(toUint8(bytes));\n  };\n}); // export after wrapping\n\nexport var isLikely = _isLikely; // A useful list of file signatures can be found here\n// https://en.wikipedia.org/wiki/List_of_file_signatures\n\nexport var detectContainerForBytes = function detectContainerForBytes(bytes) {\n  bytes = toUint8(bytes);\n\n  for (var i = 0; i < isLikelyTypes.length; i++) {\n    var type = isLikelyTypes[i];\n\n    if (isLikely[type](bytes)) {\n      return type;\n    }\n  }\n\n  return '';\n}; // fmp4 is not a container\n\nexport var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {\n  return findBox(bytes, ['moof']).length > 0;\n};","/**\n * mux.js\n *\n * Copyright (c) Brightcove\n * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n */\nvar\n  ONE_SECOND_IN_TS = 90000, // 90kHz clock\n  secondsToVideoTs,\n  secondsToAudioTs,\n  videoTsToSeconds,\n  audioTsToSeconds,\n  audioTsToVideoTs,\n  videoTsToAudioTs,\n  metadataTsToSeconds;\n\nsecondsToVideoTs = function(seconds) {\n  return seconds * ONE_SECOND_IN_TS;\n};\n\nsecondsToAudioTs = function(seconds, sampleRate) {\n  return seconds * sampleRate;\n};\n\nvideoTsToSeconds = function(timestamp) {\n  return timestamp / ONE_SECOND_IN_TS;\n};\n\naudioTsToSeconds = function(timestamp, sampleRate) {\n  return timestamp / sampleRate;\n};\n\naudioTsToVideoTs = function(timestamp, sampleRate) {\n  return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));\n};\n\nvideoTsToAudioTs = function(timestamp, sampleRate) {\n  return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);\n};\n\n/**\n * Adjust ID3 tag or caption timing information by the timeline pts values\n * (if keepOriginalTimestamps is false) and convert to seconds\n */\nmetadataTsToSeconds = function(timestamp, timelineStartPts, keepOriginalTimestamps) {\n  return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);\n};\n\nmodule.exports = {\n  ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,\n  secondsToVideoTs: secondsToVideoTs,\n  secondsToAudioTs: secondsToAudioTs,\n  videoTsToSeconds: videoTsToSeconds,\n  audioTsToSeconds: audioTsToSeconds,\n  audioTsToVideoTs: audioTsToVideoTs,\n  videoTsToAudioTs: videoTsToAudioTs,\n  metadataTsToSeconds: metadataTsToSeconds\n};\n","/**\n * @license\n * Video.js 8.23.4 <http://videojs.com/>\n * Copyright Brightcove, Inc. <https://www.brightcove.com/>\n * Available under Apache License Version 2.0\n * <https://github.com/videojs/video.js/blob/main/LICENSE>\n *\n * Includes vtt.js <https://github.com/mozilla/vtt.js>\n * Available under Apache License Version 2.0\n * <https://github.com/mozilla/vtt.js/blob/main/LICENSE>\n */\n\nimport window$1 from 'global/window';\nimport document$1 from 'global/document';\nimport XHR from '@videojs/xhr';\nimport vtt from 'videojs-vtt.js';\nimport _extends from '@babel/runtime/helpers/extends';\nimport _resolveUrl from '@videojs/vhs-utils/es/resolve-url.js';\nimport { Parser } from 'm3u8-parser';\nimport { DEFAULT_VIDEO_CODEC, DEFAULT_AUDIO_CODEC, parseCodecs, muxerSupportsCodec, browserSupportsCodec, translateLegacyCodec, codecsFromDefault, isAudioCodec, getMimeForCodec } from '@videojs/vhs-utils/es/codecs.js';\nimport { simpleTypeFromSourceType } from '@videojs/vhs-utils/es/media-types.js';\nimport { isArrayBufferView, concatTypedArrays, stringToBytes, toUint8 } from '@videojs/vhs-utils/es/byte-helpers';\nimport { generateSidxKey, parseUTCTiming, parse, addSidxSegmentsToPlaylist } from 'mpd-parser';\nimport parseSidx from 'mux.js/lib/tools/parse-sidx';\nimport { getId3Offset } from '@videojs/vhs-utils/es/id3-helpers';\nimport { detectContainerForBytes, isLikelyFmp4MediaSegment } from '@videojs/vhs-utils/es/containers';\nimport { ONE_SECOND_IN_TS } from 'mux.js/lib/utils/clock';\n\nvar version$6 = \"8.23.4\";\n\n/**\n * An Object that contains lifecycle hooks as keys which point to an array\n * of functions that are run when a lifecycle is triggered\n *\n * @private\n */\nconst hooks_ = {};\n\n/**\n * Get a list of hooks for a specific lifecycle\n *\n * @param  {string} type\n *         the lifecycle to get hooks from\n *\n * @param  {Function|Function[]} [fn]\n *         Optionally add a hook (or hooks) to the lifecycle that your are getting.\n *\n * @return {Array}\n *         an array of hooks, or an empty array if there are none.\n */\nconst hooks = function (type, fn) {\n  hooks_[type] = hooks_[type] || [];\n  if (fn) {\n    hooks_[type] = hooks_[type].concat(fn);\n  }\n  return hooks_[type];\n};\n\n/**\n * Add a function hook to a specific videojs lifecycle.\n *\n * @param {string} type\n *        the lifecycle to hook the function to.\n *\n * @param {Function|Function[]}\n *        The function or array of functions to attach.\n */\nconst hook = function (type, fn) {\n  hooks(type, fn);\n};\n\n/**\n * Remove a hook from a specific videojs lifecycle.\n *\n * @param  {string} type\n *         the lifecycle that the function hooked to\n *\n * @param  {Function} fn\n *         The hooked function to remove\n *\n * @return {boolean}\n *         The function that was removed or undef\n */\nconst removeHook = function (type, fn) {\n  const index = hooks(type).indexOf(fn);\n  if (index <= -1) {\n    return false;\n  }\n  hooks_[type] = hooks_[type].slice();\n  hooks_[type].splice(index, 1);\n  return true;\n};\n\n/**\n * Add a function hook that will only run once to a specific videojs lifecycle.\n *\n * @param {string} type\n *        the lifecycle to hook the function to.\n *\n * @param {Function|Function[]}\n *        The function or array of functions to attach.\n */\nconst hookOnce = function (type, fn) {\n  hooks(type, [].concat(fn).map(original => {\n    const wrapper = (...args) => {\n      removeHook(type, wrapper);\n      return original(...args);\n    };\n    return wrapper;\n  }));\n};\n\n/**\n * @file fullscreen-api.js\n * @module fullscreen-api\n */\n\n/**\n * Store the browser-specific methods for the fullscreen API.\n *\n * @type {Object}\n * @see [Specification]{@link https://fullscreen.spec.whatwg.org}\n * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}\n */\nconst FullscreenApi = {\n  prefixed: true\n};\n\n// browser API methods\nconst apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'],\n// WebKit\n['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen']];\nconst specApi = apiMap[0];\nlet browserApi;\n\n// determine the supported set of functions\nfor (let i = 0; i < apiMap.length; i++) {\n  // check for exitFullscreen function\n  if (apiMap[i][1] in document$1) {\n    browserApi = apiMap[i];\n    break;\n  }\n}\n\n// map the browser API names to the spec API names\nif (browserApi) {\n  for (let i = 0; i < browserApi.length; i++) {\n    FullscreenApi[specApi[i]] = browserApi[i];\n  }\n  FullscreenApi.prefixed = browserApi[0] !== specApi[0];\n}\n\n/**\n * @file create-logger.js\n * @module create-logger\n */\n\n// This is the private tracking variable for the logging history.\nlet history = [];\n\n/**\n * Log messages to the console and history based on the type of message\n *\n * @private\n * @param  {string} name\n *         The name of the console method to use.\n *\n * @param  {Object} log\n *         The arguments to be passed to the matching console method.\n *\n * @param {string} [styles]\n *        styles for name\n */\nconst LogByTypeFactory = (name, log, styles) => (type, level, args) => {\n  const lvl = log.levels[level];\n  const lvlRegExp = new RegExp(`^(${lvl})$`);\n  let resultName = name;\n  if (type !== 'log') {\n    // Add the type to the front of the message when it's not \"log\".\n    args.unshift(type.toUpperCase() + ':');\n  }\n  if (styles) {\n    resultName = `%c${name}`;\n    args.unshift(styles);\n  }\n\n  // Add console prefix after adding to history.\n  args.unshift(resultName + ':');\n\n  // Add a clone of the args at this point to history.\n  if (history) {\n    history.push([].concat(args));\n\n    // only store 1000 history entries\n    const splice = history.length - 1000;\n    history.splice(0, splice > 0 ? splice : 0);\n  }\n\n  // If there's no console then don't try to output messages, but they will\n  // still be stored in history.\n  if (!window$1.console) {\n    return;\n  }\n\n  // Was setting these once outside of this function, but containing them\n  // in the function makes it easier to test cases where console doesn't exist\n  // when the module is executed.\n  let fn = window$1.console[type];\n  if (!fn && type === 'debug') {\n    // Certain browsers don't have support for console.debug. For those, we\n    // should default to the closest comparable log.\n    fn = window$1.console.info || window$1.console.log;\n  }\n\n  // Bail out if there's no console or if this type is not allowed by the\n  // current logging level.\n  if (!fn || !lvl || !lvlRegExp.test(type)) {\n    return;\n  }\n  fn[Array.isArray(args) ? 'apply' : 'call'](window$1.console, args);\n};\nfunction createLogger$1(name, delimiter = ':', styles = '') {\n  // This is the private tracking variable for logging level.\n  let level = 'info';\n\n  // the curried logByType bound to the specific log and history\n  let logByType;\n\n  /**\n   * Logs plain debug messages. Similar to `console.log`.\n   *\n   * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)\n   * of our JSDoc template, we cannot properly document this as both a function\n   * and a namespace, so its function signature is documented here.\n   *\n   * #### Arguments\n   * ##### *args\n   * *[]\n   *\n   * Any combination of values that could be passed to `console.log()`.\n   *\n   * #### Return Value\n   *\n   * `undefined`\n   *\n   * @namespace\n   * @param    {...*} args\n   *           One or more messages or objects that should be logged.\n   */\n  function log(...args) {\n    logByType('log', level, args);\n  }\n\n  // This is the logByType helper that the logging methods below use\n  logByType = LogByTypeFactory(name, log, styles);\n\n  /**\n   * Create a new subLogger which chains the old name to the new name.\n   *\n   * For example, doing `mylogger = videojs.log.createLogger('player')` and then using that logger will log the following:\n   * ```js\n   *  mylogger('foo');\n   *  // > VIDEOJS: player: foo\n   * ```\n   *\n   * @param {string} subName\n   *        The name to add call the new logger\n   * @param {string} [subDelimiter]\n   *        Optional delimiter\n   * @param {string} [subStyles]\n   *        Optional styles\n   * @return {Object}\n   */\n  log.createLogger = (subName, subDelimiter, subStyles) => {\n    const resultDelimiter = subDelimiter !== undefined ? subDelimiter : delimiter;\n    const resultStyles = subStyles !== undefined ? subStyles : styles;\n    const resultName = `${name} ${resultDelimiter} ${subName}`;\n    return createLogger$1(resultName, resultDelimiter, resultStyles);\n  };\n\n  /**\n   * Create a new logger.\n   *\n   * @param {string} newName\n   *        The name for the new logger\n   * @param {string} [newDelimiter]\n   *        Optional delimiter\n   * @param {string} [newStyles]\n   *        Optional styles\n   * @return {Object}\n   */\n  log.createNewLogger = (newName, newDelimiter, newStyles) => {\n    return createLogger$1(newName, newDelimiter, newStyles);\n  };\n\n  /**\n   * Enumeration of available logging levels, where the keys are the level names\n   * and the values are `|`-separated strings containing logging methods allowed\n   * in that logging level. These strings are used to create a regular expression\n   * matching the function name being called.\n   *\n   * Levels provided by Video.js are:\n   *\n   * - `off`: Matches no calls. Any value that can be cast to `false` will have\n   *   this effect. The most restrictive.\n   * - `all`: Matches only Video.js-provided functions (`debug`, `log`,\n   *   `log.warn`, and `log.error`).\n   * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.\n   * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.\n   * - `warn`: Matches `log.warn` and `log.error` calls.\n   * - `error`: Matches only `log.error` calls.\n   *\n   * @type {Object}\n   */\n  log.levels = {\n    all: 'debug|log|warn|error',\n    off: '',\n    debug: 'debug|log|warn|error',\n    info: 'log|warn|error',\n    warn: 'warn|error',\n    error: 'error',\n    DEFAULT: level\n  };\n\n  /**\n   * Get or set the current logging level.\n   *\n   * If a string matching a key from {@link module:log.levels} is provided, acts\n   * as a setter.\n   *\n   * @param  {'all'|'debug'|'info'|'warn'|'error'|'off'} [lvl]\n   *         Pass a valid level to set a new logging level.\n   *\n   * @return {string}\n   *         The current logging level.\n   */\n  log.level = lvl => {\n    if (typeof lvl === 'string') {\n      if (!log.levels.hasOwnProperty(lvl)) {\n        throw new Error(`\"${lvl}\" in not a valid log level`);\n      }\n      level = lvl;\n    }\n    return level;\n  };\n\n  /**\n   * Returns an array containing everything that has been logged to the history.\n   *\n   * This array is a shallow clone of the internal history record. However, its\n   * contents are _not_ cloned; so, mutating objects inside this array will\n   * mutate them in history.\n   *\n   * @return {Array}\n   */\n  log.history = () => history ? [].concat(history) : [];\n\n  /**\n   * Allows you to filter the history by the given logger name\n   *\n   * @param {string} fname\n   *        The name to filter by\n   *\n   * @return {Array}\n   *         The filtered list to return\n   */\n  log.history.filter = fname => {\n    return (history || []).filter(historyItem => {\n      // if the first item in each historyItem includes `fname`, then it's a match\n      return new RegExp(`.*${fname}.*`).test(historyItem[0]);\n    });\n  };\n\n  /**\n   * Clears the internal history tracking, but does not prevent further history\n   * tracking.\n   */\n  log.history.clear = () => {\n    if (history) {\n      history.length = 0;\n    }\n  };\n\n  /**\n   * Disable history tracking if it is currently enabled.\n   */\n  log.history.disable = () => {\n    if (history !== null) {\n      history.length = 0;\n      history = null;\n    }\n  };\n\n  /**\n   * Enable history tracking if it is currently disabled.\n   */\n  log.history.enable = () => {\n    if (history === null) {\n      history = [];\n    }\n  };\n\n  /**\n   * Logs error messages. Similar to `console.error`.\n   *\n   * @param {...*} args\n   *        One or more messages or objects that should be logged as an error\n   */\n  log.error = (...args) => logByType('error', level, args);\n\n  /**\n   * Logs warning messages. Similar to `console.warn`.\n   *\n   * @param {...*} args\n   *        One or more messages or objects that should be logged as a warning.\n   */\n  log.warn = (...args) => logByType('warn', level, args);\n\n  /**\n   * Logs debug messages. Similar to `console.debug`, but may also act as a comparable\n   * log if `console.debug` is not available\n   *\n   * @param {...*} args\n   *        One or more messages or objects that should be logged as debug.\n   */\n  log.debug = (...args) => logByType('debug', level, args);\n  return log;\n}\n\n/**\n * @file log.js\n * @module log\n */\nconst log$1 = createLogger$1('VIDEOJS');\nconst createLogger = log$1.createLogger;\n\n/**\n * @file obj.js\n * @module obj\n */\n\n/**\n * @callback obj:EachCallback\n *\n * @param {*} value\n *        The current key for the object that is being iterated over.\n *\n * @param {string} key\n *        The current key-value for object that is being iterated over\n */\n\n/**\n * @callback obj:ReduceCallback\n *\n * @param {*} accum\n *        The value that is accumulating over the reduce loop.\n *\n * @param {*} value\n *        The current key for the object that is being iterated over.\n *\n * @param {string} key\n *        The current key-value for object that is being iterated over\n *\n * @return {*}\n *         The new accumulated value.\n */\nconst toString = Object.prototype.toString;\n\n/**\n * Get the keys of an Object\n *\n * @param {Object}\n *        The Object to get the keys from\n *\n * @return {string[]}\n *         An array of the keys from the object. Returns an empty array if the\n *         object passed in was invalid or had no keys.\n *\n * @private\n */\nconst keys = function (object) {\n  return isObject(object) ? Object.keys(object) : [];\n};\n\n/**\n * Array-like iteration for objects.\n *\n * @param {Object} object\n *        The object to iterate over\n *\n * @param {obj:EachCallback} fn\n *        The callback function which is called for each key in the object.\n */\nfunction each(object, fn) {\n  keys(object).forEach(key => fn(object[key], key));\n}\n\n/**\n * Array-like reduce for objects.\n *\n * @param {Object} object\n *        The Object that you want to reduce.\n *\n * @param {Function} fn\n *         A callback function which is called for each key in the object. It\n *         receives the accumulated value and the per-iteration value and key\n *         as arguments.\n *\n * @param {*} [initial = 0]\n *        Starting value\n *\n * @return {*}\n *         The final accumulated value.\n */\nfunction reduce(object, fn, initial = 0) {\n  return keys(object).reduce((accum, key) => fn(accum, object[key], key), initial);\n}\n\n/**\n * Returns whether a value is an object of any kind - including DOM nodes,\n * arrays, regular expressions, etc. Not functions, though.\n *\n * This avoids the gotcha where using `typeof` on a `null` value\n * results in `'object'`.\n *\n * @param  {Object} value\n * @return {boolean}\n */\nfunction isObject(value) {\n  return !!value && typeof value === 'object';\n}\n\n/**\n * Returns whether an object appears to be a \"plain\" object - that is, a\n * direct instance of `Object`.\n *\n * @param  {Object} value\n * @return {boolean}\n */\nfunction isPlain(value) {\n  return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object;\n}\n\n/**\n * Merge two objects recursively.\n *\n * Performs a deep merge like\n * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges\n * plain objects (not arrays, elements, or anything else).\n *\n * Non-plain object values will be copied directly from the right-most\n * argument.\n *\n * @param   {Object[]} sources\n *          One or more objects to merge into a new object.\n *\n * @return {Object}\n *          A new object that is the merged result of all sources.\n */\nfunction merge$1(...sources) {\n  const result = {};\n  sources.forEach(source => {\n    if (!source) {\n      return;\n    }\n    each(source, (value, key) => {\n      if (!isPlain(value)) {\n        result[key] = value;\n        return;\n      }\n      if (!isPlain(result[key])) {\n        result[key] = {};\n      }\n      result[key] = merge$1(result[key], value);\n    });\n  });\n  return result;\n}\n\n/**\n * Returns an array of values for a given object\n *\n * @param  {Object} source - target object\n * @return {Array<unknown>} - object values\n */\nfunction values(source = {}) {\n  const result = [];\n  for (const key in source) {\n    if (source.hasOwnProperty(key)) {\n      const value = source[key];\n      result.push(value);\n    }\n  }\n  return result;\n}\n\n/**\n * Object.defineProperty but \"lazy\", which means that the value is only set after\n * it is retrieved the first time, rather than being set right away.\n *\n * @param {Object} obj the object to set the property on\n * @param {string} key the key for the property to set\n * @param {Function} getValue the function used to get the value when it is needed.\n * @param {boolean} setter whether a setter should be allowed or not\n */\nfunction defineLazyProperty(obj, key, getValue, setter = true) {\n  const set = value => Object.defineProperty(obj, key, {\n    value,\n    enumerable: true,\n    writable: true\n  });\n  const options = {\n    configurable: true,\n    enumerable: true,\n    get() {\n      const value = getValue();\n      set(value);\n      return value;\n    }\n  };\n  if (setter) {\n    options.set = set;\n  }\n  return Object.defineProperty(obj, key, options);\n}\n\nvar Obj = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  each: each,\n  reduce: reduce,\n  isObject: isObject,\n  isPlain: isPlain,\n  merge: merge$1,\n  values: values,\n  defineLazyProperty: defineLazyProperty\n});\n\n/**\n * @file browser.js\n * @module browser\n */\n\n/**\n * Whether or not this device is an iPod.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_IPOD = false;\n\n/**\n * The detected iOS version - or `null`.\n *\n * @static\n * @type {string|null}\n */\nlet IOS_VERSION = null;\n\n/**\n * Whether or not this is an Android device.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_ANDROID = false;\n\n/**\n * The detected Android version - or `null` if not Android or indeterminable.\n *\n * @static\n * @type {number|string|null}\n */\nlet ANDROID_VERSION;\n\n/**\n * Whether or not this is Mozilla Firefox.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_FIREFOX = false;\n\n/**\n * Whether or not this is Microsoft Edge.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_EDGE = false;\n\n/**\n * Whether or not this is any Chromium Browser\n *\n * @static\n * @type {Boolean}\n */\nlet IS_CHROMIUM = false;\n\n/**\n * Whether or not this is any Chromium browser that is not Edge.\n *\n * This will also be `true` for Chrome on iOS, which will have different support\n * as it is actually Safari under the hood.\n *\n * Deprecated, as the behaviour to not match Edge was to prevent Legacy Edge's UA matching.\n * IS_CHROMIUM should be used instead.\n * \"Chromium but not Edge\" could be explicitly tested with IS_CHROMIUM && !IS_EDGE\n *\n * @static\n * @deprecated\n * @type {Boolean}\n */\nlet IS_CHROME = false;\n\n/**\n * The detected Chromium version - or `null`.\n *\n * @static\n * @type {number|null}\n */\nlet CHROMIUM_VERSION = null;\n\n/**\n * The detected Google Chrome version - or `null`.\n * This has always been the _Chromium_ version, i.e. would return on Chromium Edge.\n * Deprecated, use CHROMIUM_VERSION instead.\n *\n * @static\n * @deprecated\n * @type {number|null}\n */\nlet CHROME_VERSION = null;\n\n/**\n * Whether or not this is a Chromecast receiver application.\n *\n * @static\n * @type {Boolean}\n */\nconst IS_CHROMECAST_RECEIVER = Boolean(window$1.cast && window$1.cast.framework && window$1.cast.framework.CastReceiverContext);\n\n/**\n * The detected Internet Explorer version - or `null`.\n *\n * @static\n * @deprecated\n * @type {number|null}\n */\nlet IE_VERSION = null;\n\n/**\n * Whether or not this is desktop Safari.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_SAFARI = false;\n\n/**\n * Whether or not this is a Windows machine.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_WINDOWS = false;\n\n/**\n * Whether or not this device is an iPad.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_IPAD = false;\n\n/**\n * Whether or not this device is an iPhone.\n *\n * @static\n * @type {Boolean}\n */\n// The Facebook app's UIWebView identifies as both an iPhone and iPad, so\n// to identify iPhones, we need to exclude iPads.\n// http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/\nlet IS_IPHONE = false;\n\n/**\n * Whether or not this is a Tizen device.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_TIZEN = false;\n\n/**\n * Whether or not this is a WebOS device.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_WEBOS = false;\n\n/**\n * Whether or not this is a Smart TV (Tizen or WebOS) device.\n *\n * @static\n * @type {Boolean}\n */\nlet IS_SMART_TV = false;\n\n/**\n * Whether or not this device is touch-enabled.\n *\n * @static\n * @const\n * @type {Boolean}\n */\nconst TOUCH_ENABLED = Boolean(isReal() && ('ontouchstart' in window$1 || window$1.navigator.maxTouchPoints || window$1.DocumentTouch && window$1.document instanceof window$1.DocumentTouch));\nconst UAD = window$1.navigator && window$1.navigator.userAgentData;\nif (UAD && UAD.platform && UAD.brands) {\n  // If userAgentData is present, use it instead of userAgent to avoid warnings\n  // Currently only implemented on Chromium\n  // userAgentData does not expose Android version, so ANDROID_VERSION remains `null`\n\n  IS_ANDROID = UAD.platform === 'Android';\n  IS_EDGE = Boolean(UAD.brands.find(b => b.brand === 'Microsoft Edge'));\n  IS_CHROMIUM = Boolean(UAD.brands.find(b => b.brand === 'Chromium'));\n  IS_CHROME = !IS_EDGE && IS_CHROMIUM;\n  CHROMIUM_VERSION = CHROME_VERSION = (UAD.brands.find(b => b.brand === 'Chromium') || {}).version || null;\n  IS_WINDOWS = UAD.platform === 'Windows';\n}\n\n// If the browser is not Chromium, either userAgentData is not present which could be an old Chromium browser,\n//  or it's a browser that has added userAgentData since that we don't have tests for yet. In either case,\n// the checks need to be made agiainst the regular userAgent string.\nif (!IS_CHROMIUM) {\n  const USER_AGENT = window$1.navigator && window$1.navigator.userAgent || '';\n  IS_IPOD = /iPod/i.test(USER_AGENT);\n  IOS_VERSION = function () {\n    const match = USER_AGENT.match(/OS (\\d+)_/i);\n    if (match && match[1]) {\n      return match[1];\n    }\n    return null;\n  }();\n  IS_ANDROID = /Android/i.test(USER_AGENT);\n  ANDROID_VERSION = function () {\n    // This matches Android Major.Minor.Patch versions\n    // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned\n    const match = USER_AGENT.match(/Android (\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))*/i);\n    if (!match) {\n      return null;\n    }\n    const major = match[1] && parseFloat(match[1]);\n    const minor = match[2] && parseFloat(match[2]);\n    if (major && minor) {\n      return parseFloat(match[1] + '.' + match[2]);\n    } else if (major) {\n      return major;\n    }\n    return null;\n  }();\n  IS_FIREFOX = /Firefox/i.test(USER_AGENT);\n  IS_EDGE = /Edg/i.test(USER_AGENT);\n  IS_CHROMIUM = /Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT);\n  IS_CHROME = !IS_EDGE && IS_CHROMIUM;\n  CHROMIUM_VERSION = CHROME_VERSION = function () {\n    const match = USER_AGENT.match(/(Chrome|CriOS)\\/(\\d+)/);\n    if (match && match[2]) {\n      return parseFloat(match[2]);\n    }\n    return null;\n  }();\n  IE_VERSION = function () {\n    const result = /MSIE\\s(\\d+)\\.\\d/.exec(USER_AGENT);\n    let version = result && parseFloat(result[1]);\n    if (!version && /Trident\\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {\n      // IE 11 has a different user agent string than other IE versions\n      version = 11.0;\n    }\n    return version;\n  }();\n  IS_TIZEN = /Tizen/i.test(USER_AGENT);\n  IS_WEBOS = /Web0S/i.test(USER_AGENT);\n  IS_SMART_TV = IS_TIZEN || IS_WEBOS;\n  IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE && !IS_SMART_TV;\n  IS_WINDOWS = /Windows/i.test(USER_AGENT);\n  IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);\n  IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;\n}\n\n/**\n * Whether or not this is an iOS device.\n *\n * @static\n * @const\n * @type {Boolean}\n */\nconst IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;\n\n/**\n * Whether or not this is any flavor of Safari - including iOS.\n *\n * @static\n * @const\n * @type {Boolean}\n */\nconst IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;\n\nvar browser = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  get IS_IPOD () { return IS_IPOD; },\n  get IOS_VERSION () { return IOS_VERSION; },\n  get IS_ANDROID () { return IS_ANDROID; },\n  get ANDROID_VERSION () { return ANDROID_VERSION; },\n  get IS_FIREFOX () { return IS_FIREFOX; },\n  get IS_EDGE () { return IS_EDGE; },\n  get IS_CHROMIUM () { return IS_CHROMIUM; },\n  get IS_CHROME () { return IS_CHROME; },\n  get CHROMIUM_VERSION () { return CHROMIUM_VERSION; },\n  get CHROME_VERSION () { return CHROME_VERSION; },\n  IS_CHROMECAST_RECEIVER: IS_CHROMECAST_RECEIVER,\n  get IE_VERSION () { return IE_VERSION; },\n  get IS_SAFARI () { return IS_SAFARI; },\n  get IS_WINDOWS () { return IS_WINDOWS; },\n  get IS_IPAD () { return IS_IPAD; },\n  get IS_IPHONE () { return IS_IPHONE; },\n  get IS_TIZEN () { return IS_TIZEN; },\n  get IS_WEBOS () { return IS_WEBOS; },\n  get IS_SMART_TV () { return IS_SMART_TV; },\n  TOUCH_ENABLED: TOUCH_ENABLED,\n  IS_IOS: IS_IOS,\n  IS_ANY_SAFARI: IS_ANY_SAFARI\n});\n\n/**\n * @file dom.js\n * @module dom\n */\n\n/**\n * Detect if a value is a string with any non-whitespace characters.\n *\n * @private\n * @param  {string} str\n *         The string to check\n *\n * @return {boolean}\n *         Will be `true` if the string is non-blank, `false` otherwise.\n *\n */\nfunction isNonBlankString(str) {\n  // we use str.trim as it will trim any whitespace characters\n  // from the front or back of non-whitespace characters. aka\n  // Any string that contains non-whitespace characters will\n  // still contain them after `trim` but whitespace only strings\n  // will have a length of 0, failing this check.\n  return typeof str === 'string' && Boolean(str.trim());\n}\n\n/**\n * Throws an error if the passed string has whitespace. This is used by\n * class methods to be relatively consistent with the classList API.\n *\n * @private\n * @param  {string} str\n *         The string to check for whitespace.\n *\n * @throws {Error}\n *         Throws an error if there is whitespace in the string.\n */\nfunction throwIfWhitespace(str) {\n  // str.indexOf instead of regex because str.indexOf is faster performance wise.\n  if (str.indexOf(' ') >= 0) {\n    throw new Error('class has illegal whitespace characters');\n  }\n}\n\n/**\n * Whether the current DOM interface appears to be real (i.e. not simulated).\n *\n * @return {boolean}\n *         Will be `true` if the DOM appears to be real, `false` otherwise.\n */\nfunction isReal() {\n  // Both document and window will never be undefined thanks to `global`.\n  return document$1 === window$1.document;\n}\n\n/**\n * Determines, via duck typing, whether or not a value is a DOM element.\n *\n * @param  {*} value\n *         The value to check.\n *\n * @return {boolean}\n *         Will be `true` if the value is a DOM element, `false` otherwise.\n */\nfunction isEl(value) {\n  return isObject(value) && value.nodeType === 1;\n}\n\n/**\n * Determines if the current DOM is embedded in an iframe.\n *\n * @return {boolean}\n *         Will be `true` if the DOM is embedded in an iframe, `false`\n *         otherwise.\n */\nfunction isInFrame() {\n  // We need a try/catch here because Safari will throw errors when attempting\n  // to get either `parent` or `self`\n  try {\n    return window$1.parent !== window$1.self;\n  } catch (x) {\n    return true;\n  }\n}\n\n/**\n * Creates functions to query the DOM using a given method.\n *\n * @private\n * @param   {string} method\n *          The method to create the query with.\n *\n * @return  {Function}\n *          The query method\n */\nfunction createQuerier(method) {\n  return function (selector, context) {\n    if (!isNonBlankString(selector)) {\n      return document$1[method](null);\n    }\n    if (isNonBlankString(context)) {\n      context = document$1.querySelector(context);\n    }\n    const ctx = isEl(context) ? context : document$1;\n    return ctx[method] && ctx[method](selector);\n  };\n}\n\n/**\n * Creates an element and applies properties, attributes, and inserts content.\n *\n * @param  {string} [tagName='div']\n *         Name of tag to be created.\n *\n * @param  {Object} [properties={}]\n *         Element properties to be applied.\n *\n * @param  {Object} [attributes={}]\n *         Element attributes to be applied.\n *\n * @param {ContentDescriptor} [content]\n *        A content descriptor object.\n *\n * @return {Element}\n *         The element that was created.\n */\nfunction createEl(tagName = 'div', properties = {}, attributes = {}, content) {\n  const el = document$1.createElement(tagName);\n  Object.getOwnPropertyNames(properties).forEach(function (propName) {\n    const val = properties[propName];\n\n    // Handle textContent since it's not supported everywhere and we have a\n    // method for it.\n    if (propName === 'textContent') {\n      textContent(el, val);\n    } else if (el[propName] !== val || propName === 'tabIndex') {\n      el[propName] = val;\n    }\n  });\n  Object.getOwnPropertyNames(attributes).forEach(function (attrName) {\n    el.setAttribute(attrName, attributes[attrName]);\n  });\n  if (content) {\n    appendContent(el, content);\n  }\n  return el;\n}\n\n/**\n * Injects text into an element, replacing any existing contents entirely.\n *\n * @param  {HTMLElement} el\n *         The element to add text content into\n *\n * @param  {string} text\n *         The text content to add.\n *\n * @return {Element}\n *         The element with added text content.\n */\nfunction textContent(el, text) {\n  if (typeof el.textContent === 'undefined') {\n    el.innerText = text;\n  } else {\n    el.textContent = text;\n  }\n  return el;\n}\n\n/**\n * Insert an element as the first child node of another\n *\n * @param {Element} child\n *        Element to insert\n *\n * @param {Element} parent\n *        Element to insert child into\n */\nfunction prependTo(child, parent) {\n  if (parent.firstChild) {\n    parent.insertBefore(child, parent.firstChild);\n  } else {\n    parent.appendChild(child);\n  }\n}\n\n/**\n * Check if an element has a class name.\n *\n * @param  {Element} element\n *         Element to check\n *\n * @param  {string} classToCheck\n *         Class name to check for\n *\n * @return {boolean}\n *         Will be `true` if the element has a class, `false` otherwise.\n *\n * @throws {Error}\n *         Throws an error if `classToCheck` has white space.\n */\nfunction hasClass(element, classToCheck) {\n  throwIfWhitespace(classToCheck);\n  return element.classList.contains(classToCheck);\n}\n\n/**\n * Add a class name to an element.\n *\n * @param  {Element} element\n *         Element to add class name to.\n *\n * @param  {...string} classesToAdd\n *         One or more class name to add.\n *\n * @return {Element}\n *         The DOM element with the added class name.\n */\nfunction addClass(element, ...classesToAdd) {\n  element.classList.add(...classesToAdd.reduce((prev, current) => prev.concat(current.split(/\\s+/)), []));\n  return element;\n}\n\n/**\n * Remove a class name from an element.\n *\n * @param  {Element} element\n *         Element to remove a class name from.\n *\n * @param  {...string} classesToRemove\n *         One or more class name to remove.\n *\n * @return {Element}\n *         The DOM element with class name removed.\n */\nfunction removeClass(element, ...classesToRemove) {\n  // Protect in case the player gets disposed\n  if (!element) {\n    log$1.warn(\"removeClass was called with an element that doesn't exist\");\n    return null;\n  }\n  element.classList.remove(...classesToRemove.reduce((prev, current) => prev.concat(current.split(/\\s+/)), []));\n  return element;\n}\n\n/**\n * The callback definition for toggleClass.\n *\n * @callback PredicateCallback\n * @param    {Element} element\n *           The DOM element of the Component.\n *\n * @param    {string} classToToggle\n *           The `className` that wants to be toggled\n *\n * @return   {boolean|undefined}\n *           If `true` is returned, the `classToToggle` will be added to the\n *           `element`, but not removed. If `false`, the `classToToggle` will be removed from\n *           the `element`, but not added. If `undefined`, the callback will be ignored.\n *\n */\n\n/**\n * Adds or removes a class name to/from an element depending on an optional\n * condition or the presence/absence of the class name.\n *\n * @param  {Element} element\n *         The element to toggle a class name on.\n *\n * @param  {string} classToToggle\n *         The class that should be toggled.\n *\n * @param  {boolean|PredicateCallback} [predicate]\n *         See the return value for {@link module:dom~PredicateCallback}\n *\n * @return {Element}\n *         The element with a class that has been toggled.\n */\nfunction toggleClass(element, classToToggle, predicate) {\n  if (typeof predicate === 'function') {\n    predicate = predicate(element, classToToggle);\n  }\n  if (typeof predicate !== 'boolean') {\n    predicate = undefined;\n  }\n  classToToggle.split(/\\s+/).forEach(className => element.classList.toggle(className, predicate));\n  return element;\n}\n\n/**\n * Apply attributes to an HTML element.\n *\n * @param {Element} el\n *        Element to add attributes to.\n *\n * @param {Object} [attributes]\n *        Attributes to be applied.\n */\nfunction setAttributes(el, attributes) {\n  Object.getOwnPropertyNames(attributes).forEach(function (attrName) {\n    const attrValue = attributes[attrName];\n    if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {\n      el.removeAttribute(attrName);\n    } else {\n      el.setAttribute(attrName, attrValue === true ? '' : attrValue);\n    }\n  });\n}\n\n/**\n * Get an element's attribute values, as defined on the HTML tag.\n *\n * Attributes are not the same as properties. They're defined on the tag\n * or with setAttribute.\n *\n * @param  {Element} tag\n *         Element from which to get tag attributes.\n *\n * @return {Object}\n *         All attributes of the element. Boolean attributes will be `true` or\n *         `false`, others will be strings.\n */\nfunction getAttributes(tag) {\n  const obj = {};\n\n  // known boolean attributes\n  // we can check for matching boolean properties, but not all browsers\n  // and not all tags know about these attributes, so, we still want to check them manually\n  const knownBooleans = ['autoplay', 'controls', 'playsinline', 'loop', 'muted', 'default', 'defaultMuted'];\n  if (tag && tag.attributes && tag.attributes.length > 0) {\n    const attrs = tag.attributes;\n    for (let i = attrs.length - 1; i >= 0; i--) {\n      const attrName = attrs[i].name;\n      /** @type {boolean|string} */\n      let attrVal = attrs[i].value;\n\n      // check for known booleans\n      // the matching element property will return a value for typeof\n      if (knownBooleans.includes(attrName)) {\n        // the value of an included boolean attribute is typically an empty\n        // string ('') which would equal false if we just check for a false value.\n        // we also don't want support bad code like autoplay='false'\n        attrVal = attrVal !== null ? true : false;\n      }\n      obj[attrName] = attrVal;\n    }\n  }\n  return obj;\n}\n\n/**\n * Get the value of an element's attribute.\n *\n * @param {Element} el\n *        A DOM element.\n *\n * @param {string} attribute\n *        Attribute to get the value of.\n *\n * @return {string}\n *         The value of the attribute.\n */\nfunction getAttribute(el, attribute) {\n  return el.getAttribute(attribute);\n}\n\n/**\n * Set the value of an element's attribute.\n *\n * @param {Element} el\n *        A DOM element.\n *\n * @param {string} attribute\n *        Attribute to set.\n *\n * @param {string} value\n *        Value to set the attribute to.\n */\nfunction setAttribute(el, attribute, value) {\n  el.setAttribute(attribute, value);\n}\n\n/**\n * Remove an element's attribute.\n *\n * @param {Element} el\n *        A DOM element.\n *\n * @param {string} attribute\n *        Attribute to remove.\n */\nfunction removeAttribute(el, attribute) {\n  el.removeAttribute(attribute);\n}\n\n/**\n * Attempt to block the ability to select text.\n */\nfunction blockTextSelection() {\n  document$1.body.focus();\n  document$1.onselectstart = function () {\n    return false;\n  };\n}\n\n/**\n * Turn off text selection blocking.\n */\nfunction unblockTextSelection() {\n  document$1.onselectstart = function () {\n    return true;\n  };\n}\n\n/**\n * Identical to the native `getBoundingClientRect` function, but ensures that\n * the method is supported at all (it is in all browsers we claim to support)\n * and that the element is in the DOM before continuing.\n *\n * This wrapper function also shims properties which are not provided by some\n * older browsers (namely, IE8).\n *\n * Additionally, some browsers do not support adding properties to a\n * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard\n * properties (except `x` and `y` which are not widely supported). This helps\n * avoid implementations where keys are non-enumerable.\n *\n * @param  {Element} el\n *         Element whose `ClientRect` we want to calculate.\n *\n * @return {Object|undefined}\n *         Always returns a plain object - or `undefined` if it cannot.\n */\nfunction getBoundingClientRect(el) {\n  if (el && el.getBoundingClientRect && el.parentNode) {\n    const rect = el.getBoundingClientRect();\n    const result = {};\n    ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(k => {\n      if (rect[k] !== undefined) {\n        result[k] = rect[k];\n      }\n    });\n    if (!result.height) {\n      result.height = parseFloat(computedStyle(el, 'height'));\n    }\n    if (!result.width) {\n      result.width = parseFloat(computedStyle(el, 'width'));\n    }\n    return result;\n  }\n}\n\n/**\n * Represents the position of a DOM element on the page.\n *\n * @typedef  {Object} module:dom~Position\n *\n * @property {number} left\n *           Pixels to the left.\n *\n * @property {number} top\n *           Pixels from the top.\n */\n\n/**\n * Get the position of an element in the DOM.\n *\n * Uses `getBoundingClientRect` technique from John Resig.\n *\n * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/\n *\n * @param  {Element} el\n *         Element from which to get offset.\n *\n * @return {module:dom~Position}\n *         The position of the element that was passed in.\n */\nfunction findPosition(el) {\n  if (!el || el && !el.offsetParent) {\n    return {\n      left: 0,\n      top: 0,\n      width: 0,\n      height: 0\n    };\n  }\n  const width = el.offsetWidth;\n  const height = el.offsetHeight;\n  let left = 0;\n  let top = 0;\n  while (el.offsetParent && el !== document$1[FullscreenApi.fullscreenElement]) {\n    left += el.offsetLeft;\n    top += el.offsetTop;\n    el = el.offsetParent;\n  }\n  return {\n    left,\n    top,\n    width,\n    height\n  };\n}\n\n/**\n * Represents x and y coordinates for a DOM element or mouse pointer.\n *\n * @typedef  {Object} module:dom~Coordinates\n *\n * @property {number} x\n *           x coordinate in pixels\n *\n * @property {number} y\n *           y coordinate in pixels\n */\n\n/**\n * Get the pointer position within an element.\n *\n * The base on the coordinates are the bottom left of the element.\n *\n * @param  {Element} el\n *         Element on which to get the pointer position on.\n *\n * @param  {Event} event\n *         Event object.\n *\n * @return {module:dom~Coordinates}\n *         A coordinates object corresponding to the mouse position.\n *\n */\nfunction getPointerPosition(el, event) {\n  const translated = {\n    x: 0,\n    y: 0\n  };\n  if (IS_IOS) {\n    let item = el;\n    while (item && item.nodeName.toLowerCase() !== 'html') {\n      const transform = computedStyle(item, 'transform');\n      if (/^matrix/.test(transform)) {\n        const values = transform.slice(7, -1).split(/,\\s/).map(Number);\n        translated.x += values[4];\n        translated.y += values[5];\n      } else if (/^matrix3d/.test(transform)) {\n        const values = transform.slice(9, -1).split(/,\\s/).map(Number);\n        translated.x += values[12];\n        translated.y += values[13];\n      }\n      if (item.assignedSlot && item.assignedSlot.parentElement && window$1.WebKitCSSMatrix) {\n        const transformValue = window$1.getComputedStyle(item.assignedSlot.parentElement).transform;\n        const matrix = new window$1.WebKitCSSMatrix(transformValue);\n        translated.x += matrix.m41;\n        translated.y += matrix.m42;\n      }\n      item = item.parentNode || item.host;\n    }\n  }\n  const position = {};\n  const boxTarget = findPosition(event.target);\n  const box = findPosition(el);\n  const boxW = box.width;\n  const boxH = box.height;\n  let offsetY = event.offsetY - (box.top - boxTarget.top);\n  let offsetX = event.offsetX - (box.left - boxTarget.left);\n  if (event.changedTouches) {\n    offsetX = event.changedTouches[0].pageX - box.left;\n    offsetY = event.changedTouches[0].pageY + box.top;\n    if (IS_IOS) {\n      offsetX -= translated.x;\n      offsetY -= translated.y;\n    }\n  }\n  position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));\n  position.x = Math.max(0, Math.min(1, offsetX / boxW));\n  return position;\n}\n\n/**\n * Determines, via duck typing, whether or not a value is a text node.\n *\n * @param  {*} value\n *         Check if this value is a text node.\n *\n * @return {boolean}\n *         Will be `true` if the value is a text node, `false` otherwise.\n */\nfunction isTextNode(value) {\n  return isObject(value) && value.nodeType === 3;\n}\n\n/**\n * Empties the contents of an element.\n *\n * @param  {Element} el\n *         The element to empty children from\n *\n * @return {Element}\n *         The element with no children\n */\nfunction emptyEl(el) {\n  while (el.firstChild) {\n    el.removeChild(el.firstChild);\n  }\n  return el;\n}\n\n/**\n * This is a mixed value that describes content to be injected into the DOM\n * via some method. It can be of the following types:\n *\n * Type       | Description\n * -----------|-------------\n * `string`   | The value will be normalized into a text node.\n * `Element`  | The value will be accepted as-is.\n * `Text`     | A TextNode. The value will be accepted as-is.\n * `Array`    | A one-dimensional array of strings, elements, text nodes, or functions. These functions should return a string, element, or text node (any other return value, like an array, will be ignored).\n * `Function` | A function, which is expected to return a string, element, text node, or array - any of the other possible values described above. This means that a content descriptor could be a function that returns an array of functions, but those second-level functions must return strings, elements, or text nodes.\n *\n * @typedef {string|Element|Text|Array|Function} ContentDescriptor\n */\n\n/**\n * Normalizes content for eventual insertion into the DOM.\n *\n * This allows a wide range of content definition methods, but helps protect\n * from falling into the trap of simply writing to `innerHTML`, which could\n * be an XSS concern.\n *\n * The content for an element can be passed in multiple types and\n * combinations, whose behavior is as follows:\n *\n * @param {ContentDescriptor} content\n *        A content descriptor value.\n *\n * @return {Array}\n *         All of the content that was passed in, normalized to an array of\n *         elements or text nodes.\n */\nfunction normalizeContent(content) {\n  // First, invoke content if it is a function. If it produces an array,\n  // that needs to happen before normalization.\n  if (typeof content === 'function') {\n    content = content();\n  }\n\n  // Next up, normalize to an array, so one or many items can be normalized,\n  // filtered, and returned.\n  return (Array.isArray(content) ? content : [content]).map(value => {\n    // First, invoke value if it is a function to produce a new value,\n    // which will be subsequently normalized to a Node of some kind.\n    if (typeof value === 'function') {\n      value = value();\n    }\n    if (isEl(value) || isTextNode(value)) {\n      return value;\n    }\n    if (typeof value === 'string' && /\\S/.test(value)) {\n      return document$1.createTextNode(value);\n    }\n  }).filter(value => value);\n}\n\n/**\n * Normalizes and appends content to an element.\n *\n * @param  {Element} el\n *         Element to append normalized content to.\n *\n * @param {ContentDescriptor} content\n *        A content descriptor value.\n *\n * @return {Element}\n *         The element with appended normalized content.\n */\nfunction appendContent(el, content) {\n  normalizeContent(content).forEach(node => el.appendChild(node));\n  return el;\n}\n\n/**\n * Normalizes and inserts content into an element; this is identical to\n * `appendContent()`, except it empties the element first.\n *\n * @param {Element} el\n *        Element to insert normalized content into.\n *\n * @param {ContentDescriptor} content\n *        A content descriptor value.\n *\n * @return {Element}\n *         The element with inserted normalized content.\n */\nfunction insertContent(el, content) {\n  return appendContent(emptyEl(el), content);\n}\n\n/**\n * Check if an event was a single left click.\n *\n * @param  {MouseEvent} event\n *         Event object.\n *\n * @return {boolean}\n *         Will be `true` if a single left click, `false` otherwise.\n */\nfunction isSingleLeftClick(event) {\n  // Note: if you create something draggable, be sure to\n  // call it on both `mousedown` and `mousemove` event,\n  // otherwise `mousedown` should be enough for a button\n\n  if (event.button === undefined && event.buttons === undefined) {\n    // Why do we need `buttons` ?\n    // Because, middle mouse sometimes have this:\n    // e.button === 0 and e.buttons === 4\n    // Furthermore, we want to prevent combination click, something like\n    // HOLD middlemouse then left click, that would be\n    // e.button === 0, e.buttons === 5\n    // just `button` is not gonna work\n\n    // Alright, then what this block does ?\n    // this is for chrome `simulate mobile devices`\n    // I want to support this as well\n\n    return true;\n  }\n  if (event.button === 0 && event.buttons === undefined) {\n    // Touch screen, sometimes on some specific device, `buttons`\n    // doesn't have anything (safari on ios, blackberry...)\n\n    return true;\n  }\n\n  // `mouseup` event on a single left click has\n  // `button` and `buttons` equal to 0\n  if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {\n    return true;\n  }\n\n  // MacOS Sonoma trackpad when \"tap to click enabled\"\n  if (event.type === 'mousedown' && event.button === 0 && event.buttons === 0) {\n    return true;\n  }\n  if (event.button !== 0 || event.buttons !== 1) {\n    // This is the reason we have those if else block above\n    // if any special case we can catch and let it slide\n    // we do it above, when get to here, this definitely\n    // is-not-left-click\n\n    return false;\n  }\n  return true;\n}\n\n/**\n * Finds a single DOM element matching `selector` within the optional\n * `context` of another DOM element (defaulting to `document`).\n *\n * @param  {string} selector\n *         A valid CSS selector, which will be passed to `querySelector`.\n *\n * @param  {Element|String} [context=document]\n *         A DOM element within which to query. Can also be a selector\n *         string in which case the first matching element will be used\n *         as context. If missing (or no element matches selector), falls\n *         back to `document`.\n *\n * @return {Element|null}\n *         The element that was found or null.\n */\nconst $ = createQuerier('querySelector');\n\n/**\n * Finds a all DOM elements matching `selector` within the optional\n * `context` of another DOM element (defaulting to `document`).\n *\n * @param  {string} selector\n *         A valid CSS selector, which will be passed to `querySelectorAll`.\n *\n * @param  {Element|String} [context=document]\n *         A DOM element within which to query. Can also be a selector\n *         string in which case the first matching element will be used\n *         as context. If missing (or no element matches selector), falls\n *         back to `document`.\n *\n * @return {NodeList}\n *         A element list of elements that were found. Will be empty if none\n *         were found.\n *\n */\nconst $$ = createQuerier('querySelectorAll');\n\n/**\n * A safe getComputedStyle.\n *\n * This is needed because in Firefox, if the player is loaded in an iframe with\n * `display:none`, then `getComputedStyle` returns `null`, so, we do a\n * null-check to make sure that the player doesn't break in these cases.\n *\n * @param    {Element} el\n *           The element you want the computed style of\n *\n * @param    {string} prop\n *           The property name you want\n *\n * @see      https://bugzilla.mozilla.org/show_bug.cgi?id=548397\n */\nfunction computedStyle(el, prop) {\n  if (!el || !prop) {\n    return '';\n  }\n  if (typeof window$1.getComputedStyle === 'function') {\n    let computedStyleValue;\n    try {\n      computedStyleValue = window$1.getComputedStyle(el);\n    } catch (e) {\n      return '';\n    }\n    return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';\n  }\n  return '';\n}\n\n/**\n * Copy document style sheets to another window.\n *\n * @param    {Window} win\n *           The window element you want to copy the document style sheets to.\n *\n */\nfunction copyStyleSheetsToWindow(win) {\n  [...document$1.styleSheets].forEach(styleSheet => {\n    try {\n      const cssRules = [...styleSheet.cssRules].map(rule => rule.cssText).join('');\n      const style = document$1.createElement('style');\n      style.textContent = cssRules;\n      win.document.head.appendChild(style);\n    } catch (e) {\n      const link = document$1.createElement('link');\n      link.rel = 'stylesheet';\n      link.type = styleSheet.type;\n      // For older Safari this has to be the string; on other browsers setting the MediaList works\n      link.media = styleSheet.media.mediaText;\n      link.href = styleSheet.href;\n      win.document.head.appendChild(link);\n    }\n  });\n}\n\nvar Dom = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  isReal: isReal,\n  isEl: isEl,\n  isInFrame: isInFrame,\n  createEl: createEl,\n  textContent: textContent,\n  prependTo: prependTo,\n  hasClass: hasClass,\n  addClass: addClass,\n  removeClass: removeClass,\n  toggleClass: toggleClass,\n  setAttributes: setAttributes,\n  getAttributes: getAttributes,\n  getAttribute: getAttribute,\n  setAttribute: setAttribute,\n  removeAttribute: removeAttribute,\n  blockTextSelection: blockTextSelection,\n  unblockTextSelection: unblockTextSelection,\n  getBoundingClientRect: getBoundingClientRect,\n  findPosition: findPosition,\n  getPointerPosition: getPointerPosition,\n  isTextNode: isTextNode,\n  emptyEl: emptyEl,\n  normalizeContent: normalizeContent,\n  appendContent: appendContent,\n  insertContent: insertContent,\n  isSingleLeftClick: isSingleLeftClick,\n  $: $,\n  $$: $$,\n  computedStyle: computedStyle,\n  copyStyleSheetsToWindow: copyStyleSheetsToWindow\n});\n\n/**\n * @file setup.js - Functions for setting up a player without\n * user interaction based on the data-setup `attribute` of the video tag.\n *\n * @module setup\n */\nlet _windowLoaded = false;\nlet videojs$1;\n\n/**\n * Set up any tags that have a data-setup `attribute` when the player is started.\n */\nconst autoSetup = function () {\n  if (videojs$1.options.autoSetup === false) {\n    return;\n  }\n  const vids = Array.prototype.slice.call(document$1.getElementsByTagName('video'));\n  const audios = Array.prototype.slice.call(document$1.getElementsByTagName('audio'));\n  const divs = Array.prototype.slice.call(document$1.getElementsByTagName('video-js'));\n  const mediaEls = vids.concat(audios, divs);\n\n  // Check if any media elements exist\n  if (mediaEls && mediaEls.length > 0) {\n    for (let i = 0, e = mediaEls.length; i < e; i++) {\n      const mediaEl = mediaEls[i];\n\n      // Check if element exists, has getAttribute func.\n      if (mediaEl && mediaEl.getAttribute) {\n        // Make sure this player hasn't already been set up.\n        if (mediaEl.player === undefined) {\n          const options = mediaEl.getAttribute('data-setup');\n\n          // Check if data-setup attr exists.\n          // We only auto-setup if they've added the data-setup attr.\n          if (options !== null) {\n            // Create new video.js instance.\n            videojs$1(mediaEl);\n          }\n        }\n\n        // If getAttribute isn't defined, we need to wait for the DOM.\n      } else {\n        autoSetupTimeout(1);\n        break;\n      }\n    }\n\n    // No videos were found, so keep looping unless page is finished loading.\n  } else if (!_windowLoaded) {\n    autoSetupTimeout(1);\n  }\n};\n\n/**\n * Wait until the page is loaded before running autoSetup. This will be called in\n * autoSetup if `hasLoaded` returns false.\n *\n * @param {number} wait\n *        How long to wait in ms\n *\n * @param {module:videojs} [vjs]\n *        The videojs library function\n */\nfunction autoSetupTimeout(wait, vjs) {\n  // Protect against breakage in non-browser environments\n  if (!isReal()) {\n    return;\n  }\n  if (vjs) {\n    videojs$1 = vjs;\n  }\n  window$1.setTimeout(autoSetup, wait);\n}\n\n/**\n * Used to set the internal tracking of window loaded state to true.\n *\n * @private\n */\nfunction setWindowLoaded() {\n  _windowLoaded = true;\n  window$1.removeEventListener('load', setWindowLoaded);\n}\nif (isReal()) {\n  if (document$1.readyState === 'complete') {\n    setWindowLoaded();\n  } else {\n    /**\n     * Listen for the load event on window, and set _windowLoaded to true.\n     *\n     * We use a standard event listener here to avoid incrementing the GUID\n     * before any players are created.\n     *\n     * @listens load\n     */\n    window$1.addEventListener('load', setWindowLoaded);\n  }\n}\n\n/**\n * @file stylesheet.js\n * @module stylesheet\n */\n\n/**\n * Create a DOM style element given a className for it.\n *\n * @param {string} className\n *        The className to add to the created style element.\n *\n * @return {Element}\n *         The element that was created.\n */\nconst createStyleElement = function (className) {\n  const style = document$1.createElement('style');\n  style.className = className;\n  return style;\n};\n\n/**\n * Add text to a DOM element.\n *\n * @param {Element} el\n *        The Element to add text content to.\n *\n * @param {string} content\n *        The text to add to the element.\n */\nconst setTextContent = function (el, content) {\n  if (el.styleSheet) {\n    el.styleSheet.cssText = content;\n  } else {\n    el.textContent = content;\n  }\n};\n\n/**\n * @file dom-data.js\n * @module dom-data\n */\n\n/**\n * Element Data Store.\n *\n * Allows for binding data to an element without putting it directly on the\n * element. Ex. Event listeners are stored here.\n * (also from jsninja.com, slightly modified and updated for closure compiler)\n *\n * @type {Object}\n * @private\n */\nvar DomData = new WeakMap();\n\n/**\n * @file guid.js\n * @module guid\n */\n\n// Default value for GUIDs. This allows us to reset the GUID counter in tests.\n//\n// The initial GUID is 3 because some users have come to rely on the first\n// default player ID ending up as `vjs_video_3`.\n//\n// See: https://github.com/videojs/video.js/pull/6216\nconst _initialGuid = 3;\n\n/**\n * Unique ID for an element or function\n *\n * @type {Number}\n */\nlet _guid = _initialGuid;\n\n/**\n * Get a unique auto-incrementing ID by number that has not been returned before.\n *\n * @return {number}\n *         A new unique ID.\n */\nfunction newGUID() {\n  return _guid++;\n}\n\n/**\n * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)\n * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)\n * This should work very similarly to jQuery's events, however it's based off the book version which isn't as\n * robust as jquery's, so there's probably some differences.\n *\n * @file events.js\n * @module events\n */\n\n/**\n * Clean up the listener cache and dispatchers\n *\n * @param {Element|Object} elem\n *        Element to clean up\n *\n * @param {string} type\n *        Type of event to clean up\n */\nfunction _cleanUpEvents(elem, type) {\n  if (!DomData.has(elem)) {\n    return;\n  }\n  const data = DomData.get(elem);\n\n  // Remove the events of a particular type if there are none left\n  if (data.handlers[type].length === 0) {\n    delete data.handlers[type];\n    // data.handlers[type] = null;\n    // Setting to null was causing an error with data.handlers\n\n    // Remove the meta-handler from the element\n    if (elem.removeEventListener) {\n      elem.removeEventListener(type, data.dispatcher, false);\n    } else if (elem.detachEvent) {\n      elem.detachEvent('on' + type, data.dispatcher);\n    }\n  }\n\n  // Remove the events object if there are no types left\n  if (Object.getOwnPropertyNames(data.handlers).length <= 0) {\n    delete data.handlers;\n    delete data.dispatcher;\n    delete data.disabled;\n  }\n\n  // Finally remove the element data if there is no data left\n  if (Object.getOwnPropertyNames(data).length === 0) {\n    DomData.delete(elem);\n  }\n}\n\n/**\n * Loops through an array of event types and calls the requested method for each type.\n *\n * @param {Function} fn\n *        The event method we want to use.\n *\n * @param {Element|Object} elem\n *        Element or object to bind listeners to\n *\n * @param {string[]} types\n *        Type of event to bind to.\n *\n * @param {Function} callback\n *        Event listener.\n */\nfunction _handleMultipleEvents(fn, elem, types, callback) {\n  types.forEach(function (type) {\n    // Call the event method for each one of the types\n    fn(elem, type, callback);\n  });\n}\n\n/**\n * Fix a native event to have standard property values\n *\n * @param {Object} event\n *        Event object to fix.\n *\n * @return {Object}\n *         Fixed event object.\n */\nfunction fixEvent(event) {\n  if (event.fixed_) {\n    return event;\n  }\n  function returnTrue() {\n    return true;\n  }\n  function returnFalse() {\n    return false;\n  }\n\n  // Test if fixing up is needed\n  // Used to check if !event.stopPropagation instead of isPropagationStopped\n  // But native events return true for stopPropagation, but don't have\n  // other expected methods like isPropagationStopped. Seems to be a problem\n  // with the Javascript Ninja code. So we're just overriding all events now.\n  if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {\n    const old = event || window$1.event;\n    event = {};\n    // Clone the old object so that we can modify the values event = {};\n    // IE8 Doesn't like when you mess with native event properties\n    // Firefox returns false for event.hasOwnProperty('type') and other props\n    //  which makes copying more difficult.\n\n    // TODO: Probably best to create an allowlist of event props\n    const deprecatedProps = ['layerX', 'layerY', 'keyLocation', 'path', 'webkitMovementX', 'webkitMovementY', 'mozPressure', 'mozInputSource'];\n    for (const key in old) {\n      // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y\n      // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation\n      // and webkitMovementX/Y\n      // Lighthouse complains if Event.path is copied\n      if (!deprecatedProps.includes(key)) {\n        // Chrome 32+ warns if you try to copy deprecated returnValue, but\n        // we still want to if preventDefault isn't supported (IE8).\n        if (!(key === 'returnValue' && old.preventDefault)) {\n          event[key] = old[key];\n        }\n      }\n    }\n\n    // The event occurred on this element\n    if (!event.target) {\n      event.target = event.srcElement || document$1;\n    }\n\n    // Handle which other element the event is related to\n    if (!event.relatedTarget) {\n      event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;\n    }\n\n    // Stop the default browser action\n    event.preventDefault = function () {\n      if (old.preventDefault) {\n        old.preventDefault();\n      }\n      event.returnValue = false;\n      old.returnValue = false;\n      event.defaultPrevented = true;\n    };\n    event.defaultPrevented = false;\n\n    // Stop the event from bubbling\n    event.stopPropagation = function () {\n      if (old.stopPropagation) {\n        old.stopPropagation();\n      }\n      event.cancelBubble = true;\n      old.cancelBubble = true;\n      event.isPropagationStopped = returnTrue;\n    };\n    event.isPropagationStopped = returnFalse;\n\n    // Stop the event from bubbling and executing other handlers\n    event.stopImmediatePropagation = function () {\n      if (old.stopImmediatePropagation) {\n        old.stopImmediatePropagation();\n      }\n      event.isImmediatePropagationStopped = returnTrue;\n      event.stopPropagation();\n    };\n    event.isImmediatePropagationStopped = returnFalse;\n\n    // Handle mouse position\n    if (event.clientX !== null && event.clientX !== undefined) {\n      const doc = document$1.documentElement;\n      const body = document$1.body;\n      event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);\n      event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);\n    }\n\n    // Handle key presses\n    event.which = event.charCode || event.keyCode;\n\n    // Fix button for mouse clicks:\n    // 0 == left; 1 == middle; 2 == right\n    if (event.button !== null && event.button !== undefined) {\n      // The following is disabled because it does not pass videojs-standard\n      // and... yikes.\n      /* eslint-disable */\n      event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;\n      /* eslint-enable */\n    }\n  }\n  event.fixed_ = true;\n  // Returns fixed-up instance\n  return event;\n}\n\n/**\n * Whether passive event listeners are supported\n */\nlet _supportsPassive;\nconst supportsPassive = function () {\n  if (typeof _supportsPassive !== 'boolean') {\n    _supportsPassive = false;\n    try {\n      const opts = Object.defineProperty({}, 'passive', {\n        get() {\n          _supportsPassive = true;\n        }\n      });\n      window$1.addEventListener('test', null, opts);\n      window$1.removeEventListener('test', null, opts);\n    } catch (e) {\n      // disregard\n    }\n  }\n  return _supportsPassive;\n};\n\n/**\n * Touch events Chrome expects to be passive\n */\nconst passiveEvents = ['touchstart', 'touchmove'];\n\n/**\n * Add an event listener to element\n * It stores the handler function in a separate cache object\n * and adds a generic handler to the element's event,\n * along with a unique id (guid) to the element.\n *\n * @param {Element|Object} elem\n *        Element or object to bind listeners to\n *\n * @param {string|string[]} type\n *        Type of event to bind to.\n *\n * @param {Function} fn\n *        Event listener.\n */\nfunction on(elem, type, fn) {\n  if (Array.isArray(type)) {\n    return _handleMultipleEvents(on, elem, type, fn);\n  }\n  if (!DomData.has(elem)) {\n    DomData.set(elem, {});\n  }\n  const data = DomData.get(elem);\n\n  // We need a place to store all our handler data\n  if (!data.handlers) {\n    data.handlers = {};\n  }\n  if (!data.handlers[type]) {\n    data.handlers[type] = [];\n  }\n  if (!fn.guid) {\n    fn.guid = newGUID();\n  }\n  data.handlers[type].push(fn);\n  if (!data.dispatcher) {\n    data.disabled = false;\n    data.dispatcher = function (event, hash) {\n      if (data.disabled) {\n        return;\n      }\n      event = fixEvent(event);\n      const handlers = data.handlers[event.type];\n      if (handlers) {\n        // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.\n        const handlersCopy = handlers.slice(0);\n        for (let m = 0, n = handlersCopy.length; m < n; m++) {\n          if (event.isImmediatePropagationStopped()) {\n            break;\n          } else {\n            try {\n              handlersCopy[m].call(elem, event, hash);\n            } catch (e) {\n              log$1.error(e);\n            }\n          }\n        }\n      }\n    };\n  }\n  if (data.handlers[type].length === 1) {\n    if (elem.addEventListener) {\n      let options = false;\n      if (supportsPassive() && passiveEvents.indexOf(type) > -1) {\n        options = {\n          passive: true\n        };\n      }\n      elem.addEventListener(type, data.dispatcher, options);\n    } else if (elem.attachEvent) {\n      elem.attachEvent('on' + type, data.dispatcher);\n    }\n  }\n}\n\n/**\n * Removes event listeners from an element\n *\n * @param {Element|Object} elem\n *        Object to remove listeners from.\n *\n * @param {string|string[]} [type]\n *        Type of listener to remove. Don't include to remove all events from element.\n *\n * @param {Function} [fn]\n *        Specific listener to remove. Don't include to remove listeners for an event\n *        type.\n */\nfunction off(elem, type, fn) {\n  // Don't want to add a cache object through getElData if not needed\n  if (!DomData.has(elem)) {\n    return;\n  }\n  const data = DomData.get(elem);\n\n  // If no events exist, nothing to unbind\n  if (!data.handlers) {\n    return;\n  }\n  if (Array.isArray(type)) {\n    return _handleMultipleEvents(off, elem, type, fn);\n  }\n\n  // Utility function\n  const removeType = function (el, t) {\n    data.handlers[t] = [];\n    _cleanUpEvents(el, t);\n  };\n\n  // Are we removing all bound events?\n  if (type === undefined) {\n    for (const t in data.handlers) {\n      if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {\n        removeType(elem, t);\n      }\n    }\n    return;\n  }\n  const handlers = data.handlers[type];\n\n  // If no handlers exist, nothing to unbind\n  if (!handlers) {\n    return;\n  }\n\n  // If no listener was provided, remove all listeners for type\n  if (!fn) {\n    removeType(elem, type);\n    return;\n  }\n\n  // We're only removing a single handler\n  if (fn.guid) {\n    for (let n = 0; n < handlers.length; n++) {\n      if (handlers[n].guid === fn.guid) {\n        handlers.splice(n--, 1);\n      }\n    }\n  }\n  _cleanUpEvents(elem, type);\n}\n\n/**\n * Trigger an event for an element\n *\n * @param {Element|Object} elem\n *        Element to trigger an event on\n *\n * @param {EventTarget~Event|string} event\n *        A string (the type) or an event object with a type attribute\n *\n * @param {Object} [hash]\n *        data hash to pass along with the event\n *\n * @return {boolean|undefined}\n *         Returns the opposite of `defaultPrevented` if default was\n *         prevented. Otherwise, returns `undefined`\n */\nfunction trigger(elem, event, hash) {\n  // Fetches element data and a reference to the parent (for bubbling).\n  // Don't want to add a data object to cache for every parent,\n  // so checking hasElData first.\n  const elemData = DomData.has(elem) ? DomData.get(elem) : {};\n  const parent = elem.parentNode || elem.ownerDocument;\n  // type = event.type || event,\n  // handler;\n\n  // If an event name was passed as a string, creates an event out of it\n  if (typeof event === 'string') {\n    event = {\n      type: event,\n      target: elem\n    };\n  } else if (!event.target) {\n    event.target = elem;\n  }\n\n  // Normalizes the event properties.\n  event = fixEvent(event);\n\n  // If the passed element has a dispatcher, executes the established handlers.\n  if (elemData.dispatcher) {\n    elemData.dispatcher.call(elem, event, hash);\n  }\n\n  // Unless explicitly stopped or the event does not bubble (e.g. media events)\n  // recursively calls this function to bubble the event up the DOM.\n  if (parent && !event.isPropagationStopped() && event.bubbles === true) {\n    trigger.call(null, parent, event, hash);\n\n    // If at the top of the DOM, triggers the default action unless disabled.\n  } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {\n    if (!DomData.has(event.target)) {\n      DomData.set(event.target, {});\n    }\n    const targetData = DomData.get(event.target);\n\n    // Checks if the target has a default action for this event.\n    if (event.target[event.type]) {\n      // Temporarily disables event dispatching on the target as we have already executed the handler.\n      targetData.disabled = true;\n      // Executes the default action.\n      if (typeof event.target[event.type] === 'function') {\n        event.target[event.type]();\n      }\n      // Re-enables event dispatching.\n      targetData.disabled = false;\n    }\n  }\n\n  // Inform the triggerer if the default was prevented by returning false\n  return !event.defaultPrevented;\n}\n\n/**\n * Trigger a listener only once for an event.\n *\n * @param {Element|Object} elem\n *        Element or object to bind to.\n *\n * @param {string|string[]} type\n *        Name/type of event\n *\n * @param {Event~EventListener} fn\n *        Event listener function\n */\nfunction one(elem, type, fn) {\n  if (Array.isArray(type)) {\n    return _handleMultipleEvents(one, elem, type, fn);\n  }\n  const func = function () {\n    off(elem, type, func);\n    fn.apply(this, arguments);\n  };\n\n  // copy the guid to the new function so it can removed using the original function's ID\n  func.guid = fn.guid = fn.guid || newGUID();\n  on(elem, type, func);\n}\n\n/**\n * Trigger a listener only once and then turn if off for all\n * configured events\n *\n * @param {Element|Object} elem\n *        Element or object to bind to.\n *\n * @param {string|string[]} type\n *        Name/type of event\n *\n * @param {Event~EventListener} fn\n *        Event listener function\n */\nfunction any(elem, type, fn) {\n  const func = function () {\n    off(elem, type, func);\n    fn.apply(this, arguments);\n  };\n\n  // copy the guid to the new function so it can removed using the original function's ID\n  func.guid = fn.guid = fn.guid || newGUID();\n\n  // multiple ons, but one off for everything\n  on(elem, type, func);\n}\n\nvar Events = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  fixEvent: fixEvent,\n  on: on,\n  off: off,\n  trigger: trigger,\n  one: one,\n  any: any\n});\n\n/**\n * @file fn.js\n * @module fn\n */\nconst UPDATE_REFRESH_INTERVAL = 30;\n\n/**\n * A private, internal-only function for changing the context of a function.\n *\n * It also stores a unique id on the function so it can be easily removed from\n * events.\n *\n * @private\n * @function\n * @param    {*} context\n *           The object to bind as scope.\n *\n * @param    {Function} fn\n *           The function to be bound to a scope.\n *\n * @param    {number} [uid]\n *           An optional unique ID for the function to be set\n *\n * @return   {Function}\n *           The new function that will be bound into the context given\n */\nconst bind_ = function (context, fn, uid) {\n  // Make sure the function has a unique ID\n  if (!fn.guid) {\n    fn.guid = newGUID();\n  }\n\n  // Create the new function that changes the context\n  const bound = fn.bind(context);\n\n  // Allow for the ability to individualize this function\n  // Needed in the case where multiple objects might share the same prototype\n  // IF both items add an event listener with the same function, then you try to remove just one\n  // it will remove both because they both have the same guid.\n  // when using this, you need to use the bind method when you remove the listener as well.\n  // currently used in text tracks\n  bound.guid = uid ? uid + '_' + fn.guid : fn.guid;\n  return bound;\n};\n\n/**\n * Wraps the given function, `fn`, with a new function that only invokes `fn`\n * at most once per every `wait` milliseconds.\n *\n * @function\n * @param    {Function} fn\n *           The function to be throttled.\n *\n * @param    {number}   wait\n *           The number of milliseconds by which to throttle.\n *\n * @return   {Function}\n */\nconst throttle = function (fn, wait) {\n  let last = window$1.performance.now();\n  const throttled = function (...args) {\n    const now = window$1.performance.now();\n    if (now - last >= wait) {\n      fn(...args);\n      last = now;\n    }\n  };\n  return throttled;\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked.\n *\n * Inspired by lodash and underscore implementations.\n *\n * @function\n * @param    {Function} func\n *           The function to wrap with debounce behavior.\n *\n * @param    {number} wait\n *           The number of milliseconds to wait after the last invocation.\n *\n * @param    {boolean} [immediate]\n *           Whether or not to invoke the function immediately upon creation.\n *\n * @param    {Object} [context=window]\n *           The \"context\" in which the debounced function should debounce. For\n *           example, if this function should be tied to a Video.js player,\n *           the player can be passed here. Alternatively, defaults to the\n *           global `window` object.\n *\n * @return   {Function}\n *           A debounced function.\n */\nconst debounce$1 = function (func, wait, immediate, context = window$1) {\n  let timeout;\n  const cancel = () => {\n    context.clearTimeout(timeout);\n    timeout = null;\n  };\n\n  /* eslint-disable consistent-this */\n  const debounced = function () {\n    const self = this;\n    const args = arguments;\n    let later = function () {\n      timeout = null;\n      later = null;\n      if (!immediate) {\n        func.apply(self, args);\n      }\n    };\n    if (!timeout && immediate) {\n      func.apply(self, args);\n    }\n    context.clearTimeout(timeout);\n    timeout = context.setTimeout(later, wait);\n  };\n  /* eslint-enable consistent-this */\n\n  debounced.cancel = cancel;\n  return debounced;\n};\n\nvar Fn = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  UPDATE_REFRESH_INTERVAL: UPDATE_REFRESH_INTERVAL,\n  bind_: bind_,\n  throttle: throttle,\n  debounce: debounce$1\n});\n\n/**\n * @file src/js/event-target.js\n */\nlet EVENT_MAP;\n\n/**\n * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It\n * adds shorthand functions that wrap around lengthy functions. For example:\n * the `on` function is a wrapper around `addEventListener`.\n *\n * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}\n * @class EventTarget\n */\nclass EventTarget$2 {\n  /**\n   * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a\n   * function that will get called when an event with a certain name gets triggered.\n   *\n   * @param {string|string[]} type\n   *        An event name or an array of event names.\n   *\n   * @param {Function} fn\n   *        The function to call with `EventTarget`s\n   */\n  on(type, fn) {\n    // Remove the addEventListener alias before calling Events.on\n    // so we don't get into an infinite type loop\n    const ael = this.addEventListener;\n    this.addEventListener = () => {};\n    on(this, type, fn);\n    this.addEventListener = ael;\n  }\n  /**\n   * Removes an `event listener` for a specific event from an instance of `EventTarget`.\n   * This makes it so that the `event listener` will no longer get called when the\n   * named event happens.\n   *\n   * @param {string|string[]} type\n   *        An event name or an array of event names.\n   *\n   * @param {Function} fn\n   *        The function to remove.\n   */\n  off(type, fn) {\n    off(this, type, fn);\n  }\n  /**\n   * This function will add an `event listener` that gets triggered only once. After the\n   * first trigger it will get removed. This is like adding an `event listener`\n   * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.\n   *\n   * @param {string|string[]} type\n   *        An event name or an array of event names.\n   *\n   * @param {Function} fn\n   *        The function to be called once for each event name.\n   */\n  one(type, fn) {\n    // Remove the addEventListener aliasing Events.on\n    // so we don't get into an infinite type loop\n    const ael = this.addEventListener;\n    this.addEventListener = () => {};\n    one(this, type, fn);\n    this.addEventListener = ael;\n  }\n  /**\n   * This function will add an `event listener` that gets triggered only once and is\n   * removed from all events. This is like adding an array of `event listener`s\n   * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the\n   * first time it is triggered.\n   *\n   * @param {string|string[]} type\n   *        An event name or an array of event names.\n   *\n   * @param {Function} fn\n   *        The function to be called once for each event name.\n   */\n  any(type, fn) {\n    // Remove the addEventListener aliasing Events.on\n    // so we don't get into an infinite type loop\n    const ael = this.addEventListener;\n    this.addEventListener = () => {};\n    any(this, type, fn);\n    this.addEventListener = ael;\n  }\n  /**\n   * This function causes an event to happen. This will then cause any `event listeners`\n   * that are waiting for that event, to get called. If there are no `event listeners`\n   * for an event then nothing will happen.\n   *\n   * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.\n   * Trigger will also call the `on` + `uppercaseEventName` function.\n   *\n   * Example:\n   * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call\n   * `onClick` if it exists.\n   *\n   * @param {string|EventTarget~Event|Object} event\n   *        The name of the event, an `Event`, or an object with a key of type set to\n   *        an event name.\n   */\n  trigger(event) {\n    const type = event.type || event;\n\n    // deprecation\n    // In a future version we should default target to `this`\n    // similar to how we default the target to `elem` in\n    // `Events.trigger`. Right now the default `target` will be\n    // `document` due to the `Event.fixEvent` call.\n    if (typeof event === 'string') {\n      event = {\n        type\n      };\n    }\n    event = fixEvent(event);\n    if (this.allowedEvents_[type] && this['on' + type]) {\n      this['on' + type](event);\n    }\n    trigger(this, event);\n  }\n  queueTrigger(event) {\n    // only set up EVENT_MAP if it'll be used\n    if (!EVENT_MAP) {\n      EVENT_MAP = new Map();\n    }\n    const type = event.type || event;\n    let map = EVENT_MAP.get(this);\n    if (!map) {\n      map = new Map();\n      EVENT_MAP.set(this, map);\n    }\n    const oldTimeout = map.get(type);\n    map.delete(type);\n    window$1.clearTimeout(oldTimeout);\n    const timeout = window$1.setTimeout(() => {\n      map.delete(type);\n      // if we cleared out all timeouts for the current target, delete its map\n      if (map.size === 0) {\n        map = null;\n        EVENT_MAP.delete(this);\n      }\n      this.trigger(event);\n    }, 0);\n    map.set(type, timeout);\n  }\n}\n\n/**\n * A Custom DOM event.\n *\n * @typedef {CustomEvent} Event\n * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}\n */\n\n/**\n * All event listeners should follow the following format.\n *\n * @callback EventListener\n * @this {EventTarget}\n *\n * @param {Event} event\n *        the event that triggered this function\n *\n * @param {Object} [hash]\n *        hash of data sent during the event\n */\n\n/**\n * An object containing event names as keys and booleans as values.\n *\n * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}\n *         will have extra functionality. See that function for more information.\n *\n * @property EventTarget.prototype.allowedEvents_\n * @protected\n */\nEventTarget$2.prototype.allowedEvents_ = {};\n\n/**\n * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic\n * the standard DOM API.\n *\n * @function\n * @see {@link EventTarget#on}\n */\nEventTarget$2.prototype.addEventListener = EventTarget$2.prototype.on;\n\n/**\n * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic\n * the standard DOM API.\n *\n * @function\n * @see {@link EventTarget#off}\n */\nEventTarget$2.prototype.removeEventListener = EventTarget$2.prototype.off;\n\n/**\n * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic\n * the standard DOM API.\n *\n * @function\n * @see {@link EventTarget#trigger}\n */\nEventTarget$2.prototype.dispatchEvent = EventTarget$2.prototype.trigger;\n\n/**\n * @file mixins/evented.js\n * @module evented\n */\nconst objName = obj => {\n  if (typeof obj.name === 'function') {\n    return obj.name();\n  }\n  if (typeof obj.name === 'string') {\n    return obj.name;\n  }\n  if (obj.name_) {\n    return obj.name_;\n  }\n  if (obj.constructor && obj.constructor.name) {\n    return obj.constructor.name;\n  }\n  return typeof obj;\n};\n\n/**\n * Returns whether or not an object has had the evented mixin applied.\n *\n * @param  {Object} object\n *         An object to test.\n *\n * @return {boolean}\n *         Whether or not the object appears to be evented.\n */\nconst isEvented = object => object instanceof EventTarget$2 || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(k => typeof object[k] === 'function');\n\n/**\n * Adds a callback to run after the evented mixin applied.\n *\n * @param  {Object} target\n *         An object to Add\n * @param  {Function} callback\n *         The callback to run.\n */\nconst addEventedCallback = (target, callback) => {\n  if (isEvented(target)) {\n    callback();\n  } else {\n    if (!target.eventedCallbacks) {\n      target.eventedCallbacks = [];\n    }\n    target.eventedCallbacks.push(callback);\n  }\n};\n\n/**\n * Whether a value is a valid event type - non-empty string or array.\n *\n * @private\n * @param  {string|Array} type\n *         The type value to test.\n *\n * @return {boolean}\n *         Whether or not the type is a valid event type.\n */\nconst isValidEventType = type =>\n// The regex here verifies that the `type` contains at least one non-\n// whitespace character.\ntypeof type === 'string' && /\\S/.test(type) || Array.isArray(type) && !!type.length;\n\n/**\n * Validates a value to determine if it is a valid event target. Throws if not.\n *\n * @private\n * @throws {Error}\n *         If the target does not appear to be a valid event target.\n *\n * @param  {Object} target\n *         The object to test.\n *\n * @param  {Object} obj\n *         The evented object we are validating for\n *\n * @param  {string} fnName\n *         The name of the evented mixin function that called this.\n */\nconst validateTarget = (target, obj, fnName) => {\n  if (!target || !target.nodeName && !isEvented(target)) {\n    throw new Error(`Invalid target for ${objName(obj)}#${fnName}; must be a DOM node or evented object.`);\n  }\n};\n\n/**\n * Validates a value to determine if it is a valid event target. Throws if not.\n *\n * @private\n * @throws {Error}\n *         If the type does not appear to be a valid event type.\n *\n * @param  {string|Array} type\n *         The type to test.\n *\n * @param  {Object} obj\n*         The evented object we are validating for\n *\n * @param  {string} fnName\n *         The name of the evented mixin function that called this.\n */\nconst validateEventType = (type, obj, fnName) => {\n  if (!isValidEventType(type)) {\n    throw new Error(`Invalid event type for ${objName(obj)}#${fnName}; must be a non-empty string or array.`);\n  }\n};\n\n/**\n * Validates a value to determine if it is a valid listener. Throws if not.\n *\n * @private\n * @throws {Error}\n *         If the listener is not a function.\n *\n * @param  {Function} listener\n *         The listener to test.\n *\n * @param  {Object} obj\n *         The evented object we are validating for\n *\n * @param  {string} fnName\n *         The name of the evented mixin function that called this.\n */\nconst validateListener = (listener, obj, fnName) => {\n  if (typeof listener !== 'function') {\n    throw new Error(`Invalid listener for ${objName(obj)}#${fnName}; must be a function.`);\n  }\n};\n\n/**\n * Takes an array of arguments given to `on()` or `one()`, validates them, and\n * normalizes them into an object.\n *\n * @private\n * @param  {Object} self\n *         The evented object on which `on()` or `one()` was called. This\n *         object will be bound as the `this` value for the listener.\n *\n * @param  {Array} args\n *         An array of arguments passed to `on()` or `one()`.\n *\n * @param  {string} fnName\n *         The name of the evented mixin function that called this.\n *\n * @return {Object}\n *         An object containing useful values for `on()` or `one()` calls.\n */\nconst normalizeListenArgs = (self, args, fnName) => {\n  // If the number of arguments is less than 3, the target is always the\n  // evented object itself.\n  const isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;\n  let target;\n  let type;\n  let listener;\n  if (isTargetingSelf) {\n    target = self.eventBusEl_;\n\n    // Deal with cases where we got 3 arguments, but we are still listening to\n    // the evented object itself.\n    if (args.length >= 3) {\n      args.shift();\n    }\n    [type, listener] = args;\n  } else {\n    // This was `[target, type, listener] = args;` but this block needs more than\n    // one statement to produce minified output compatible with Chrome 53.\n    // See https://github.com/videojs/video.js/pull/8810\n    target = args[0];\n    type = args[1];\n    listener = args[2];\n  }\n  validateTarget(target, self, fnName);\n  validateEventType(type, self, fnName);\n  validateListener(listener, self, fnName);\n  listener = bind_(self, listener);\n  return {\n    isTargetingSelf,\n    target,\n    type,\n    listener\n  };\n};\n\n/**\n * Adds the listener to the event type(s) on the target, normalizing for\n * the type of target.\n *\n * @private\n * @param  {Element|Object} target\n *         A DOM node or evented object.\n *\n * @param  {string} method\n *         The event binding method to use (\"on\" or \"one\").\n *\n * @param  {string|Array} type\n *         One or more event type(s).\n *\n * @param  {Function} listener\n *         A listener function.\n */\nconst listen = (target, method, type, listener) => {\n  validateTarget(target, target, method);\n  if (target.nodeName) {\n    Events[method](target, type, listener);\n  } else {\n    target[method](type, listener);\n  }\n};\n\n/**\n * Contains methods that provide event capabilities to an object which is passed\n * to {@link module:evented|evented}.\n *\n * @mixin EventedMixin\n */\nconst EventedMixin = {\n  /**\n   * Add a listener to an event (or events) on this object or another evented\n   * object.\n   *\n   * @param  {string|Array|Element|Object} targetOrType\n   *         If this is a string or array, it represents the event type(s)\n   *         that will trigger the listener.\n   *\n   *         Another evented object can be passed here instead, which will\n   *         cause the listener to listen for events on _that_ object.\n   *\n   *         In either case, the listener's `this` value will be bound to\n   *         this object.\n   *\n   * @param  {string|Array|Function} typeOrListener\n   *         If the first argument was a string or array, this should be the\n   *         listener function. Otherwise, this is a string or array of event\n   *         type(s).\n   *\n   * @param  {Function} [listener]\n   *         If the first argument was another evented object, this will be\n   *         the listener function.\n   */\n  on(...args) {\n    const {\n      isTargetingSelf,\n      target,\n      type,\n      listener\n    } = normalizeListenArgs(this, args, 'on');\n    listen(target, 'on', type, listener);\n\n    // If this object is listening to another evented object.\n    if (!isTargetingSelf) {\n      // If this object is disposed, remove the listener.\n      const removeListenerOnDispose = () => this.off(target, type, listener);\n\n      // Use the same function ID as the listener so we can remove it later it\n      // using the ID of the original listener.\n      removeListenerOnDispose.guid = listener.guid;\n\n      // Add a listener to the target's dispose event as well. This ensures\n      // that if the target is disposed BEFORE this object, we remove the\n      // removal listener that was just added. Otherwise, we create a memory leak.\n      const removeRemoverOnTargetDispose = () => this.off('dispose', removeListenerOnDispose);\n\n      // Use the same function ID as the listener so we can remove it later\n      // it using the ID of the original listener.\n      removeRemoverOnTargetDispose.guid = listener.guid;\n      listen(this, 'on', 'dispose', removeListenerOnDispose);\n      listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);\n    }\n  },\n  /**\n   * Add a listener to an event (or events) on this object or another evented\n   * object. The listener will be called once per event and then removed.\n   *\n   * @param  {string|Array|Element|Object} targetOrType\n   *         If this is a string or array, it represents the event type(s)\n   *         that will trigger the listener.\n   *\n   *         Another evented object can be passed here instead, which will\n   *         cause the listener to listen for events on _that_ object.\n   *\n   *         In either case, the listener's `this` value will be bound to\n   *         this object.\n   *\n   * @param  {string|Array|Function} typeOrListener\n   *         If the first argument was a string or array, this should be the\n   *         listener function. Otherwise, this is a string or array of event\n   *         type(s).\n   *\n   * @param  {Function} [listener]\n   *         If the first argument was another evented object, this will be\n   *         the listener function.\n   */\n  one(...args) {\n    const {\n      isTargetingSelf,\n      target,\n      type,\n      listener\n    } = normalizeListenArgs(this, args, 'one');\n\n    // Targeting this evented object.\n    if (isTargetingSelf) {\n      listen(target, 'one', type, listener);\n\n      // Targeting another evented object.\n    } else {\n      // TODO: This wrapper is incorrect! It should only\n      //       remove the wrapper for the event type that called it.\n      //       Instead all listeners are removed on the first trigger!\n      //       see https://github.com/videojs/video.js/issues/5962\n      const wrapper = (...largs) => {\n        this.off(target, type, wrapper);\n        listener.apply(null, largs);\n      };\n\n      // Use the same function ID as the listener so we can remove it later\n      // it using the ID of the original listener.\n      wrapper.guid = listener.guid;\n      listen(target, 'one', type, wrapper);\n    }\n  },\n  /**\n   * Add a listener to an event (or events) on this object or another evented\n   * object. The listener will only be called once for the first event that is triggered\n   * then removed.\n   *\n   * @param  {string|Array|Element|Object} targetOrType\n   *         If this is a string or array, it represents the event type(s)\n   *         that will trigger the listener.\n   *\n   *         Another evented object can be passed here instead, which will\n   *         cause the listener to listen for events on _that_ object.\n   *\n   *         In either case, the listener's `this` value will be bound to\n   *         this object.\n   *\n   * @param  {string|Array|Function} typeOrListener\n   *         If the first argument was a string or array, this should be the\n   *         listener function. Otherwise, this is a string or array of event\n   *         type(s).\n   *\n   * @param  {Function} [listener]\n   *         If the first argument was another evented object, this will be\n   *         the listener function.\n   */\n  any(...args) {\n    const {\n      isTargetingSelf,\n      target,\n      type,\n      listener\n    } = normalizeListenArgs(this, args, 'any');\n\n    // Targeting this evented object.\n    if (isTargetingSelf) {\n      listen(target, 'any', type, listener);\n\n      // Targeting another evented object.\n    } else {\n      const wrapper = (...largs) => {\n        this.off(target, type, wrapper);\n        listener.apply(null, largs);\n      };\n\n      // Use the same function ID as the listener so we can remove it later\n      // it using the ID of the original listener.\n      wrapper.guid = listener.guid;\n      listen(target, 'any', type, wrapper);\n    }\n  },\n  /**\n   * Removes listener(s) from event(s) on an evented object.\n   *\n   * @param  {string|Array|Element|Object} [targetOrType]\n   *         If this is a string or array, it represents the event type(s).\n   *\n   *         Another evented object can be passed here instead, in which case\n   *         ALL 3 arguments are _required_.\n   *\n   * @param  {string|Array|Function} [typeOrListener]\n   *         If the first argument was a string or array, this may be the\n   *         listener function. Otherwise, this is a string or array of event\n   *         type(s).\n   *\n   * @param  {Function} [listener]\n   *         If the first argument was another evented object, this will be\n   *         the listener function; otherwise, _all_ listeners bound to the\n   *         event type(s) will be removed.\n   */\n  off(targetOrType, typeOrListener, listener) {\n    // Targeting this evented object.\n    if (!targetOrType || isValidEventType(targetOrType)) {\n      off(this.eventBusEl_, targetOrType, typeOrListener);\n\n      // Targeting another evented object.\n    } else {\n      const target = targetOrType;\n      const type = typeOrListener;\n\n      // Fail fast and in a meaningful way!\n      validateTarget(target, this, 'off');\n      validateEventType(type, this, 'off');\n      validateListener(listener, this, 'off');\n\n      // Ensure there's at least a guid, even if the function hasn't been used\n      listener = bind_(this, listener);\n\n      // Remove the dispose listener on this evented object, which was given\n      // the same guid as the event listener in on().\n      this.off('dispose', listener);\n      if (target.nodeName) {\n        off(target, type, listener);\n        off(target, 'dispose', listener);\n      } else if (isEvented(target)) {\n        target.off(type, listener);\n        target.off('dispose', listener);\n      }\n    }\n  },\n  /**\n   * Fire an event on this evented object, causing its listeners to be called.\n   *\n   * @param   {string|Object} event\n   *          An event type or an object with a type property.\n   *\n   * @param   {Object} [hash]\n   *          An additional object to pass along to listeners.\n   *\n   * @return {boolean}\n   *          Whether or not the default behavior was prevented.\n   */\n  trigger(event, hash) {\n    validateTarget(this.eventBusEl_, this, 'trigger');\n    const type = event && typeof event !== 'string' ? event.type : event;\n    if (!isValidEventType(type)) {\n      throw new Error(`Invalid event type for ${objName(this)}#trigger; ` + 'must be a non-empty string or object with a type key that has a non-empty value.');\n    }\n    return trigger(this.eventBusEl_, event, hash);\n  }\n};\n\n/**\n * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.\n *\n * @param  {Object} target\n *         The object to which to add event methods.\n *\n * @param  {Object} [options={}]\n *         Options for customizing the mixin behavior.\n *\n * @param  {string} [options.eventBusKey]\n *         By default, adds a `eventBusEl_` DOM element to the target object,\n *         which is used as an event bus. If the target object already has a\n *         DOM element that should be used, pass its key here.\n *\n * @return {Object}\n *         The target object.\n */\nfunction evented(target, options = {}) {\n  const {\n    eventBusKey\n  } = options;\n\n  // Set or create the eventBusEl_.\n  if (eventBusKey) {\n    if (!target[eventBusKey].nodeName) {\n      throw new Error(`The eventBusKey \"${eventBusKey}\" does not refer to an element.`);\n    }\n    target.eventBusEl_ = target[eventBusKey];\n  } else {\n    target.eventBusEl_ = createEl('span', {\n      className: 'vjs-event-bus'\n    });\n  }\n  Object.assign(target, EventedMixin);\n  if (target.eventedCallbacks) {\n    target.eventedCallbacks.forEach(callback => {\n      callback();\n    });\n  }\n\n  // When any evented object is disposed, it removes all its listeners.\n  target.on('dispose', () => {\n    target.off();\n    [target, target.el_, target.eventBusEl_].forEach(function (val) {\n      if (val && DomData.has(val)) {\n        DomData.delete(val);\n      }\n    });\n    window$1.setTimeout(() => {\n      target.eventBusEl_ = null;\n    }, 0);\n  });\n  return target;\n}\n\n/**\n * @file mixins/stateful.js\n * @module stateful\n */\n\n/**\n * Contains methods that provide statefulness to an object which is passed\n * to {@link module:stateful}.\n *\n * @mixin StatefulMixin\n */\nconst StatefulMixin = {\n  /**\n   * A hash containing arbitrary keys and values representing the state of\n   * the object.\n   *\n   * @type {Object}\n   */\n  state: {},\n  /**\n   * Set the state of an object by mutating its\n   * {@link module:stateful~StatefulMixin.state|state} object in place.\n   *\n   * @fires   module:stateful~StatefulMixin#statechanged\n   * @param   {Object|Function} stateUpdates\n   *          A new set of properties to shallow-merge into the plugin state.\n   *          Can be a plain object or a function returning a plain object.\n   *\n   * @return {Object|undefined}\n   *          An object containing changes that occurred. If no changes\n   *          occurred, returns `undefined`.\n   */\n  setState(stateUpdates) {\n    // Support providing the `stateUpdates` state as a function.\n    if (typeof stateUpdates === 'function') {\n      stateUpdates = stateUpdates();\n    }\n    let changes;\n    each(stateUpdates, (value, key) => {\n      // Record the change if the value is different from what's in the\n      // current state.\n      if (this.state[key] !== value) {\n        changes = changes || {};\n        changes[key] = {\n          from: this.state[key],\n          to: value\n        };\n      }\n      this.state[key] = value;\n    });\n\n    // Only trigger \"statechange\" if there were changes AND we have a trigger\n    // function. This allows us to not require that the target object be an\n    // evented object.\n    if (changes && isEvented(this)) {\n      /**\n       * An event triggered on an object that is both\n       * {@link module:stateful|stateful} and {@link module:evented|evented}\n       * indicating that its state has changed.\n       *\n       * @event    module:stateful~StatefulMixin#statechanged\n       * @type     {Object}\n       * @property {Object} changes\n       *           A hash containing the properties that were changed and\n       *           the values they were changed `from` and `to`.\n       */\n      this.trigger({\n        changes,\n        type: 'statechanged'\n      });\n    }\n    return changes;\n  }\n};\n\n/**\n * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target\n * object.\n *\n * If the target object is {@link module:evented|evented} and has a\n * `handleStateChanged` method, that method will be automatically bound to the\n * `statechanged` event on itself.\n *\n * @param   {Object} target\n *          The object to be made stateful.\n *\n * @param   {Object} [defaultState]\n *          A default set of properties to populate the newly-stateful object's\n *          `state` property.\n *\n * @return {Object}\n *          Returns the `target`.\n */\nfunction stateful(target, defaultState) {\n  Object.assign(target, StatefulMixin);\n\n  // This happens after the mixing-in because we need to replace the `state`\n  // added in that step.\n  target.state = Object.assign({}, target.state, defaultState);\n\n  // Auto-bind the `handleStateChanged` method of the target object if it exists.\n  if (typeof target.handleStateChanged === 'function' && isEvented(target)) {\n    target.on('statechanged', target.handleStateChanged);\n  }\n  return target;\n}\n\n/**\n * @file str.js\n * @module to-lower-case\n */\n\n/**\n * Lowercase the first letter of a string.\n *\n * @param {string} string\n *        String to be lowercased\n *\n * @return {string}\n *         The string with a lowercased first letter\n */\nconst toLowerCase = function (string) {\n  if (typeof string !== 'string') {\n    return string;\n  }\n  return string.replace(/./, w => w.toLowerCase());\n};\n\n/**\n * Uppercase the first letter of a string.\n *\n * @param {string} string\n *        String to be uppercased\n *\n * @return {string}\n *         The string with an uppercased first letter\n */\nconst toTitleCase$1 = function (string) {\n  if (typeof string !== 'string') {\n    return string;\n  }\n  return string.replace(/./, w => w.toUpperCase());\n};\n\n/**\n * Compares the TitleCase versions of the two strings for equality.\n *\n * @param {string} str1\n *        The first string to compare\n *\n * @param {string} str2\n *        The second string to compare\n *\n * @return {boolean}\n *         Whether the TitleCase versions of the strings are equal\n */\nconst titleCaseEquals = function (str1, str2) {\n  return toTitleCase$1(str1) === toTitleCase$1(str2);\n};\n\nvar Str = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  toLowerCase: toLowerCase,\n  toTitleCase: toTitleCase$1,\n  titleCaseEquals: titleCaseEquals\n});\n\n/**\n * Player Component - Base class for all UI objects\n *\n * @file component.js\n */\n\n/** @import Player from './player' */\n\n/**\n * A callback to be called if and when the component is ready.\n * `this` will be the Component instance.\n *\n * @callback ReadyCallback\n * @returns  {void}\n */\n\n/**\n * Base class for all UI Components.\n * Components are UI objects which represent both a javascript object and an element\n * in the DOM. They can be children of other components, and can have\n * children themselves.\n *\n * Components can also use methods from {@link EventTarget}\n */\nclass Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of component options.\n   *\n   * @param {Object[]} [options.children]\n   *        An array of children objects to initialize this component with. Children objects have\n   *        a name property that will be used if more than one component of the same type needs to be\n   *        added.\n   *\n   * @param  {string} [options.className]\n   *         A class or space separated list of classes to add the component\n   *\n   * @param {ReadyCallback} [ready]\n   *        Function that gets called when the `Component` is ready.\n   */\n  constructor(player, options, ready) {\n    // The component might be the player itself and we can't pass `this` to super\n    if (!player && this.play) {\n      this.player_ = player = this; // eslint-disable-line\n    } else {\n      this.player_ = player;\n    }\n    this.isDisposed_ = false;\n\n    // Hold the reference to the parent component via `addChild` method\n    this.parentComponent_ = null;\n\n    // Make a copy of prototype.options_ to protect against overriding defaults\n    this.options_ = merge$1({}, this.options_);\n\n    // Updated options with supplied options\n    options = this.options_ = merge$1(this.options_, options);\n\n    // Get ID from options or options element if one is supplied\n    this.id_ = options.id || options.el && options.el.id;\n\n    // If there was no ID from the options, generate one\n    if (!this.id_) {\n      // Don't require the player ID function in the case of mock players\n      const id = player && player.id && player.id() || 'no_player';\n      this.id_ = `${id}_component_${newGUID()}`;\n    }\n    this.name_ = options.name || null;\n\n    // Create element if one wasn't provided in options\n    if (options.el) {\n      this.el_ = options.el;\n    } else if (options.createEl !== false) {\n      this.el_ = this.createEl();\n    }\n    if (options.className && this.el_) {\n      options.className.split(' ').forEach(c => this.addClass(c));\n    }\n\n    // Remove the placeholder event methods. If the component is evented, the\n    // real methods are added next\n    ['on', 'off', 'one', 'any', 'trigger'].forEach(fn => {\n      this[fn] = undefined;\n    });\n\n    // if evented is anything except false, we want to mixin in evented\n    if (options.evented !== false) {\n      // Make this an evented object and use `el_`, if available, as its event bus\n      evented(this, {\n        eventBusKey: this.el_ ? 'el_' : null\n      });\n      this.handleLanguagechange = this.handleLanguagechange.bind(this);\n      this.on(this.player_, 'languagechange', this.handleLanguagechange);\n    }\n    stateful(this, this.constructor.defaultState);\n    this.children_ = [];\n    this.childIndex_ = {};\n    this.childNameIndex_ = {};\n    this.setTimeoutIds_ = new Set();\n    this.setIntervalIds_ = new Set();\n    this.rafIds_ = new Set();\n    this.namedRafs_ = new Map();\n    this.clearingTimersOnDispose_ = false;\n\n    // Add any child components in options\n    if (options.initChildren !== false) {\n      this.initChildren();\n    }\n\n    // Don't want to trigger ready here or it will go before init is actually\n    // finished for all children that run this constructor\n    this.ready(ready);\n    if (options.reportTouchActivity !== false) {\n      this.enableTouchActivity();\n    }\n  }\n\n  // `on`, `off`, `one`, `any` and `trigger` are here so tsc includes them in definitions.\n  // They are replaced or removed in the constructor\n\n  /**\n   * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a\n   * function that will get called when an event with a certain name gets triggered.\n   *\n   * @param {string|string[]} type\n   *        An event name or an array of event names.\n   *\n   * @param {Function} fn\n   *        The function to call with `EventTarget`s\n   */\n\n  /**\n   * Removes an `event listener` for a specific event from an instance of `EventTarget`.\n   * This makes it so that the `event listener` will no longer get called when the\n   * named event happens.\n   *\n   * @param {string|string[]} type\n   *        An event name or an array of event names.\n   *\n   * @param {Function} [fn]\n   *        The function to remove. If not specified, all listeners managed by Video.js will be removed.\n   */\n\n  /**\n   * This function will add an `event listener` that gets triggered only once. After the\n   * first trigger it will get removed. This is like adding an `event listener`\n   * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.\n   *\n   * @param {string|string[]} type\n   *        An event name or an array of event names.\n   *\n   * @param {Function} fn\n   *        The function to be called once for each event name.\n   */\n\n  /**\n   * This function will add an `event listener` that gets triggered only once and is\n   * removed from all events. This is like adding an array of `event listener`s\n   * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the\n   * first time it is triggered.\n   *\n   * @param {string|string[]} type\n   *        An event name or an array of event names.\n   *\n   * @param {Function} fn\n   *        The function to be called once for each event name.\n   */\n\n  /**\n   * This function causes an event to happen. This will then cause any `event listeners`\n   * that are waiting for that event, to get called. If there are no `event listeners`\n   * for an event then nothing will happen.\n   *\n   * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.\n   * Trigger will also call the `on` + `uppercaseEventName` function.\n   *\n   * Example:\n   * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call\n   * `onClick` if it exists.\n   *\n   * @param {string|Event|Object} event\n   *        The name of the event, an `Event`, or an object with a key of type set to\n   *        an event name.\n   *\n   * @param {Object} [hash]\n   *        Optionally extra argument to pass through to an event listener\n   */\n\n  /**\n   * Dispose of the `Component` and all child components.\n   *\n   * @fires Component#dispose\n   *\n   * @param {Object} options\n   * @param {Element} options.originalEl element with which to replace player element\n   */\n  dispose(options = {}) {\n    // Bail out if the component has already been disposed.\n    if (this.isDisposed_) {\n      return;\n    }\n    if (this.readyQueue_) {\n      this.readyQueue_.length = 0;\n    }\n\n    /**\n     * Triggered when a `Component` is disposed.\n     *\n     * @event Component#dispose\n     * @type {Event}\n     *\n     * @property {boolean} [bubbles=false]\n     *           set to false so that the dispose event does not\n     *           bubble up\n     */\n    this.trigger({\n      type: 'dispose',\n      bubbles: false\n    });\n    this.isDisposed_ = true;\n\n    // Dispose all children.\n    if (this.children_) {\n      for (let i = this.children_.length - 1; i >= 0; i--) {\n        if (this.children_[i].dispose) {\n          this.children_[i].dispose();\n        }\n      }\n    }\n\n    // Delete child references\n    this.children_ = null;\n    this.childIndex_ = null;\n    this.childNameIndex_ = null;\n    this.parentComponent_ = null;\n    if (this.el_) {\n      // Remove element from DOM\n      if (this.el_.parentNode) {\n        if (options.restoreEl) {\n          this.el_.parentNode.replaceChild(options.restoreEl, this.el_);\n        } else {\n          this.el_.parentNode.removeChild(this.el_);\n        }\n      }\n      this.el_ = null;\n    }\n\n    // remove reference to the player after disposing of the element\n    this.player_ = null;\n  }\n\n  /**\n   * Determine whether or not this component has been disposed.\n   *\n   * @return {boolean}\n   *         If the component has been disposed, will be `true`. Otherwise, `false`.\n   */\n  isDisposed() {\n    return Boolean(this.isDisposed_);\n  }\n\n  /**\n   * Return the {@link Player} that the `Component` has attached to.\n   *\n   * @return {Player}\n   *         The player that this `Component` has attached to.\n   */\n  player() {\n    return this.player_;\n  }\n\n  /**\n   * Deep merge of options objects with new options.\n   * > Note: When both `obj` and `options` contain properties whose values are objects.\n   *         The two properties get merged using {@link module:obj.merge}\n   *\n   * @param {Object} obj\n   *        The object that contains new options.\n   *\n   * @return {Object}\n   *         A new object of `this.options_` and `obj` merged together.\n   */\n  options(obj) {\n    if (!obj) {\n      return this.options_;\n    }\n    this.options_ = merge$1(this.options_, obj);\n    return this.options_;\n  }\n\n  /**\n   * Get the `Component`s DOM element\n   *\n   * @return {Element}\n   *         The DOM element for this `Component`.\n   */\n  el() {\n    return this.el_;\n  }\n\n  /**\n   * Create the `Component`s DOM element.\n   *\n   * @param {string} [tagName]\n   *        Element's DOM node type. e.g. 'div'\n   *\n   * @param {Object} [properties]\n   *        An object of properties that should be set.\n   *\n   * @param {Object} [attributes]\n   *        An object of attributes that should be set.\n   *\n   * @return {Element}\n   *         The element that gets created.\n   */\n  createEl(tagName, properties, attributes) {\n    return createEl(tagName, properties, attributes);\n  }\n\n  /**\n   * Localize a string given the string in english.\n   *\n   * If tokens are provided, it'll try and run a simple token replacement on the provided string.\n   * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.\n   *\n   * If a `defaultValue` is provided, it'll use that over `string`,\n   * if a value isn't found in provided language files.\n   * This is useful if you want to have a descriptive key for token replacement\n   * but have a succinct localized string and not require `en.json` to be included.\n   *\n   * Currently, it is used for the progress bar timing.\n   * ```js\n   * {\n   *   \"progress bar timing: currentTime={1} duration={2}\": \"{1} of {2}\"\n   * }\n   * ```\n   * It is then used like so:\n   * ```js\n   * this.localize('progress bar timing: currentTime={1} duration{2}',\n   *               [this.player_.currentTime(), this.player_.duration()],\n   *               '{1} of {2}');\n   * ```\n   *\n   * Which outputs something like: `01:23 of 24:56`.\n   *\n   *\n   * @param {string} string\n   *        The string to localize and the key to lookup in the language files.\n   * @param {string[]} [tokens]\n   *        If the current item has token replacements, provide the tokens here.\n   * @param {string} [defaultValue]\n   *        Defaults to `string`. Can be a default value to use for token replacement\n   *        if the lookup key is needed to be separate.\n   *\n   * @return {string}\n   *         The localized string or if no localization exists the english string.\n   */\n  localize(string, tokens, defaultValue = string) {\n    const code = this.player_.language && this.player_.language();\n    const languages = this.player_.languages && this.player_.languages();\n    const language = languages && languages[code];\n    const primaryCode = code && code.split('-')[0];\n    const primaryLang = languages && languages[primaryCode];\n    let localizedString = defaultValue;\n    if (language && language[string]) {\n      localizedString = language[string];\n    } else if (primaryLang && primaryLang[string]) {\n      localizedString = primaryLang[string];\n    }\n    if (tokens) {\n      localizedString = localizedString.replace(/\\{(\\d+)\\}/g, function (match, index) {\n        const value = tokens[index - 1];\n        let ret = value;\n        if (typeof value === 'undefined') {\n          ret = match;\n        }\n        return ret;\n      });\n    }\n    return localizedString;\n  }\n\n  /**\n   * Handles language change for the player in components. Should be overridden by sub-components.\n   *\n   * @abstract\n   */\n  handleLanguagechange() {}\n\n  /**\n   * Return the `Component`s DOM element. This is where children get inserted.\n   * This will usually be the the same as the element returned in {@link Component#el}.\n   *\n   * @return {Element}\n   *         The content element for this `Component`.\n   */\n  contentEl() {\n    return this.contentEl_ || this.el_;\n  }\n\n  /**\n   * Get this `Component`s ID\n   *\n   * @return {string}\n   *         The id of this `Component`\n   */\n  id() {\n    return this.id_;\n  }\n\n  /**\n   * Get the `Component`s name. The name gets used to reference the `Component`\n   * and is set during registration.\n   *\n   * @return {string}\n   *         The name of this `Component`.\n   */\n  name() {\n    return this.name_;\n  }\n\n  /**\n   * Get an array of all child components\n   *\n   * @return {Array}\n   *         The children\n   */\n  children() {\n    return this.children_;\n  }\n\n  /**\n   * Returns the child `Component` with the given `id`.\n   *\n   * @param {string} id\n   *        The id of the child `Component` to get.\n   *\n   * @return {Component|undefined}\n   *         The child `Component` with the given `id` or undefined.\n   */\n  getChildById(id) {\n    return this.childIndex_[id];\n  }\n\n  /**\n   * Returns the child `Component` with the given `name`.\n   *\n   * @param {string} name\n   *        The name of the child `Component` to get.\n   *\n   * @return {Component|undefined}\n   *         The child `Component` with the given `name` or undefined.\n   */\n  getChild(name) {\n    if (!name) {\n      return;\n    }\n    return this.childNameIndex_[name];\n  }\n\n  /**\n   * Returns the descendant `Component` following the givent\n   * descendant `names`. For instance ['foo', 'bar', 'baz'] would\n   * try to get 'foo' on the current component, 'bar' on the 'foo'\n   * component and 'baz' on the 'bar' component and return undefined\n   * if any of those don't exist.\n   *\n   * @param {...string[]|...string} names\n   *        The name of the child `Component` to get.\n   *\n   * @return {Component|undefined}\n   *         The descendant `Component` following the given descendant\n   *         `names` or undefined.\n   */\n  getDescendant(...names) {\n    // flatten array argument into the main array\n    names = names.reduce((acc, n) => acc.concat(n), []);\n    let currentChild = this;\n    for (let i = 0; i < names.length; i++) {\n      currentChild = currentChild.getChild(names[i]);\n      if (!currentChild || !currentChild.getChild) {\n        return;\n      }\n    }\n    return currentChild;\n  }\n\n  /**\n   * Adds an SVG icon element to another element or component.\n   *\n   * @param {string} iconName\n   *        The name of icon. A list of all the icon names can be found at 'sandbox/svg-icons.html'\n   *\n   * @param {Element} [el=this.el()]\n   *        Element to set the title on. Defaults to the current Component's element.\n   *\n   * @return {Element}\n   *        The newly created icon element.\n   */\n  setIcon(iconName, el = this.el()) {\n    // TODO: In v9 of video.js, we will want to remove font icons entirely.\n    // This means this check, as well as the others throughout the code, and\n    // the unecessary CSS for font icons, will need to be removed.\n    // See https://github.com/videojs/video.js/pull/8260 as to which components\n    // need updating.\n    if (!this.player_.options_.experimentalSvgIcons) {\n      return;\n    }\n    const xmlnsURL = 'http://www.w3.org/2000/svg';\n\n    // The below creates an element in the format of:\n    // <span><svg><use>....</use></svg></span>\n    const iconContainer = createEl('span', {\n      className: 'vjs-icon-placeholder vjs-svg-icon'\n    }, {\n      'aria-hidden': 'true'\n    });\n    const svgEl = document$1.createElementNS(xmlnsURL, 'svg');\n    svgEl.setAttributeNS(null, 'viewBox', '0 0 512 512');\n    const useEl = document$1.createElementNS(xmlnsURL, 'use');\n    svgEl.appendChild(useEl);\n    useEl.setAttributeNS(null, 'href', `#vjs-icon-${iconName}`);\n    iconContainer.appendChild(svgEl);\n\n    // Replace a pre-existing icon if one exists.\n    if (this.iconIsSet_) {\n      el.replaceChild(iconContainer, el.querySelector('.vjs-icon-placeholder'));\n    } else {\n      el.appendChild(iconContainer);\n    }\n    this.iconIsSet_ = true;\n    return iconContainer;\n  }\n\n  /**\n   * Add a child `Component` inside the current `Component`.\n   *\n   * @param {string|Component} child\n   *        The name or instance of a child to add.\n   *\n   * @param {Object} [options={}]\n   *        The key/value store of options that will get passed to children of\n   *        the child.\n   *\n   * @param {number} [index=this.children_.length]\n   *        The index to attempt to add a child into.\n   *\n   *\n   * @return {Component}\n   *         The `Component` that gets added as a child. When using a string the\n   *         `Component` will get created by this process.\n   */\n  addChild(child, options = {}, index = this.children_.length) {\n    let component;\n    let componentName;\n\n    // If child is a string, create component with options\n    if (typeof child === 'string') {\n      componentName = toTitleCase$1(child);\n      const componentClassName = options.componentClass || componentName;\n\n      // Set name through options\n      options.name = componentName;\n\n      // Create a new object & element for this controls set\n      // If there's no .player_, this is a player\n      const ComponentClass = Component$1.getComponent(componentClassName);\n      if (!ComponentClass) {\n        throw new Error(`Component ${componentClassName} does not exist`);\n      }\n\n      // data stored directly on the videojs object may be\n      // misidentified as a component to retain\n      // backwards-compatibility with 4.x. check to make sure the\n      // component class can be instantiated.\n      if (typeof ComponentClass !== 'function') {\n        return null;\n      }\n      component = new ComponentClass(this.player_ || this, options);\n\n      // child is a component instance\n    } else {\n      component = child;\n    }\n    if (component.parentComponent_) {\n      component.parentComponent_.removeChild(component);\n    }\n    this.children_.splice(index, 0, component);\n    component.parentComponent_ = this;\n    if (typeof component.id === 'function') {\n      this.childIndex_[component.id()] = component;\n    }\n\n    // If a name wasn't used to create the component, check if we can use the\n    // name function of the component\n    componentName = componentName || component.name && toTitleCase$1(component.name());\n    if (componentName) {\n      this.childNameIndex_[componentName] = component;\n      this.childNameIndex_[toLowerCase(componentName)] = component;\n    }\n\n    // Add the UI object's element to the container div (box)\n    // Having an element is not required\n    if (typeof component.el === 'function' && component.el()) {\n      // If inserting before a component, insert before that component's element\n      let refNode = null;\n      if (this.children_[index + 1]) {\n        // Most children are components, but the video tech is an HTML element\n        if (this.children_[index + 1].el_) {\n          refNode = this.children_[index + 1].el_;\n        } else if (isEl(this.children_[index + 1])) {\n          refNode = this.children_[index + 1];\n        }\n      }\n      this.contentEl().insertBefore(component.el(), refNode);\n    }\n\n    // Return so it can stored on parent object if desired.\n    return component;\n  }\n\n  /**\n   * Remove a child `Component` from this `Component`s list of children. Also removes\n   * the child `Component`s element from this `Component`s element.\n   *\n   * @param {string|Component} component\n   *       The name or instance of a child to remove.\n   */\n  removeChild(component) {\n    if (typeof component === 'string') {\n      component = this.getChild(component);\n    }\n    if (!component || !this.children_) {\n      return;\n    }\n    let childFound = false;\n    for (let i = this.children_.length - 1; i >= 0; i--) {\n      if (this.children_[i] === component) {\n        childFound = true;\n        this.children_.splice(i, 1);\n        break;\n      }\n    }\n    if (!childFound) {\n      return;\n    }\n    component.parentComponent_ = null;\n    this.childIndex_[component.id()] = null;\n    this.childNameIndex_[toTitleCase$1(component.name())] = null;\n    this.childNameIndex_[toLowerCase(component.name())] = null;\n    const compEl = component.el();\n    if (compEl && compEl.parentNode === this.contentEl()) {\n      this.contentEl().removeChild(component.el());\n    }\n  }\n\n  /**\n   * Add and initialize default child `Component`s based upon options.\n   */\n  initChildren() {\n    const children = this.options_.children;\n    if (children) {\n      // `this` is `parent`\n      const parentOptions = this.options_;\n      const handleAdd = child => {\n        const name = child.name;\n        let opts = child.opts;\n\n        // Allow options for children to be set at the parent options\n        // e.g. videojs(id, { controlBar: false });\n        // instead of videojs(id, { children: { controlBar: false });\n        if (parentOptions[name] !== undefined) {\n          opts = parentOptions[name];\n        }\n\n        // Allow for disabling default components\n        // e.g. options['children']['posterImage'] = false\n        if (opts === false) {\n          return;\n        }\n\n        // Allow options to be passed as a simple boolean if no configuration\n        // is necessary.\n        if (opts === true) {\n          opts = {};\n        }\n\n        // We also want to pass the original player options\n        // to each component as well so they don't need to\n        // reach back into the player for options later.\n        opts.playerOptions = this.options_.playerOptions;\n\n        // Create and add the child component.\n        // Add a direct reference to the child by name on the parent instance.\n        // If two of the same component are used, different names should be supplied\n        // for each\n        const newChild = this.addChild(name, opts);\n        if (newChild) {\n          this[name] = newChild;\n        }\n      };\n\n      // Allow for an array of children details to passed in the options\n      let workingChildren;\n      const Tech = Component$1.getComponent('Tech');\n      if (Array.isArray(children)) {\n        workingChildren = children;\n      } else {\n        workingChildren = Object.keys(children);\n      }\n      workingChildren\n      // children that are in this.options_ but also in workingChildren  would\n      // give us extra children we do not want. So, we want to filter them out.\n      .concat(Object.keys(this.options_).filter(function (child) {\n        return !workingChildren.some(function (wchild) {\n          if (typeof wchild === 'string') {\n            return child === wchild;\n          }\n          return child === wchild.name;\n        });\n      })).map(child => {\n        let name;\n        let opts;\n        if (typeof child === 'string') {\n          name = child;\n          opts = children[name] || this.options_[name] || {};\n        } else {\n          name = child.name;\n          opts = child;\n        }\n        return {\n          name,\n          opts\n        };\n      }).filter(child => {\n        // we have to make sure that child.name isn't in the techOrder since\n        // techs are registered as Components but can't aren't compatible\n        // See https://github.com/videojs/video.js/issues/2772\n        const c = Component$1.getComponent(child.opts.componentClass || toTitleCase$1(child.name));\n        return c && !Tech.isTech(c);\n      }).forEach(handleAdd);\n    }\n  }\n\n  /**\n   * Builds the default DOM class name. Should be overridden by sub-components.\n   *\n   * @return {string}\n   *         The DOM class name for this object.\n   *\n   * @abstract\n   */\n  buildCSSClass() {\n    // Child classes can include a function that does:\n    // return 'CLASS NAME' + this._super();\n    return '';\n  }\n\n  /**\n   * Bind a listener to the component's ready state.\n   * Different from event listeners in that if the ready event has already happened\n   * it will trigger the function immediately.\n   *\n   * @param {ReadyCallback} fn\n   *        Function that gets called when the `Component` is ready.\n   */\n  ready(fn, sync = false) {\n    if (!fn) {\n      return;\n    }\n    if (!this.isReady_) {\n      this.readyQueue_ = this.readyQueue_ || [];\n      this.readyQueue_.push(fn);\n      return;\n    }\n    if (sync) {\n      fn.call(this);\n    } else {\n      // Call the function asynchronously by default for consistency\n      this.setTimeout(fn, 1);\n    }\n  }\n\n  /**\n   * Trigger all the ready listeners for this `Component`.\n   *\n   * @fires Component#ready\n   */\n  triggerReady() {\n    this.isReady_ = true;\n\n    // Ensure ready is triggered asynchronously\n    this.setTimeout(function () {\n      const readyQueue = this.readyQueue_;\n\n      // Reset Ready Queue\n      this.readyQueue_ = [];\n      if (readyQueue && readyQueue.length > 0) {\n        readyQueue.forEach(function (fn) {\n          fn.call(this);\n        }, this);\n      }\n\n      // Allow for using event listeners also\n      /**\n       * Triggered when a `Component` is ready.\n       *\n       * @event Component#ready\n       * @type {Event}\n       */\n      this.trigger('ready');\n    }, 1);\n  }\n\n  /**\n   * Find a single DOM element matching a `selector`. This can be within the `Component`s\n   * `contentEl()` or another custom context.\n   *\n   * @param {string} selector\n   *        A valid CSS selector, which will be passed to `querySelector`.\n   *\n   * @param {Element|string} [context=this.contentEl()]\n   *        A DOM element within which to query. Can also be a selector string in\n   *        which case the first matching element will get used as context. If\n   *        missing `this.contentEl()` gets used. If  `this.contentEl()` returns\n   *        nothing it falls back to `document`.\n   *\n   * @return {Element|null}\n   *         the dom element that was found, or null\n   *\n   * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)\n   */\n  $(selector, context) {\n    return $(selector, context || this.contentEl());\n  }\n\n  /**\n   * Finds all DOM element matching a `selector`. This can be within the `Component`s\n   * `contentEl()` or another custom context.\n   *\n   * @param {string} selector\n   *        A valid CSS selector, which will be passed to `querySelectorAll`.\n   *\n   * @param {Element|string} [context=this.contentEl()]\n   *        A DOM element within which to query. Can also be a selector string in\n   *        which case the first matching element will get used as context. If\n   *        missing `this.contentEl()` gets used. If  `this.contentEl()` returns\n   *        nothing it falls back to `document`.\n   *\n   * @return {NodeList}\n   *         a list of dom elements that were found\n   *\n   * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)\n   */\n  $$(selector, context) {\n    return $$(selector, context || this.contentEl());\n  }\n\n  /**\n   * Check if a component's element has a CSS class name.\n   *\n   * @param {string} classToCheck\n   *        CSS class name to check.\n   *\n   * @return {boolean}\n   *         - True if the `Component` has the class.\n   *         - False if the `Component` does not have the class`\n   */\n  hasClass(classToCheck) {\n    return hasClass(this.el_, classToCheck);\n  }\n\n  /**\n   * Add a CSS class name to the `Component`s element.\n   *\n   * @param {...string} classesToAdd\n   *        One or more CSS class name to add.\n   */\n  addClass(...classesToAdd) {\n    addClass(this.el_, ...classesToAdd);\n  }\n\n  /**\n   * Remove a CSS class name from the `Component`s element.\n   *\n   * @param {...string} classesToRemove\n   *        One or more CSS class name to remove.\n   */\n  removeClass(...classesToRemove) {\n    removeClass(this.el_, ...classesToRemove);\n  }\n\n  /**\n   * Add or remove a CSS class name from the component's element.\n   * - `classToToggle` gets added when {@link Component#hasClass} would return false.\n   * - `classToToggle` gets removed when {@link Component#hasClass} would return true.\n   *\n   * @param  {string} classToToggle\n   *         The class to add or remove. Passed to DOMTokenList's toggle()\n   *\n   * @param  {boolean|Dom.PredicateCallback} [predicate]\n   *         A boolean or function that returns a boolean. Passed to DOMTokenList's toggle().\n   */\n  toggleClass(classToToggle, predicate) {\n    toggleClass(this.el_, classToToggle, predicate);\n  }\n\n  /**\n   * Show the `Component`s element if it is hidden by removing the\n   * 'vjs-hidden' class name from it.\n   */\n  show() {\n    this.removeClass('vjs-hidden');\n  }\n\n  /**\n   * Hide the `Component`s element if it is currently showing by adding the\n   * 'vjs-hidden` class name to it.\n   */\n  hide() {\n    this.addClass('vjs-hidden');\n  }\n\n  /**\n   * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'\n   * class name to it. Used during fadeIn/fadeOut.\n   *\n   * @private\n   */\n  lockShowing() {\n    this.addClass('vjs-lock-showing');\n  }\n\n  /**\n   * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'\n   * class name from it. Used during fadeIn/fadeOut.\n   *\n   * @private\n   */\n  unlockShowing() {\n    this.removeClass('vjs-lock-showing');\n  }\n\n  /**\n   * Get the value of an attribute on the `Component`s element.\n   *\n   * @param {string} attribute\n   *        Name of the attribute to get the value from.\n   *\n   * @return {string|null}\n   *         - The value of the attribute that was asked for.\n   *         - Can be an empty string on some browsers if the attribute does not exist\n   *           or has no value\n   *         - Most browsers will return null if the attribute does not exist or has\n   *           no value.\n   *\n   * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}\n   */\n  getAttribute(attribute) {\n    return getAttribute(this.el_, attribute);\n  }\n\n  /**\n   * Set the value of an attribute on the `Component`'s element\n   *\n   * @param {string} attribute\n   *        Name of the attribute to set.\n   *\n   * @param {string} value\n   *        Value to set the attribute to.\n   *\n   * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}\n   */\n  setAttribute(attribute, value) {\n    setAttribute(this.el_, attribute, value);\n  }\n\n  /**\n   * Remove an attribute from the `Component`s element.\n   *\n   * @param {string} attribute\n   *        Name of the attribute to remove.\n   *\n   * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}\n   */\n  removeAttribute(attribute) {\n    removeAttribute(this.el_, attribute);\n  }\n\n  /**\n   * Get or set the width of the component based upon the CSS styles.\n   * See {@link Component#dimension} for more detailed information.\n   *\n   * @param {number|string} [num]\n   *        The width that you want to set postfixed with '%', 'px' or nothing.\n   *\n   * @param {boolean} [skipListeners]\n   *        Skip the componentresize event trigger\n   *\n   * @return {number|undefined}\n   *         The width when getting, zero if there is no width\n   */\n  width(num, skipListeners) {\n    return this.dimension('width', num, skipListeners);\n  }\n\n  /**\n   * Get or set the height of the component based upon the CSS styles.\n   * See {@link Component#dimension} for more detailed information.\n   *\n   * @param {number|string} [num]\n   *        The height that you want to set postfixed with '%', 'px' or nothing.\n   *\n   * @param {boolean} [skipListeners]\n   *        Skip the componentresize event trigger\n   *\n   * @return {number|undefined}\n   *         The height when getting, zero if there is no height\n   */\n  height(num, skipListeners) {\n    return this.dimension('height', num, skipListeners);\n  }\n\n  /**\n   * Set both the width and height of the `Component` element at the same time.\n   *\n   * @param  {number|string} width\n   *         Width to set the `Component`s element to.\n   *\n   * @param  {number|string} height\n   *         Height to set the `Component`s element to.\n   */\n  dimensions(width, height) {\n    // Skip componentresize listeners on width for optimization\n    this.width(width, true);\n    this.height(height);\n  }\n\n  /**\n   * Get or set width or height of the `Component` element. This is the shared code\n   * for the {@link Component#width} and {@link Component#height}.\n   *\n   * Things to know:\n   * - If the width or height in an number this will return the number postfixed with 'px'.\n   * - If the width/height is a percent this will return the percent postfixed with '%'\n   * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function\n   *   defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.\n   *   See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}\n   *   for more information\n   * - If you want the computed style of the component, use {@link Component#currentWidth}\n   *   and {@link {Component#currentHeight}\n   *\n   * @fires Component#componentresize\n   *\n   * @param {string} widthOrHeight\n   8        'width' or 'height'\n   *\n   * @param  {number|string} [num]\n   8         New dimension\n   *\n   * @param  {boolean} [skipListeners]\n   *         Skip componentresize event trigger\n   *\n   * @return {number|undefined}\n   *         The dimension when getting or 0 if unset\n   */\n  dimension(widthOrHeight, num, skipListeners) {\n    if (num !== undefined) {\n      // Set to zero if null or literally NaN (NaN !== NaN)\n      if (num === null || num !== num) {\n        num = 0;\n      }\n\n      // Check if using css width/height (% or px) and adjust\n      if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {\n        this.el_.style[widthOrHeight] = num;\n      } else if (num === 'auto') {\n        this.el_.style[widthOrHeight] = '';\n      } else {\n        this.el_.style[widthOrHeight] = num + 'px';\n      }\n\n      // skipListeners allows us to avoid triggering the resize event when setting both width and height\n      if (!skipListeners) {\n        /**\n         * Triggered when a component is resized.\n         *\n         * @event Component#componentresize\n         * @type {Event}\n         */\n        this.trigger('componentresize');\n      }\n      return;\n    }\n\n    // Not setting a value, so getting it\n    // Make sure element exists\n    if (!this.el_) {\n      return 0;\n    }\n\n    // Get dimension value from style\n    const val = this.el_.style[widthOrHeight];\n    const pxIndex = val.indexOf('px');\n    if (pxIndex !== -1) {\n      // Return the pixel value with no 'px'\n      return parseInt(val.slice(0, pxIndex), 10);\n    }\n\n    // No px so using % or no style was set, so falling back to offsetWidth/height\n    // If component has display:none, offset will return 0\n    // TODO: handle display:none and no dimension style using px\n    return parseInt(this.el_['offset' + toTitleCase$1(widthOrHeight)], 10);\n  }\n\n  /**\n   * Get the computed width or the height of the component's element.\n   *\n   * Uses `window.getComputedStyle`.\n   *\n   * @param {string} widthOrHeight\n   *        A string containing 'width' or 'height'. Whichever one you want to get.\n   *\n   * @return {number}\n   *         The dimension that gets asked for or 0 if nothing was set\n   *         for that dimension.\n   */\n  currentDimension(widthOrHeight) {\n    let computedWidthOrHeight = 0;\n    if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {\n      throw new Error('currentDimension only accepts width or height value');\n    }\n    computedWidthOrHeight = computedStyle(this.el_, widthOrHeight);\n\n    // remove 'px' from variable and parse as integer\n    computedWidthOrHeight = parseFloat(computedWidthOrHeight);\n\n    // if the computed value is still 0, it's possible that the browser is lying\n    // and we want to check the offset values.\n    // This code also runs wherever getComputedStyle doesn't exist.\n    if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {\n      const rule = `offset${toTitleCase$1(widthOrHeight)}`;\n      computedWidthOrHeight = this.el_[rule];\n    }\n    return computedWidthOrHeight;\n  }\n\n  /**\n   * An object that contains width and height values of the `Component`s\n   * computed style. Uses `window.getComputedStyle`.\n   *\n   * @typedef {Object} Component~DimensionObject\n   *\n   * @property {number} width\n   *           The width of the `Component`s computed style.\n   *\n   * @property {number} height\n   *           The height of the `Component`s computed style.\n   */\n\n  /**\n   * Get an object that contains computed width and height values of the\n   * component's element.\n   *\n   * Uses `window.getComputedStyle`.\n   *\n   * @return {Component~DimensionObject}\n   *         The computed dimensions of the component's element.\n   */\n  currentDimensions() {\n    return {\n      width: this.currentDimension('width'),\n      height: this.currentDimension('height')\n    };\n  }\n\n  /**\n   * Get the computed width of the component's element.\n   *\n   * Uses `window.getComputedStyle`.\n   *\n   * @return {number}\n   *         The computed width of the component's element.\n   */\n  currentWidth() {\n    return this.currentDimension('width');\n  }\n\n  /**\n   * Get the computed height of the component's element.\n   *\n   * Uses `window.getComputedStyle`.\n   *\n   * @return {number}\n   *         The computed height of the component's element.\n   */\n  currentHeight() {\n    return this.currentDimension('height');\n  }\n\n  /**\n   * Retrieves the position and size information of the component's element.\n   *\n   * @return {Object} An object with `boundingClientRect` and `center` properties.\n   *         - `boundingClientRect`: An object with properties `x`, `y`, `width`,\n   *           `height`, `top`, `right`, `bottom`, and `left`, representing\n   *           the bounding rectangle of the element.\n   *         - `center`: An object with properties `x` and `y`, representing\n   *           the center point of the element. `width` and `height` are set to 0.\n   */\n  getPositions() {\n    const rect = this.el_.getBoundingClientRect();\n\n    // Creating objects that mirror DOMRectReadOnly for boundingClientRect and center\n    const boundingClientRect = {\n      x: rect.x,\n      y: rect.y,\n      width: rect.width,\n      height: rect.height,\n      top: rect.top,\n      right: rect.right,\n      bottom: rect.bottom,\n      left: rect.left\n    };\n\n    // Calculating the center position\n    const center = {\n      x: rect.left + rect.width / 2,\n      y: rect.top + rect.height / 2,\n      width: 0,\n      height: 0,\n      top: rect.top + rect.height / 2,\n      right: rect.left + rect.width / 2,\n      bottom: rect.top + rect.height / 2,\n      left: rect.left + rect.width / 2\n    };\n    return {\n      boundingClientRect,\n      center\n    };\n  }\n\n  /**\n   * Set the focus to this component\n   */\n  focus() {\n    this.el_.focus();\n  }\n\n  /**\n   * Remove the focus from this component\n   */\n  blur() {\n    this.el_.blur();\n  }\n\n  /**\n   * When this Component receives a `keydown` event which it does not process,\n   *  it passes the event to the Player for handling.\n   *\n   * @param {KeyboardEvent} event\n   *        The `keydown` event that caused this function to be called.\n   */\n  handleKeyDown(event) {\n    if (this.player_) {\n      // We only stop propagation here because we want unhandled events to fall\n      // back to the browser. Exclude Tab for focus trapping, exclude also when spatialNavigation is enabled.\n      if (event.key !== 'Tab' && !(this.player_.options_.playerOptions.spatialNavigation && this.player_.options_.playerOptions.spatialNavigation.enabled)) {\n        event.stopPropagation();\n      }\n      this.player_.handleKeyDown(event);\n    }\n  }\n\n  /**\n   * Many components used to have a `handleKeyPress` method, which was poorly\n   * named because it listened to a `keydown` event. This method name now\n   * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`\n   * will not see their method calls stop working.\n   *\n   * @param {KeyboardEvent} event\n   *        The event that caused this function to be called.\n   */\n  handleKeyPress(event) {\n    this.handleKeyDown(event);\n  }\n\n  /**\n   * Emit a 'tap' events when touch event support gets detected. This gets used to\n   * support toggling the controls through a tap on the video. They get enabled\n   * because every sub-component would have extra overhead otherwise.\n   *\n   * @protected\n   * @fires Component#tap\n   * @listens Component#touchstart\n   * @listens Component#touchmove\n   * @listens Component#touchleave\n   * @listens Component#touchcancel\n   * @listens Component#touchend\n    */\n  emitTapEvents() {\n    // Track the start time so we can determine how long the touch lasted\n    let touchStart = 0;\n    let firstTouch = null;\n\n    // Maximum movement allowed during a touch event to still be considered a tap\n    // Other popular libs use anywhere from 2 (hammer.js) to 15,\n    // so 10 seems like a nice, round number.\n    const tapMovementThreshold = 10;\n\n    // The maximum length a touch can be while still being considered a tap\n    const touchTimeThreshold = 200;\n    let couldBeTap;\n    this.on('touchstart', function (event) {\n      // If more than one finger, don't consider treating this as a click\n      if (event.touches.length === 1) {\n        // Copy pageX/pageY from the object\n        firstTouch = {\n          pageX: event.touches[0].pageX,\n          pageY: event.touches[0].pageY\n        };\n        // Record start time so we can detect a tap vs. \"touch and hold\"\n        touchStart = window$1.performance.now();\n        // Reset couldBeTap tracking\n        couldBeTap = true;\n      }\n    });\n    this.on('touchmove', function (event) {\n      // If more than one finger, don't consider treating this as a click\n      if (event.touches.length > 1) {\n        couldBeTap = false;\n      } else if (firstTouch) {\n        // Some devices will throw touchmoves for all but the slightest of taps.\n        // So, if we moved only a small distance, this could still be a tap\n        const xdiff = event.touches[0].pageX - firstTouch.pageX;\n        const ydiff = event.touches[0].pageY - firstTouch.pageY;\n        const touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);\n        if (touchDistance > tapMovementThreshold) {\n          couldBeTap = false;\n        }\n      }\n    });\n    const noTap = function () {\n      couldBeTap = false;\n    };\n\n    // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s\n    this.on('touchleave', noTap);\n    this.on('touchcancel', noTap);\n\n    // When the touch ends, measure how long it took and trigger the appropriate\n    // event\n    this.on('touchend', function (event) {\n      firstTouch = null;\n      // Proceed only if the touchmove/leave/cancel event didn't happen\n      if (couldBeTap === true) {\n        // Measure how long the touch lasted\n        const touchTime = window$1.performance.now() - touchStart;\n\n        // Make sure the touch was less than the threshold to be considered a tap\n        if (touchTime < touchTimeThreshold) {\n          // Don't let browser turn this into a click\n          event.preventDefault();\n          /**\n           * Triggered when a `Component` is tapped.\n           *\n           * @event Component#tap\n           * @type {MouseEvent}\n           */\n          this.trigger('tap');\n          // It may be good to copy the touchend event object and change the\n          // type to tap, if the other event properties aren't exact after\n          // Events.fixEvent runs (e.g. event.target)\n        }\n      }\n    });\n  }\n\n  /**\n   * This function reports user activity whenever touch events happen. This can get\n   * turned off by any sub-components that wants touch events to act another way.\n   *\n   * Report user touch activity when touch events occur. User activity gets used to\n   * determine when controls should show/hide. It is simple when it comes to mouse\n   * events, because any mouse event should show the controls. So we capture mouse\n   * events that bubble up to the player and report activity when that happens.\n   * With touch events it isn't as easy as `touchstart` and `touchend` toggle player\n   * controls. So touch events can't help us at the player level either.\n   *\n   * User activity gets checked asynchronously. So what could happen is a tap event\n   * on the video turns the controls off. Then the `touchend` event bubbles up to\n   * the player. Which, if it reported user activity, would turn the controls right\n   * back on. We also don't want to completely block touch events from bubbling up.\n   * Furthermore a `touchmove` event and anything other than a tap, should not turn\n   * controls back on.\n   *\n   * @listens Component#touchstart\n   * @listens Component#touchmove\n   * @listens Component#touchend\n   * @listens Component#touchcancel\n   */\n  enableTouchActivity() {\n    // Don't continue if the root player doesn't support reporting user activity\n    if (!this.player() || !this.player().reportUserActivity) {\n      return;\n    }\n\n    // listener for reporting that the user is active\n    const report = bind_(this.player(), this.player().reportUserActivity);\n    let touchHolding;\n    this.on('touchstart', function () {\n      report();\n      // For as long as the they are touching the device or have their mouse down,\n      // we consider them active even if they're not moving their finger or mouse.\n      // So we want to continue to update that they are active\n      this.clearInterval(touchHolding);\n      // report at the same interval as activityCheck\n      touchHolding = this.setInterval(report, 250);\n    });\n    const touchEnd = function (event) {\n      report();\n      // stop the interval that maintains activity if the touch is holding\n      this.clearInterval(touchHolding);\n    };\n    this.on('touchmove', report);\n    this.on('touchend', touchEnd);\n    this.on('touchcancel', touchEnd);\n  }\n\n  /**\n   * A callback that has no parameters and is bound into `Component`s context.\n   *\n   * @callback Component~GenericCallback\n   * @this Component\n   */\n\n  /**\n   * Creates a function that runs after an `x` millisecond timeout. This function is a\n   * wrapper around `window.setTimeout`. There are a few reasons to use this one\n   * instead though:\n   * 1. It gets cleared via  {@link Component#clearTimeout} when\n   *    {@link Component#dispose} gets called.\n   * 2. The function callback will gets turned into a {@link Component~GenericCallback}\n   *\n   * > Note: You can't use `window.clearTimeout` on the id returned by this function. This\n   *         will cause its dispose listener not to get cleaned up! Please use\n   *         {@link Component#clearTimeout} or {@link Component#dispose} instead.\n   *\n   * @param {Component~GenericCallback} fn\n   *        The function that will be run after `timeout`.\n   *\n   * @param {number} timeout\n   *        Timeout in milliseconds to delay before executing the specified function.\n   *\n   * @return {number}\n   *         Returns a timeout ID that gets used to identify the timeout. It can also\n   *         get used in {@link Component#clearTimeout} to clear the timeout that\n   *         was set.\n   *\n   * @listens Component#dispose\n   * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}\n   */\n  setTimeout(fn, timeout) {\n    // declare as variables so they are properly available in timeout function\n    // eslint-disable-next-line\n    var timeoutId;\n    fn = bind_(this, fn);\n    this.clearTimersOnDispose_();\n    timeoutId = window$1.setTimeout(() => {\n      if (this.setTimeoutIds_.has(timeoutId)) {\n        this.setTimeoutIds_.delete(timeoutId);\n      }\n      fn();\n    }, timeout);\n    this.setTimeoutIds_.add(timeoutId);\n    return timeoutId;\n  }\n\n  /**\n   * Clears a timeout that gets created via `window.setTimeout` or\n   * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}\n   * use this function instead of `window.clearTimout`. If you don't your dispose\n   * listener will not get cleaned up until {@link Component#dispose}!\n   *\n   * @param {number} timeoutId\n   *        The id of the timeout to clear. The return value of\n   *        {@link Component#setTimeout} or `window.setTimeout`.\n   *\n   * @return {number}\n   *         Returns the timeout id that was cleared.\n   *\n   * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}\n   */\n  clearTimeout(timeoutId) {\n    if (this.setTimeoutIds_.has(timeoutId)) {\n      this.setTimeoutIds_.delete(timeoutId);\n      window$1.clearTimeout(timeoutId);\n    }\n    return timeoutId;\n  }\n\n  /**\n   * Creates a function that gets run every `x` milliseconds. This function is a wrapper\n   * around `window.setInterval`. There are a few reasons to use this one instead though.\n   * 1. It gets cleared via  {@link Component#clearInterval} when\n   *    {@link Component#dispose} gets called.\n   * 2. The function callback will be a {@link Component~GenericCallback}\n   *\n   * @param {Component~GenericCallback} fn\n   *        The function to run every `x` seconds.\n   *\n   * @param {number} interval\n   *        Execute the specified function every `x` milliseconds.\n   *\n   * @return {number}\n   *         Returns an id that can be used to identify the interval. It can also be be used in\n   *         {@link Component#clearInterval} to clear the interval.\n   *\n   * @listens Component#dispose\n   * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}\n   */\n  setInterval(fn, interval) {\n    fn = bind_(this, fn);\n    this.clearTimersOnDispose_();\n    const intervalId = window$1.setInterval(fn, interval);\n    this.setIntervalIds_.add(intervalId);\n    return intervalId;\n  }\n\n  /**\n   * Clears an interval that gets created via `window.setInterval` or\n   * {@link Component#setInterval}. If you set an interval via {@link Component#setInterval}\n   * use this function instead of `window.clearInterval`. If you don't your dispose\n   * listener will not get cleaned up until {@link Component#dispose}!\n   *\n   * @param {number} intervalId\n   *        The id of the interval to clear. The return value of\n   *        {@link Component#setInterval} or `window.setInterval`.\n   *\n   * @return {number}\n   *         Returns the interval id that was cleared.\n   *\n   * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}\n   */\n  clearInterval(intervalId) {\n    if (this.setIntervalIds_.has(intervalId)) {\n      this.setIntervalIds_.delete(intervalId);\n      window$1.clearInterval(intervalId);\n    }\n    return intervalId;\n  }\n\n  /**\n   * Queues up a callback to be passed to requestAnimationFrame (rAF), but\n   * with a few extra bonuses:\n   *\n   * - Supports browsers that do not support rAF by falling back to\n   *   {@link Component#setTimeout}.\n   *\n   * - The callback is turned into a {@link Component~GenericCallback} (i.e.\n   *   bound to the component).\n   *\n   * - Automatic cancellation of the rAF callback is handled if the component\n   *   is disposed before it is called.\n   *\n   * @param  {Component~GenericCallback} fn\n   *         A function that will be bound to this component and executed just\n   *         before the browser's next repaint.\n   *\n   * @return {number}\n   *         Returns an rAF ID that gets used to identify the timeout. It can\n   *         also be used in {@link Component#cancelAnimationFrame} to cancel\n   *         the animation frame callback.\n   *\n   * @listens Component#dispose\n   * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}\n   */\n  requestAnimationFrame(fn) {\n    this.clearTimersOnDispose_();\n\n    // declare as variables so they are properly available in rAF function\n    // eslint-disable-next-line\n    var id;\n    fn = bind_(this, fn);\n    id = window$1.requestAnimationFrame(() => {\n      if (this.rafIds_.has(id)) {\n        this.rafIds_.delete(id);\n      }\n      fn();\n    });\n    this.rafIds_.add(id);\n    return id;\n  }\n\n  /**\n   * Request an animation frame, but only one named animation\n   * frame will be queued. Another will never be added until\n   * the previous one finishes.\n   *\n   * @param {string} name\n   *        The name to give this requestAnimationFrame\n   *\n   * @param  {Component~GenericCallback} fn\n   *         A function that will be bound to this component and executed just\n   *         before the browser's next repaint.\n   */\n  requestNamedAnimationFrame(name, fn) {\n    if (this.namedRafs_.has(name)) {\n      this.cancelNamedAnimationFrame(name);\n    }\n    this.clearTimersOnDispose_();\n    fn = bind_(this, fn);\n    const id = this.requestAnimationFrame(() => {\n      fn();\n      if (this.namedRafs_.has(name)) {\n        this.namedRafs_.delete(name);\n      }\n    });\n    this.namedRafs_.set(name, id);\n    return name;\n  }\n\n  /**\n   * Cancels a current named animation frame if it exists.\n   *\n   * @param {string} name\n   *        The name of the requestAnimationFrame to cancel.\n   */\n  cancelNamedAnimationFrame(name) {\n    if (!this.namedRafs_.has(name)) {\n      return;\n    }\n    this.cancelAnimationFrame(this.namedRafs_.get(name));\n    this.namedRafs_.delete(name);\n  }\n\n  /**\n   * Cancels a queued callback passed to {@link Component#requestAnimationFrame}\n   * (rAF).\n   *\n   * If you queue an rAF callback via {@link Component#requestAnimationFrame},\n   * use this function instead of `window.cancelAnimationFrame`. If you don't,\n   * your dispose listener will not get cleaned up until {@link Component#dispose}!\n   *\n   * @param {number} id\n   *        The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.\n   *\n   * @return {number}\n   *         Returns the rAF ID that was cleared.\n   *\n   * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}\n   */\n  cancelAnimationFrame(id) {\n    if (this.rafIds_.has(id)) {\n      this.rafIds_.delete(id);\n      window$1.cancelAnimationFrame(id);\n    }\n    return id;\n  }\n\n  /**\n   * A function to setup `requestAnimationFrame`, `setTimeout`,\n   * and `setInterval`, clearing on dispose.\n   *\n   * > Previously each timer added and removed dispose listeners on it's own.\n   * For better performance it was decided to batch them all, and use `Set`s\n   * to track outstanding timer ids.\n   *\n   * @private\n   */\n  clearTimersOnDispose_() {\n    if (this.clearingTimersOnDispose_) {\n      return;\n    }\n    this.clearingTimersOnDispose_ = true;\n    this.one('dispose', () => {\n      [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(([idName, cancelName]) => {\n        // for a `Set` key will actually be the value again\n        // so forEach((val, val) =>` but for maps we want to use\n        // the key.\n        this[idName].forEach((val, key) => this[cancelName](key));\n      });\n      this.clearingTimersOnDispose_ = false;\n    });\n  }\n\n  /**\n    * Decide whether an element is actually disabled or not.\n    *\n    * @function isActuallyDisabled\n    * @param element {Node}\n    * @return {boolean}\n    *\n    * @see {@link https://html.spec.whatwg.org/multipage/semantics-other.html#concept-element-disabled}\n    */\n  getIsDisabled() {\n    return Boolean(this.el_.disabled);\n  }\n\n  /**\n    * Decide whether the element is expressly inert or not.\n    *\n    * @see {@link https://html.spec.whatwg.org/multipage/interaction.html#expressly-inert}\n    * @function isExpresslyInert\n    * @param element {Node}\n    * @return {boolean}\n    */\n  getIsExpresslyInert() {\n    return this.el_.inert && !this.el_.ownerDocument.documentElement.inert;\n  }\n\n  /**\n   * Determine whether or not this component can be considered as focusable component.\n   *\n   * @param {HTMLElement} el - The HTML element representing the component.\n   * @return {boolean}\n   *         If the component can be focused, will be `true`. Otherwise, `false`.\n   */\n  getIsFocusable(el) {\n    const element = el || this.el_;\n    return element.tabIndex >= 0 && !(this.getIsDisabled() || this.getIsExpresslyInert());\n  }\n\n  /**\n   * Determine whether or not this component is currently visible/enabled/etc...\n   *\n   * @param {HTMLElement} el - The HTML element representing the component.\n   * @return {boolean}\n   *         If the component can is currently visible & enabled, will be `true`. Otherwise, `false`.\n   */\n  getIsAvailableToBeFocused(el) {\n    /**\n     * Decide the style property of this element is specified whether it's visible or not.\n     *\n     * @function isVisibleStyleProperty\n     * @param element {CSSStyleDeclaration}\n     * @return {boolean}\n     */\n    function isVisibleStyleProperty(element) {\n      const elementStyle = window$1.getComputedStyle(element, null);\n      const thisVisibility = elementStyle.getPropertyValue('visibility');\n      const thisDisplay = elementStyle.getPropertyValue('display');\n      const invisibleStyle = ['hidden', 'collapse'];\n      return thisDisplay !== 'none' && !invisibleStyle.includes(thisVisibility);\n    }\n\n    /**\n     * Decide whether the element is being rendered or not.\n     * 1. If an element has the style as \"visibility: hidden | collapse\" or \"display: none\", it is not being rendered.\n     * 2. If an element has the style as \"opacity: 0\", it is not being rendered.(that is, invisible).\n     * 3. If width and height of an element are explicitly set to 0, it is not being rendered.\n     * 4. If a parent element is hidden, an element itself is not being rendered.\n     * (CSS visibility property and display property are inherited.)\n     *\n     * @see {@link https://html.spec.whatwg.org/multipage/rendering.html#being-rendered}\n     * @function isBeingRendered\n     * @param element {Node}\n     * @return {boolean}\n     */\n    function isBeingRendered(element) {\n      if (!isVisibleStyleProperty(element.parentElement)) {\n        return false;\n      }\n      if (!isVisibleStyleProperty(element) || element.style.opacity === '0' || window$1.getComputedStyle(element).height === '0px' || window$1.getComputedStyle(element).width === '0px') {\n        return false;\n      }\n      return true;\n    }\n\n    /**\n     * Determine if the element is visible for the user or not.\n     * 1. If an element sum of its offsetWidth, offsetHeight, height and width is less than 1 is not visible.\n     * 2. If elementCenter.x is less than is not visible.\n     * 3. If elementCenter.x is more than the document's width is not visible.\n     * 4. If elementCenter.y is less than 0 is not visible.\n     * 5. If elementCenter.y is the document's height is not visible.\n     *\n     * @function isVisible\n     * @param element {Node}\n     * @return {boolean}\n     */\n    function isVisible(element) {\n      if (element.offsetWidth + element.offsetHeight + element.getBoundingClientRect().height + element.getBoundingClientRect().width === 0) {\n        return false;\n      }\n\n      // Define elementCenter object with props of x and y\n      // x: Left position relative to the viewport plus element's width (no margin) divided between 2.\n      // y: Top position relative to the viewport plus element's height (no margin) divided between 2.\n      const elementCenter = {\n        x: element.getBoundingClientRect().left + element.offsetWidth / 2,\n        y: element.getBoundingClientRect().top + element.offsetHeight / 2\n      };\n      if (elementCenter.x < 0) {\n        return false;\n      }\n      if (elementCenter.x > (document$1.documentElement.clientWidth || window$1.innerWidth)) {\n        return false;\n      }\n      if (elementCenter.y < 0) {\n        return false;\n      }\n      if (elementCenter.y > (document$1.documentElement.clientHeight || window$1.innerHeight)) {\n        return false;\n      }\n      let pointContainer = document$1.elementFromPoint(elementCenter.x, elementCenter.y);\n      while (pointContainer) {\n        if (pointContainer === element) {\n          return true;\n        }\n        if (pointContainer.parentNode) {\n          pointContainer = pointContainer.parentNode;\n        } else {\n          return false;\n        }\n      }\n    }\n\n    // If no DOM element was passed as argument use this component's element.\n    if (!el) {\n      el = this.el();\n    }\n\n    // If element is visible, is being rendered & either does not have a parent element or its tabIndex is not negative.\n    if (isVisible(el) && isBeingRendered(el) && (!el.parentElement || el.tabIndex >= 0)) {\n      return true;\n    }\n    return false;\n  }\n\n  /**\n   * Register a `Component` with `videojs` given the name and the component.\n   *\n   * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s\n   *         should be registered using {@link Tech.registerTech} or\n   *         {@link videojs:videojs.registerTech}.\n   *\n   * > NOTE: This function can also be seen on videojs as\n   *         {@link videojs:videojs.registerComponent}.\n   *\n   * @param {string} name\n   *        The name of the `Component` to register.\n   *\n   * @param {Component} ComponentToRegister\n   *        The `Component` class to register.\n   *\n   * @return {Component}\n   *         The `Component` that was registered.\n   */\n  static registerComponent(name, ComponentToRegister) {\n    if (typeof name !== 'string' || !name) {\n      throw new Error(`Illegal component name, \"${name}\"; must be a non-empty string.`);\n    }\n    const Tech = Component$1.getComponent('Tech');\n\n    // We need to make sure this check is only done if Tech has been registered.\n    const isTech = Tech && Tech.isTech(ComponentToRegister);\n    const isComp = Component$1 === ComponentToRegister || Component$1.prototype.isPrototypeOf(ComponentToRegister.prototype);\n    if (isTech || !isComp) {\n      let reason;\n      if (isTech) {\n        reason = 'techs must be registered using Tech.registerTech()';\n      } else {\n        reason = 'must be a Component subclass';\n      }\n      throw new Error(`Illegal component, \"${name}\"; ${reason}.`);\n    }\n    name = toTitleCase$1(name);\n    if (!Component$1.components_) {\n      Component$1.components_ = {};\n    }\n    const Player = Component$1.getComponent('Player');\n    if (name === 'Player' && Player && Player.players) {\n      const players = Player.players;\n      const playerNames = Object.keys(players);\n\n      // If we have players that were disposed, then their name will still be\n      // in Players.players. So, we must loop through and verify that the value\n      // for each item is null. This allows registration of the Player component\n      // after all players have been disposed or before any were created.\n      if (players && playerNames.length > 0) {\n        for (let i = 0; i < playerNames.length; i++) {\n          if (players[playerNames[i]] !== null) {\n            throw new Error('Can not register Player component after player has been created.');\n          }\n        }\n      }\n    }\n    Component$1.components_[name] = ComponentToRegister;\n    Component$1.components_[toLowerCase(name)] = ComponentToRegister;\n    return ComponentToRegister;\n  }\n\n  /**\n   * Get a `Component` based on the name it was registered with.\n   *\n   * @param {string} name\n   *        The Name of the component to get.\n   *\n   * @return {typeof Component}\n   *         The `Component` that got registered under the given name.\n   */\n  static getComponent(name) {\n    if (!name || !Component$1.components_) {\n      return;\n    }\n    return Component$1.components_[name];\n  }\n}\nComponent$1.registerComponent('Component', Component$1);\n\n/**\n * @file time.js\n * @module time\n */\n\n/**\n * Returns the time for the specified index at the start or end\n * of a TimeRange object.\n *\n * @typedef    {Function} TimeRangeIndex\n *\n * @param      {number} [index=0]\n *             The range number to return the time for.\n *\n * @return     {number}\n *             The time offset at the specified index.\n *\n * @deprecated The index argument must be provided.\n *             In the future, leaving it out will throw an error.\n */\n\n/**\n * An object that contains ranges of time, which mimics {@link TimeRanges}.\n *\n * @typedef  {Object} TimeRange\n *\n * @property {number} length\n *           The number of time ranges represented by this object.\n *\n * @property {module:time~TimeRangeIndex} start\n *           Returns the time offset at which a specified time range begins.\n *\n * @property {module:time~TimeRangeIndex} end\n *           Returns the time offset at which a specified time range ends.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges\n */\n\n/**\n * Check if any of the time ranges are over the maximum index.\n *\n * @private\n * @param   {string} fnName\n *          The function name to use for logging\n *\n * @param   {number} index\n *          The index to check\n *\n * @param   {number} maxIndex\n *          The maximum possible index\n *\n * @throws  {Error} if the timeRanges provided are over the maxIndex\n */\nfunction rangeCheck(fnName, index, maxIndex) {\n  if (typeof index !== 'number' || index < 0 || index > maxIndex) {\n    throw new Error(`Failed to execute '${fnName}' on 'TimeRanges': The index provided (${index}) is non-numeric or out of bounds (0-${maxIndex}).`);\n  }\n}\n\n/**\n * Get the time for the specified index at the start or end\n * of a TimeRange object.\n *\n * @private\n * @param      {string} fnName\n *             The function name to use for logging\n *\n * @param      {string} valueIndex\n *             The property that should be used to get the time. should be\n *             'start' or 'end'\n *\n * @param      {Array} ranges\n *             An array of time ranges\n *\n * @param      {Array} [rangeIndex=0]\n *             The index to start the search at\n *\n * @return     {number}\n *             The time that offset at the specified index.\n *\n * @deprecated rangeIndex must be set to a value, in the future this will throw an error.\n * @throws     {Error} if rangeIndex is more than the length of ranges\n */\nfunction getRange(fnName, valueIndex, ranges, rangeIndex) {\n  rangeCheck(fnName, rangeIndex, ranges.length - 1);\n  return ranges[rangeIndex][valueIndex];\n}\n\n/**\n * Create a time range object given ranges of time.\n *\n * @private\n * @param   {Array} [ranges]\n *          An array of time ranges.\n *\n * @return  {TimeRange}\n */\nfunction createTimeRangesObj(ranges) {\n  let timeRangesObj;\n  if (ranges === undefined || ranges.length === 0) {\n    timeRangesObj = {\n      length: 0,\n      start() {\n        throw new Error('This TimeRanges object is empty');\n      },\n      end() {\n        throw new Error('This TimeRanges object is empty');\n      }\n    };\n  } else {\n    timeRangesObj = {\n      length: ranges.length,\n      start: getRange.bind(null, 'start', 0, ranges),\n      end: getRange.bind(null, 'end', 1, ranges)\n    };\n  }\n  if (window$1.Symbol && window$1.Symbol.iterator) {\n    timeRangesObj[window$1.Symbol.iterator] = () => (ranges || []).values();\n  }\n  return timeRangesObj;\n}\n\n/**\n * Create a `TimeRange` object which mimics an\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.\n *\n * @param {number|Array[]} start\n *        The start of a single range (a number) or an array of ranges (an\n *        array of arrays of two numbers each).\n *\n * @param {number} end\n *        The end of a single range. Cannot be used with the array form of\n *        the `start` argument.\n *\n * @return {TimeRange}\n */\nfunction createTimeRanges$1(start, end) {\n  if (Array.isArray(start)) {\n    return createTimeRangesObj(start);\n  } else if (start === undefined || end === undefined) {\n    return createTimeRangesObj();\n  }\n  return createTimeRangesObj([[start, end]]);\n}\n\n/**\n * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in\n * seconds) will force a number of leading zeros to cover the length of the\n * guide.\n *\n * @private\n * @param  {number} seconds\n *         Number of seconds to be turned into a string\n *\n * @param  {number} guide\n *         Number (in seconds) to model the string after\n *\n * @return {string}\n *         Time formatted as H:MM:SS or M:SS\n */\nconst defaultImplementation = function (seconds, guide) {\n  seconds = seconds < 0 ? 0 : seconds;\n  let s = Math.floor(seconds % 60);\n  let m = Math.floor(seconds / 60 % 60);\n  let h = Math.floor(seconds / 3600);\n  const gm = Math.floor(guide / 60 % 60);\n  const gh = Math.floor(guide / 3600);\n\n  // handle invalid times\n  if (isNaN(seconds) || seconds === Infinity) {\n    // '-' is false for all relational operators (e.g. <, >=) so this setting\n    // will add the minimum number of fields specified by the guide\n    h = m = s = '-';\n  }\n\n  // Check if we need to show hours\n  h = h > 0 || gh > 0 ? h + ':' : '';\n\n  // If hours are showing, we may need to add a leading zero.\n  // Always show at least one digit of minutes.\n  m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';\n\n  // Check if leading zero is need for seconds\n  s = s < 10 ? '0' + s : s;\n  return h + m + s;\n};\n\n// Internal pointer to the current implementation.\nlet implementation = defaultImplementation;\n\n/**\n * Replaces the default formatTime implementation with a custom implementation.\n *\n * @param {Function} customImplementation\n *        A function which will be used in place of the default formatTime\n *        implementation. Will receive the current time in seconds and the\n *        guide (in seconds) as arguments.\n */\nfunction setFormatTime(customImplementation) {\n  implementation = customImplementation;\n}\n\n/**\n * Resets formatTime to the default implementation.\n */\nfunction resetFormatTime() {\n  implementation = defaultImplementation;\n}\n\n/**\n * Delegates to either the default time formatting function or a custom\n * function supplied via `setFormatTime`.\n *\n * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a\n * guide (in seconds) will force a number of leading zeros to cover the\n * length of the guide.\n *\n * @example  formatTime(125, 600) === \"02:05\"\n * @param    {number} seconds\n *           Number of seconds to be turned into a string\n *\n * @param    {number} guide\n *           Number (in seconds) to model the string after\n *\n * @return   {string}\n *           Time formatted as H:MM:SS or M:SS\n */\nfunction formatTime(seconds, guide = seconds) {\n  return implementation(seconds, guide);\n}\n\nvar Time = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  createTimeRanges: createTimeRanges$1,\n  createTimeRange: createTimeRanges$1,\n  setFormatTime: setFormatTime,\n  resetFormatTime: resetFormatTime,\n  formatTime: formatTime\n});\n\n/**\n * @file buffer.js\n * @module buffer\n */\n\n/** @import { TimeRange } from './time' */\n\n/**\n * Compute the percentage of the media that has been buffered.\n *\n * @param {TimeRange} buffered\n *        The current `TimeRanges` object representing buffered time ranges\n *\n * @param {number} duration\n *        Total duration of the media\n *\n * @return {number}\n *         Percent buffered of the total duration in decimal form.\n */\nfunction bufferedPercent(buffered, duration) {\n  let bufferedDuration = 0;\n  let start;\n  let end;\n  if (!duration) {\n    return 0;\n  }\n  if (!buffered || !buffered.length) {\n    buffered = createTimeRanges$1(0, 0);\n  }\n  for (let i = 0; i < buffered.length; i++) {\n    start = buffered.start(i);\n    end = buffered.end(i);\n\n    // buffered end can be bigger than duration by a very small fraction\n    if (end > duration) {\n      end = duration;\n    }\n    bufferedDuration += end - start;\n  }\n  return bufferedDuration / duration;\n}\n\n/**\n * @file media-error.js\n */\n\n/**\n * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.\n *\n * @param {number|string|Object|MediaError} value\n *        This can be of multiple types:\n *        - number: should be a standard error code\n *        - string: an error message (the code will be 0)\n *        - Object: arbitrary properties\n *        - `MediaError` (native): used to populate a video.js `MediaError` object\n *        - `MediaError` (video.js): will return itself if it's already a\n *          video.js `MediaError` object.\n *\n * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}\n * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}\n *\n * @class MediaError\n */\nfunction MediaError(value) {\n  // Allow redundant calls to this constructor to avoid having `instanceof`\n  // checks peppered around the code.\n  if (value instanceof MediaError) {\n    return value;\n  }\n  if (typeof value === 'number') {\n    this.code = value;\n  } else if (typeof value === 'string') {\n    // default code is zero, so this is a custom error\n    this.message = value;\n  } else if (isObject(value)) {\n    // We assign the `code` property manually because native `MediaError` objects\n    // do not expose it as an own/enumerable property of the object.\n    if (typeof value.code === 'number') {\n      this.code = value.code;\n    }\n    Object.assign(this, value);\n  }\n  if (!this.message) {\n    this.message = MediaError.defaultMessages[this.code] || '';\n  }\n}\n\n/**\n * The error code that refers two one of the defined `MediaError` types\n *\n * @type {Number}\n */\nMediaError.prototype.code = 0;\n\n/**\n * An optional message that to show with the error. Message is not part of the HTML5\n * video spec but allows for more informative custom errors.\n *\n * @type {String}\n */\nMediaError.prototype.message = '';\n\n/**\n * An optional status code that can be set by plugins to allow even more detail about\n * the error. For example a plugin might provide a specific HTTP status code and an\n * error message for that code. Then when the plugin gets that error this class will\n * know how to display an error message for it. This allows a custom message to show\n * up on the `Player` error overlay.\n *\n * @type {Array}\n */\nMediaError.prototype.status = null;\n\n/**\n * An object containing an error type, as well as other information regarding the error.\n *\n * @typedef {{errorType: string, [key: string]: any}} ErrorMetadata\n */\n\n/**\n * An optional object to give more detail about the error. This can be used to give\n * a higher level of specificity to an error versus the more generic MediaError codes.\n * `metadata` expects an `errorType` string that should align with the values from videojs.Error.\n *\n * @type {ErrorMetadata}\n */\nMediaError.prototype.metadata = null;\n\n/**\n * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the\n * specification listed under {@link MediaError} for more information.\n *\n * @enum {array}\n * @readonly\n * @property {string} 0 - MEDIA_ERR_CUSTOM\n * @property {string} 1 - MEDIA_ERR_ABORTED\n * @property {string} 2 - MEDIA_ERR_NETWORK\n * @property {string} 3 - MEDIA_ERR_DECODE\n * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED\n * @property {string} 5 - MEDIA_ERR_ENCRYPTED\n */\nMediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];\n\n/**\n * The default `MediaError` messages based on the {@link MediaError.errorTypes}.\n *\n * @type {Array}\n * @constant\n */\nMediaError.defaultMessages = {\n  1: 'You aborted the media playback',\n  2: 'A network error caused the media download to fail part-way.',\n  3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',\n  4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',\n  5: 'The media is encrypted and we do not have the keys to decrypt it.'\n};\n\n/**\n * W3C error code for any custom error.\n *\n * @member MediaError#MEDIA_ERR_CUSTOM\n * @constant {number}\n * @default 0\n */\nMediaError.MEDIA_ERR_CUSTOM = 0;\n\n/**\n * W3C error code for any custom error.\n *\n * @member MediaError.MEDIA_ERR_CUSTOM\n * @constant {number}\n * @default 0\n */\nMediaError.prototype.MEDIA_ERR_CUSTOM = 0;\n\n/**\n * W3C error code for media error aborted.\n *\n * @member MediaError#MEDIA_ERR_ABORTED\n * @constant {number}\n * @default 1\n */\nMediaError.MEDIA_ERR_ABORTED = 1;\n\n/**\n * W3C error code for media error aborted.\n *\n * @member MediaError.MEDIA_ERR_ABORTED\n * @constant {number}\n * @default 1\n */\nMediaError.prototype.MEDIA_ERR_ABORTED = 1;\n\n/**\n * W3C error code for any network error.\n *\n * @member MediaError#MEDIA_ERR_NETWORK\n * @constant {number}\n * @default 2\n */\nMediaError.MEDIA_ERR_NETWORK = 2;\n\n/**\n * W3C error code for any network error.\n *\n * @member MediaError.MEDIA_ERR_NETWORK\n * @constant {number}\n * @default 2\n */\nMediaError.prototype.MEDIA_ERR_NETWORK = 2;\n\n/**\n * W3C error code for any decoding error.\n *\n * @member MediaError#MEDIA_ERR_DECODE\n * @constant {number}\n * @default 3\n */\nMediaError.MEDIA_ERR_DECODE = 3;\n\n/**\n * W3C error code for any decoding error.\n *\n * @member MediaError.MEDIA_ERR_DECODE\n * @constant {number}\n * @default 3\n */\nMediaError.prototype.MEDIA_ERR_DECODE = 3;\n\n/**\n * W3C error code for any time that a source is not supported.\n *\n * @member MediaError#MEDIA_ERR_SRC_NOT_SUPPORTED\n * @constant {number}\n * @default 4\n */\nMediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;\n\n/**\n * W3C error code for any time that a source is not supported.\n *\n * @member MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED\n * @constant {number}\n * @default 4\n */\nMediaError.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;\n\n/**\n * W3C error code for any time that a source is encrypted.\n *\n * @member MediaError#MEDIA_ERR_ENCRYPTED\n * @constant {number}\n * @default 5\n */\nMediaError.MEDIA_ERR_ENCRYPTED = 5;\n\n/**\n * W3C error code for any time that a source is encrypted.\n *\n * @member MediaError.MEDIA_ERR_ENCRYPTED\n * @constant {number}\n * @default 5\n */\nMediaError.prototype.MEDIA_ERR_ENCRYPTED = 5;\n\n/**\n * Returns whether an object is `Promise`-like (i.e. has a `then` method).\n *\n * @param  {Object}  value\n *         An object that may or may not be `Promise`-like.\n *\n * @return {boolean}\n *         Whether or not the object is `Promise`-like.\n */\nfunction isPromise(value) {\n  return value !== undefined && value !== null && typeof value.then === 'function';\n}\n\n/**\n * Silence a Promise-like object.\n *\n * This is useful for avoiding non-harmful, but potentially confusing \"uncaught\n * play promise\" rejection error messages.\n *\n * @param  {Object} value\n *         An object that may or may not be `Promise`-like.\n */\nfunction silencePromise(value) {\n  if (isPromise(value)) {\n    value.then(null, e => {});\n  }\n}\n\n/**\n * @file text-track-list-converter.js Utilities for capturing text track state and\n * re-creating tracks based on a capture.\n *\n * @module text-track-list-converter\n */\n\n/** @import Tech from '../tech/tech' */\n\n/**\n * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that\n * represents the {@link TextTrack}'s state.\n *\n * @param {TextTrack} track\n *        The text track to query.\n *\n * @return {Object}\n *         A serializable javascript representation of the TextTrack.\n * @private\n */\nconst trackToJson = function (track) {\n  const ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce((acc, prop, i) => {\n    if (track[prop]) {\n      acc[prop] = track[prop];\n    }\n    return acc;\n  }, {\n    cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {\n      return {\n        startTime: cue.startTime,\n        endTime: cue.endTime,\n        text: cue.text,\n        id: cue.id\n      };\n    })\n  });\n  return ret;\n};\n\n/**\n * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the\n * state of all {@link TextTrack}s currently configured. The return array is compatible with\n * {@link text-track-list-converter:jsonToTextTracks}.\n *\n * @param {Tech} tech\n *        The tech object to query\n *\n * @return {Array}\n *         A serializable javascript representation of the {@link Tech}s\n *         {@link TextTrackList}.\n */\nconst textTracksToJson = function (tech) {\n  const trackEls = tech.$$('track');\n  const trackObjs = Array.prototype.map.call(trackEls, t => t.track);\n  const tracks = Array.prototype.map.call(trackEls, function (trackEl) {\n    const json = trackToJson(trackEl.track);\n    if (trackEl.src) {\n      json.src = trackEl.src;\n    }\n    return json;\n  });\n  return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {\n    return trackObjs.indexOf(track) === -1;\n  }).map(trackToJson));\n};\n\n/**\n * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript\n * object {@link TextTrack} representations.\n *\n * @param {Array} json\n *        An array of `TextTrack` representation objects, like those that would be\n *        produced by `textTracksToJson`.\n *\n * @param {Tech} tech\n *        The `Tech` to create the `TextTrack`s on.\n */\nconst jsonToTextTracks = function (json, tech) {\n  json.forEach(function (track) {\n    const addedTrack = tech.addRemoteTextTrack(track).track;\n    if (!track.src && track.cues) {\n      track.cues.forEach(cue => addedTrack.addCue(cue));\n    }\n  });\n  return tech.textTracks();\n};\nvar textTrackConverter = {\n  textTracksToJson,\n  jsonToTextTracks,\n  trackToJson\n};\n\n/**\n * @file modal-dialog.js\n */\n\n/** @import Player from './player' */\n/** @import { ContentDescriptor } from './utils/dom' */\n\nconst MODAL_CLASS_NAME = 'vjs-modal-dialog';\n\n/**\n * The `ModalDialog` displays over the video and its controls, which blocks\n * interaction with the player until it is closed.\n *\n * Modal dialogs include a \"Close\" button and will close when that button\n * is activated - or when ESC is pressed anywhere.\n *\n * @extends Component\n */\nclass ModalDialog extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {ContentDescriptor} [options.content=undefined]\n   *        Provide customized content for this modal.\n   *\n   * @param {string} [options.description]\n   *        A text description for the modal, primarily for accessibility.\n   *\n   * @param {boolean} [options.fillAlways=false]\n   *        Normally, modals are automatically filled only the first time\n   *        they open. This tells the modal to refresh its content\n   *        every time it opens.\n   *\n   * @param {string} [options.label]\n   *        A text label for the modal, primarily for accessibility.\n   *\n   * @param {boolean} [options.pauseOnOpen=true]\n   *        If `true`, playback will will be paused if playing when\n   *        the modal opens, and resumed when it closes.\n   *\n   * @param {boolean} [options.temporary=true]\n   *        If `true`, the modal can only be opened once; it will be\n   *        disposed as soon as it's closed.\n   *\n   * @param {boolean} [options.uncloseable=false]\n   *        If `true`, the user will not be able to close the modal\n   *        through the UI in the normal ways. Programmatic closing is\n   *        still possible.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.handleKeyDown_ = e => this.handleKeyDown(e);\n    this.close_ = e => this.close(e);\n    this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false;\n    this.closeable(!this.options_.uncloseable);\n    this.content(this.options_.content);\n\n    // Make sure the contentEl is defined AFTER any children are initialized\n    // because we only want the contents of the modal in the contentEl\n    // (not the UI elements like the close button).\n    this.contentEl_ = createEl('div', {\n      className: `${MODAL_CLASS_NAME}-content`\n    }, {\n      role: 'document'\n    });\n    this.descEl_ = createEl('p', {\n      className: `${MODAL_CLASS_NAME}-description vjs-control-text`,\n      id: this.el().getAttribute('aria-describedby')\n    });\n    textContent(this.descEl_, this.description());\n    this.el_.appendChild(this.descEl_);\n    this.el_.appendChild(this.contentEl_);\n  }\n\n  /**\n   * Create the `ModalDialog`'s DOM element\n   *\n   * @return {Element}\n   *         The DOM element that gets created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: this.buildCSSClass(),\n      tabIndex: -1\n    }, {\n      'aria-describedby': `${this.id()}_description`,\n      'aria-hidden': 'true',\n      'aria-label': this.label(),\n      'role': 'dialog',\n      'aria-live': 'polite'\n    });\n  }\n  dispose() {\n    this.contentEl_ = null;\n    this.descEl_ = null;\n    this.previouslyActiveEl_ = null;\n    super.dispose();\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `${MODAL_CLASS_NAME} vjs-hidden ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * Returns the label string for this modal. Primarily used for accessibility.\n   *\n   * @return {string}\n   *         the localized or raw label of this modal.\n   */\n  label() {\n    return this.localize(this.options_.label || 'Modal Window');\n  }\n\n  /**\n   * Returns the description string for this modal. Primarily used for\n   * accessibility.\n   *\n   * @return {string}\n   *         The localized or raw description of this modal.\n   */\n  description() {\n    let desc = this.options_.description || this.localize('This is a modal window.');\n\n    // Append a universal closeability message if the modal is closeable.\n    if (this.closeable()) {\n      desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');\n    }\n    return desc;\n  }\n\n  /**\n   * Opens the modal.\n   *\n   * @fires ModalDialog#beforemodalopen\n   * @fires ModalDialog#modalopen\n   */\n  open() {\n    if (this.opened_) {\n      if (this.options_.fillAlways) {\n        this.fill();\n      }\n      return;\n    }\n    const player = this.player();\n\n    /**\n      * Fired just before a `ModalDialog` is opened.\n      *\n      * @event ModalDialog#beforemodalopen\n      * @type {Event}\n      */\n    this.trigger('beforemodalopen');\n    this.opened_ = true;\n\n    // Fill content if the modal has never opened before and\n    // never been filled.\n    if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {\n      this.fill();\n    }\n\n    // If the player was playing, pause it and take note of its previously\n    // playing state.\n    this.wasPlaying_ = !player.paused();\n    if (this.options_.pauseOnOpen && this.wasPlaying_) {\n      player.pause();\n    }\n    this.on('keydown', this.handleKeyDown_);\n\n    // Hide controls and note if they were enabled.\n    this.hadControls_ = player.controls();\n    player.controls(false);\n    this.show();\n    this.conditionalFocus_();\n    this.el().setAttribute('aria-hidden', 'false');\n\n    /**\n      * Fired just after a `ModalDialog` is opened.\n      *\n      * @event ModalDialog#modalopen\n      * @type {Event}\n      */\n    this.trigger('modalopen');\n    this.hasBeenOpened_ = true;\n  }\n\n  /**\n   * If the `ModalDialog` is currently open or closed.\n   *\n   * @param  {boolean} [value]\n   *         If given, it will open (`true`) or close (`false`) the modal.\n   *\n   * @return {boolean}\n   *         the current open state of the modaldialog\n   */\n  opened(value) {\n    if (typeof value === 'boolean') {\n      this[value ? 'open' : 'close']();\n    }\n    return this.opened_;\n  }\n\n  /**\n   * Closes the modal, does nothing if the `ModalDialog` is\n   * not open.\n   *\n   * @fires ModalDialog#beforemodalclose\n   * @fires ModalDialog#modalclose\n   */\n  close() {\n    if (!this.opened_) {\n      return;\n    }\n    const player = this.player();\n\n    /**\n      * Fired just before a `ModalDialog` is closed.\n      *\n      * @event ModalDialog#beforemodalclose\n      * @type {Event}\n      */\n    this.trigger('beforemodalclose');\n    this.opened_ = false;\n    if (this.wasPlaying_ && this.options_.pauseOnOpen) {\n      player.play();\n    }\n    this.off('keydown', this.handleKeyDown_);\n    if (this.hadControls_) {\n      player.controls(true);\n    }\n    this.hide();\n    this.el().setAttribute('aria-hidden', 'true');\n\n    /**\n      * Fired just after a `ModalDialog` is closed.\n      *\n      * @event ModalDialog#modalclose\n      * @type {Event}\n      *\n      * @property {boolean} [bubbles=true]\n      */\n    this.trigger({\n      type: 'modalclose',\n      bubbles: true\n    });\n    this.conditionalBlur_();\n    if (this.options_.temporary) {\n      this.dispose();\n    }\n  }\n\n  /**\n   * Check to see if the `ModalDialog` is closeable via the UI.\n   *\n   * @param  {boolean} [value]\n   *         If given as a boolean, it will set the `closeable` option.\n   *\n   * @return {boolean}\n   *         Returns the final value of the closable option.\n   */\n  closeable(value) {\n    if (typeof value === 'boolean') {\n      const closeable = this.closeable_ = !!value;\n      let close = this.getChild('closeButton');\n\n      // If this is being made closeable and has no close button, add one.\n      if (closeable && !close) {\n        // The close button should be a child of the modal - not its\n        // content element, so temporarily change the content element.\n        const temp = this.contentEl_;\n        this.contentEl_ = this.el_;\n        close = this.addChild('closeButton', {\n          controlText: 'Close Modal Dialog'\n        });\n        this.contentEl_ = temp;\n        this.on(close, 'close', this.close_);\n      }\n\n      // If this is being made uncloseable and has a close button, remove it.\n      if (!closeable && close) {\n        this.off(close, 'close', this.close_);\n        this.removeChild(close);\n        close.dispose();\n      }\n    }\n    return this.closeable_;\n  }\n\n  /**\n   * Fill the modal's content element with the modal's \"content\" option.\n   * The content element will be emptied before this change takes place.\n   */\n  fill() {\n    this.fillWith(this.content());\n  }\n\n  /**\n   * Fill the modal's content element with arbitrary content.\n   * The content element will be emptied before this change takes place.\n   *\n   * @fires ModalDialog#beforemodalfill\n   * @fires ModalDialog#modalfill\n   *\n   * @param {ContentDescriptor} [content]\n   *        The same rules apply to this as apply to the `content` option.\n   */\n  fillWith(content) {\n    const contentEl = this.contentEl();\n    const parentEl = contentEl.parentNode;\n    const nextSiblingEl = contentEl.nextSibling;\n\n    /**\n      * Fired just before a `ModalDialog` is filled with content.\n      *\n      * @event ModalDialog#beforemodalfill\n      * @type {Event}\n      */\n    this.trigger('beforemodalfill');\n    this.hasBeenFilled_ = true;\n\n    // Detach the content element from the DOM before performing\n    // manipulation to avoid modifying the live DOM multiple times.\n    parentEl.removeChild(contentEl);\n    this.empty();\n    insertContent(contentEl, content);\n    /**\n     * Fired just after a `ModalDialog` is filled with content.\n     *\n     * @event ModalDialog#modalfill\n     * @type {Event}\n     */\n    this.trigger('modalfill');\n\n    // Re-inject the re-filled content element.\n    if (nextSiblingEl) {\n      parentEl.insertBefore(contentEl, nextSiblingEl);\n    } else {\n      parentEl.appendChild(contentEl);\n    }\n\n    // make sure that the close button is last in the dialog DOM\n    const closeButton = this.getChild('closeButton');\n    if (closeButton) {\n      parentEl.appendChild(closeButton.el_);\n    }\n\n    /**\n     * Fired after `ModalDialog` is re-filled with content & close button is appended.\n     *\n     * @event ModalDialog#aftermodalfill\n     * @type {Event}\n     */\n    this.trigger('aftermodalfill');\n  }\n\n  /**\n   * Empties the content element. This happens anytime the modal is filled.\n   *\n   * @fires ModalDialog#beforemodalempty\n   * @fires ModalDialog#modalempty\n   */\n  empty() {\n    /**\n    * Fired just before a `ModalDialog` is emptied.\n    *\n    * @event ModalDialog#beforemodalempty\n    * @type {Event}\n    */\n    this.trigger('beforemodalempty');\n    emptyEl(this.contentEl());\n\n    /**\n    * Fired just after a `ModalDialog` is emptied.\n    *\n    * @event ModalDialog#modalempty\n    * @type {Event}\n    */\n    this.trigger('modalempty');\n  }\n\n  /**\n   * Gets or sets the modal content, which gets normalized before being\n   * rendered into the DOM.\n   *\n   * This does not update the DOM or fill the modal, but it is called during\n   * that process.\n   *\n   * @param  {ContentDescriptor} [value]\n   *         If defined, sets the internal content value to be used on the\n   *         next call(s) to `fill`. This value is normalized before being\n   *         inserted. To \"clear\" the internal content value, pass `null`.\n   *\n   * @return {ContentDescriptor}\n   *         The current content of the modal dialog\n   */\n  content(value) {\n    if (typeof value !== 'undefined') {\n      this.content_ = value;\n    }\n    return this.content_;\n  }\n\n  /**\n   * conditionally focus the modal dialog if focus was previously on the player.\n   *\n   * @private\n   */\n  conditionalFocus_() {\n    const activeEl = document$1.activeElement;\n    const playerEl = this.player_.el_;\n    this.previouslyActiveEl_ = null;\n    if (playerEl.contains(activeEl) || playerEl === activeEl) {\n      this.previouslyActiveEl_ = activeEl;\n      this.focus();\n    }\n  }\n\n  /**\n   * conditionally blur the element and refocus the last focused element\n   *\n   * @private\n   */\n  conditionalBlur_() {\n    if (this.previouslyActiveEl_) {\n      this.previouslyActiveEl_.focus();\n      this.previouslyActiveEl_ = null;\n    }\n  }\n\n  /**\n   * Keydown handler. Attached when modal is focused.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    /**\n     * Fired a custom keyDown event that bubbles.\n     *\n     * @event ModalDialog#modalKeydown\n     * @type {Event}\n     */\n    this.trigger({\n      type: 'modalKeydown',\n      originalEvent: event,\n      target: this,\n      bubbles: true\n    });\n    // Do not allow keydowns to reach out of the modal dialog.\n    event.stopPropagation();\n    if (event.key === 'Escape' && this.closeable()) {\n      event.preventDefault();\n      this.close();\n      return;\n    }\n\n    // exit early if it isn't a tab key\n    if (event.key !== 'Tab') {\n      return;\n    }\n    const focusableEls = this.focusableEls_();\n    const activeEl = this.el_.querySelector(':focus');\n    let focusIndex;\n    for (let i = 0; i < focusableEls.length; i++) {\n      if (activeEl === focusableEls[i]) {\n        focusIndex = i;\n        break;\n      }\n    }\n    if (document$1.activeElement === this.el_) {\n      focusIndex = 0;\n    }\n    if (event.shiftKey && focusIndex === 0) {\n      focusableEls[focusableEls.length - 1].focus();\n      event.preventDefault();\n    } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {\n      focusableEls[0].focus();\n      event.preventDefault();\n    }\n  }\n\n  /**\n   * get all focusable elements\n   *\n   * @private\n   */\n  focusableEls_() {\n    const allChildren = this.el_.querySelectorAll('*');\n    return Array.prototype.filter.call(allChildren, child => {\n      return (child instanceof window$1.HTMLAnchorElement || child instanceof window$1.HTMLAreaElement) && child.hasAttribute('href') || (child instanceof window$1.HTMLInputElement || child instanceof window$1.HTMLSelectElement || child instanceof window$1.HTMLTextAreaElement || child instanceof window$1.HTMLButtonElement) && !child.hasAttribute('disabled') || child instanceof window$1.HTMLIFrameElement || child instanceof window$1.HTMLObjectElement || child instanceof window$1.HTMLEmbedElement || child.hasAttribute('tabindex') && child.getAttribute('tabindex') !== -1 || child.hasAttribute('contenteditable');\n    });\n  }\n}\n\n/**\n * Default options for `ModalDialog` default options.\n *\n * @type {Object}\n * @private\n */\nModalDialog.prototype.options_ = {\n  pauseOnOpen: true,\n  temporary: true\n};\nComponent$1.registerComponent('ModalDialog', ModalDialog);\n\n/**\n * @file track-list.js\n */\n\n/** @import Track from './track' */\n\n/**\n * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and\n * {@link VideoTrackList}\n *\n * @extends EventTarget\n */\nclass TrackList extends EventTarget$2 {\n  /**\n   * Create an instance of this class\n   *\n   * @param { Track[] } tracks\n   *        A list of tracks to initialize the list with.\n   *\n   * @abstract\n   */\n  constructor(tracks = []) {\n    super();\n    this.tracks_ = [];\n\n    /**\n     * @memberof TrackList\n     * @member {number} length\n     *         The current number of `Track`s in the this Trackist.\n     * @instance\n     */\n    Object.defineProperty(this, 'length', {\n      get() {\n        return this.tracks_.length;\n      }\n    });\n    for (let i = 0; i < tracks.length; i++) {\n      this.addTrack(tracks[i]);\n    }\n  }\n\n  /**\n   * Add a {@link Track} to the `TrackList`\n   *\n   * @param {Track} track\n   *        The audio, video, or text track to add to the list.\n   *\n   * @fires TrackList#addtrack\n   */\n  addTrack(track) {\n    const index = this.tracks_.length;\n    if (!('' + index in this)) {\n      Object.defineProperty(this, index, {\n        get() {\n          return this.tracks_[index];\n        }\n      });\n    }\n\n    // Do not add duplicate tracks\n    if (this.tracks_.indexOf(track) === -1) {\n      this.tracks_.push(track);\n      /**\n       * Triggered when a track is added to a track list.\n       *\n       * @event TrackList#addtrack\n       * @type {Event}\n       * @property {Track} track\n       *           A reference to track that was added.\n       */\n      this.trigger({\n        track,\n        type: 'addtrack',\n        target: this\n      });\n    }\n\n    /**\n     * Triggered when a track label is changed.\n     *\n     * @event TrackList#addtrack\n     * @type {Event}\n     * @property {Track} track\n     *           A reference to track that was added.\n     */\n    track.labelchange_ = () => {\n      this.trigger({\n        track,\n        type: 'labelchange',\n        target: this\n      });\n    };\n    if (isEvented(track)) {\n      track.addEventListener('labelchange', track.labelchange_);\n    }\n  }\n\n  /**\n   * Remove a {@link Track} from the `TrackList`\n   *\n   * @param {Track} rtrack\n   *        The audio, video, or text track to remove from the list.\n   *\n   * @fires TrackList#removetrack\n   */\n  removeTrack(rtrack) {\n    let track;\n    for (let i = 0, l = this.length; i < l; i++) {\n      if (this[i] === rtrack) {\n        track = this[i];\n        if (track.off) {\n          track.off();\n        }\n        this.tracks_.splice(i, 1);\n        break;\n      }\n    }\n    if (!track) {\n      return;\n    }\n\n    /**\n     * Triggered when a track is removed from track list.\n     *\n     * @event TrackList#removetrack\n     * @type {Event}\n     * @property {Track} track\n     *           A reference to track that was removed.\n     */\n    this.trigger({\n      track,\n      type: 'removetrack',\n      target: this\n    });\n  }\n\n  /**\n   * Get a Track from the TrackList by a tracks id\n   *\n   * @param {string} id - the id of the track to get\n   * @method getTrackById\n   * @return {Track}\n   * @private\n   */\n  getTrackById(id) {\n    let result = null;\n    for (let i = 0, l = this.length; i < l; i++) {\n      const track = this[i];\n      if (track.id === id) {\n        result = track;\n        break;\n      }\n    }\n    return result;\n  }\n}\n\n/**\n * Triggered when a different track is selected/enabled.\n *\n * @event TrackList#change\n * @type {Event}\n */\n\n/**\n * Events that can be called with on + eventName. See {@link EventHandler}.\n *\n * @property {Object} TrackList#allowedEvents_\n * @protected\n */\nTrackList.prototype.allowedEvents_ = {\n  change: 'change',\n  addtrack: 'addtrack',\n  removetrack: 'removetrack',\n  labelchange: 'labelchange'\n};\n\n// emulate attribute EventHandler support to allow for feature detection\nfor (const event in TrackList.prototype.allowedEvents_) {\n  TrackList.prototype['on' + event] = null;\n}\n\n/**\n * @file audio-track-list.js\n */\n\n/** @import AudioTrack from './audio-track' */\n\n/**\n * Anywhere we call this function we diverge from the spec\n * as we only support one enabled audiotrack at a time\n *\n * @param {AudioTrackList} list\n *        list to work on\n *\n * @param {AudioTrack} track\n *        The track to skip\n *\n * @private\n */\nconst disableOthers$1 = function (list, track) {\n  for (let i = 0; i < list.length; i++) {\n    if (!Object.keys(list[i]).length || track.id === list[i].id) {\n      continue;\n    }\n    // another audio track is enabled, disable it\n    list[i].enabled = false;\n  }\n};\n\n/**\n * The current list of {@link AudioTrack} for a media file.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}\n * @extends TrackList\n */\nclass AudioTrackList extends TrackList {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {AudioTrack[]} [tracks=[]]\n   *        A list of `AudioTrack` to instantiate the list with.\n   */\n  constructor(tracks = []) {\n    // make sure only 1 track is enabled\n    // sorted from last index to first index\n    for (let i = tracks.length - 1; i >= 0; i--) {\n      if (tracks[i].enabled) {\n        disableOthers$1(tracks, tracks[i]);\n        break;\n      }\n    }\n    super(tracks);\n    this.changing_ = false;\n  }\n\n  /**\n   * Add an {@link AudioTrack} to the `AudioTrackList`.\n   *\n   * @param {AudioTrack} track\n   *        The AudioTrack to add to the list\n   *\n   * @fires TrackList#addtrack\n   */\n  addTrack(track) {\n    if (track.enabled) {\n      disableOthers$1(this, track);\n    }\n    super.addTrack(track);\n    // native tracks don't have this\n    if (!track.addEventListener) {\n      return;\n    }\n    track.enabledChange_ = () => {\n      // when we are disabling other tracks (since we don't support\n      // more than one track at a time) we will set changing_\n      // to true so that we don't trigger additional change events\n      if (this.changing_) {\n        return;\n      }\n      this.changing_ = true;\n      disableOthers$1(this, track);\n      this.changing_ = false;\n      this.trigger('change');\n    };\n\n    /**\n     * @listens AudioTrack#enabledchange\n     * @fires TrackList#change\n     */\n    track.addEventListener('enabledchange', track.enabledChange_);\n  }\n  removeTrack(rtrack) {\n    super.removeTrack(rtrack);\n    if (rtrack.removeEventListener && rtrack.enabledChange_) {\n      rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);\n      rtrack.enabledChange_ = null;\n    }\n  }\n}\n\n/**\n * @file video-track-list.js\n */\n\n/** @import VideoTrack from './video-track' */\n\n/**\n * Un-select all other {@link VideoTrack}s that are selected.\n *\n * @param {VideoTrackList} list\n *        list to work on\n *\n * @param {VideoTrack} track\n *        The track to skip\n *\n * @private\n */\nconst disableOthers = function (list, track) {\n  for (let i = 0; i < list.length; i++) {\n    if (!Object.keys(list[i]).length || track.id === list[i].id) {\n      continue;\n    }\n    // another video track is enabled, disable it\n    list[i].selected = false;\n  }\n};\n\n/**\n * The current list of {@link VideoTrack} for a video.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}\n * @extends TrackList\n */\nclass VideoTrackList extends TrackList {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {VideoTrack[]} [tracks=[]]\n   *        A list of `VideoTrack` to instantiate the list with.\n   */\n  constructor(tracks = []) {\n    // make sure only 1 track is enabled\n    // sorted from last index to first index\n    for (let i = tracks.length - 1; i >= 0; i--) {\n      if (tracks[i].selected) {\n        disableOthers(tracks, tracks[i]);\n        break;\n      }\n    }\n    super(tracks);\n    this.changing_ = false;\n\n    /**\n     * @member {number} VideoTrackList#selectedIndex\n     *         The current index of the selected {@link VideoTrack`}.\n     */\n    Object.defineProperty(this, 'selectedIndex', {\n      get() {\n        for (let i = 0; i < this.length; i++) {\n          if (this[i].selected) {\n            return i;\n          }\n        }\n        return -1;\n      },\n      set() {}\n    });\n  }\n\n  /**\n   * Add a {@link VideoTrack} to the `VideoTrackList`.\n   *\n   * @param {VideoTrack} track\n   *        The VideoTrack to add to the list\n   *\n   * @fires TrackList#addtrack\n   */\n  addTrack(track) {\n    if (track.selected) {\n      disableOthers(this, track);\n    }\n    super.addTrack(track);\n    // native tracks don't have this\n    if (!track.addEventListener) {\n      return;\n    }\n    track.selectedChange_ = () => {\n      if (this.changing_) {\n        return;\n      }\n      this.changing_ = true;\n      disableOthers(this, track);\n      this.changing_ = false;\n      this.trigger('change');\n    };\n\n    /**\n     * @listens VideoTrack#selectedchange\n     * @fires TrackList#change\n     */\n    track.addEventListener('selectedchange', track.selectedChange_);\n  }\n  removeTrack(rtrack) {\n    super.removeTrack(rtrack);\n    if (rtrack.removeEventListener && rtrack.selectedChange_) {\n      rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);\n      rtrack.selectedChange_ = null;\n    }\n  }\n}\n\n/**\n * @file text-track-list.js\n */\n\n/** @import TextTrack from './text-track' */\n\n/**\n * The current list of {@link TextTrack} for a media file.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}\n * @extends TrackList\n */\nclass TextTrackList extends TrackList {\n  /**\n   * Add a {@link TextTrack} to the `TextTrackList`\n   *\n   * @param {TextTrack} track\n   *        The text track to add to the list.\n   *\n   * @fires TrackList#addtrack\n   */\n  addTrack(track) {\n    super.addTrack(track);\n    if (!this.queueChange_) {\n      this.queueChange_ = () => this.queueTrigger('change');\n    }\n    if (!this.triggerSelectedlanguagechange) {\n      this.triggerSelectedlanguagechange_ = () => this.trigger('selectedlanguagechange');\n    }\n\n    /**\n     * @listens TextTrack#modechange\n     * @fires TrackList#change\n     */\n    track.addEventListener('modechange', this.queueChange_);\n    const nonLanguageTextTrackKind = ['metadata', 'chapters'];\n    if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {\n      track.addEventListener('modechange', this.triggerSelectedlanguagechange_);\n    }\n  }\n  removeTrack(rtrack) {\n    super.removeTrack(rtrack);\n\n    // manually remove the event handlers we added\n    if (rtrack.removeEventListener) {\n      if (this.queueChange_) {\n        rtrack.removeEventListener('modechange', this.queueChange_);\n      }\n      if (this.selectedlanguagechange_) {\n        rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);\n      }\n    }\n  }\n\n  /**\n   * Creates a serializable array of objects that contains serialized copies\n   * of each text track.\n   *\n   * @return {Object[]} A serializable list of objects for the text track list\n   */\n  toJSON() {\n    return this.tracks_.map(track => track.toJSON());\n  }\n}\n\n/**\n * @file html-track-element-list.js\n */\n\n/**\n * The current list of {@link HtmlTrackElement}s.\n */\nclass HtmlTrackElementList {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {HtmlTrackElement[]} [tracks=[]]\n   *        A list of `HtmlTrackElement` to instantiate the list with.\n   */\n  constructor(trackElements = []) {\n    this.trackElements_ = [];\n\n    /**\n     * @memberof HtmlTrackElementList\n     * @member {number} length\n     *         The current number of `Track`s in the this Trackist.\n     * @instance\n     */\n    Object.defineProperty(this, 'length', {\n      get() {\n        return this.trackElements_.length;\n      }\n    });\n    for (let i = 0, length = trackElements.length; i < length; i++) {\n      this.addTrackElement_(trackElements[i]);\n    }\n  }\n\n  /**\n   * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`\n   *\n   * @param {HtmlTrackElement} trackElement\n   *        The track element to add to the list.\n   *\n   * @private\n   */\n  addTrackElement_(trackElement) {\n    const index = this.trackElements_.length;\n    if (!('' + index in this)) {\n      Object.defineProperty(this, index, {\n        get() {\n          return this.trackElements_[index];\n        }\n      });\n    }\n\n    // Do not add duplicate elements\n    if (this.trackElements_.indexOf(trackElement) === -1) {\n      this.trackElements_.push(trackElement);\n    }\n  }\n\n  /**\n   * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an\n   * {@link TextTrack}.\n   *\n   * @param {TextTrack} track\n   *        The track associated with a track element.\n   *\n   * @return {HtmlTrackElement|undefined}\n   *         The track element that was found or undefined.\n   *\n   * @private\n   */\n  getTrackElementByTrack_(track) {\n    let trackElement_;\n    for (let i = 0, length = this.trackElements_.length; i < length; i++) {\n      if (track === this.trackElements_[i].track) {\n        trackElement_ = this.trackElements_[i];\n        break;\n      }\n    }\n    return trackElement_;\n  }\n\n  /**\n   * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`\n   *\n   * @param {HtmlTrackElement} trackElement\n   *        The track element to remove from the list.\n   *\n   * @private\n   */\n  removeTrackElement_(trackElement) {\n    for (let i = 0, length = this.trackElements_.length; i < length; i++) {\n      if (trackElement === this.trackElements_[i]) {\n        if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {\n          this.trackElements_[i].track.off();\n        }\n        if (typeof this.trackElements_[i].off === 'function') {\n          this.trackElements_[i].off();\n        }\n        this.trackElements_.splice(i, 1);\n        break;\n      }\n    }\n  }\n}\n\n/**\n * @file text-track-cue-list.js\n */\n\n/**\n * @typedef {Object} TextTrackCueList~TextTrackCue\n *\n * @property {string} id\n *           The unique id for this text track cue\n *\n * @property {number} startTime\n *           The start time for this text track cue\n *\n * @property {number} endTime\n *           The end time for this text track cue\n *\n * @property {boolean} pauseOnExit\n *           Pause when the end time is reached if true.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}\n */\n\n/**\n * A List of TextTrackCues.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}\n */\nclass TextTrackCueList {\n  /**\n   * Create an instance of this class..\n   *\n   * @param {Array} cues\n   *        A list of cues to be initialized with\n   */\n  constructor(cues) {\n    TextTrackCueList.prototype.setCues_.call(this, cues);\n\n    /**\n     * @memberof TextTrackCueList\n     * @member {number} length\n     *         The current number of `TextTrackCue`s in the TextTrackCueList.\n     * @instance\n     */\n    Object.defineProperty(this, 'length', {\n      get() {\n        return this.length_;\n      }\n    });\n  }\n\n  /**\n   * A setter for cues in this list. Creates getters\n   * an an index for the cues.\n   *\n   * @param {Array} cues\n   *        An array of cues to set\n   *\n   * @private\n   */\n  setCues_(cues) {\n    const oldLength = this.length || 0;\n    let i = 0;\n    const l = cues.length;\n    this.cues_ = cues;\n    this.length_ = cues.length;\n    const defineProp = function (index) {\n      if (!('' + index in this)) {\n        Object.defineProperty(this, '' + index, {\n          get() {\n            return this.cues_[index];\n          }\n        });\n      }\n    };\n    if (oldLength < l) {\n      i = oldLength;\n      for (; i < l; i++) {\n        defineProp.call(this, i);\n      }\n    }\n  }\n\n  /**\n   * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.\n   *\n   * @param {string} id\n   *        The id of the cue that should be searched for.\n   *\n   * @return {TextTrackCueList~TextTrackCue|null}\n   *         A single cue or null if none was found.\n   */\n  getCueById(id) {\n    let result = null;\n    for (let i = 0, l = this.length; i < l; i++) {\n      const cue = this[i];\n      if (cue.id === id) {\n        result = cue;\n        break;\n      }\n    }\n    return result;\n  }\n}\n\n/**\n * @file track-kinds.js\n */\n\n/**\n * All possible `VideoTrackKind`s\n *\n * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind\n * @typedef VideoTrack~Kind\n * @enum\n */\nconst VideoTrackKind = {\n  alternative: 'alternative',\n  captions: 'captions',\n  main: 'main',\n  sign: 'sign',\n  subtitles: 'subtitles',\n  commentary: 'commentary'\n};\n\n/**\n * All possible `AudioTrackKind`s\n *\n * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind\n * @typedef AudioTrack~Kind\n * @enum\n */\nconst AudioTrackKind = {\n  'alternative': 'alternative',\n  'descriptions': 'descriptions',\n  'main': 'main',\n  'main-desc': 'main-desc',\n  'translation': 'translation',\n  'commentary': 'commentary'\n};\n\n/**\n * All possible `TextTrackKind`s\n *\n * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind\n * @typedef TextTrack~Kind\n * @enum\n */\nconst TextTrackKind = {\n  subtitles: 'subtitles',\n  captions: 'captions',\n  descriptions: 'descriptions',\n  chapters: 'chapters',\n  metadata: 'metadata'\n};\n\n/**\n * All possible `TextTrackMode`s\n *\n * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode\n * @typedef TextTrack~Mode\n * @enum\n */\nconst TextTrackMode = {\n  disabled: 'disabled',\n  hidden: 'hidden',\n  showing: 'showing'\n};\n\n/**\n * @file track.js\n */\n\n/**\n * A Track class that contains all of the common functionality for {@link AudioTrack},\n * {@link VideoTrack}, and {@link TextTrack}.\n *\n * > Note: This class should not be used directly\n *\n * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}\n * @extends EventTarget\n * @abstract\n */\nclass Track extends EventTarget$2 {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {Object} [options={}]\n   *        Object of option names and values\n   *\n   * @param {string} [options.kind='']\n   *        A valid kind for the track type you are creating.\n   *\n   * @param {string} [options.id='vjs_track_' + Guid.newGUID()]\n   *        A unique id for this AudioTrack.\n   *\n   * @param {string} [options.label='']\n   *        The menu label for this track.\n   *\n   * @param {string} [options.language='']\n   *        A valid two character language code.\n   *\n   * @abstract\n   */\n  constructor(options = {}) {\n    super();\n    const trackProps = {\n      id: options.id || 'vjs_track_' + newGUID(),\n      kind: options.kind || '',\n      language: options.language || ''\n    };\n    let label = options.label || '';\n\n    /**\n     * @memberof Track\n     * @member {string} id\n     *         The id of this track. Cannot be changed after creation.\n     * @instance\n     *\n     * @readonly\n     */\n\n    /**\n     * @memberof Track\n     * @member {string} kind\n     *         The kind of track that this is. Cannot be changed after creation.\n     * @instance\n     *\n     * @readonly\n     */\n\n    /**\n     * @memberof Track\n     * @member {string} language\n     *         The two letter language code for this track. Cannot be changed after\n     *         creation.\n     * @instance\n     *\n     * @readonly\n     */\n\n    for (const key in trackProps) {\n      Object.defineProperty(this, key, {\n        get() {\n          return trackProps[key];\n        },\n        set() {}\n      });\n    }\n\n    /**\n     * @memberof Track\n     * @member {string} label\n     *         The label of this track. Cannot be changed after creation.\n     * @instance\n     *\n     * @fires Track#labelchange\n     */\n    Object.defineProperty(this, 'label', {\n      get() {\n        return label;\n      },\n      set(newLabel) {\n        if (newLabel !== label) {\n          label = newLabel;\n\n          /**\n           * An event that fires when label changes on this track.\n           *\n           * > Note: This is not part of the spec!\n           *\n           * @event Track#labelchange\n           * @type {Event}\n           */\n          this.trigger('labelchange');\n        }\n      }\n    });\n  }\n}\n\n/**\n * @file url.js\n * @module url\n */\n\n/**\n * Resolve and parse the elements of a URL.\n *\n * @function\n * @param    {string} url\n *           The url to parse\n *\n * @return   {URL}\n *           An object of url details\n */\nconst parseUrl = function (url) {\n  return new URL(url, document$1.baseURI);\n};\n\n/**\n * Get absolute version of relative URL.\n *\n * @function\n * @param    {string} url\n *           URL to make absolute\n *\n * @return   {string}\n *           Absolute URL\n */\nconst getAbsoluteURL = function (url) {\n  return new URL(url, document$1.baseURI).href;\n};\n\n/**\n * Returns the extension of the passed file name. It will return an empty string\n * if passed an invalid path.\n *\n * @function\n * @param    {string} path\n *           The fileName path like '/path/to/file.mp4'\n *\n * @return  {string}\n *           The extension in lower case or an empty string if no\n *           extension could be found.\n */\nconst getFileExtension = function (path) {\n  if (typeof path === 'string') {\n    const cleanPath = path.split('?')[0].replace(/\\/+$/, '');\n    const match = cleanPath.match(/\\.([^.\\/]+)$/);\n    return match ? match[1].toLowerCase() : '';\n  }\n  return '';\n};\n\n/**\n * Returns whether the url passed is a cross domain request or not.\n *\n * @function\n * @param    {string} url\n *           The url to check.\n *\n * @param    {URL} [winLoc]\n *           the domain to check the url against, defaults to window.location\n *\n * @return   {boolean}\n *           Whether it is a cross domain request or not.\n */\nconst isCrossOrigin = function (url, winLoc = window$1.location) {\n  return parseUrl(url).origin !== winLoc.origin;\n};\n\nvar Url = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  parseUrl: parseUrl,\n  getAbsoluteURL: getAbsoluteURL,\n  getFileExtension: getFileExtension,\n  isCrossOrigin: isCrossOrigin\n});\n\n/**\n * @file text-track.js\n */\n\n/** @import Tech from '../tech/tech' */\n\n/**\n * Takes a webvtt file contents and parses it into cues\n *\n * @param {string} srcContent\n *        webVTT file contents\n *\n * @param {TextTrack} track\n *        TextTrack to add cues to. Cues come from the srcContent.\n *\n * @private\n */\nconst parseCues = function (srcContent, track) {\n  const parser = new window$1.WebVTT.Parser(window$1, window$1.vttjs, window$1.WebVTT.StringDecoder());\n  const errors = [];\n  parser.oncue = function (cue) {\n    track.addCue(cue);\n  };\n  parser.onparsingerror = function (error) {\n    errors.push(error);\n  };\n  parser.onflush = function () {\n    track.trigger({\n      type: 'loadeddata',\n      target: track\n    });\n  };\n  parser.parse(srcContent);\n  if (errors.length > 0) {\n    if (window$1.console && window$1.console.groupCollapsed) {\n      window$1.console.groupCollapsed(`Text Track parsing errors for ${track.src}`);\n    }\n    errors.forEach(error => log$1.error(error));\n    if (window$1.console && window$1.console.groupEnd) {\n      window$1.console.groupEnd();\n    }\n  }\n  parser.flush();\n};\n\n/**\n * Load a `TextTrack` from a specified url.\n *\n * @param {string} src\n *        Url to load track from.\n *\n * @param {TextTrack} track\n *        Track to add cues to. Comes from the content at the end of `url`.\n *\n * @private\n */\nconst loadTrack = function (src, track) {\n  const opts = {\n    uri: src\n  };\n  const crossOrigin = isCrossOrigin(src);\n  if (crossOrigin) {\n    opts.cors = crossOrigin;\n  }\n  const withCredentials = track.tech_.crossOrigin() === 'use-credentials';\n  if (withCredentials) {\n    opts.withCredentials = withCredentials;\n  }\n  XHR(opts, bind_(this, function (err, response, responseBody) {\n    if (err) {\n      return log$1.error(err, response);\n    }\n    track.loaded_ = true;\n\n    // Make sure that vttjs has loaded, otherwise, wait till it finished loading\n    // NOTE: this is only used for the alt/video.novtt.js build\n    if (typeof window$1.WebVTT !== 'function') {\n      if (track.tech_) {\n        // to prevent use before define eslint error, we define loadHandler\n        // as a let here\n        track.tech_.any(['vttjsloaded', 'vttjserror'], event => {\n          if (event.type === 'vttjserror') {\n            log$1.error(`vttjs failed to load, stopping trying to process ${track.src}`);\n            return;\n          }\n          return parseCues(responseBody, track);\n        });\n      }\n    } else {\n      parseCues(responseBody, track);\n    }\n  }));\n};\n\n/**\n * A representation of a single `TextTrack`.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}\n * @extends Track\n */\nclass TextTrack extends Track {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {Object} options={}\n   *        Object of option names and values\n   *\n   * @param {Tech} options.tech\n   *        A reference to the tech that owns this TextTrack.\n   *\n   * @param {TextTrack~Kind} [options.kind='subtitles']\n   *        A valid text track kind.\n   *\n   * @param {TextTrack~Mode} [options.mode='disabled']\n   *        A valid text track mode.\n   *\n   * @param {string} [options.id='vjs_track_' + Guid.newGUID()]\n   *        A unique id for this TextTrack.\n   *\n   * @param {string} [options.label='']\n   *        The menu label for this track.\n   *\n   * @param {string} [options.language='']\n   *        A valid two character language code.\n   *\n   * @param {string} [options.srclang='']\n   *        A valid two character language code. An alternative, but deprioritized\n   *        version of `options.language`\n   *\n   * @param {string} [options.src]\n   *        A url to TextTrack cues.\n   *\n   * @param {boolean} [options.default]\n   *        If this track should default to on or off.\n   */\n  constructor(options = {}) {\n    if (!options.tech) {\n      throw new Error('A tech was not provided.');\n    }\n    const settings = merge$1(options, {\n      kind: TextTrackKind[options.kind] || 'subtitles',\n      language: options.language || options.srclang || ''\n    });\n    let mode = TextTrackMode[settings.mode] || 'disabled';\n    const default_ = settings.default;\n    if (settings.kind === 'metadata' || settings.kind === 'chapters') {\n      mode = 'hidden';\n    }\n    super(settings);\n    this.tech_ = settings.tech;\n    this.cues_ = [];\n    this.activeCues_ = [];\n    this.preload_ = this.tech_.preloadTextTracks !== false;\n    const cues = new TextTrackCueList(this.cues_);\n    const activeCues = new TextTrackCueList(this.activeCues_);\n    let changed = false;\n    this.timeupdateHandler = bind_(this, function (event = {}) {\n      if (this.tech_.isDisposed()) {\n        return;\n      }\n      if (!this.tech_.isReady_) {\n        if (event.type !== 'timeupdate') {\n          this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);\n        }\n        return;\n      }\n\n      // Accessing this.activeCues for the side-effects of updating itself\n      // due to its nature as a getter function. Do not remove or cues will\n      // stop updating!\n      // Use the setter to prevent deletion from uglify (pure_getters rule)\n      this.activeCues = this.activeCues;\n      if (changed) {\n        this.trigger('cuechange');\n        changed = false;\n      }\n      if (event.type !== 'timeupdate') {\n        this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);\n      }\n    });\n    const disposeHandler = () => {\n      this.stopTracking();\n    };\n    this.tech_.one('dispose', disposeHandler);\n    if (mode !== 'disabled') {\n      this.startTracking();\n    }\n    Object.defineProperties(this, {\n      /**\n       * @memberof TextTrack\n       * @member {boolean} default\n       *         If this track was set to be on or off by default. Cannot be changed after\n       *         creation.\n       * @instance\n       *\n       * @readonly\n       */\n      default: {\n        get() {\n          return default_;\n        },\n        set() {}\n      },\n      /**\n       * @memberof TextTrack\n       * @member {string} mode\n       *         Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will\n       *         not be set if setting to an invalid mode.\n       * @instance\n       *\n       * @fires TextTrack#modechange\n       */\n      mode: {\n        get() {\n          return mode;\n        },\n        set(newMode) {\n          if (!TextTrackMode[newMode]) {\n            return;\n          }\n          if (mode === newMode) {\n            return;\n          }\n          mode = newMode;\n          if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {\n            // On-demand load.\n            loadTrack(this.src, this);\n          }\n          this.stopTracking();\n          if (mode !== 'disabled') {\n            this.startTracking();\n          }\n          /**\n           * An event that fires when mode changes on this track. This allows\n           * the TextTrackList that holds this track to act accordingly.\n           *\n           * > Note: This is not part of the spec!\n           *\n           * @event TextTrack#modechange\n           * @type {Event}\n           */\n          this.trigger('modechange');\n        }\n      },\n      /**\n       * @memberof TextTrack\n       * @member {TextTrackCueList} cues\n       *         The text track cue list for this TextTrack.\n       * @instance\n       */\n      cues: {\n        get() {\n          if (!this.loaded_) {\n            return null;\n          }\n          return cues;\n        },\n        set() {}\n      },\n      /**\n       * @memberof TextTrack\n       * @member {TextTrackCueList} activeCues\n       *         The list text track cues that are currently active for this TextTrack.\n       * @instance\n       */\n      activeCues: {\n        get() {\n          if (!this.loaded_) {\n            return null;\n          }\n\n          // nothing to do\n          if (this.cues.length === 0) {\n            return activeCues;\n          }\n          const ct = this.tech_.currentTime();\n          const active = [];\n          for (let i = 0, l = this.cues.length; i < l; i++) {\n            const cue = this.cues[i];\n            if (cue.startTime <= ct && cue.endTime >= ct) {\n              active.push(cue);\n            }\n          }\n          changed = false;\n          if (active.length !== this.activeCues_.length) {\n            changed = true;\n          } else {\n            for (let i = 0; i < active.length; i++) {\n              if (this.activeCues_.indexOf(active[i]) === -1) {\n                changed = true;\n              }\n            }\n          }\n          this.activeCues_ = active;\n          activeCues.setCues_(this.activeCues_);\n          return activeCues;\n        },\n        // /!\\ Keep this setter empty (see the timeupdate handler above)\n        set() {}\n      }\n    });\n    if (settings.src) {\n      this.src = settings.src;\n      if (!this.preload_) {\n        // Tracks will load on-demand.\n        // Act like we're loaded for other purposes.\n        this.loaded_ = true;\n      }\n      if (this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {\n        loadTrack(this.src, this);\n      }\n    } else {\n      this.loaded_ = true;\n    }\n  }\n  startTracking() {\n    // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback\n    this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);\n    // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)\n    this.tech_.on('timeupdate', this.timeupdateHandler);\n  }\n  stopTracking() {\n    if (this.rvf_) {\n      this.tech_.cancelVideoFrameCallback(this.rvf_);\n      this.rvf_ = undefined;\n    }\n    this.tech_.off('timeupdate', this.timeupdateHandler);\n  }\n\n  /**\n   * Add a cue to the internal list of cues.\n   *\n   * @param {TextTrack~Cue} cue\n   *        The cue to add to our internal list\n   */\n  addCue(originalCue) {\n    let cue = originalCue;\n\n    // Testing if the cue is a VTTCue in a way that survives minification\n    if (!('getCueAsHTML' in cue)) {\n      cue = new window$1.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);\n      for (const prop in originalCue) {\n        if (!(prop in cue)) {\n          cue[prop] = originalCue[prop];\n        }\n      }\n\n      // make sure that `id` is copied over\n      cue.id = originalCue.id;\n      cue.originalCue_ = originalCue;\n    }\n    const tracks = this.tech_.textTracks();\n    for (let i = 0; i < tracks.length; i++) {\n      if (tracks[i] !== this) {\n        tracks[i].removeCue(cue);\n      }\n    }\n    this.cues_.push(cue);\n    this.cues.setCues_(this.cues_);\n  }\n\n  /**\n   * Creates a copy of the text track and makes it serializable\n   * by removing circular dependencies.\n   *\n   * @return {Object} The track information as a serializable object\n   */\n  toJSON() {\n    return textTrackConverter.trackToJson(this);\n  }\n\n  /**\n   * Remove a cue from our internal list\n   *\n   * @param {TextTrack~Cue} removeCue\n   *        The cue to remove from our internal list\n   */\n  removeCue(removeCue) {\n    let i = this.cues_.length;\n    while (i--) {\n      const cue = this.cues_[i];\n      if (cue === removeCue || cue.originalCue_ && cue.originalCue_ === removeCue) {\n        this.cues_.splice(i, 1);\n        this.cues.setCues_(this.cues_);\n        break;\n      }\n    }\n  }\n}\n\n/**\n * cuechange - One or more cues in the track have become active or stopped being active.\n *\n * @protected\n */\nTextTrack.prototype.allowedEvents_ = {\n  cuechange: 'cuechange'\n};\n\n/**\n * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}\n * only one `AudioTrack` in the list will be enabled at a time.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}\n * @extends Track\n */\nclass AudioTrack extends Track {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {Object} [options={}]\n   *        Object of option names and values\n   *\n   * @param {AudioTrack~Kind} [options.kind='']\n   *        A valid audio track kind\n   *\n   * @param {string} [options.id='vjs_track_' + Guid.newGUID()]\n   *        A unique id for this AudioTrack.\n   *\n   * @param {string} [options.label='']\n   *        The menu label for this track.\n   *\n   * @param {string} [options.language='']\n   *        A valid two character language code.\n   *\n   * @param {boolean} [options.enabled]\n   *        If this track is the one that is currently playing. If this track is part of\n   *        an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.\n   */\n  constructor(options = {}) {\n    const settings = merge$1(options, {\n      kind: AudioTrackKind[options.kind] || ''\n    });\n    super(settings);\n    let enabled = false;\n\n    /**\n     * @memberof AudioTrack\n     * @member {boolean} enabled\n     *         If this `AudioTrack` is enabled or not. When setting this will\n     *         fire {@link AudioTrack#enabledchange} if the state of enabled is changed.\n     * @instance\n     *\n     * @fires VideoTrack#selectedchange\n     */\n    Object.defineProperty(this, 'enabled', {\n      get() {\n        return enabled;\n      },\n      set(newEnabled) {\n        // an invalid or unchanged value\n        if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {\n          return;\n        }\n        enabled = newEnabled;\n\n        /**\n         * An event that fires when enabled changes on this track. This allows\n         * the AudioTrackList that holds this track to act accordingly.\n         *\n         * > Note: This is not part of the spec! Native tracks will do\n         *         this internally without an event.\n         *\n         * @event AudioTrack#enabledchange\n         * @type {Event}\n         */\n        this.trigger('enabledchange');\n      }\n    });\n\n    // if the user sets this track to selected then\n    // set selected to that true value otherwise\n    // we keep it false\n    if (settings.enabled) {\n      this.enabled = settings.enabled;\n    }\n    this.loaded_ = true;\n  }\n}\n\n/**\n * A representation of a single `VideoTrack`.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}\n * @extends Track\n */\nclass VideoTrack extends Track {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {Object} [options={}]\n   *        Object of option names and values\n   *\n   * @param {string} [options.kind='']\n   *        A valid {@link VideoTrack~Kind}\n   *\n   * @param {string} [options.id='vjs_track_' + Guid.newGUID()]\n   *        A unique id for this AudioTrack.\n   *\n   * @param {string} [options.label='']\n   *        The menu label for this track.\n   *\n   * @param {string} [options.language='']\n   *        A valid two character language code.\n   *\n   * @param {boolean} [options.selected]\n   *        If this track is the one that is currently playing.\n   */\n  constructor(options = {}) {\n    const settings = merge$1(options, {\n      kind: VideoTrackKind[options.kind] || ''\n    });\n    super(settings);\n    let selected = false;\n\n    /**\n     * @memberof VideoTrack\n     * @member {boolean} selected\n     *         If this `VideoTrack` is selected or not. When setting this will\n     *         fire {@link VideoTrack#selectedchange} if the state of selected changed.\n     * @instance\n     *\n     * @fires VideoTrack#selectedchange\n     */\n    Object.defineProperty(this, 'selected', {\n      get() {\n        return selected;\n      },\n      set(newSelected) {\n        // an invalid or unchanged value\n        if (typeof newSelected !== 'boolean' || newSelected === selected) {\n          return;\n        }\n        selected = newSelected;\n\n        /**\n         * An event that fires when selected changes on this track. This allows\n         * the VideoTrackList that holds this track to act accordingly.\n         *\n         * > Note: This is not part of the spec! Native tracks will do\n         *         this internally without an event.\n         *\n         * @event VideoTrack#selectedchange\n         * @type {Event}\n         */\n        this.trigger('selectedchange');\n      }\n    });\n\n    // if the user sets this track to selected then\n    // set selected to that true value otherwise\n    // we keep it false\n    if (settings.selected) {\n      this.selected = settings.selected;\n    }\n  }\n}\n\n/**\n * @file html-track-element.js\n */\n\n/** @import Tech from '../tech/tech' */\n\n/**\n * A single track represented in the DOM.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}\n * @extends EventTarget\n */\nclass HTMLTrackElement extends EventTarget$2 {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {Object} options={}\n   *        Object of option names and values\n   *\n   * @param {Tech} options.tech\n   *        A reference to the tech that owns this HTMLTrackElement.\n   *\n   * @param {TextTrack~Kind} [options.kind='subtitles']\n   *        A valid text track kind.\n   *\n   * @param {TextTrack~Mode} [options.mode='disabled']\n   *        A valid text track mode.\n   *\n   * @param {string} [options.id='vjs_track_' + Guid.newGUID()]\n   *        A unique id for this TextTrack.\n   *\n   * @param {string} [options.label='']\n   *        The menu label for this track.\n   *\n   * @param {string} [options.language='']\n   *        A valid two character language code.\n   *\n   * @param {string} [options.srclang='']\n   *        A valid two character language code. An alternative, but deprioritized\n   *        version of `options.language`\n   *\n   * @param {string} [options.src]\n   *        A url to TextTrack cues.\n   *\n   * @param {boolean} [options.default]\n   *        If this track should default to on or off.\n   */\n  constructor(options = {}) {\n    super();\n    let readyState;\n    const track = new TextTrack(options);\n    this.kind = track.kind;\n    this.src = track.src;\n    this.srclang = track.language;\n    this.label = track.label;\n    this.default = track.default;\n    Object.defineProperties(this, {\n      /**\n       * @memberof HTMLTrackElement\n       * @member {HTMLTrackElement~ReadyState} readyState\n       *         The current ready state of the track element.\n       * @instance\n       */\n      readyState: {\n        get() {\n          return readyState;\n        }\n      },\n      /**\n       * @memberof HTMLTrackElement\n       * @member {TextTrack} track\n       *         The underlying TextTrack object.\n       * @instance\n       *\n       */\n      track: {\n        get() {\n          return track;\n        }\n      }\n    });\n    readyState = HTMLTrackElement.NONE;\n\n    /**\n     * @listens TextTrack#loadeddata\n     * @fires HTMLTrackElement#load\n     */\n    track.addEventListener('loadeddata', () => {\n      readyState = HTMLTrackElement.LOADED;\n      this.trigger({\n        type: 'load',\n        target: this\n      });\n    });\n  }\n}\n\n/**\n * @protected\n */\nHTMLTrackElement.prototype.allowedEvents_ = {\n  load: 'load'\n};\n\n/**\n * The text track not loaded state.\n *\n * @type {number}\n * @static\n */\nHTMLTrackElement.NONE = 0;\n\n/**\n * The text track loading state.\n *\n * @type {number}\n * @static\n */\nHTMLTrackElement.LOADING = 1;\n\n/**\n * The text track loaded state.\n *\n * @type {number}\n * @static\n */\nHTMLTrackElement.LOADED = 2;\n\n/**\n * The text track failed to load state.\n *\n * @type {number}\n * @static\n */\nHTMLTrackElement.ERROR = 3;\n\n/*\n * This file contains all track properties that are used in\n * player.js, tech.js, html5.js and possibly other techs in the future.\n */\n\nconst NORMAL = {\n  audio: {\n    ListClass: AudioTrackList,\n    TrackClass: AudioTrack,\n    capitalName: 'Audio'\n  },\n  video: {\n    ListClass: VideoTrackList,\n    TrackClass: VideoTrack,\n    capitalName: 'Video'\n  },\n  text: {\n    ListClass: TextTrackList,\n    TrackClass: TextTrack,\n    capitalName: 'Text'\n  }\n};\nObject.keys(NORMAL).forEach(function (type) {\n  NORMAL[type].getterName = `${type}Tracks`;\n  NORMAL[type].privateName = `${type}Tracks_`;\n});\nconst REMOTE = {\n  remoteText: {\n    ListClass: TextTrackList,\n    TrackClass: TextTrack,\n    capitalName: 'RemoteText',\n    getterName: 'remoteTextTracks',\n    privateName: 'remoteTextTracks_'\n  },\n  remoteTextEl: {\n    ListClass: HtmlTrackElementList,\n    TrackClass: HTMLTrackElement,\n    capitalName: 'RemoteTextTrackEls',\n    getterName: 'remoteTextTrackEls',\n    privateName: 'remoteTextTrackEls_'\n  }\n};\nconst ALL = Object.assign({}, NORMAL, REMOTE);\nREMOTE.names = Object.keys(REMOTE);\nNORMAL.names = Object.keys(NORMAL);\nALL.names = [].concat(REMOTE.names).concat(NORMAL.names);\n\n/**\n * @file tech.js\n */\n\n/** @import { TimeRange } from '../utils/time' */\n\n/**\n * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string\n * that just contains the src url alone.\n * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`\n   * `var SourceString = 'http://example.com/some-video.mp4';`\n *\n * @typedef {Object|string} SourceObject\n *\n * @property {string} src\n *           The url to the source\n *\n * @property {string} type\n *           The mime type of the source\n */\n\n/**\n * A function used by {@link Tech} to create a new {@link TextTrack}.\n *\n * @private\n *\n * @param {Tech} self\n *        An instance of the Tech class.\n *\n * @param {string} kind\n *        `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)\n *\n * @param {string} [label]\n *        Label to identify the text track\n *\n * @param {string} [language]\n *        Two letter language abbreviation\n *\n * @param {Object} [options={}]\n *        An object with additional text track options\n *\n * @return {TextTrack}\n *          The text track that was created.\n */\nfunction createTrackHelper(self, kind, label, language, options = {}) {\n  const tracks = self.textTracks();\n  options.kind = kind;\n  if (label) {\n    options.label = label;\n  }\n  if (language) {\n    options.language = language;\n  }\n  options.tech = self;\n  const track = new ALL.text.TrackClass(options);\n  tracks.addTrack(track);\n  return track;\n}\n\n/**\n * This is the base class for media playback technology controllers, such as\n * {@link HTML5}\n *\n * @extends Component\n */\nclass Tech extends Component$1 {\n  /**\n  * Create an instance of this Tech.\n  *\n  * @param {Object} [options]\n  *        The key/value store of player options.\n  *\n  * @param {Function} [ready]\n  *        Callback function to call when the `HTML5` Tech is ready.\n  */\n  constructor(options = {}, ready = function () {}) {\n    // we don't want the tech to report user activity automatically.\n    // This is done manually in addControlsListeners\n    options.reportTouchActivity = false;\n    super(null, options, ready);\n    this.onDurationChange_ = e => this.onDurationChange(e);\n    this.trackProgress_ = e => this.trackProgress(e);\n    this.trackCurrentTime_ = e => this.trackCurrentTime(e);\n    this.stopTrackingCurrentTime_ = e => this.stopTrackingCurrentTime(e);\n    this.disposeSourceHandler_ = e => this.disposeSourceHandler(e);\n    this.queuedHanders_ = new Set();\n\n    // keep track of whether the current source has played at all to\n    // implement a very limited played()\n    this.hasStarted_ = false;\n    this.on('playing', function () {\n      this.hasStarted_ = true;\n    });\n    this.on('loadstart', function () {\n      this.hasStarted_ = false;\n    });\n    ALL.names.forEach(name => {\n      const props = ALL[name];\n      if (options && options[props.getterName]) {\n        this[props.privateName] = options[props.getterName];\n      }\n    });\n\n    // Manually track progress in cases where the browser/tech doesn't report it.\n    if (!this.featuresProgressEvents) {\n      this.manualProgressOn();\n    }\n\n    // Manually track timeupdates in cases where the browser/tech doesn't report it.\n    if (!this.featuresTimeupdateEvents) {\n      this.manualTimeUpdatesOn();\n    }\n    ['Text', 'Audio', 'Video'].forEach(track => {\n      if (options[`native${track}Tracks`] === false) {\n        this[`featuresNative${track}Tracks`] = false;\n      }\n    });\n    if (options.nativeCaptions === false || options.nativeTextTracks === false) {\n      this.featuresNativeTextTracks = false;\n    } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {\n      this.featuresNativeTextTracks = true;\n    }\n    if (!this.featuresNativeTextTracks) {\n      this.emulateTextTracks();\n    }\n    this.preloadTextTracks = options.preloadTextTracks !== false;\n    this.autoRemoteTextTracks_ = new ALL.text.ListClass();\n    this.initTrackListeners();\n\n    // Turn on component tap events only if not using native controls\n    if (!options.nativeControlsForTouch) {\n      this.emitTapEvents();\n    }\n    if (this.constructor) {\n      this.name_ = this.constructor.name || 'Unknown Tech';\n    }\n  }\n\n  /**\n   * A special function to trigger source set in a way that will allow player\n   * to re-trigger if the player or tech are not ready yet.\n   *\n   * @fires Tech#sourceset\n   * @param {string} src The source string at the time of the source changing.\n   */\n  triggerSourceset(src) {\n    if (!this.isReady_) {\n      // on initial ready we have to trigger source set\n      // 1ms after ready so that player can watch for it.\n      this.one('ready', () => this.setTimeout(() => this.triggerSourceset(src), 1));\n    }\n\n    /**\n     * Fired when the source is set on the tech causing the media element\n     * to reload.\n     *\n     * @see {@link Player#event:sourceset}\n     * @event Tech#sourceset\n     * @type {Event}\n     */\n    this.trigger({\n      src,\n      type: 'sourceset'\n    });\n  }\n\n  /* Fallbacks for unsupported event types\n  ================================================================================ */\n\n  /**\n   * Polyfill the `progress` event for browsers that don't support it natively.\n   *\n   * @see {@link Tech#trackProgress}\n   */\n  manualProgressOn() {\n    this.on('durationchange', this.onDurationChange_);\n    this.manualProgress = true;\n\n    // Trigger progress watching when a source begins loading\n    this.one('ready', this.trackProgress_);\n  }\n\n  /**\n   * Turn off the polyfill for `progress` events that was created in\n   * {@link Tech#manualProgressOn}\n   */\n  manualProgressOff() {\n    this.manualProgress = false;\n    this.stopTrackingProgress();\n    this.off('durationchange', this.onDurationChange_);\n  }\n\n  /**\n   * This is used to trigger a `progress` event when the buffered percent changes. It\n   * sets an interval function that will be called every 500 milliseconds to check if the\n   * buffer end percent has changed.\n   *\n   * > This function is called by {@link Tech#manualProgressOn}\n   *\n   * @param {Event} event\n   *        The `ready` event that caused this to run.\n   *\n   * @listens Tech#ready\n   * @fires Tech#progress\n   */\n  trackProgress(event) {\n    this.stopTrackingProgress();\n    this.progressInterval = this.setInterval(bind_(this, function () {\n      // Don't trigger unless buffered amount is greater than last time\n\n      const numBufferedPercent = this.bufferedPercent();\n      if (this.bufferedPercent_ !== numBufferedPercent) {\n        /**\n         * See {@link Player#progress}\n         *\n         * @event Tech#progress\n         * @type {Event}\n         */\n        this.trigger('progress');\n      }\n      this.bufferedPercent_ = numBufferedPercent;\n      if (numBufferedPercent === 1) {\n        this.stopTrackingProgress();\n      }\n    }), 500);\n  }\n\n  /**\n   * Update our internal duration on a `durationchange` event by calling\n   * {@link Tech#duration}.\n   *\n   * @param {Event} event\n   *        The `durationchange` event that caused this to run.\n   *\n   * @listens Tech#durationchange\n   */\n  onDurationChange(event) {\n    this.duration_ = this.duration();\n  }\n\n  /**\n   * Get and create a `TimeRange` object for buffering.\n   *\n   * @return {TimeRange}\n   *         The time range object that was created.\n   */\n  buffered() {\n    return createTimeRanges$1(0, 0);\n  }\n\n  /**\n   * Get the percentage of the current video that is currently buffered.\n   *\n   * @return {number}\n   *         A number from 0 to 1 that represents the decimal percentage of the\n   *         video that is buffered.\n   *\n   */\n  bufferedPercent() {\n    return bufferedPercent(this.buffered(), this.duration_);\n  }\n\n  /**\n   * Turn off the polyfill for `progress` events that was created in\n   * {@link Tech#manualProgressOn}\n   * Stop manually tracking progress events by clearing the interval that was set in\n   * {@link Tech#trackProgress}.\n   */\n  stopTrackingProgress() {\n    this.clearInterval(this.progressInterval);\n  }\n\n  /**\n   * Polyfill the `timeupdate` event for browsers that don't support it.\n   *\n   * @see {@link Tech#trackCurrentTime}\n   */\n  manualTimeUpdatesOn() {\n    this.manualTimeUpdates = true;\n    this.on('play', this.trackCurrentTime_);\n    this.on('pause', this.stopTrackingCurrentTime_);\n  }\n\n  /**\n   * Turn off the polyfill for `timeupdate` events that was created in\n   * {@link Tech#manualTimeUpdatesOn}\n   */\n  manualTimeUpdatesOff() {\n    this.manualTimeUpdates = false;\n    this.stopTrackingCurrentTime();\n    this.off('play', this.trackCurrentTime_);\n    this.off('pause', this.stopTrackingCurrentTime_);\n  }\n\n  /**\n   * Sets up an interval function to track current time and trigger `timeupdate` every\n   * 250 milliseconds.\n   *\n   * @listens Tech#play\n   * @triggers Tech#timeupdate\n   */\n  trackCurrentTime() {\n    if (this.currentTimeInterval) {\n      this.stopTrackingCurrentTime();\n    }\n    this.currentTimeInterval = this.setInterval(function () {\n      /**\n       * Triggered at an interval of 250ms to indicated that time is passing in the video.\n       *\n       * @event Tech#timeupdate\n       * @type {Event}\n       */\n      this.trigger({\n        type: 'timeupdate',\n        target: this,\n        manuallyTriggered: true\n      });\n\n      // 42 = 24 fps // 250 is what Webkit uses // FF uses 15\n    }, 250);\n  }\n\n  /**\n   * Stop the interval function created in {@link Tech#trackCurrentTime} so that the\n   * `timeupdate` event is no longer triggered.\n   *\n   * @listens {Tech#pause}\n   */\n  stopTrackingCurrentTime() {\n    this.clearInterval(this.currentTimeInterval);\n\n    // #1002 - if the video ends right before the next timeupdate would happen,\n    // the progress bar won't make it all the way to the end\n    this.trigger({\n      type: 'timeupdate',\n      target: this,\n      manuallyTriggered: true\n    });\n  }\n\n  /**\n   * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},\n   * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.\n   *\n   * @fires Component#dispose\n   */\n  dispose() {\n    // clear out all tracks because we can't reuse them between techs\n    this.clearTracks(NORMAL.names);\n\n    // Turn off any manual progress or timeupdate tracking\n    if (this.manualProgress) {\n      this.manualProgressOff();\n    }\n    if (this.manualTimeUpdates) {\n      this.manualTimeUpdatesOff();\n    }\n    super.dispose();\n  }\n\n  /**\n   * Clear out a single `TrackList` or an array of `TrackLists` given their names.\n   *\n   * > Note: Techs without source handlers should call this between sources for `video`\n   *         & `audio` tracks. You don't want to use them between tracks!\n   *\n   * @param {string[]|string} types\n   *        TrackList names to clear, valid names are `video`, `audio`, and\n   *        `text`.\n   */\n  clearTracks(types) {\n    types = [].concat(types);\n    // clear out all tracks because we can't reuse them between techs\n    types.forEach(type => {\n      const list = this[`${type}Tracks`]() || [];\n      let i = list.length;\n      while (i--) {\n        const track = list[i];\n        if (type === 'text') {\n          this.removeRemoteTextTrack(track);\n        }\n        list.removeTrack(track);\n      }\n    });\n  }\n\n  /**\n   * Remove any TextTracks added via addRemoteTextTrack that are\n   * flagged for automatic garbage collection\n   */\n  cleanupAutoTextTracks() {\n    const list = this.autoRemoteTextTracks_ || [];\n    let i = list.length;\n    while (i--) {\n      const track = list[i];\n      this.removeRemoteTextTrack(track);\n    }\n  }\n\n  /**\n   * Reset the tech, which will removes all sources and reset the internal readyState.\n   *\n   * @abstract\n   */\n  reset() {}\n\n  /**\n   * Get the value of `crossOrigin` from the tech.\n   *\n   * @abstract\n   *\n   * @see {Html5#crossOrigin}\n   */\n  crossOrigin() {}\n\n  /**\n   * Set the value of `crossOrigin` on the tech.\n   *\n   * @abstract\n   *\n   * @param {string} crossOrigin the crossOrigin value\n   * @see {Html5#setCrossOrigin}\n   */\n  setCrossOrigin() {}\n\n  /**\n   * Get or set an error on the Tech.\n   *\n   * @param {MediaError} [err]\n   *        Error to set on the Tech\n   *\n   * @return {MediaError|null}\n   *         The current error object on the tech, or null if there isn't one.\n   */\n  error(err) {\n    if (err !== undefined) {\n      this.error_ = new MediaError(err);\n      this.trigger('error');\n    }\n    return this.error_;\n  }\n\n  /**\n   * Returns the `TimeRange`s that have been played through for the current source.\n   *\n   * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.\n   *         It only checks whether the source has played at all or not.\n   *\n   * @return {TimeRange}\n   *         - A single time range if this video has played\n   *         - An empty set of ranges if not.\n   */\n  played() {\n    if (this.hasStarted_) {\n      return createTimeRanges$1(0, 0);\n    }\n    return createTimeRanges$1();\n  }\n\n  /**\n   * Start playback\n   *\n   * @abstract\n   *\n   * @see {Html5#play}\n   */\n  play() {}\n\n  /**\n   * Set whether we are scrubbing or not\n   *\n   * @abstract\n   * @param {boolean} _isScrubbing\n   *                  - true for we are currently scrubbing\n   *                  - false for we are no longer scrubbing\n   *\n   * @see {Html5#setScrubbing}\n   */\n  setScrubbing(_isScrubbing) {}\n\n  /**\n   * Get whether we are scrubbing or not\n   *\n   * @abstract\n   *\n   * @see {Html5#scrubbing}\n   */\n  scrubbing() {}\n\n  /**\n   * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was\n   * previously called.\n   *\n   * @param {number} _seconds\n   *        Set the current time of the media to this.\n   * @fires Tech#timeupdate\n   */\n  setCurrentTime(_seconds) {\n    // improve the accuracy of manual timeupdates\n    if (this.manualTimeUpdates) {\n      /**\n       * A manual `timeupdate` event.\n       *\n       * @event Tech#timeupdate\n       * @type {Event}\n       */\n      this.trigger({\n        type: 'timeupdate',\n        target: this,\n        manuallyTriggered: true\n      });\n    }\n  }\n\n  /**\n   * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and\n   * {@link TextTrackList} events.\n   *\n   * This adds {@link EventTarget~EventListeners} for `addtrack`, and  `removetrack`.\n   *\n   * @fires Tech#audiotrackchange\n   * @fires Tech#videotrackchange\n   * @fires Tech#texttrackchange\n   */\n  initTrackListeners() {\n    /**\n      * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}\n      *\n      * @event Tech#audiotrackchange\n      * @type {Event}\n      */\n\n    /**\n      * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}\n      *\n      * @event Tech#videotrackchange\n      * @type {Event}\n      */\n\n    /**\n      * Triggered when tracks are added or removed on the Tech {@link TextTrackList}\n      *\n      * @event Tech#texttrackchange\n      * @type {Event}\n      */\n    NORMAL.names.forEach(name => {\n      const props = NORMAL[name];\n      const trackListChanges = () => {\n        this.trigger(`${name}trackchange`);\n      };\n      const tracks = this[props.getterName]();\n      tracks.addEventListener('removetrack', trackListChanges);\n      tracks.addEventListener('addtrack', trackListChanges);\n      this.on('dispose', () => {\n        tracks.removeEventListener('removetrack', trackListChanges);\n        tracks.removeEventListener('addtrack', trackListChanges);\n      });\n    });\n  }\n\n  /**\n   * Emulate TextTracks using vtt.js if necessary\n   *\n   * @fires Tech#vttjsloaded\n   * @fires Tech#vttjserror\n   */\n  addWebVttScript_() {\n    if (window$1.WebVTT) {\n      return;\n    }\n\n    // Initially, Tech.el_ is a child of a dummy-div wait until the Component system\n    // signals that the Tech is ready at which point Tech.el_ is part of the DOM\n    // before inserting the WebVTT script\n    if (document$1.body.contains(this.el())) {\n      // load via require if available and vtt.js script location was not passed in\n      // as an option. novtt builds will turn the above require call into an empty object\n      // which will cause this if check to always fail.\n      if (!this.options_['vtt.js'] && isPlain(vtt) && Object.keys(vtt).length > 0) {\n        this.trigger('vttjsloaded');\n        return;\n      }\n\n      // load vtt.js via the script location option or the cdn of no location was\n      // passed in\n      const script = document$1.createElement('script');\n      script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';\n      script.onload = () => {\n        /**\n         * Fired when vtt.js is loaded.\n         *\n         * @event Tech#vttjsloaded\n         * @type {Event}\n         */\n        this.trigger('vttjsloaded');\n      };\n      script.onerror = () => {\n        /**\n         * Fired when vtt.js was not loaded due to an error\n         *\n         * @event Tech#vttjsloaded\n         * @type {Event}\n         */\n        this.trigger('vttjserror');\n      };\n      this.on('dispose', () => {\n        script.onload = null;\n        script.onerror = null;\n      });\n      // but have not loaded yet and we set it to true before the inject so that\n      // we don't overwrite the injected window.WebVTT if it loads right away\n      window$1.WebVTT = true;\n      this.el().parentNode.appendChild(script);\n    } else {\n      this.ready(this.addWebVttScript_);\n    }\n  }\n\n  /**\n   * Emulate texttracks\n   *\n   */\n  emulateTextTracks() {\n    const tracks = this.textTracks();\n    const remoteTracks = this.remoteTextTracks();\n    const handleAddTrack = e => tracks.addTrack(e.track);\n    const handleRemoveTrack = e => tracks.removeTrack(e.track);\n    remoteTracks.on('addtrack', handleAddTrack);\n    remoteTracks.on('removetrack', handleRemoveTrack);\n    this.addWebVttScript_();\n    const updateDisplay = () => this.trigger('texttrackchange');\n    const textTracksChanges = () => {\n      updateDisplay();\n      for (let i = 0; i < tracks.length; i++) {\n        const track = tracks[i];\n        track.removeEventListener('cuechange', updateDisplay);\n        if (track.mode === 'showing') {\n          track.addEventListener('cuechange', updateDisplay);\n        }\n      }\n    };\n    textTracksChanges();\n    tracks.addEventListener('change', textTracksChanges);\n    tracks.addEventListener('addtrack', textTracksChanges);\n    tracks.addEventListener('removetrack', textTracksChanges);\n    this.on('dispose', function () {\n      remoteTracks.off('addtrack', handleAddTrack);\n      remoteTracks.off('removetrack', handleRemoveTrack);\n      tracks.removeEventListener('change', textTracksChanges);\n      tracks.removeEventListener('addtrack', textTracksChanges);\n      tracks.removeEventListener('removetrack', textTracksChanges);\n      for (let i = 0; i < tracks.length; i++) {\n        const track = tracks[i];\n        track.removeEventListener('cuechange', updateDisplay);\n      }\n    });\n  }\n\n  /**\n   * Create and returns a remote {@link TextTrack} object.\n   *\n   * @param {string} kind\n   *        `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)\n   *\n   * @param {string} [label]\n   *        Label to identify the text track\n   *\n   * @param {string} [language]\n   *        Two letter language abbreviation\n   *\n   * @return {TextTrack}\n   *         The TextTrack that gets created.\n   */\n  addTextTrack(kind, label, language) {\n    if (!kind) {\n      throw new Error('TextTrack kind is required but was not provided');\n    }\n    return createTrackHelper(this, kind, label, language);\n  }\n\n  /**\n   * Create an emulated TextTrack for use by addRemoteTextTrack\n   *\n   * This is intended to be overridden by classes that inherit from\n   * Tech in order to create native or custom TextTracks.\n   *\n   * @param {Object} options\n   *        The object should contain the options to initialize the TextTrack with.\n   *\n   * @param {string} [options.kind]\n   *        `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).\n   *\n   * @param {string} [options.label].\n   *        Label to identify the text track\n   *\n   * @param {string} [options.language]\n   *        Two letter language abbreviation.\n   *\n   * @return {HTMLTrackElement}\n   *         The track element that gets created.\n   */\n  createRemoteTextTrack(options) {\n    const track = merge$1(options, {\n      tech: this\n    });\n    return new REMOTE.remoteTextEl.TrackClass(track);\n  }\n\n  /**\n   * Creates a remote text track object and returns an html track element.\n   *\n   * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.\n   *\n   * @param {Object} options\n   *        See {@link Tech#createRemoteTextTrack} for more detailed properties.\n   *\n   * @param {boolean} [manualCleanup=false]\n   *        - When false: the TextTrack will be automatically removed from the video\n   *          element whenever the source changes\n   *        - When True: The TextTrack will have to be cleaned up manually\n   *\n   * @return {HTMLTrackElement}\n   *         An Html Track Element.\n   *\n   */\n  addRemoteTextTrack(options = {}, manualCleanup) {\n    const htmlTrackElement = this.createRemoteTextTrack(options);\n    if (typeof manualCleanup !== 'boolean') {\n      manualCleanup = false;\n    }\n\n    // store HTMLTrackElement and TextTrack to remote list\n    this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);\n    this.remoteTextTracks().addTrack(htmlTrackElement.track);\n    if (manualCleanup === false) {\n      // create the TextTrackList if it doesn't exist\n      this.ready(() => this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track));\n    }\n    return htmlTrackElement;\n  }\n\n  /**\n   * Remove a remote text track from the remote `TextTrackList`.\n   *\n   * @param {TextTrack} track\n   *        `TextTrack` to remove from the `TextTrackList`\n   */\n  removeRemoteTextTrack(track) {\n    const trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);\n\n    // remove HTMLTrackElement and TextTrack from remote list\n    this.remoteTextTrackEls().removeTrackElement_(trackElement);\n    this.remoteTextTracks().removeTrack(track);\n    this.autoRemoteTextTracks_.removeTrack(track);\n  }\n\n  /**\n   * Gets available media playback quality metrics as specified by the W3C's Media\n   * Playback Quality API.\n   *\n   * @see [Spec]{@link https://wicg.github.io/media-playback-quality}\n   *\n   * @return {Object}\n   *         An object with supported media playback quality metrics\n   *\n   * @abstract\n   */\n  getVideoPlaybackQuality() {\n    return {};\n  }\n\n  /**\n   * Attempt to create a floating video window always on top of other windows\n   * so that users may continue consuming media while they interact with other\n   * content sites, or applications on their device.\n   *\n   * @see [Spec]{@link https://wicg.github.io/picture-in-picture}\n   *\n   * @return {Promise|undefined}\n   *         A promise with a Picture-in-Picture window if the browser supports\n   *         Promises (or one was passed in as an option). It returns undefined\n   *         otherwise.\n   *\n   * @abstract\n   */\n  requestPictureInPicture() {\n    return Promise.reject();\n  }\n\n  /**\n   * A method to check for the value of the 'disablePictureInPicture' <video> property.\n   * Defaults to true, as it should be considered disabled if the tech does not support pip\n   *\n   * @abstract\n   */\n  disablePictureInPicture() {\n    return true;\n  }\n\n  /**\n   * A method to set or unset the 'disablePictureInPicture' <video> property.\n   *\n   * @abstract\n   */\n  setDisablePictureInPicture() {}\n\n  /**\n   * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame\n   *\n   * @param {function} cb\n   * @return {number} request id\n   */\n  requestVideoFrameCallback(cb) {\n    const id = newGUID();\n    if (!this.isReady_ || this.paused()) {\n      this.queuedHanders_.add(id);\n      this.one('playing', () => {\n        if (this.queuedHanders_.has(id)) {\n          this.queuedHanders_.delete(id);\n          cb();\n        }\n      });\n    } else {\n      this.requestNamedAnimationFrame(id, cb);\n    }\n    return id;\n  }\n\n  /**\n   * A fallback implementation of cancelVideoFrameCallback\n   *\n   * @param {number} id id of callback to be cancelled\n   */\n  cancelVideoFrameCallback(id) {\n    if (this.queuedHanders_.has(id)) {\n      this.queuedHanders_.delete(id);\n    } else {\n      this.cancelNamedAnimationFrame(id);\n    }\n  }\n\n  /**\n   * A method to set a poster from a `Tech`.\n   *\n   * @abstract\n   */\n  setPoster() {}\n\n  /**\n   * A method to check for the presence of the 'playsinline' <video> attribute.\n   *\n   * @abstract\n   */\n  playsinline() {}\n\n  /**\n   * A method to set or unset the 'playsinline' <video> attribute.\n   *\n   * @abstract\n   */\n  setPlaysinline() {}\n\n  /**\n   * Attempt to force override of native audio tracks.\n   *\n   * @param {boolean} override - If set to true native audio will be overridden,\n   * otherwise native audio will potentially be used.\n   *\n   * @abstract\n   */\n  overrideNativeAudioTracks(override) {}\n\n  /**\n   * Attempt to force override of native video tracks.\n   *\n   * @param {boolean} override - If set to true native video will be overridden,\n   * otherwise native video will potentially be used.\n   *\n   * @abstract\n   */\n  overrideNativeVideoTracks(override) {}\n\n  /**\n   * Check if the tech can support the given mime-type.\n   *\n   * The base tech does not support any type, but source handlers might\n   * overwrite this.\n   *\n   * @param  {string} _type\n   *         The mimetype to check for support\n   *\n   * @return {string}\n   *         'probably', 'maybe', or empty string\n   *\n   * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}\n   *\n   * @abstract\n   */\n  canPlayType(_type) {\n    return '';\n  }\n\n  /**\n   * Check if the type is supported by this tech.\n   *\n   * The base tech does not support any type, but source handlers might\n   * overwrite this.\n   *\n   * @param {string} _type\n   *        The media type to check\n   * @return {string} Returns the native video element's response\n   */\n  static canPlayType(_type) {\n    return '';\n  }\n\n  /**\n   * Check if the tech can support the given source\n   *\n   * @param {Object} srcObj\n   *        The source object\n   * @param {Object} options\n   *        The options passed to the tech\n   * @return {string} 'probably', 'maybe', or '' (empty string)\n   */\n  static canPlaySource(srcObj, options) {\n    return Tech.canPlayType(srcObj.type);\n  }\n\n  /*\n   * Return whether the argument is a Tech or not.\n   * Can be passed either a Class like `Html5` or a instance like `player.tech_`\n   *\n   * @param {Object} component\n   *        The item to check\n   *\n   * @return {boolean}\n   *         Whether it is a tech or not\n   *         - True if it is a tech\n   *         - False if it is not\n   */\n  static isTech(component) {\n    return component.prototype instanceof Tech || component instanceof Tech || component === Tech;\n  }\n\n  /**\n   * Registers a `Tech` into a shared list for videojs.\n   *\n   * @param {string} name\n   *        Name of the `Tech` to register.\n   *\n   * @param {Object} tech\n   *        The `Tech` class to register.\n   */\n  static registerTech(name, tech) {\n    if (!Tech.techs_) {\n      Tech.techs_ = {};\n    }\n    if (!Tech.isTech(tech)) {\n      throw new Error(`Tech ${name} must be a Tech`);\n    }\n    if (!Tech.canPlayType) {\n      throw new Error('Techs must have a static canPlayType method on them');\n    }\n    if (!Tech.canPlaySource) {\n      throw new Error('Techs must have a static canPlaySource method on them');\n    }\n    name = toTitleCase$1(name);\n    Tech.techs_[name] = tech;\n    Tech.techs_[toLowerCase(name)] = tech;\n    if (name !== 'Tech') {\n      // camel case the techName for use in techOrder\n      Tech.defaultTechOrder_.push(name);\n    }\n    return tech;\n  }\n\n  /**\n   * Get a `Tech` from the shared list by name.\n   *\n   * @param {string} name\n   *        `camelCase` or `TitleCase` name of the Tech to get\n   *\n   * @return {Tech|undefined}\n   *         The `Tech` or undefined if there was no tech with the name requested.\n   */\n  static getTech(name) {\n    if (!name) {\n      return;\n    }\n    if (Tech.techs_ && Tech.techs_[name]) {\n      return Tech.techs_[name];\n    }\n    name = toTitleCase$1(name);\n    if (window$1 && window$1.videojs && window$1.videojs[name]) {\n      log$1.warn(`The ${name} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`);\n      return window$1.videojs[name];\n    }\n  }\n}\n\n/**\n * Get the {@link VideoTrackList}\n *\n * @returns {VideoTrackList}\n * @method Tech.prototype.videoTracks\n */\n\n/**\n * Get the {@link AudioTrackList}\n *\n * @returns {AudioTrackList}\n * @method Tech.prototype.audioTracks\n */\n\n/**\n * Get the {@link TextTrackList}\n *\n * @returns {TextTrackList}\n * @method Tech.prototype.textTracks\n */\n\n/**\n * Get the remote element {@link TextTrackList}\n *\n * @returns {TextTrackList}\n * @method Tech.prototype.remoteTextTracks\n */\n\n/**\n * Get the remote element {@link HtmlTrackElementList}\n *\n * @returns {HtmlTrackElementList}\n * @method Tech.prototype.remoteTextTrackEls\n */\n\nALL.names.forEach(function (name) {\n  const props = ALL[name];\n  Tech.prototype[props.getterName] = function () {\n    this[props.privateName] = this[props.privateName] || new props.ListClass();\n    return this[props.privateName];\n  };\n});\n\n/**\n * List of associated text tracks\n *\n * @type {TextTrackList}\n * @private\n * @property Tech#textTracks_\n */\n\n/**\n * List of associated audio tracks.\n *\n * @type {AudioTrackList}\n * @private\n * @property Tech#audioTracks_\n */\n\n/**\n * List of associated video tracks.\n *\n * @type {VideoTrackList}\n * @private\n * @property Tech#videoTracks_\n */\n\n/**\n * Boolean indicating whether the `Tech` supports volume control.\n *\n * @type {boolean}\n * @default\n */\nTech.prototype.featuresVolumeControl = true;\n\n/**\n * Boolean indicating whether the `Tech` supports muting volume.\n *\n * @type {boolean}\n * @default\n */\nTech.prototype.featuresMuteControl = true;\n\n/**\n * Boolean indicating whether the `Tech` supports fullscreen resize control.\n * Resizing plugins using request fullscreen reloads the plugin\n *\n * @type {boolean}\n * @default\n */\nTech.prototype.featuresFullscreenResize = false;\n\n/**\n * Boolean indicating whether the `Tech` supports changing the speed at which the video\n * plays. Examples:\n *   - Set player to play 2x (twice) as fast\n *   - Set player to play 0.5x (half) as fast\n *\n * @type {boolean}\n * @default\n */\nTech.prototype.featuresPlaybackRate = false;\n\n/**\n * Boolean indicating whether the `Tech` supports the `progress` event.\n * This will be used to determine if {@link Tech#manualProgressOn} should be called.\n *\n * @type {boolean}\n * @default\n */\nTech.prototype.featuresProgressEvents = false;\n\n/**\n * Boolean indicating whether the `Tech` supports the `sourceset` event.\n *\n * A tech should set this to `true` and then use {@link Tech#triggerSourceset}\n * to trigger a {@link Tech#event:sourceset} at the earliest time after getting\n * a new source.\n *\n * @type {boolean}\n * @default\n */\nTech.prototype.featuresSourceset = false;\n\n/**\n * Boolean indicating whether the `Tech` supports the `timeupdate` event.\n * This will be used to determine if {@link Tech#manualTimeUpdates} should be called.\n *\n * @type {boolean}\n * @default\n */\nTech.prototype.featuresTimeupdateEvents = false;\n\n/**\n * Boolean indicating whether the `Tech` supports the native `TextTrack`s.\n * This will help us integrate with native `TextTrack`s if the browser supports them.\n *\n * @type {boolean}\n * @default\n */\nTech.prototype.featuresNativeTextTracks = false;\n\n/**\n * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.\n *\n * @type {boolean}\n * @default\n */\nTech.prototype.featuresVideoFrameCallback = false;\n\n/**\n * A functional mixin for techs that want to use the Source Handler pattern.\n * Source handlers are scripts for handling specific formats.\n * The source handler pattern is used for adaptive formats (HLS, DASH) that\n * manually load video data and feed it into a Source Buffer (Media Source Extensions)\n * Example: `Tech.withSourceHandlers.call(MyTech);`\n *\n * @param {Tech} _Tech\n *        The tech to add source handler functions to.\n *\n * @mixes Tech~SourceHandlerAdditions\n */\nTech.withSourceHandlers = function (_Tech) {\n  /**\n   * Register a source handler\n   *\n   * @param {Function} handler\n   *        The source handler class\n   *\n   * @param {number} [index]\n   *        Register it at the following index\n   */\n  _Tech.registerSourceHandler = function (handler, index) {\n    let handlers = _Tech.sourceHandlers;\n    if (!handlers) {\n      handlers = _Tech.sourceHandlers = [];\n    }\n    if (index === undefined) {\n      // add to the end of the list\n      index = handlers.length;\n    }\n    handlers.splice(index, 0, handler);\n  };\n\n  /**\n   * Check if the tech can support the given type. Also checks the\n   * Techs sourceHandlers.\n   *\n   * @param {string} type\n   *         The mimetype to check.\n   *\n   * @return {string}\n   *         'probably', 'maybe', or '' (empty string)\n   */\n  _Tech.canPlayType = function (type) {\n    const handlers = _Tech.sourceHandlers || [];\n    let can;\n    for (let i = 0; i < handlers.length; i++) {\n      can = handlers[i].canPlayType(type);\n      if (can) {\n        return can;\n      }\n    }\n    return '';\n  };\n\n  /**\n   * Returns the first source handler that supports the source.\n   *\n   * TODO: Answer question: should 'probably' be prioritized over 'maybe'\n   *\n   * @param {SourceObject} source\n   *        The source object\n   *\n   * @param {Object} options\n   *        The options passed to the tech\n   *\n   * @return {SourceHandler|null}\n   *          The first source handler that supports the source or null if\n   *          no SourceHandler supports the source\n   */\n  _Tech.selectSourceHandler = function (source, options) {\n    const handlers = _Tech.sourceHandlers || [];\n    let can;\n    for (let i = 0; i < handlers.length; i++) {\n      can = handlers[i].canHandleSource(source, options);\n      if (can) {\n        return handlers[i];\n      }\n    }\n    return null;\n  };\n\n  /**\n   * Check if the tech can support the given source.\n   *\n   * @param {SourceObject} srcObj\n   *        The source object\n   *\n   * @param {Object} options\n   *        The options passed to the tech\n   *\n   * @return {string}\n   *         'probably', 'maybe', or '' (empty string)\n   */\n  _Tech.canPlaySource = function (srcObj, options) {\n    const sh = _Tech.selectSourceHandler(srcObj, options);\n    if (sh) {\n      return sh.canHandleSource(srcObj, options);\n    }\n    return '';\n  };\n\n  /**\n   * When using a source handler, prefer its implementation of\n   * any function normally provided by the tech.\n   */\n  const deferrable = ['seekable', 'seeking', 'duration'];\n\n  /**\n   * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable\n   * function if it exists, with a fallback to the Techs seekable function.\n   *\n   * @method _Tech.seekable\n   */\n\n  /**\n   * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration\n   * function if it exists, otherwise it will fallback to the techs duration function.\n   *\n   * @method _Tech.duration\n   */\n\n  deferrable.forEach(function (fnName) {\n    const originalFn = this[fnName];\n    if (typeof originalFn !== 'function') {\n      return;\n    }\n    this[fnName] = function () {\n      if (this.sourceHandler_ && this.sourceHandler_[fnName]) {\n        return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);\n      }\n      return originalFn.apply(this, arguments);\n    };\n  }, _Tech.prototype);\n\n  /**\n   * Create a function for setting the source using a source object\n   * and source handlers.\n   * Should never be called unless a source handler was found.\n   *\n   * @param {SourceObject} source\n   *        A source object with src and type keys\n   */\n  _Tech.prototype.setSource = function (source) {\n    let sh = _Tech.selectSourceHandler(source, this.options_);\n    if (!sh) {\n      // Fall back to a native source handler when unsupported sources are\n      // deliberately set\n      if (_Tech.nativeSourceHandler) {\n        sh = _Tech.nativeSourceHandler;\n      } else {\n        log$1.error('No source handler found for the current source.');\n      }\n    }\n\n    // Dispose any existing source handler\n    this.disposeSourceHandler();\n    this.off('dispose', this.disposeSourceHandler_);\n    if (sh !== _Tech.nativeSourceHandler) {\n      this.currentSource_ = source;\n    }\n    this.sourceHandler_ = sh.handleSource(source, this, this.options_);\n    this.one('dispose', this.disposeSourceHandler_);\n  };\n\n  /**\n   * Clean up any existing SourceHandlers and listeners when the Tech is disposed.\n   *\n   * @listens Tech#dispose\n   */\n  _Tech.prototype.disposeSourceHandler = function () {\n    // if we have a source and get another one\n    // then we are loading something new\n    // than clear all of our current tracks\n    if (this.currentSource_) {\n      this.clearTracks(['audio', 'video']);\n      this.currentSource_ = null;\n    }\n\n    // always clean up auto-text tracks\n    this.cleanupAutoTextTracks();\n    if (this.sourceHandler_) {\n      if (this.sourceHandler_.dispose) {\n        this.sourceHandler_.dispose();\n      }\n      this.sourceHandler_ = null;\n    }\n  };\n};\n\n// The base Tech class needs to be registered as a Component. It is the only\n// Tech that can be registered as a Component.\nComponent$1.registerComponent('Tech', Tech);\nTech.registerTech('Tech', Tech);\n\n/**\n * A list of techs that should be added to techOrder on Players\n *\n * @private\n */\nTech.defaultTechOrder_ = [];\n\n/**\n * @file middleware.js\n * @module middleware\n */\n\n/** @import Player from '../player' */\n/** @import Tech from '../tech/tech' */\n\nconst middlewares = {};\nconst middlewareInstances = {};\nconst TERMINATOR = {};\n\n/**\n * A middleware object is a plain JavaScript object that has methods that\n * match the {@link Tech} methods found in the lists of allowed\n * {@link module:middleware.allowedGetters|getters},\n * {@link module:middleware.allowedSetters|setters}, and\n * {@link module:middleware.allowedMediators|mediators}.\n *\n * @typedef {Object} MiddlewareObject\n */\n\n/**\n * A middleware factory function that should return a\n * {@link module:middleware~MiddlewareObject|MiddlewareObject}.\n *\n * This factory will be called for each player when needed, with the player\n * passed in as an argument.\n *\n * @callback MiddlewareFactory\n * @param {Player} player\n *        A Video.js player.\n */\n\n/**\n * Define a middleware that the player should use by way of a factory function\n * that returns a middleware object.\n *\n * @param  {string} type\n *         The MIME type to match or `\"*\"` for all MIME types.\n *\n * @param  {MiddlewareFactory} middleware\n *         A middleware factory function that will be executed for\n *         matching types.\n */\nfunction use(type, middleware) {\n  middlewares[type] = middlewares[type] || [];\n  middlewares[type].push(middleware);\n}\n\n/**\n * Asynchronously sets a source using middleware by recursing through any\n * matching middlewares and calling `setSource` on each, passing along the\n * previous returned value each time.\n *\n * @param  {Player} player\n *         A {@link Player} instance.\n *\n * @param  {Tech~SourceObject} src\n *         A source object.\n *\n * @param  {Function}\n *         The next middleware to run.\n */\nfunction setSource(player, src, next) {\n  player.setTimeout(() => setSourceHelper(src, middlewares[src.type], next, player), 1);\n}\n\n/**\n * When the tech is set, passes the tech to each middleware's `setTech` method.\n *\n * @param {Object[]} middleware\n *        An array of middleware instances.\n *\n * @param {Tech} tech\n *        A Video.js tech.\n */\nfunction setTech(middleware, tech) {\n  middleware.forEach(mw => mw.setTech && mw.setTech(tech));\n}\n\n/**\n * Calls a getter on the tech first, through each middleware\n * from right to left to the player.\n *\n * @param  {Object[]} middleware\n *         An array of middleware instances.\n *\n * @param  {Tech} tech\n *         The current tech.\n *\n * @param  {string} method\n *         A method name.\n *\n * @return {*}\n *         The final value from the tech after middleware has intercepted it.\n */\nfunction get(middleware, tech, method) {\n  return middleware.reduceRight(middlewareIterator(method), tech[method]());\n}\n\n/**\n * Takes the argument given to the player and calls the setter method on each\n * middleware from left to right to the tech.\n *\n * @param  {Object[]} middleware\n *         An array of middleware instances.\n *\n * @param  {Tech} tech\n *         The current tech.\n *\n * @param  {string} method\n *         A method name.\n *\n * @param  {*} arg\n *         The value to set on the tech.\n *\n * @return {*}\n *         The return value of the `method` of the `tech`.\n */\nfunction set(middleware, tech, method, arg) {\n  return tech[method](middleware.reduce(middlewareIterator(method), arg));\n}\n\n/**\n * Takes the argument given to the player and calls the `call` version of the\n * method on each middleware from left to right.\n *\n * Then, call the passed in method on the tech and return the result unchanged\n * back to the player, through middleware, this time from right to left.\n *\n * @param  {Object[]} middleware\n *         An array of middleware instances.\n *\n * @param  {Tech} tech\n *         The current tech.\n *\n * @param  {string} method\n *         A method name.\n *\n * @param  {*} arg\n *         The value to set on the tech.\n *\n * @return {*}\n *         The return value of the `method` of the `tech`, regardless of the\n *         return values of middlewares.\n */\nfunction mediate(middleware, tech, method, arg = null) {\n  const callMethod = 'call' + toTitleCase$1(method);\n  const middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);\n  const terminated = middlewareValue === TERMINATOR;\n  // deprecated. The `null` return value should instead return TERMINATOR to\n  // prevent confusion if a techs method actually returns null.\n  const returnValue = terminated ? null : tech[method](middlewareValue);\n  executeRight(middleware, method, returnValue, terminated);\n  return returnValue;\n}\n\n/**\n * Enumeration of allowed getters where the keys are method names.\n *\n * @type {Object}\n */\nconst allowedGetters = {\n  buffered: 1,\n  currentTime: 1,\n  duration: 1,\n  muted: 1,\n  played: 1,\n  paused: 1,\n  seekable: 1,\n  volume: 1,\n  ended: 1\n};\n\n/**\n * Enumeration of allowed setters where the keys are method names.\n *\n * @type {Object}\n */\nconst allowedSetters = {\n  setCurrentTime: 1,\n  setMuted: 1,\n  setVolume: 1\n};\n\n/**\n * Enumeration of allowed mediators where the keys are method names.\n *\n * @type {Object}\n */\nconst allowedMediators = {\n  play: 1,\n  pause: 1\n};\nfunction middlewareIterator(method) {\n  return (value, mw) => {\n    // if the previous middleware terminated, pass along the termination\n    if (value === TERMINATOR) {\n      return TERMINATOR;\n    }\n    if (mw[method]) {\n      return mw[method](value);\n    }\n    return value;\n  };\n}\nfunction executeRight(mws, method, value, terminated) {\n  for (let i = mws.length - 1; i >= 0; i--) {\n    const mw = mws[i];\n    if (mw[method]) {\n      mw[method](terminated, value);\n    }\n  }\n}\n\n/**\n * Clear the middleware cache for a player.\n *\n * @param  {Player} player\n *         A {@link Player} instance.\n */\nfunction clearCacheForPlayer(player) {\n  if (middlewareInstances.hasOwnProperty(player.id())) {\n    delete middlewareInstances[player.id()];\n  }\n}\n\n/**\n * {\n *  [playerId]: [[mwFactory, mwInstance], ...]\n * }\n *\n * @private\n */\nfunction getOrCreateFactory(player, mwFactory) {\n  const mws = middlewareInstances[player.id()];\n  let mw = null;\n  if (mws === undefined || mws === null) {\n    mw = mwFactory(player);\n    middlewareInstances[player.id()] = [[mwFactory, mw]];\n    return mw;\n  }\n  for (let i = 0; i < mws.length; i++) {\n    const [mwf, mwi] = mws[i];\n    if (mwf !== mwFactory) {\n      continue;\n    }\n    mw = mwi;\n  }\n  if (mw === null) {\n    mw = mwFactory(player);\n    mws.push([mwFactory, mw]);\n  }\n  return mw;\n}\nfunction setSourceHelper(src = {}, middleware = [], next, player, acc = [], lastRun = false) {\n  const [mwFactory, ...mwrest] = middleware;\n\n  // if mwFactory is a string, then we're at a fork in the road\n  if (typeof mwFactory === 'string') {\n    setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);\n\n    // if we have an mwFactory, call it with the player to get the mw,\n    // then call the mw's setSource method\n  } else if (mwFactory) {\n    const mw = getOrCreateFactory(player, mwFactory);\n\n    // if setSource isn't present, implicitly select this middleware\n    if (!mw.setSource) {\n      acc.push(mw);\n      return setSourceHelper(src, mwrest, next, player, acc, lastRun);\n    }\n    mw.setSource(Object.assign({}, src), function (err, _src) {\n      // something happened, try the next middleware on the current level\n      // make sure to use the old src\n      if (err) {\n        return setSourceHelper(src, mwrest, next, player, acc, lastRun);\n      }\n\n      // we've succeeded, now we need to go deeper\n      acc.push(mw);\n\n      // if it's the same type, continue down the current chain\n      // otherwise, we want to go down the new chain\n      setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);\n    });\n  } else if (mwrest.length) {\n    setSourceHelper(src, mwrest, next, player, acc, lastRun);\n  } else if (lastRun) {\n    next(src, acc);\n  } else {\n    setSourceHelper(src, middlewares['*'], next, player, acc, true);\n  }\n}\n\n/** @import Player from '../player' */\n\n/**\n * Mimetypes\n *\n * @see https://www.iana.org/assignments/media-types/media-types.xhtml\n * @typedef Mimetypes~Kind\n * @enum\n */\nconst MimetypesKind = {\n  opus: 'video/ogg',\n  ogv: 'video/ogg',\n  mp4: 'video/mp4',\n  mov: 'video/mp4',\n  m4v: 'video/mp4',\n  mkv: 'video/x-matroska',\n  m4a: 'audio/mp4',\n  mp3: 'audio/mpeg',\n  aac: 'audio/aac',\n  caf: 'audio/x-caf',\n  flac: 'audio/flac',\n  oga: 'audio/ogg',\n  wav: 'audio/wav',\n  m3u8: 'application/x-mpegURL',\n  mpd: 'application/dash+xml',\n  jpg: 'image/jpeg',\n  jpeg: 'image/jpeg',\n  gif: 'image/gif',\n  png: 'image/png',\n  svg: 'image/svg+xml',\n  webp: 'image/webp'\n};\n\n/**\n * Get the mimetype of a given src url if possible\n *\n * @param {string} src\n *        The url to the src\n *\n * @return {string}\n *         return the mimetype if it was known or empty string otherwise\n */\nconst getMimetype = function (src = '') {\n  const ext = getFileExtension(src);\n  const mimetype = MimetypesKind[ext.toLowerCase()];\n  return mimetype || '';\n};\n\n/**\n * Find the mime type of a given source string if possible. Uses the player\n * source cache.\n *\n * @param {Player} player\n *        The player object\n *\n * @param {string} src\n *        The source string\n *\n * @return {string}\n *         The type that was found\n */\nconst findMimetype = (player, src) => {\n  if (!src) {\n    return '';\n  }\n\n  // 1. check for the type in the `source` cache\n  if (player.cache_.source.src === src && player.cache_.source.type) {\n    return player.cache_.source.type;\n  }\n\n  // 2. see if we have this source in our `currentSources` cache\n  const matchingSources = player.cache_.sources.filter(s => s.src === src);\n  if (matchingSources.length) {\n    return matchingSources[0].type;\n  }\n\n  // 3. look for the src url in source elements and use the type there\n  const sources = player.$$('source');\n  for (let i = 0; i < sources.length; i++) {\n    const s = sources[i];\n    if (s.type && s.src && s.src === src) {\n      return s.type;\n    }\n  }\n\n  // 4. finally fallback to our list of mime types based on src url extension\n  return getMimetype(src);\n};\n\n/**\n * @module filter-source\n */\n\n/**\n * Filter out single bad source objects or multiple source objects in an\n * array. Also flattens nested source object arrays into a 1 dimensional\n * array of source objects.\n *\n * @param {Tech~SourceObject|Tech~SourceObject[]} src\n *        The src object to filter\n *\n * @return {Tech~SourceObject[]}\n *         An array of sourceobjects containing only valid sources\n *\n * @private\n */\nconst filterSource = function (src) {\n  // traverse array\n  if (Array.isArray(src)) {\n    let newsrc = [];\n    src.forEach(function (srcobj) {\n      srcobj = filterSource(srcobj);\n      if (Array.isArray(srcobj)) {\n        newsrc = newsrc.concat(srcobj);\n      } else if (isObject(srcobj)) {\n        newsrc.push(srcobj);\n      }\n    });\n    src = newsrc;\n  } else if (typeof src === 'string' && src.trim()) {\n    // convert string into object\n    src = [fixSource({\n      src\n    })];\n  } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {\n    // src is already valid\n    src = [fixSource(src)];\n  } else {\n    // invalid source, turn it into an empty array\n    src = [];\n  }\n  return src;\n};\n\n/**\n * Checks src mimetype, adding it when possible\n *\n * @param {Tech~SourceObject} src\n *        The src object to check\n * @return {Tech~SourceObject}\n *        src Object with known type\n */\nfunction fixSource(src) {\n  if (!src.type) {\n    const mimetype = getMimetype(src.src);\n    if (mimetype) {\n      src.type = mimetype;\n    }\n  }\n  return src;\n}\n\nvar icons = \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\">\\n  <defs>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-play\\\">\\n      <path d=\\\"M16 10v28l22-14z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-pause\\\">\\n      <path d=\\\"M12 38h8V10h-8v28zm16-28v28h8V10h-8z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-audio\\\">\\n      <path d=\\\"M24 2C14.06 2 6 10.06 6 20v14c0 3.31 2.69 6 6 6h6V24h-8v-4c0-7.73 6.27-14 14-14s14 6.27 14 14v4h-8v16h6c3.31 0 6-2.69 6-6V20c0-9.94-8.06-18-18-18z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-captions\\\">\\n      <path d=\\\"M38 8H10c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM22 22h-3v-1h-4v6h4v-1h3v2a2 2 0 0 1-2 2h-6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2zm14 0h-3v-1h-4v6h4v-1h3v2a2 2 0 0 1-2 2h-6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-subtitles\\\">\\n      <path d=\\\"M40 8H8c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM8 24h8v4H8v-4zm20 12H8v-4h20v4zm12 0h-8v-4h8v4zm0-8H20v-4h20v4z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-fullscreen-enter\\\">\\n      <path d=\\\"M14 28h-4v10h10v-4h-6v-6zm-4-8h4v-6h6v-4H10v10zm24 14h-6v4h10V28h-4v6zm-6-24v4h6v6h4V10H28z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-fullscreen-exit\\\">\\n      <path d=\\\"M10 32h6v6h4V28H10v4zm6-16h-6v4h10V10h-4v6zm12 22h4v-6h6v-4H28v10zm4-22v-6h-4v10h10v-4h-6z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-play-circle\\\">\\n      <path d=\\\"M20 33l12-9-12-9v18zm4-29C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-volume-mute\\\">\\n      <path d=\\\"M33 24c0-3.53-2.04-6.58-5-8.05v4.42l4.91 4.91c.06-.42.09-.85.09-1.28zm5 0c0 1.88-.41 3.65-1.08 5.28l3.03 3.03C41.25 29.82 42 27 42 24c0-8.56-5.99-15.72-14-17.54v4.13c5.78 1.72 10 7.07 10 13.41zM8.55 6L6 8.55 15.45 18H6v12h8l10 10V26.55l8.51 8.51c-1.34 1.03-2.85 1.86-4.51 2.36v4.13a17.94 17.94 0 0 0 7.37-3.62L39.45 42 42 39.45l-18-18L8.55 6zM24 8l-4.18 4.18L24 16.36V8z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-volume-low\\\">\\n      <path d=\\\"M14 18v12h8l10 10V8L22 18h-8z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-volume-medium\\\">\\n      <path d=\\\"M37 24c0-3.53-2.04-6.58-5-8.05v16.11c2.96-1.48 5-4.53 5-8.06zm-27-6v12h8l10 10V8L18 18h-8z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-volume-high\\\">\\n      <path d=\\\"M6 18v12h8l10 10V8L14 18H6zm27 6c0-3.53-2.04-6.58-5-8.05v16.11c2.96-1.48 5-4.53 5-8.06zM28 6.46v4.13c5.78 1.72 10 7.07 10 13.41s-4.22 11.69-10 13.41v4.13c8.01-1.82 14-8.97 14-17.54S36.01 8.28 28 6.46z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-spinner\\\">\\n      <path d=\\\"M18.8 21l9.53-16.51C26.94 4.18 25.49 4 24 4c-4.8 0-9.19 1.69-12.64 4.51l7.33 12.69.11-.2zm24.28-3c-1.84-5.85-6.3-10.52-11.99-12.68L23.77 18h19.31zm.52 2H28.62l.58 1 9.53 16.5C41.99 33.94 44 29.21 44 24c0-1.37-.14-2.71-.4-4zm-26.53 4l-7.8-13.5C6.01 14.06 4 18.79 4 24c0 1.37.14 2.71.4 4h14.98l-2.31-4zM4.92 30c1.84 5.85 6.3 10.52 11.99 12.68L24.23 30H4.92zm22.54 0l-7.8 13.51c1.4.31 2.85.49 4.34.49 4.8 0 9.19-1.69 12.64-4.51L29.31 26.8 27.46 30z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 24 24\\\" id=\\\"vjs-icon-hd\\\">\\n      <path d=\\\"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-8 12H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm2-6h4c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1h-4V9zm1.5 4.5h2v-3h-2v3z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-chapters\\\">\\n      <path d=\\\"M6 26h4v-4H6v4zm0 8h4v-4H6v4zm0-16h4v-4H6v4zm8 8h28v-4H14v4zm0 8h28v-4H14v4zm0-20v4h28v-4H14z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 40 40\\\" id=\\\"vjs-icon-downloading\\\">\\n      <path d=\\\"M18.208 36.875q-3.208-.292-5.979-1.729-2.771-1.438-4.812-3.729-2.042-2.292-3.188-5.229-1.146-2.938-1.146-6.23 0-6.583 4.334-11.416 4.333-4.834 10.833-5.5v3.166q-5.167.75-8.583 4.646Q6.25 14.75 6.25 19.958q0 5.209 3.396 9.104 3.396 3.896 8.562 4.646zM20 28.417L11.542 20l2.083-2.083 4.917 4.916v-11.25h2.916v11.25l4.875-4.916L28.417 20zm1.792 8.458v-3.167q1.833-.25 3.541-.958 1.709-.708 3.167-1.875l2.333 2.292q-1.958 1.583-4.25 2.541-2.291.959-4.791 1.167zm6.791-27.792q-1.541-1.125-3.25-1.854-1.708-.729-3.541-1.021V3.042q2.5.25 4.77 1.208 2.271.958 4.271 2.5zm4.584 21.584l-2.25-2.25q1.166-1.5 1.854-3.209.687-1.708.937-3.541h3.209q-.292 2.5-1.229 4.791-.938 2.292-2.521 4.209zm.541-12.417q-.291-1.833-.958-3.562-.667-1.73-1.833-3.188l2.375-2.208q1.541 1.916 2.458 4.208.917 2.292 1.167 4.75z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-file-download\\\">\\n      <path d=\\\"M10.8 40.55q-1.35 0-2.375-1T7.4 37.15v-7.7h3.4v7.7h26.35v-7.7h3.4v7.7q0 1.4-1 2.4t-2.4 1zM24 32.1L13.9 22.05l2.45-2.45 5.95 5.95V7.15h3.4v18.4l5.95-5.95 2.45 2.45z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-file-download-done\\\">\\n      <path d=\\\"M9.8 40.5v-3.45h28.4v3.45zm9.2-9.05L7.4 19.85l2.45-2.35L19 26.65l19.2-19.2 2.4 2.4z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-file-download-off\\\">\\n      <path d=\\\"M4.9 4.75L43.25 43.1 41 45.3l-4.75-4.75q-.05.05-.075.025-.025-.025-.075-.025H10.8q-1.35 0-2.375-1T7.4 37.15v-7.7h3.4v7.7h22.05l-7-7-1.85 1.8L13.9 21.9l1.85-1.85L2.7 7zm26.75 14.7l2.45 2.45-3.75 3.8-2.45-2.5zM25.7 7.15V21.1l-3.4-3.45V7.15z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-share\\\">\\n      <path d=\\\"M36 32.17c-1.52 0-2.89.59-3.93 1.54L17.82 25.4c.11-.45.18-.92.18-1.4s-.07-.95-.18-1.4l14.1-8.23c1.07 1 2.5 1.62 4.08 1.62 3.31 0 6-2.69 6-6s-2.69-6-6-6-6 2.69-6 6c0 .48.07.95.18 1.4l-14.1 8.23c-1.07-1-2.5-1.62-4.08-1.62-3.31 0-6 2.69-6 6s2.69 6 6 6c1.58 0 3.01-.62 4.08-1.62l14.25 8.31c-.1.42-.16.86-.16 1.31A5.83 5.83 0 1 0 36 32.17z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-cog\\\">\\n      <path d=\\\"M38.86 25.95c.08-.64.14-1.29.14-1.95s-.06-1.31-.14-1.95l4.23-3.31c.38-.3.49-.84.24-1.28l-4-6.93c-.25-.43-.77-.61-1.22-.43l-4.98 2.01c-1.03-.79-2.16-1.46-3.38-1.97L29 4.84c-.09-.47-.5-.84-1-.84h-8c-.5 0-.91.37-.99.84l-.75 5.3a14.8 14.8 0 0 0-3.38 1.97L9.9 10.1a1 1 0 0 0-1.22.43l-4 6.93c-.25.43-.14.97.24 1.28l4.22 3.31C9.06 22.69 9 23.34 9 24s.06 1.31.14 1.95l-4.22 3.31c-.38.3-.49.84-.24 1.28l4 6.93c.25.43.77.61 1.22.43l4.98-2.01c1.03.79 2.16 1.46 3.38 1.97l.75 5.3c.08.47.49.84.99.84h8c.5 0 .91-.37.99-.84l.75-5.3a14.8 14.8 0 0 0 3.38-1.97l4.98 2.01a1 1 0 0 0 1.22-.43l4-6.93c.25-.43.14-.97-.24-1.28l-4.22-3.31zM24 31c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-square\\\">\\n      <path d=\\\"M36 8H12c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h24c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zm0 28H12V12h24v24z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-circle\\\">\\n      <circle cx=\\\"24\\\" cy=\\\"24\\\" r=\\\"20\\\"></circle>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-circle-outline\\\">\\n      <path d=\\\"M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-circle-inner-circle\\\">\\n      <path d=\\\"M24 4C12.97 4 4 12.97 4 24s8.97 20 20 20 20-8.97 20-20S35.03 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16zm6-16c0 3.31-2.69 6-6 6s-6-2.69-6-6 2.69-6 6-6 6 2.69 6 6z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-cancel\\\">\\n      <path d=\\\"M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm10 27.17L31.17 34 24 26.83 16.83 34 14 31.17 21.17 24 14 16.83 16.83 14 24 21.17 31.17 14 34 16.83 26.83 24 34 31.17z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-replay\\\">\\n      <path d=\\\"M24 10V2L14 12l10 10v-8c6.63 0 12 5.37 12 12s-5.37 12-12 12-12-5.37-12-12H8c0 8.84 7.16 16 16 16s16-7.16 16-16-7.16-16-16-16z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-repeat\\\">\\n      <path d=\\\"M14 14h20v6l8-8-8-8v6H10v12h4v-8zm20 20H14v-6l-8 8 8 8v-6h24V26h-4v8z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 96 48 48\\\" id=\\\"vjs-icon-replay-5\\\">\\n      <path d=\\\"M17.689 98l-8.697 8.696 8.697 8.697 2.486-2.485-4.32-4.319h1.302c4.93 0 9.071 1.722 12.424 5.165 3.352 3.443 5.029 7.638 5.029 12.584h3.55c0-2.958-.553-5.73-1.658-8.313-1.104-2.583-2.622-4.841-4.555-6.774-1.932-1.932-4.19-3.45-6.773-4.555-2.584-1.104-5.355-1.657-8.313-1.657H15.5l4.615-4.615zm-8.08 21.659v13.861h11.357v5.008H9.609V143h12.7c.834 0 1.55-.298 2.146-.894.596-.597.895-1.31.895-2.145v-7.781c0-.835-.299-1.55-.895-2.147a2.929 2.929 0 0 0-2.147-.894h-8.227v-5.096H25.35v-4.384z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 96 48 48\\\" id=\\\"vjs-icon-replay-10\\\">\\n      <path d=\\\"M42.315 125.63c0-4.997-1.694-9.235-5.08-12.713-3.388-3.479-7.571-5.218-12.552-5.218h-1.315l4.363 4.363-2.51 2.51-8.787-8.786L25.221 97l2.45 2.45-4.662 4.663h1.375c2.988 0 5.788.557 8.397 1.673 2.61 1.116 4.892 2.65 6.844 4.602 1.953 1.953 3.487 4.234 4.602 6.844 1.116 2.61 1.674 5.41 1.674 8.398zM8.183 142v-19.657H3.176V117.8h9.643V142zm13.63 0c-1.156 0-2.127-.393-2.912-1.178-.778-.778-1.168-1.746-1.168-2.902v-16.04c0-1.156.393-2.127 1.178-2.912.779-.779 1.746-1.168 2.902-1.168h7.696c1.156 0 2.126.392 2.911 1.177.779.78 1.168 1.747 1.168 2.903v16.04c0 1.156-.392 2.127-1.177 2.912-.779.779-1.746 1.168-2.902 1.168zm.556-4.636h6.583v-15.02H22.37z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 96 48 48\\\" id=\\\"vjs-icon-replay-30\\\">\\n      <path d=\\\"M26.047 97l-8.733 8.732 8.733 8.733 2.496-2.494-4.336-4.338h1.307c4.95 0 9.108 1.73 12.474 5.187 3.367 3.458 5.051 7.668 5.051 12.635h3.565c0-2.97-.556-5.751-1.665-8.346-1.109-2.594-2.633-4.862-4.574-6.802-1.94-1.941-4.208-3.466-6.803-4.575-2.594-1.109-5.375-1.664-8.345-1.664H23.85l4.634-4.634zM2.555 117.531v4.688h10.297v5.25H5.873v4.687h6.979v5.156H2.555V142H13.36c1.061 0 1.95-.395 2.668-1.186.718-.79 1.076-1.772 1.076-2.94v-16.218c0-1.168-.358-2.149-1.076-2.94-.717-.79-1.607-1.185-2.668-1.185zm22.482.14c-1.149 0-2.11.39-2.885 1.165-.78.78-1.172 1.744-1.172 2.893v15.943c0 1.149.388 2.11 1.163 2.885.78.78 1.745 1.172 2.894 1.172h7.649c1.148 0 2.11-.388 2.884-1.163.78-.78 1.17-1.745 1.17-2.894v-15.943c0-1.15-.386-2.111-1.16-2.885-.78-.78-1.746-1.172-2.894-1.172zm.553 4.518h6.545v14.93H25.59z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 96 48 48\\\" id=\\\"vjs-icon-forward-5\\\">\\n      <path d=\\\"M29.508 97l-2.431 2.43 4.625 4.625h-1.364c-2.965 0-5.742.554-8.332 1.66-2.589 1.107-4.851 2.629-6.788 4.566-1.937 1.937-3.458 4.2-4.565 6.788-1.107 2.59-1.66 5.367-1.66 8.331h3.557c0-4.957 1.68-9.16 5.04-12.611 3.36-3.45 7.51-5.177 12.451-5.177h1.304l-4.326 4.33 2.49 2.49 8.715-8.716zm-9.783 21.61v13.89h11.382v5.018H19.725V142h12.727a2.93 2.93 0 0 0 2.15-.896 2.93 2.93 0 0 0 .896-2.15v-7.798c0-.837-.299-1.554-.896-2.152a2.93 2.93 0 0 0-2.15-.896h-8.245V123h11.29v-4.392z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 96 48 48\\\" id=\\\"vjs-icon-forward-10\\\">\\n      <path d=\\\"M23.119 97l-2.386 2.383 4.538 4.538h-1.339c-2.908 0-5.633.543-8.173 1.63-2.54 1.085-4.76 2.577-6.66 4.478-1.9 1.9-3.392 4.12-4.478 6.66-1.085 2.54-1.629 5.264-1.629 8.172h3.49c0-4.863 1.648-8.986 4.944-12.372 3.297-3.385 7.368-5.078 12.216-5.078h1.279l-4.245 4.247 2.443 2.442 8.55-8.55zm-9.52 21.45v4.42h4.871V142h4.513v-23.55zm18.136 0c-1.125 0-2.066.377-2.824 1.135-.764.764-1.148 1.709-1.148 2.834v15.612c0 1.124.38 2.066 1.139 2.824.764.764 1.708 1.145 2.833 1.145h7.489c1.125 0 2.066-.378 2.824-1.136.764-.764 1.145-1.709 1.145-2.833v-15.612c0-1.125-.378-2.067-1.136-2.825-.764-.764-1.708-1.145-2.833-1.145zm.54 4.42h6.408v14.617h-6.407z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 96 48 48\\\" id=\\\"vjs-icon-forward-30\\\">\\n      <path d=\\\"M25.549 97l-2.437 2.434 4.634 4.635H26.38c-2.97 0-5.753.555-8.347 1.664-2.594 1.109-4.861 2.633-6.802 4.574-1.94 1.94-3.465 4.207-4.574 6.802-1.109 2.594-1.664 5.377-1.664 8.347h3.565c0-4.967 1.683-9.178 5.05-12.636 3.366-3.458 7.525-5.187 12.475-5.187h1.307l-4.335 4.338 2.495 2.494 8.732-8.732zm-11.553 20.53v4.689h10.297v5.249h-6.978v4.688h6.978v5.156H13.996V142h10.808c1.06 0 1.948-.395 2.666-1.186.718-.79 1.077-1.771 1.077-2.94v-16.217c0-1.169-.36-2.15-1.077-2.94-.718-.79-1.605-1.186-2.666-1.186zm21.174.168c-1.149 0-2.11.389-2.884 1.163-.78.78-1.172 1.745-1.172 2.894v15.942c0 1.15.388 2.11 1.162 2.885.78.78 1.745 1.17 2.894 1.17h7.649c1.149 0 2.11-.386 2.885-1.16.78-.78 1.17-1.746 1.17-2.895v-15.942c0-1.15-.387-2.11-1.161-2.885-.78-.78-1.745-1.172-2.894-1.172zm.552 4.516h6.542v14.931h-6.542z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 512 512\\\" id=\\\"vjs-icon-audio-description\\\">\\n      <g fill-rule=\\\"evenodd\\\"><path d=\\\"M227.29 381.351V162.993c50.38-1.017 89.108-3.028 117.631 17.126 27.374 19.342 48.734 56.965 44.89 105.325-4.067 51.155-41.335 94.139-89.776 98.475-24.085 2.155-71.972 0-71.972 0s-.84-1.352-.773-2.568m48.755-54.804c31.43 1.26 53.208-16.633 56.495-45.386 4.403-38.51-21.188-63.552-58.041-60.796v103.612c-.036 1.466.575 2.22 1.546 2.57\\\"></path><path d=\\\"M383.78 381.328c13.336 3.71 17.387-11.06 23.215-21.408 12.722-22.571 22.294-51.594 22.445-84.774.221-47.594-18.343-82.517-35.6-106.182h-8.51c-.587 3.874 2.226 7.315 3.865 10.276 13.166 23.762 25.367 56.553 25.54 94.194.2 43.176-14.162 79.278-30.955 107.894\\\"></path><path d=\\\"M425.154 381.328c13.336 3.71 17.384-11.061 23.215-21.408 12.721-22.571 22.291-51.594 22.445-84.774.221-47.594-18.343-82.517-35.6-106.182h-8.511c-.586 3.874 2.226 7.315 3.866 10.276 13.166 23.762 25.367 56.553 25.54 94.194.2 43.176-14.162 79.278-30.955 107.894\\\"></path><path d=\\\"M466.26 381.328c13.337 3.71 17.385-11.061 23.216-21.408 12.722-22.571 22.292-51.594 22.445-84.774.221-47.594-18.343-82.517-35.6-106.182h-8.51c-.587 3.874 2.225 7.315 3.865 10.276 13.166 23.762 25.367 56.553 25.54 94.194.2 43.176-14.162 79.278-30.955 107.894M4.477 383.005H72.58l18.573-28.484 64.169-.135s.065 19.413.065 28.62h48.756V160.307h-58.816c-5.653 9.537-140.85 222.697-140.85 222.697zm152.667-145.282v71.158l-40.453-.27 40.453-70.888z\\\"></path></g>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-next-item\\\">\\n      <path d=\\\"M12 36l17-12-17-12v24zm20-24v24h4V12h-4z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-previous-item\\\">\\n      <path d=\\\"M12 12h4v24h-4zm7 12l17 12V12z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-shuffle\\\">\\n      <path d=\\\"M21.17 18.34L10.83 8 8 10.83l10.34 10.34 2.83-2.83zM29 8l4.09 4.09L8 37.17 10.83 40l25.09-25.09L40 19V8H29zm.66 18.83l-2.83 2.83 6.26 6.26L29 40h11V29l-4.09 4.09-6.25-6.26z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-cast\\\">\\n      <path d=\\\"M42 6H6c-2.21 0-4 1.79-4 4v6h4v-6h36v28H28v4h14c2.21 0 4-1.79 4-4V10c0-2.21-1.79-4-4-4zM2 36v6h6c0-3.31-2.69-6-6-6zm0-8v4c5.52 0 10 4.48 10 10h4c0-7.73-6.27-14-14-14zm0-8v4c9.94 0 18 8.06 18 18h4c0-12.15-9.85-22-22-22z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 48 48\\\" id=\\\"vjs-icon-picture-in-picture-enter\\\">\\n      <path d=\\\"M38 22H22v11.99h16V22zm8 16V9.96C46 7.76 44.2 6 42 6H6C3.8 6 2 7.76 2 9.96V38c0 2.2 1.8 4 4 4h36c2.2 0 4-1.8 4-4zm-4 .04H6V9.94h36v28.1z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 22 18\\\" id=\\\"vjs-icon-picture-in-picture-exit\\\">\\n      <path d=\\\"M18 4H4v10h14V4zm4 12V1.98C22 .88 21.1 0 20 0H2C.9 0 0 .88 0 1.98V16c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2zm-2 .02H2V1.97h18v14.05z\\\"></path>\\n      <path fill=\\\"none\\\" d=\\\"M-1-3h24v24H-1z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 1792 1792\\\" id=\\\"vjs-icon-facebook\\\">\\n      <path d=\\\"M1343 12v264h-157q-86 0-116 36t-30 108v189h293l-39 296h-254v759H734V905H479V609h255V391q0-186 104-288.5T1115 0q147 0 228 12z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 1792 1792\\\" id=\\\"vjs-icon-linkedin\\\">\\n      <path d=\\\"M477 625v991H147V625h330zm21-306q1 73-50.5 122T312 490h-2q-82 0-132-49t-50-122q0-74 51.5-122.5T314 148t133 48.5T498 319zm1166 729v568h-329v-530q0-105-40.5-164.5T1168 862q-63 0-105.5 34.5T999 982q-11 30-11 81v553H659q2-399 2-647t-1-296l-1-48h329v144h-2q20-32 41-56t56.5-52 87-43.5T1285 602q171 0 275 113.5t104 332.5z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 1200 1227\\\" id=\\\"vjs-icon-twitter\\\">\\n      <path d=\\\"M714.163 519.284L1160.89 0H1055.03L667.137 450.887L357.328 0H0L468.492 681.821L0 1226.37H105.866L515.491 750.218L842.672 1226.37H1200L714.137 519.284H714.163ZM569.165 687.828L521.697 619.934L144.011 79.6944H306.615L611.412 515.685L658.88 583.579L1055.08 1150.3H892.476L569.165 687.854V687.828Z\\\"/>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 1792 1792\\\" id=\\\"vjs-icon-tumblr\\\">\\n      <path d=\\\"M1328 1329l80 237q-23 35-111 66t-177 32q-104 2-190.5-26T787 1564t-95-106-55.5-120-16.5-118V676H452V461q72-26 129-69.5t91-90 58-102 34-99T779 12q1-5 4.5-8.5T791 0h244v424h333v252h-334v518q0 30 6.5 56t22.5 52.5 49.5 41.5 81.5 14q78-2 134-29z\\\"></path>\\n    </symbol>\\n    <symbol viewBox=\\\"0 0 1792 1792\\\" id=\\\"vjs-icon-pinterest\\\">\\n      <path d=\\\"M1664 896q0 209-103 385.5T1281.5 1561 896 1664q-111 0-218-32 59-93 78-164 9-34 54-211 20 39 73 67.5t114 28.5q121 0 216-68.5t147-188.5 52-270q0-114-59.5-214T1180 449t-255-63q-105 0-196 29t-154.5 77-109 110.5-67 129.5T377 866q0 104 40 183t117 111q30 12 38-20 2-7 8-31t8-30q6-23-11-43-51-61-51-151 0-151 104.5-259.5T904 517q151 0 235.5 82t84.5 213q0 170-68.5 289T980 1220q-61 0-98-43.5T859 1072q8-35 26.5-93.5t30-103T927 800q0-50-27-83t-77-33q-62 0-105 57t-43 142q0 73 25 122l-99 418q-17 70-13 177-206-91-333-281T128 896q0-209 103-385.5T510.5 231 896 128t385.5 103T1561 510.5 1664 896z\\\"></path>\\n    </symbol>\\n  </defs>\\n</svg>\";\n\n// /**\n\n// Determine the keycode for the 'back' key based on the platform\nconst backKeyCode = IS_TIZEN ? 10009 : IS_WEBOS ? 461 : 8;\nconst SpatialNavKeyCodes = {\n  codes: {\n    play: 415,\n    pause: 19,\n    ff: 417,\n    rw: 412,\n    back: backKeyCode\n  },\n  names: {\n    415: 'play',\n    19: 'pause',\n    417: 'ff',\n    412: 'rw',\n    [backKeyCode]: 'back'\n  },\n  isEventKey(event, keyName) {\n    keyName = keyName.toLowerCase();\n    if (this.names[event.keyCode] && this.names[event.keyCode] === keyName) {\n      return true;\n    }\n    return false;\n  },\n  getEventName(event) {\n    if (this.names[event.keyCode]) {\n      return this.names[event.keyCode];\n    } else if (this.codes[event.code]) {\n      const code = this.codes[event.code];\n      return this.names[code];\n    }\n    return null;\n  }\n};\n\n/**\n * @file spatial-navigation.js\n */\n\n/** @import Component from './component' */\n/** @import Player from './player' */\n\n// The number of seconds the `step*` functions move the timeline.\nconst STEP_SECONDS = 5;\n\n/**\n * Spatial Navigation in Video.js enhances user experience and accessibility on smartTV devices,\n * enabling seamless navigation through interactive elements within the player using remote control arrow keys.\n * This functionality allows users to effortlessly navigate through focusable components.\n *\n * @extends EventTarget\n */\nclass SpatialNavigation extends EventTarget$2 {\n  /**\n   * Constructs a SpatialNavigation instance with initial settings.\n   * Sets up the player instance, and prepares the spatial navigation system.\n   *\n   * @class\n   * @param {Player} player - The Video.js player instance to which the spatial navigation is attached.\n   */\n  constructor(player) {\n    super();\n    this.player_ = player;\n    this.focusableComponents = [];\n    this.isListening_ = false;\n    this.isPaused_ = false;\n    this.onKeyDown_ = this.onKeyDown_.bind(this);\n    this.lastFocusedComponent_ = null;\n  }\n\n  /**\n   * Starts the spatial navigation by adding a keydown event listener to the video container.\n   * This method ensures that the event listener is added only once.\n   */\n  start() {\n    // If the listener is already active, exit early.\n    if (this.isListening_) {\n      return;\n    }\n\n    // Add the event listener since the listener is not yet active.\n    this.player_.on('keydown', this.onKeyDown_);\n    this.player_.on('modalKeydown', this.onKeyDown_);\n    // Listen for source change events\n    this.player_.on('loadedmetadata', () => {\n      this.focus(this.updateFocusableComponents()[0]);\n    });\n    this.player_.on('modalclose', () => {\n      this.refocusComponent();\n    });\n    this.player_.on('focusin', this.handlePlayerFocus_.bind(this));\n    this.player_.on('focusout', this.handlePlayerBlur_.bind(this));\n    this.isListening_ = true;\n    if (this.player_.errorDisplay) {\n      this.player_.errorDisplay.on('aftermodalfill', () => {\n        this.updateFocusableComponents();\n        if (this.focusableComponents.length) {\n          // The modal has focusable components:\n\n          if (this.focusableComponents.length > 1) {\n            // The modal has close button + some additional buttons.\n            // Focusing first additional button:\n\n            this.focusableComponents[1].focus();\n          } else {\n            // The modal has only close button,\n            // Focusing it:\n\n            this.focusableComponents[0].focus();\n          }\n        }\n      });\n    }\n  }\n\n  /**\n   * Stops the spatial navigation by removing the keydown event listener from the video container.\n   * Also sets the `isListening_` flag to false.\n   */\n  stop() {\n    this.player_.off('keydown', this.onKeyDown_);\n    this.isListening_ = false;\n  }\n\n  /**\n   * Responds to keydown events for spatial navigation and media control.\n   *\n   * Determines if spatial navigation or media control is active and handles key inputs accordingly.\n   *\n   * @param {KeyboardEvent} event - The keydown event to be handled.\n   */\n  onKeyDown_(event) {\n    // Determine if the event is a custom modalKeydown event\n    const actualEvent = event.originalEvent ? event.originalEvent : event;\n    if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(actualEvent.key)) {\n      // Handle directional navigation\n      if (this.isPaused_) {\n        return;\n      }\n      actualEvent.preventDefault();\n\n      // \"ArrowLeft\" => \"left\" etc\n      const direction = actualEvent.key.substring(5).toLowerCase();\n      this.move(direction);\n    } else if (SpatialNavKeyCodes.isEventKey(actualEvent, 'play') || SpatialNavKeyCodes.isEventKey(actualEvent, 'pause') || SpatialNavKeyCodes.isEventKey(actualEvent, 'ff') || SpatialNavKeyCodes.isEventKey(actualEvent, 'rw')) {\n      // Handle media actions\n      actualEvent.preventDefault();\n      const action = SpatialNavKeyCodes.getEventName(actualEvent);\n      this.performMediaAction_(action);\n    } else if (SpatialNavKeyCodes.isEventKey(actualEvent, 'Back') && event.target && typeof event.target.closeable === 'function' && event.target.closeable()) {\n      actualEvent.preventDefault();\n      event.target.close();\n    }\n  }\n\n  /**\n   * Performs media control actions based on the given key input.\n   *\n   * Controls the playback and seeking functionalities of the media player.\n   *\n   * @param {string} key - The key representing the media action to be performed.\n   *   Accepted keys: 'play', 'pause', 'ff' (fast-forward), 'rw' (rewind).\n   */\n  performMediaAction_(key) {\n    if (this.player_) {\n      switch (key) {\n        case 'play':\n          if (this.player_.paused()) {\n            this.player_.play();\n          }\n          break;\n        case 'pause':\n          if (!this.player_.paused()) {\n            this.player_.pause();\n          }\n          break;\n        case 'ff':\n          this.userSeek_(this.player_.currentTime() + STEP_SECONDS);\n          break;\n        case 'rw':\n          this.userSeek_(this.player_.currentTime() - STEP_SECONDS);\n          break;\n      }\n    }\n  }\n\n  /**\n   * Prevent liveThreshold from causing seeks to seem like they\n   * are not happening from a user perspective.\n   *\n   * @param {number} ct\n   *        current time to seek to\n   */\n  userSeek_(ct) {\n    if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {\n      this.player_.liveTracker.nextSeekedFromUser();\n    }\n    this.player_.currentTime(ct);\n  }\n\n  /**\n   * Pauses the spatial navigation functionality.\n   * This method sets a flag that can be used to temporarily disable the navigation logic.\n   */\n  pause() {\n    this.isPaused_ = true;\n  }\n\n  /**\n   * Resumes the spatial navigation functionality if it has been paused.\n   * This method resets the pause flag, re-enabling the navigation logic.\n   */\n  resume() {\n    this.isPaused_ = false;\n  }\n\n  /**\n   * Handles Player Blur.\n   *\n   * @param {string|Event|Object} event\n   *        The name of the event, an `Event`, or an object with a key of type set to\n   *        an event name.\n   *\n   * Calls for handling of the Player Blur if:\n   * *The next focused element is not a child of current focused element &\n   * The next focused element is not a child of the Player.\n   * *There is no next focused element\n   */\n  handlePlayerBlur_(event) {\n    const nextFocusedElement = event.relatedTarget;\n    let isChildrenOfPlayer = null;\n    const currentComponent = this.getCurrentComponent(event.target);\n    if (nextFocusedElement) {\n      isChildrenOfPlayer = Boolean(nextFocusedElement.closest('.video-js'));\n\n      // If nextFocusedElement is the 'TextTrackSettings' component\n      if (nextFocusedElement.classList.contains('vjs-text-track-settings') && !this.isPaused_) {\n        this.searchForTrackSelect_();\n      }\n    }\n    if (!event.currentTarget.contains(event.relatedTarget) && !isChildrenOfPlayer || !nextFocusedElement) {\n      if (currentComponent && currentComponent.name() === 'CloseButton') {\n        this.refocusComponent();\n      } else {\n        this.pause();\n        if (currentComponent && currentComponent.el()) {\n          // Store last focused component\n          this.lastFocusedComponent_ = currentComponent;\n        }\n      }\n    }\n  }\n\n  /**\n   * Handles the Player focus event.\n   *\n   * Calls for handling of the Player Focus if current element is focusable.\n   */\n  handlePlayerFocus_() {\n    if (this.getCurrentComponent() && this.getCurrentComponent().getIsFocusable()) {\n      this.resume();\n    }\n  }\n\n  /**\n   * Gets a set of focusable components.\n   *\n   * @return {Array}\n   *         Returns an array of focusable components.\n   */\n  updateFocusableComponents() {\n    const player = this.player_;\n    const focusableComponents = [];\n\n    /**\n     * Searches for children candidates.\n     *\n     * Pushes Components to array of 'focusableComponents'.\n     * Calls itself if there is children elements inside iterated component.\n     *\n     * @param {Array} componentsArray - The array of components to search for focusable children.\n     */\n    function searchForChildrenCandidates(componentsArray) {\n      for (const i of componentsArray) {\n        if (i.hasOwnProperty('el_') && i.getIsFocusable() && i.getIsAvailableToBeFocused(i.el())) {\n          focusableComponents.push(i);\n        }\n        if (i.hasOwnProperty('children_') && i.children_.length > 0) {\n          searchForChildrenCandidates(i.children_);\n        }\n      }\n    }\n\n    // Iterate inside all children components of the player.\n    player.children_.forEach(value => {\n      if (value.hasOwnProperty('el_')) {\n        // If component has required functions 'getIsFocusable' & 'getIsAvailableToBeFocused', is focusable & available to be focused.\n        if (value.getIsFocusable && value.getIsAvailableToBeFocused && value.getIsFocusable() && value.getIsAvailableToBeFocused(value.el())) {\n          focusableComponents.push(value);\n          return;\n          // If component has posible children components as candidates.\n        } else if (value.hasOwnProperty('children_') && value.children_.length > 0) {\n          searchForChildrenCandidates(value.children_);\n          // If component has posible item components as candidates.\n        } else if (value.hasOwnProperty('items') && value.items.length > 0) {\n          searchForChildrenCandidates(value.items);\n          // If there is a suitable child element within the component's DOM element.\n        } else if (this.findSuitableDOMChild(value)) {\n          focusableComponents.push(value);\n        }\n      }\n\n      // TODO - Refactor the following logic after refactor of videojs-errors elements to be components is done.\n      if (value.name_ === 'ErrorDisplay' && value.opened_) {\n        const buttonContainer = value.el_.querySelector('.vjs-errors-ok-button-container');\n        if (buttonContainer) {\n          const modalButtons = buttonContainer.querySelectorAll('button');\n          modalButtons.forEach((element, index) => {\n            // Add elements as objects to be handled by the spatial navigation\n            focusableComponents.push({\n              name: () => {\n                return 'ModalButton' + (index + 1);\n              },\n              el: () => element,\n              getPositions: () => {\n                const rect = element.getBoundingClientRect();\n\n                // Creating objects that mirror DOMRectReadOnly for boundingClientRect and center\n                const boundingClientRect = {\n                  x: rect.x,\n                  y: rect.y,\n                  width: rect.width,\n                  height: rect.height,\n                  top: rect.top,\n                  right: rect.right,\n                  bottom: rect.bottom,\n                  left: rect.left\n                };\n\n                // Calculating the center position\n                const center = {\n                  x: rect.left + rect.width / 2,\n                  y: rect.top + rect.height / 2,\n                  width: 0,\n                  height: 0,\n                  top: rect.top + rect.height / 2,\n                  right: rect.left + rect.width / 2,\n                  bottom: rect.top + rect.height / 2,\n                  left: rect.left + rect.width / 2\n                };\n                return {\n                  boundingClientRect,\n                  center\n                };\n              },\n              // Asume that the following are always focusable\n              getIsAvailableToBeFocused: () => true,\n              getIsFocusable: el => true,\n              focus: () => element.focus()\n            });\n          });\n        }\n      }\n    });\n    this.focusableComponents = focusableComponents;\n    return this.focusableComponents;\n  }\n\n  /**\n   * Finds a suitable child element within the provided component's DOM element.\n   *\n   * @param {Object} component - The component containing the DOM element to search within.\n   * @return {HTMLElement|null} Returns the suitable child element if found, or null if not found.\n   */\n  findSuitableDOMChild(component) {\n    /**\n     * Recursively searches for a suitable child node that can be focused within a given component.\n     * It first checks if the provided node itself can be focused according to the component's\n     * `getIsFocusable` and `getIsAvailableToBeFocused` methods. If not, it recursively searches\n     * through the node's children to find a suitable child node that meets the focusability criteria.\n     *\n     * @param {HTMLElement} node - The DOM node to start the search from.\n     * @return {HTMLElement|null} The first child node that is focusable and available to be focused,\n     * or `null` if no suitable child is found.\n     */\n    function searchForSuitableChild(node) {\n      if (component.getIsFocusable(node) && component.getIsAvailableToBeFocused(node)) {\n        return node;\n      }\n      for (let i = 0; i < node.children.length; i++) {\n        const child = node.children[i];\n        const suitableChild = searchForSuitableChild(child);\n        if (suitableChild) {\n          return suitableChild;\n        }\n      }\n      return null;\n    }\n    if (component.el()) {\n      return searchForSuitableChild(component.el());\n    }\n    return null;\n  }\n\n  /**\n   * Gets the currently focused component from the list of focusable components.\n   * If a target element is provided, it uses that element to find the corresponding\n   * component. If no target is provided, it defaults to using the document's currently\n   * active element.\n   *\n   * @param {HTMLElement} [target] - The DOM element to check against the focusable components.\n   *                                 If not provided, `document.activeElement` is used.\n   * @return {Component|null} - Returns the focused component if found among the focusable components,\n   *                            otherwise returns null if no matching component is found.\n   */\n  getCurrentComponent(target) {\n    this.updateFocusableComponents();\n    // eslint-disable-next-line\n    const curComp = target || document.activeElement;\n    if (this.focusableComponents.length) {\n      for (const i of this.focusableComponents) {\n        // If component Node is equal to the current active element.\n        if (i.el() === curComp) {\n          return i;\n        }\n      }\n    }\n  }\n\n  /**\n   * Adds a component to the array of focusable components.\n   *\n   * @param {Component} component\n   *        The `Component` to be added.\n   */\n  add(component) {\n    const focusableComponents = [...this.focusableComponents];\n    if (component.hasOwnProperty('el_') && component.getIsFocusable() && component.getIsAvailableToBeFocused(component.el())) {\n      focusableComponents.push(component);\n    }\n    this.focusableComponents = focusableComponents;\n    // Trigger the notification manually\n    this.trigger({\n      type: 'focusableComponentsChanged',\n      focusableComponents: this.focusableComponents\n    });\n  }\n\n  /**\n   * Removes component from the array of focusable components.\n   *\n   * @param {Component} component - The component to be removed from the focusable components array.\n   */\n  remove(component) {\n    for (let i = 0; i < this.focusableComponents.length; i++) {\n      if (this.focusableComponents[i].name() === component.name()) {\n        this.focusableComponents.splice(i, 1);\n        // Trigger the notification manually\n        this.trigger({\n          type: 'focusableComponentsChanged',\n          focusableComponents: this.focusableComponents\n        });\n        return;\n      }\n    }\n  }\n\n  /**\n   * Clears array of focusable components.\n   */\n  clear() {\n    // Check if the array is already empty to avoid unnecessary event triggering\n    if (this.focusableComponents.length > 0) {\n      // Clear the array\n      this.focusableComponents = [];\n\n      // Trigger the notification manually\n      this.trigger({\n        type: 'focusableComponentsChanged',\n        focusableComponents: this.focusableComponents\n      });\n    }\n  }\n\n  /**\n   * Navigates to the next focusable component based on the specified direction.\n   *\n   * @param {string} direction 'up', 'down', 'left', 'right'\n   */\n  move(direction) {\n    const currentFocusedComponent = this.getCurrentComponent();\n    if (!currentFocusedComponent) {\n      return;\n    }\n    const currentPositions = currentFocusedComponent.getPositions();\n    const candidates = this.focusableComponents.filter(component => component !== currentFocusedComponent && this.isInDirection_(currentPositions.boundingClientRect, component.getPositions().boundingClientRect, direction));\n    const bestCandidate = this.findBestCandidate_(currentPositions.center, candidates, direction);\n    if (bestCandidate) {\n      this.focus(bestCandidate);\n    } else {\n      this.trigger({\n        type: 'endOfFocusableComponents',\n        direction,\n        focusedComponent: currentFocusedComponent\n      });\n    }\n  }\n\n  /**\n   * Finds the best candidate on the current center position,\n   * the list of candidates, and the specified navigation direction.\n   *\n   * @param {Object} currentCenter The center position of the current focused component element.\n   * @param {Array} candidates An array of candidate components to receive focus.\n   * @param {string} direction The direction of navigation ('up', 'down', 'left', 'right').\n   * @return {Object|null} The component that is the best candidate for receiving focus.\n   */\n  findBestCandidate_(currentCenter, candidates, direction) {\n    let minDistance = Infinity;\n    let bestCandidate = null;\n    for (const candidate of candidates) {\n      const candidateCenter = candidate.getPositions().center;\n      const distance = this.calculateDistance_(currentCenter, candidateCenter, direction);\n      if (distance < minDistance) {\n        minDistance = distance;\n        bestCandidate = candidate;\n      }\n    }\n    return bestCandidate;\n  }\n\n  /**\n   * Determines if a target rectangle is in the specified navigation direction\n   * relative to a source rectangle.\n   *\n   * @param {Object} srcRect The bounding rectangle of the source element.\n   * @param {Object} targetRect The bounding rectangle of the target element.\n   * @param {string} direction The navigation direction ('up', 'down', 'left', 'right').\n   * @return {boolean} True if the target is in the specified direction relative to the source.\n   */\n  isInDirection_(srcRect, targetRect, direction) {\n    switch (direction) {\n      case 'right':\n        return targetRect.left >= srcRect.right;\n      case 'left':\n        return targetRect.right <= srcRect.left;\n      case 'down':\n        return targetRect.top >= srcRect.bottom;\n      case 'up':\n        return targetRect.bottom <= srcRect.top;\n      default:\n        return false;\n    }\n  }\n\n  /**\n   * Focus the last focused component saved before blur on player.\n   */\n  refocusComponent() {\n    if (this.lastFocusedComponent_) {\n      // If user is not active, set it to active.\n      if (!this.player_.userActive()) {\n        this.player_.userActive(true);\n      }\n      this.updateFocusableComponents();\n\n      // Search inside array of 'focusableComponents' for a match of name of\n      // the last focused component.\n      for (let i = 0; i < this.focusableComponents.length; i++) {\n        if (this.focusableComponents[i].name() === this.lastFocusedComponent_.name()) {\n          this.focus(this.focusableComponents[i]);\n          return;\n        }\n      }\n    } else {\n      this.focus(this.updateFocusableComponents()[0]);\n    }\n  }\n\n  /**\n   * Focuses on a given component.\n   * If the component is available to be focused, it focuses on the component.\n   * If not, it attempts to find a suitable DOM child within the component and focuses on it.\n   *\n   * @param {Component} component - The component to be focused.\n   */\n  focus(component) {\n    if (typeof component !== 'object') {\n      return;\n    }\n    if (component.getIsAvailableToBeFocused(component.el())) {\n      component.focus();\n    } else if (this.findSuitableDOMChild(component)) {\n      this.findSuitableDOMChild(component).focus();\n    }\n  }\n\n  /**\n   * Calculates the distance between two points, adjusting the calculation based on\n   * the specified navigation direction.\n   *\n   * @param {Object} center1 The center point of the first element.\n   * @param {Object} center2 The center point of the second element.\n   * @param {string} direction The direction of navigation ('up', 'down', 'left', 'right').\n   * @return {number} The calculated distance between the two centers.\n   */\n  calculateDistance_(center1, center2, direction) {\n    const dx = Math.abs(center1.x - center2.x);\n    const dy = Math.abs(center1.y - center2.y);\n    let distance;\n    switch (direction) {\n      case 'right':\n      case 'left':\n        // Higher weight for vertical distance in horizontal navigation.\n        distance = dx + dy * 100;\n        break;\n      case 'up':\n        // Strongly prioritize vertical proximity for UP navigation.\n        // Adjust the weight to ensure that elements directly above are favored.\n        distance = dy * 2 + dx * 0.5;\n        break;\n      case 'down':\n        // More balanced weight for vertical and horizontal distances.\n        // Adjust the weights here to find the best balance.\n        distance = dy * 5 + dx;\n        break;\n      default:\n        distance = dx + dy;\n    }\n    return distance;\n  }\n\n  /**\n   * This gets called by 'handlePlayerBlur_' if 'spatialNavigation' is enabled.\n   * Searches for the first 'TextTrackSelect' inside of modal to focus.\n   *\n   * @private\n   */\n  searchForTrackSelect_() {\n    const spatialNavigation = this;\n    for (const component of spatialNavigation.updateFocusableComponents()) {\n      if (component.constructor.name === 'TextTrackSelect') {\n        spatialNavigation.focus(component);\n        break;\n      }\n    }\n  }\n}\n\n/**\n * @file loader.js\n */\n\n/** @import Player from '../player' */\n\n/**\n * The `MediaLoader` is the `Component` that decides which playback technology to load\n * when a player is initialized.\n *\n * @extends Component\n */\nclass MediaLoader extends Component$1 {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should attach to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {Function} [ready]\n   *        The function that is run when this component is ready.\n   */\n  constructor(player, options, ready) {\n    // MediaLoader has no element\n    const options_ = merge$1({\n      createEl: false\n    }, options);\n    super(player, options_, ready);\n\n    // If there are no sources when the player is initialized,\n    // load the first supported playback technology.\n\n    if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {\n      for (let i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {\n        const techName = toTitleCase$1(j[i]);\n        let tech = Tech.getTech(techName);\n\n        // Support old behavior of techs being registered as components.\n        // Remove once that deprecated behavior is removed.\n        if (!techName) {\n          tech = Component$1.getComponent(techName);\n        }\n\n        // Check if the browser supports this technology\n        if (tech && tech.isSupported()) {\n          player.loadTech_(techName);\n          break;\n        }\n      }\n    } else {\n      // Loop through playback technologies (e.g. HTML5) and check for support.\n      // Then load the best source.\n      // A few assumptions here:\n      //   All playback technologies respect preload false.\n      player.src(options.playerOptions.sources);\n    }\n  }\n}\nComponent$1.registerComponent('MediaLoader', MediaLoader);\n\n/**\n * @file clickable-component.js\n */\n\n/** @import Player from './player' */\n\n/**\n * Component which is clickable or keyboard actionable, but is not a\n * native HTML button.\n *\n * @extends Component\n */\nclass ClickableComponent extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param  {Player} player\n   *         The `Player` that this class should be attached to.\n   *\n   * @param  {Object} [options]\n   *         The key/value store of component options.\n   *\n   * @param  {function} [options.clickHandler]\n   *         The function to call when the button is clicked / activated\n   *\n   * @param  {string} [options.controlText]\n   *         The text to set on the button\n   *\n   * @param  {string} [options.className]\n   *         A class or space separated list of classes to add the component\n   *\n   */\n  constructor(player, options) {\n    super(player, options);\n    if (this.options_.controlText) {\n      this.controlText(this.options_.controlText);\n    }\n    this.handleMouseOver_ = e => this.handleMouseOver(e);\n    this.handleMouseOut_ = e => this.handleMouseOut(e);\n    this.handleClick_ = e => this.handleClick(e);\n    this.handleKeyDown_ = e => this.handleKeyDown(e);\n    this.emitTapEvents();\n    this.enable();\n  }\n\n  /**\n   * Create the `ClickableComponent`s DOM element.\n   *\n   * @param {string} [tag=div]\n   *        The element's node type.\n   *\n   * @param {Object} [props={}]\n   *        An object of properties that should be set on the element.\n   *\n   * @param {Object} [attributes={}]\n   *        An object of attributes that should be set on the element.\n   *\n   * @return {Element}\n   *         The element that gets created.\n   */\n  createEl(tag = 'div', props = {}, attributes = {}) {\n    props = Object.assign({\n      className: this.buildCSSClass(),\n      tabIndex: 0\n    }, props);\n    if (tag === 'button') {\n      log$1.error(`Creating a ClickableComponent with an HTML element of ${tag} is not supported; use a Button instead.`);\n    }\n\n    // Add ARIA attributes for clickable element which is not a native HTML button\n    attributes = Object.assign({\n      role: 'button'\n    }, attributes);\n    this.tabIndex_ = props.tabIndex;\n    const el = createEl(tag, props, attributes);\n    if (!this.player_.options_.experimentalSvgIcons) {\n      el.appendChild(createEl('span', {\n        className: 'vjs-icon-placeholder'\n      }, {\n        'aria-hidden': true\n      }));\n    }\n    this.createControlTextEl(el);\n    return el;\n  }\n  dispose() {\n    // remove controlTextEl_ on dispose\n    this.controlTextEl_ = null;\n    super.dispose();\n  }\n\n  /**\n   * Create a control text element on this `ClickableComponent`\n   *\n   * @param {Element} [el]\n   *        Parent element for the control text.\n   *\n   * @return {Element}\n   *         The control text element that gets created.\n   */\n  createControlTextEl(el) {\n    this.controlTextEl_ = createEl('span', {\n      className: 'vjs-control-text'\n    }, {\n      // let the screen reader user know that the text of the element may change\n      'aria-live': 'polite'\n    });\n    if (el) {\n      el.appendChild(this.controlTextEl_);\n    }\n    this.controlText(this.controlText_, el);\n    return this.controlTextEl_;\n  }\n\n  /**\n   * Get or set the localize text to use for the controls on the `ClickableComponent`.\n   *\n   * @param {string} [text]\n   *        Control text for element.\n   *\n   * @param {Element} [el=this.el()]\n   *        Element to set the title on.\n   *\n   * @return {string}\n   *         - The control text when getting\n   */\n  controlText(text, el = this.el()) {\n    if (text === undefined) {\n      return this.controlText_ || 'Need Text';\n    }\n    const localizedText = this.localize(text);\n\n    /** @protected */\n    this.controlText_ = text;\n    textContent(this.controlTextEl_, localizedText);\n    if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {\n      // Set title attribute if only an icon is shown\n      el.setAttribute('title', localizedText);\n    }\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-control vjs-button ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * Enable this `ClickableComponent`\n   */\n  enable() {\n    if (!this.enabled_) {\n      this.enabled_ = true;\n      this.removeClass('vjs-disabled');\n      this.el_.setAttribute('aria-disabled', 'false');\n      if (typeof this.tabIndex_ !== 'undefined') {\n        this.el_.setAttribute('tabIndex', this.tabIndex_);\n      }\n      this.on(['tap', 'click'], this.handleClick_);\n      this.on('keydown', this.handleKeyDown_);\n    }\n  }\n\n  /**\n   * Disable this `ClickableComponent`\n   */\n  disable() {\n    this.enabled_ = false;\n    this.addClass('vjs-disabled');\n    this.el_.setAttribute('aria-disabled', 'true');\n    if (typeof this.tabIndex_ !== 'undefined') {\n      this.el_.removeAttribute('tabIndex');\n    }\n    this.off('mouseover', this.handleMouseOver_);\n    this.off('mouseout', this.handleMouseOut_);\n    this.off(['tap', 'click'], this.handleClick_);\n    this.off('keydown', this.handleKeyDown_);\n  }\n\n  /**\n   * Handles language change in ClickableComponent for the player in components\n   *\n   *\n   */\n  handleLanguagechange() {\n    this.controlText(this.controlText_);\n  }\n\n  /**\n   * Event handler that is called when a `ClickableComponent` receives a\n   * `click` or `tap` event.\n   *\n   * @param {Event} event\n   *        The `tap` or `click` event that caused this function to be called.\n   *\n   * @listens tap\n   * @listens click\n   * @abstract\n   */\n  handleClick(event) {\n    if (this.options_.clickHandler) {\n      this.options_.clickHandler.call(this, arguments);\n    }\n  }\n\n  /**\n   * Event handler that is called when a `ClickableComponent` receives a\n   * `keydown` event.\n   *\n   * By default, if the key is Space or Enter, it will trigger a `click` event.\n   *\n   * @param {KeyboardEvent} event\n   *        The `keydown` event that caused this function to be called.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    // Support Space or Enter key operation to fire a click event. Also,\n    // prevent the event from propagating through the DOM and triggering\n    // Player hotkeys.\n    if (event.key === ' ' || event.key === 'Enter') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.trigger('click');\n    } else {\n      // Pass keypress handling up for unsupported keys\n      super.handleKeyDown(event);\n    }\n  }\n}\nComponent$1.registerComponent('ClickableComponent', ClickableComponent);\n\n/**\n * @file poster-image.js\n */\n\n/** @import Player from './player' */\n\n/**\n * A `ClickableComponent` that handles showing the poster image for the player.\n *\n * @extends ClickableComponent\n */\nclass PosterImage extends ClickableComponent {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should attach to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.update();\n    this.update_ = e => this.update(e);\n    player.on('posterchange', this.update_);\n  }\n\n  /**\n   * Clean up and dispose of the `PosterImage`.\n   */\n  dispose() {\n    this.player().off('posterchange', this.update_);\n    super.dispose();\n  }\n\n  /**\n   * Create the `PosterImage`s DOM element.\n   *\n   * @return {Element}\n   *         The element that gets created.\n   */\n  createEl() {\n    // The el is an empty div to keep position in the DOM\n    // A picture and img el will be inserted when a source is set\n    return createEl('div', {\n      className: 'vjs-poster'\n    });\n  }\n\n  /**\n   * Get or set the `PosterImage`'s crossOrigin option.\n   *\n   * @param {string|null} [value]\n   *        The value to set the crossOrigin to. If an argument is\n   *        given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.\n   *\n   * @return {string|null}\n   *         - The current crossOrigin value of the `Player` when getting.\n   *         - undefined when setting\n   */\n  crossOrigin(value) {\n    // `null` can be set to unset a value\n    if (typeof value === 'undefined') {\n      if (this.$('img')) {\n        // If the poster's element exists, give its value\n        return this.$('img').crossOrigin;\n      } else if (this.player_.tech_ && this.player_.tech_.isReady_) {\n        // If not but the tech is ready, query the tech\n        return this.player_.crossOrigin();\n      }\n      // Otherwise check options as the  poster is usually set before the state of crossorigin\n      // can be retrieved by the getter\n      return this.player_.options_.crossOrigin || this.player_.options_.crossorigin || null;\n    }\n    if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {\n      this.player_.log.warn(`crossOrigin must be null,  \"anonymous\" or \"use-credentials\", given \"${value}\"`);\n      return;\n    }\n    if (this.$('img')) {\n      this.$('img').crossOrigin = value;\n    }\n    return;\n  }\n\n  /**\n   * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.\n   *\n   * @listens Player#posterchange\n   *\n   * @param {Event} [event]\n   *        The `Player#posterchange` event that triggered this function.\n   */\n  update(event) {\n    const url = this.player().poster();\n    this.setSrc(url);\n\n    // If there's no poster source we should display:none on this component\n    // so it's not still clickable or right-clickable\n    if (url) {\n      this.show();\n    } else {\n      this.hide();\n    }\n  }\n\n  /**\n   * Set the source of the `PosterImage` depending on the display method. (Re)creates\n   * the inner picture and img elementss when needed.\n   *\n   * @param {string} [url]\n   *        The URL to the source for the `PosterImage`. If not specified or falsy,\n   *        any source and ant inner picture/img are removed.\n   */\n  setSrc(url) {\n    if (!url) {\n      this.el_.textContent = '';\n      return;\n    }\n    if (!this.$('img')) {\n      this.el_.appendChild(createEl('picture', {\n        className: 'vjs-poster',\n        // Don't want poster to be tabbable.\n        tabIndex: -1\n      }, {}, createEl('img', {\n        loading: 'lazy',\n        crossOrigin: this.crossOrigin()\n      }, {\n        alt: ''\n      })));\n    }\n    this.$('img').src = url;\n  }\n\n  /**\n   * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See\n   * {@link ClickableComponent#handleClick} for instances where this will be triggered.\n   *\n   * @listens tap\n   * @listens click\n   * @listens keydown\n   *\n   * @param {Event} event\n   +        The `click`, `tap` or `keydown` event that caused this function to be called.\n   */\n  handleClick(event) {\n    // We don't want a click to trigger playback when controls are disabled\n    if (!this.player_.controls()) {\n      return;\n    }\n    if (this.player_.tech(true)) {\n      this.player_.tech(true).focus();\n    }\n    if (this.player_.paused()) {\n      silencePromise(this.player_.play());\n    } else {\n      this.player_.pause();\n    }\n  }\n}\n\n/**\n * Get or set the `PosterImage`'s crossorigin option. For the HTML5 player, this\n * sets the `crossOrigin` property on the `<img>` tag to control the CORS\n * behavior.\n *\n * @param {string|null} [value]\n *        The value to set the `PosterImages`'s crossorigin to. If an argument is\n *        given, must be one of `anonymous` or `use-credentials`.\n *\n * @return {string|null|undefined}\n *         - The current crossorigin value of the `Player` when getting.\n *         - undefined when setting\n */\nPosterImage.prototype.crossorigin = PosterImage.prototype.crossOrigin;\nComponent$1.registerComponent('PosterImage', PosterImage);\n\n/**\n * @file text-track-display.js\n */\n\n/** @import Player from '../player' */\n\nconst darkGray = '#222';\nconst lightGray = '#ccc';\nconst fontMap = {\n  monospace: 'monospace',\n  sansSerif: 'sans-serif',\n  serif: 'serif',\n  monospaceSansSerif: '\"Andale Mono\", \"Lucida Console\", monospace',\n  monospaceSerif: '\"Courier New\", monospace',\n  proportionalSansSerif: 'sans-serif',\n  proportionalSerif: 'serif',\n  casual: '\"Comic Sans MS\", Impact, fantasy',\n  script: '\"Monotype Corsiva\", cursive',\n  smallcaps: '\"Andale Mono\", \"Lucida Console\", monospace, sans-serif'\n};\n\n/**\n * Construct an rgba color from a given hex color code.\n *\n * @param {number} color\n *        Hex number for color, like #f0e or #f604e2.\n *\n * @param {number} opacity\n *        Value for opacity, 0.0 - 1.0.\n *\n * @return {string}\n *         The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.\n */\nfunction constructColor(color, opacity) {\n  let hex;\n  if (color.length === 4) {\n    // color looks like \"#f0e\"\n    hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];\n  } else if (color.length === 7) {\n    // color looks like \"#f604e2\"\n    hex = color.slice(1);\n  } else {\n    throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');\n  }\n  return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';\n}\n\n/**\n * Try to update the style of a DOM element. Some style changes will throw an error,\n * particularly in IE8. Those should be noops.\n *\n * @param {Element} el\n *        The DOM element to be styled.\n *\n * @param {string} style\n *        The CSS property on the element that should be styled.\n *\n * @param {string} rule\n *        The style rule that should be applied to the property.\n *\n * @private\n */\nfunction tryUpdateStyle(el, style, rule) {\n  try {\n    el.style[style] = rule;\n  } catch (e) {\n    // Satisfies linter.\n    return;\n  }\n}\n\n/**\n * Converts the CSS top/right/bottom/left property numeric value to string in pixels.\n *\n * @param {number} position\n *        The CSS top/right/bottom/left property value.\n *\n * @return {string}\n *          The CSS property value that was created, like '10px'.\n *\n * @private\n */\nfunction getCSSPositionValue(position) {\n  return position ? `${position}px` : '';\n}\n\n/**\n * The component for displaying text track cues.\n *\n * @extends Component\n */\nclass TextTrackDisplay extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {Function} [ready]\n   *        The function to call when `TextTrackDisplay` is ready.\n   */\n  constructor(player, options, ready) {\n    super(player, options, ready);\n    const updateDisplayTextHandler = e => this.updateDisplay(e);\n    const updateDisplayHandler = e => {\n      this.updateDisplayOverlay();\n      this.updateDisplay(e);\n    };\n    player.on('loadstart', e => this.toggleDisplay(e));\n    player.on('useractive', updateDisplayTextHandler);\n    player.on('userinactive', updateDisplayTextHandler);\n    player.on('texttrackchange', updateDisplayTextHandler);\n    player.on('loadedmetadata', e => {\n      this.updateDisplayOverlay();\n      this.preselectTrack(e);\n    });\n\n    // This used to be called during player init, but was causing an error\n    // if a track should show by default and the display hadn't loaded yet.\n    // Should probably be moved to an external track loader when we support\n    // tracks that don't need a display.\n    player.ready(bind_(this, function () {\n      if (player.tech_ && player.tech_.featuresNativeTextTracks) {\n        this.hide();\n        return;\n      }\n      player.on('fullscreenchange', updateDisplayHandler);\n      player.on('playerresize', updateDisplayHandler);\n      const screenOrientation = window$1.screen.orientation || window$1;\n      const changeOrientationEvent = window$1.screen.orientation ? 'change' : 'orientationchange';\n      screenOrientation.addEventListener(changeOrientationEvent, updateDisplayHandler);\n      player.on('dispose', () => screenOrientation.removeEventListener(changeOrientationEvent, updateDisplayHandler));\n      const tracks = this.options_.playerOptions.tracks || [];\n      for (let i = 0; i < tracks.length; i++) {\n        this.player_.addRemoteTextTrack(tracks[i], true);\n      }\n      this.preselectTrack();\n    }));\n  }\n\n  /**\n  * Preselect a track following this precedence:\n  * - matches the previously selected {@link TextTrack}'s language and kind\n  * - matches the previously selected {@link TextTrack}'s language only\n  * - is the first default captions track\n  * - is the first default descriptions track\n  *\n  * @listens Player#loadstart\n  */\n  preselectTrack() {\n    const modes = {\n      captions: 1,\n      subtitles: 1\n    };\n    const trackList = this.player_.textTracks();\n    const userPref = this.player_.cache_.selectedLanguage;\n    let firstDesc;\n    let firstCaptions;\n    let preferredTrack;\n    for (let i = 0; i < trackList.length; i++) {\n      const track = trackList[i];\n      if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {\n        // Always choose the track that matches both language and kind\n        if (track.kind === userPref.kind) {\n          preferredTrack = track;\n          // or choose the first track that matches language\n        } else if (!preferredTrack) {\n          preferredTrack = track;\n        }\n\n        // clear everything if offTextTrackMenuItem was clicked\n      } else if (userPref && !userPref.enabled) {\n        preferredTrack = null;\n        firstDesc = null;\n        firstCaptions = null;\n      } else if (track.default) {\n        if (track.kind === 'descriptions' && !firstDesc) {\n          firstDesc = track;\n        } else if (track.kind in modes && !firstCaptions) {\n          firstCaptions = track;\n        }\n      }\n    }\n\n    // The preferredTrack matches the user preference and takes\n    // precedence over all the other tracks.\n    // So, display the preferredTrack before the first default track\n    // and the subtitles/captions track before the descriptions track\n    if (preferredTrack) {\n      preferredTrack.mode = 'showing';\n    } else if (firstCaptions) {\n      firstCaptions.mode = 'showing';\n    } else if (firstDesc) {\n      firstDesc.mode = 'showing';\n    }\n  }\n\n  /**\n   * Turn display of {@link TextTrack}'s from the current state into the other state.\n   * There are only two states:\n   * - 'shown'\n   * - 'hidden'\n   *\n   * @listens Player#loadstart\n   */\n  toggleDisplay() {\n    if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {\n      this.hide();\n    } else {\n      this.show();\n    }\n  }\n\n  /**\n   * Create the {@link Component}'s DOM element.\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-text-track-display'\n    }, {\n      'translate': 'yes',\n      'aria-live': 'off',\n      'aria-atomic': 'true'\n    });\n  }\n\n  /**\n   * Clear all displayed {@link TextTrack}s.\n   */\n  clearDisplay() {\n    if (typeof window$1.WebVTT === 'function') {\n      window$1.WebVTT.processCues(window$1, [], this.el_);\n    }\n  }\n\n  /**\n   * Update the displayed {@link TextTrack} when either a {@link Player#texttrackchange},\n   * a {@link Player#fullscreenchange}, a {@link Player#useractive}, or a\n   * {@link Player#userinactive} is fired.\n   *\n   * @listens Player#texttrackchange\n   * @listens Player#fullscreenchange\n   * @listens Player#useractive\n   * @listens Player#userinactive\n   */\n  updateDisplay() {\n    const tracks = this.player_.textTracks();\n    const allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;\n    this.clearDisplay();\n    if (allowMultipleShowingTracks) {\n      const showingTracks = [];\n      for (let i = 0; i < tracks.length; ++i) {\n        const track = tracks[i];\n        if (track.mode !== 'showing') {\n          continue;\n        }\n        showingTracks.push(track);\n      }\n      this.updateForTrack(showingTracks);\n      return;\n    }\n\n    //  Track display prioritization model: if multiple tracks are 'showing',\n    //  display the first 'subtitles' or 'captions' track which is 'showing',\n    //  otherwise display the first 'descriptions' track which is 'showing'\n\n    let descriptionsTrack = null;\n    let captionsSubtitlesTrack = null;\n    let i = tracks.length;\n    while (i--) {\n      const track = tracks[i];\n      if (track.mode === 'showing') {\n        if (track.kind === 'descriptions') {\n          descriptionsTrack = track;\n        } else {\n          captionsSubtitlesTrack = track;\n        }\n      }\n    }\n    if (captionsSubtitlesTrack) {\n      if (this.getAttribute('aria-live') !== 'off') {\n        this.setAttribute('aria-live', 'off');\n      }\n      this.updateForTrack(captionsSubtitlesTrack);\n    } else if (descriptionsTrack) {\n      if (this.getAttribute('aria-live') !== 'assertive') {\n        this.setAttribute('aria-live', 'assertive');\n      }\n      this.updateForTrack(descriptionsTrack);\n    }\n    if (!window$1.CSS.supports('inset', '10px')) {\n      const textTrackDisplay = this.el_;\n      const vjsTextTrackCues = textTrackDisplay.querySelectorAll('.vjs-text-track-cue');\n      const controlBarHeight = this.player_.controlBar.el_.getBoundingClientRect().height;\n      const playerHeight = this.player_.el_.getBoundingClientRect().height;\n\n      // Clear inline style before getting actual height of textTrackDisplay\n      textTrackDisplay.style = '';\n\n      // textrack style updates, this styles are required to be inline\n      tryUpdateStyle(textTrackDisplay, 'position', 'relative');\n      tryUpdateStyle(textTrackDisplay, 'height', playerHeight - controlBarHeight + 'px');\n      tryUpdateStyle(textTrackDisplay, 'top', 'unset');\n      if (IS_SMART_TV) {\n        tryUpdateStyle(textTrackDisplay, 'bottom', playerHeight + 'px');\n      } else {\n        tryUpdateStyle(textTrackDisplay, 'bottom', '0px');\n      }\n\n      // vjsTextTrackCue style updates\n      if (vjsTextTrackCues.length > 0) {\n        vjsTextTrackCues.forEach(vjsTextTrackCue => {\n          // verify if inset styles are inline\n          if (vjsTextTrackCue.style.inset) {\n            const insetStyles = vjsTextTrackCue.style.inset.split(' ');\n\n            // expected value is always 3\n            if (insetStyles.length === 3) {\n              Object.assign(vjsTextTrackCue.style, {\n                top: insetStyles[0],\n                right: insetStyles[1],\n                bottom: insetStyles[2],\n                left: 'unset'\n              });\n            }\n          }\n        });\n      }\n    }\n  }\n\n  /**\n   * Updates the displayed TextTrack to be sure it overlays the video when a either\n   * a {@link Player#texttrackchange} or a {@link Player#fullscreenchange} is fired.\n   */\n  updateDisplayOverlay() {\n    // inset-inline and inset-block are not supprted on old chrome, but these are\n    // only likely to be used on TV devices\n    if (!this.player_.videoHeight() || !window$1.CSS.supports('inset-inline: 10px')) {\n      return;\n    }\n    const playerWidth = this.player_.currentWidth();\n    const playerHeight = this.player_.currentHeight();\n    const playerAspectRatio = playerWidth / playerHeight;\n    const videoAspectRatio = this.player_.videoWidth() / this.player_.videoHeight();\n    let insetInlineMatch = 0;\n    let insetBlockMatch = 0;\n    if (Math.abs(playerAspectRatio - videoAspectRatio) > 0.1) {\n      if (playerAspectRatio > videoAspectRatio) {\n        insetInlineMatch = Math.round((playerWidth - playerHeight * videoAspectRatio) / 2);\n      } else {\n        insetBlockMatch = Math.round((playerHeight - playerWidth / videoAspectRatio) / 2);\n      }\n    }\n    tryUpdateStyle(this.el_, 'insetInline', getCSSPositionValue(insetInlineMatch));\n    tryUpdateStyle(this.el_, 'insetBlock', getCSSPositionValue(insetBlockMatch));\n  }\n\n  /**\n   * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.\n   *\n   * @param {TextTrack} track\n   *        Text track object containing active cues to style.\n   */\n  updateDisplayState(track) {\n    const overrides = this.player_.textTrackSettings.getValues();\n    const cues = track.activeCues;\n    let i = cues.length;\n    while (i--) {\n      const cue = cues[i];\n      if (!cue) {\n        continue;\n      }\n      const cueDiv = cue.displayState;\n      if (overrides.color) {\n        cueDiv.firstChild.style.color = overrides.color;\n      }\n      if (overrides.textOpacity) {\n        tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));\n      }\n      if (overrides.backgroundColor) {\n        cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;\n      }\n      if (overrides.backgroundOpacity) {\n        tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));\n      }\n      if (overrides.windowColor) {\n        if (overrides.windowOpacity) {\n          tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));\n        } else {\n          cueDiv.style.backgroundColor = overrides.windowColor;\n        }\n      }\n      if (overrides.edgeStyle) {\n        if (overrides.edgeStyle === 'dropshadow') {\n          cueDiv.firstChild.style.textShadow = `2px 2px 3px ${darkGray}, 2px 2px 4px ${darkGray}, 2px 2px 5px ${darkGray}`;\n        } else if (overrides.edgeStyle === 'raised') {\n          cueDiv.firstChild.style.textShadow = `1px 1px ${darkGray}, 2px 2px ${darkGray}, 3px 3px ${darkGray}`;\n        } else if (overrides.edgeStyle === 'depressed') {\n          cueDiv.firstChild.style.textShadow = `1px 1px ${lightGray}, 0 1px ${lightGray}, -1px -1px ${darkGray}, 0 -1px ${darkGray}`;\n        } else if (overrides.edgeStyle === 'uniform') {\n          cueDiv.firstChild.style.textShadow = `0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}`;\n        }\n      }\n      if (overrides.fontPercent && overrides.fontPercent !== 1) {\n        const fontSize = window$1.parseFloat(cueDiv.style.fontSize);\n        cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';\n        cueDiv.style.height = 'auto';\n        cueDiv.style.top = 'auto';\n      }\n      if (overrides.fontFamily && overrides.fontFamily !== 'default') {\n        if (overrides.fontFamily === 'small-caps') {\n          cueDiv.firstChild.style.fontVariant = 'small-caps';\n        } else {\n          cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];\n        }\n      }\n    }\n  }\n\n  /**\n   * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.\n   *\n   * @param {TextTrack|TextTrack[]} tracks\n   *        Text track object or text track array to be added to the list.\n   */\n  updateForTrack(tracks) {\n    if (!Array.isArray(tracks)) {\n      tracks = [tracks];\n    }\n    if (typeof window$1.WebVTT !== 'function' || tracks.every(track => {\n      return !track.activeCues;\n    })) {\n      return;\n    }\n    const cues = [];\n\n    // push all active track cues\n    for (let i = 0; i < tracks.length; ++i) {\n      const track = tracks[i];\n      for (let j = 0; j < track.activeCues.length; ++j) {\n        cues.push(track.activeCues[j]);\n      }\n    }\n\n    // removes all cues before it processes new ones\n    window$1.WebVTT.processCues(window$1, cues, this.el_);\n\n    // add unique class to each language text track & add settings styling if necessary\n    for (let i = 0; i < tracks.length; ++i) {\n      const track = tracks[i];\n      for (let j = 0; j < track.activeCues.length; ++j) {\n        const cueEl = track.activeCues[j].displayState;\n        addClass(cueEl, 'vjs-text-track-cue', 'vjs-text-track-cue-' + (track.language ? track.language : i));\n        if (track.language) {\n          setAttribute(cueEl, 'lang', track.language);\n        }\n      }\n      if (this.player_.textTrackSettings) {\n        this.updateDisplayState(track);\n      }\n    }\n  }\n}\nComponent$1.registerComponent('TextTrackDisplay', TextTrackDisplay);\n\n/**\n * @file loading-spinner.js\n */\n\n/**\n * A loading spinner for use during waiting/loading events.\n *\n * @extends Component\n */\nclass LoadingSpinner extends Component$1 {\n  /**\n   * Create the `LoadingSpinner`s DOM element.\n   *\n   * @return {Element}\n   *         The dom element that gets created.\n   */\n  createEl() {\n    const isAudio = this.player_.isAudio();\n    const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');\n    const controlText = createEl('span', {\n      className: 'vjs-control-text',\n      textContent: this.localize('{1} is loading.', [playerType])\n    });\n    const el = super.createEl('div', {\n      className: 'vjs-loading-spinner',\n      dir: 'ltr'\n    });\n    el.appendChild(controlText);\n    return el;\n  }\n\n  /**\n   * Update control text on languagechange\n   */\n  handleLanguagechange() {\n    this.$('.vjs-control-text').textContent = this.localize('{1} is loading.', [this.player_.isAudio() ? 'Audio Player' : 'Video Player']);\n  }\n}\nComponent$1.registerComponent('LoadingSpinner', LoadingSpinner);\n\n/**\n * @file button.js\n */\n\n/**\n * Base class for all buttons.\n *\n * @extends ClickableComponent\n */\nclass Button extends ClickableComponent {\n  /**\n   * Create the `Button`s DOM element.\n   *\n   * @param {string} [tag=\"button\"]\n   *        The element's node type. This argument is IGNORED: no matter what\n   *        is passed, it will always create a `button` element.\n   *\n   * @param {Object} [props={}]\n   *        An object of properties that should be set on the element.\n   *\n   * @param {Object} [attributes={}]\n   *        An object of attributes that should be set on the element.\n   *\n   * @return {Element}\n   *         The element that gets created.\n   */\n  createEl(tag, props = {}, attributes = {}) {\n    tag = 'button';\n    props = Object.assign({\n      className: this.buildCSSClass()\n    }, props);\n\n    // Add attributes for button element\n    attributes = Object.assign({\n      // Necessary since the default button type is \"submit\"\n      type: 'button'\n    }, attributes);\n    const el = createEl(tag, props, attributes);\n    if (!this.player_.options_.experimentalSvgIcons) {\n      el.appendChild(createEl('span', {\n        className: 'vjs-icon-placeholder'\n      }, {\n        'aria-hidden': true\n      }));\n    }\n    this.createControlTextEl(el);\n    return el;\n  }\n\n  /**\n   * Add a child `Component` inside of this `Button`.\n   *\n   * @param {string|Component} child\n   *        The name or instance of a child to add.\n   *\n   * @param {Object} [options={}]\n   *        The key/value store of options that will get passed to children of\n   *        the child.\n   *\n   * @return {Component}\n   *         The `Component` that gets added as a child. When using a string the\n   *         `Component` will get created by this process.\n   *\n   * @deprecated since version 5\n   */\n  addChild(child, options = {}) {\n    const className = this.constructor.name;\n    log$1.warn(`Adding an actionable (user controllable) child to a Button (${className}) is not supported; use a ClickableComponent instead.`);\n\n    // Avoid the error message generated by ClickableComponent's addChild method\n    return Component$1.prototype.addChild.call(this, child, options);\n  }\n\n  /**\n   * Enable the `Button` element so that it can be activated or clicked. Use this with\n   * {@link Button#disable}.\n   */\n  enable() {\n    super.enable();\n    this.el_.removeAttribute('disabled');\n  }\n\n  /**\n   * Disable the `Button` element so that it cannot be activated or clicked. Use this with\n   * {@link Button#enable}.\n   */\n  disable() {\n    super.disable();\n    this.el_.setAttribute('disabled', 'disabled');\n  }\n\n  /**\n   * This gets called when a `Button` has focus and `keydown` is triggered via a key\n   * press.\n   *\n   * @param {KeyboardEvent} event\n   *        The event that caused this function to get called.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    // Ignore Space or Enter key operation, which is handled by the browser for\n    // a button - though not for its super class, ClickableComponent. Also,\n    // prevent the event from propagating through the DOM and triggering Player\n    // hotkeys. We do not preventDefault here because we _want_ the browser to\n    // handle it.\n    if (event.key === ' ' || event.key === 'Enter') {\n      event.stopPropagation();\n      return;\n    }\n\n    // Pass keypress handling up for unsupported keys\n    super.handleKeyDown(event);\n  }\n}\nComponent$1.registerComponent('Button', Button);\n\n/**\n * @file big-play-button.js\n */\n\n/**\n * The initial play button that shows before the video has played. The hiding of the\n * `BigPlayButton` get done via CSS and `Player` states.\n *\n * @extends Button\n */\nclass BigPlayButton extends Button {\n  constructor(player, options) {\n    super(player, options);\n    this.mouseused_ = false;\n    this.setIcon('play');\n    this.on('mousedown', e => this.handleMouseDown(e));\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object. Always returns 'vjs-big-play-button'.\n   */\n  buildCSSClass() {\n    return 'vjs-big-play-button';\n  }\n\n  /**\n   * This gets called when a `BigPlayButton` \"clicked\". See {@link ClickableComponent}\n   * for more detailed information on what a click can be.\n   *\n   * @param {KeyboardEvent|MouseEvent|TouchEvent} event\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    const playPromise = this.player_.play();\n\n    // exit early if tapped or clicked via the mouse\n    if (event.type === 'tap' || this.mouseused_ && 'clientX' in event && 'clientY' in event) {\n      silencePromise(playPromise);\n      if (this.player_.tech(true)) {\n        this.player_.tech(true).focus();\n      }\n      return;\n    }\n    const cb = this.player_.getChild('controlBar');\n    const playToggle = cb && cb.getChild('playToggle');\n    if (!playToggle) {\n      this.player_.tech(true).focus();\n      return;\n    }\n    const playFocus = () => playToggle.focus();\n    if (isPromise(playPromise)) {\n      playPromise.then(playFocus, () => {});\n    } else {\n      this.setTimeout(playFocus, 1);\n    }\n  }\n\n  /**\n   * Event handler that is called when a `BigPlayButton` receives a\n   * `keydown` event.\n   *\n   * @param {KeyboardEvent} event\n   *        The `keydown` event that caused this function to be called.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    this.mouseused_ = false;\n    super.handleKeyDown(event);\n  }\n\n  /**\n   * Handle `mousedown` events on the `BigPlayButton`.\n   *\n   * @param {MouseEvent} event\n   *        `mousedown` or `touchstart` event that triggered this function\n   *\n   * @listens mousedown\n   */\n  handleMouseDown(event) {\n    this.mouseused_ = true;\n  }\n}\n\n/**\n * The text that should display over the `BigPlayButton`s controls. Added to for localization.\n *\n * @type {string}\n * @protected\n */\nBigPlayButton.prototype.controlText_ = 'Play Video';\nComponent$1.registerComponent('BigPlayButton', BigPlayButton);\n\n/**\n * @file close-button.js\n */\n\n/** @import Player from './player' */\n\n/**\n * The `CloseButton` is a `{@link Button}` that fires a `close` event when\n * it gets clicked.\n *\n * @extends Button\n */\nclass CloseButton extends Button {\n  /**\n  * Creates an instance of the this class.\n  *\n  * @param  {Player} player\n  *         The `Player` that this class should be attached to.\n  *\n  * @param  {Object} [options]\n  *         The key/value store of player options.\n  */\n  constructor(player, options) {\n    super(player, options);\n    this.setIcon('cancel');\n    this.controlText(options && options.controlText || this.localize('Close'));\n  }\n\n  /**\n  * Builds the default DOM `className`.\n  *\n  * @return {string}\n  *         The DOM `className` for this object.\n  */\n  buildCSSClass() {\n    return `vjs-close-button ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * This gets called when a `CloseButton` gets clicked. See\n   * {@link ClickableComponent#handleClick} for more information on when\n   * this will be triggered\n   *\n   * @param {Event} event\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   * @fires CloseButton#close\n   */\n  handleClick(event) {\n    /**\n     * Triggered when the a `CloseButton` is clicked.\n     *\n     * @event CloseButton#close\n     * @type {Event}\n     *\n     * @property {boolean} [bubbles=false]\n     *           set to false so that the close event does not\n     *           bubble up to parents if there is no listener\n     */\n    this.trigger({\n      type: 'close',\n      bubbles: false\n    });\n  }\n  /**\n   * Event handler that is called when a `CloseButton` receives a\n   * `keydown` event.\n   *\n   * By default, if the key is Esc, it will trigger a `click` event.\n   *\n   * @param {KeyboardEvent} event\n   *        The `keydown` event that caused this function to be called.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    // Esc button will trigger `click` event\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.trigger('click');\n    } else {\n      // Pass keypress handling up for unsupported keys\n      super.handleKeyDown(event);\n    }\n  }\n}\nComponent$1.registerComponent('CloseButton', CloseButton);\n\n/**\n * @file play-toggle.js\n */\n\n/** @import Player from './player' */\n\n/**\n * Button to toggle between play and pause.\n *\n * @extends Button\n */\nclass PlayToggle extends Button {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options={}]\n   *        The key/value store of player options.\n   */\n  constructor(player, options = {}) {\n    super(player, options);\n\n    // show or hide replay icon\n    options.replay = options.replay === undefined || options.replay;\n    this.setIcon('play');\n    this.on(player, 'play', e => this.handlePlay(e));\n    this.on(player, 'pause', e => this.handlePause(e));\n    if (options.replay) {\n      this.on(player, 'ended', e => this.handleEnded(e));\n    }\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-play-control ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * This gets called when an `PlayToggle` is \"clicked\". See\n   * {@link ClickableComponent} for more detailed information on what a click can be.\n   *\n   * @param {Event} [event]\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    if (this.player_.paused()) {\n      silencePromise(this.player_.play());\n    } else {\n      this.player_.pause();\n    }\n  }\n\n  /**\n   * This gets called once after the video has ended and the user seeks so that\n   * we can change the replay button back to a play button.\n   *\n   * @param {Event} [event]\n   *        The event that caused this function to run.\n   *\n   * @listens Player#seeked\n   */\n  handleSeeked(event) {\n    this.removeClass('vjs-ended');\n    if (this.player_.paused()) {\n      this.handlePause(event);\n    } else {\n      this.handlePlay(event);\n    }\n  }\n\n  /**\n   * Add the vjs-playing class to the element so it can change appearance.\n   *\n   * @param {Event} [event]\n   *        The event that caused this function to run.\n   *\n   * @listens Player#play\n   */\n  handlePlay(event) {\n    this.removeClass('vjs-ended', 'vjs-paused');\n    this.addClass('vjs-playing');\n    // change the button text to \"Pause\"\n    this.setIcon('pause');\n    this.controlText('Pause');\n  }\n\n  /**\n   * Add the vjs-paused class to the element so it can change appearance.\n   *\n   * @param {Event} [event]\n   *        The event that caused this function to run.\n   *\n   * @listens Player#pause\n   */\n  handlePause(event) {\n    this.removeClass('vjs-playing');\n    this.addClass('vjs-paused');\n    // change the button text to \"Play\"\n    this.setIcon('play');\n    this.controlText('Play');\n  }\n\n  /**\n   * Add the vjs-ended class to the element so it can change appearance\n   *\n   * @param {Event} [event]\n   *        The event that caused this function to run.\n   *\n   * @listens Player#ended\n   */\n  handleEnded(event) {\n    this.removeClass('vjs-playing');\n    this.addClass('vjs-ended');\n    // change the button text to \"Replay\"\n    this.setIcon('replay');\n    this.controlText('Replay');\n\n    // on the next seek remove the replay button\n    this.one(this.player_, 'seeked', e => this.handleSeeked(e));\n  }\n}\n\n/**\n * The text that should display over the `PlayToggle`s controls. Added for localization.\n *\n * @type {string}\n * @protected\n */\nPlayToggle.prototype.controlText_ = 'Play';\nComponent$1.registerComponent('PlayToggle', PlayToggle);\n\n/**\n * @file time-display.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * Displays time information about the video\n *\n * @extends Component\n */\nclass TimeDisplay extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.on(player, ['timeupdate', 'ended', 'seeking'], e => this.update(e));\n    this.updateTextNode_();\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    const className = this.buildCSSClass();\n    const el = super.createEl('div', {\n      className: `${className} vjs-time-control vjs-control`\n    });\n    const span = createEl('span', {\n      className: 'vjs-control-text',\n      textContent: `${this.localize(this.labelText_)}\\u00a0`\n    }, {\n      role: 'presentation'\n    });\n    el.appendChild(span);\n    this.contentEl_ = createEl('span', {\n      className: `${className}-display`\n    }, {\n      // span elements have no implicit role, but some screen readers (notably VoiceOver)\n      // treat them as a break between items in the DOM when using arrow keys\n      // (or left-to-right swipes on iOS) to read contents of a page. Using\n      // role='presentation' causes VoiceOver to NOT treat this span as a break.\n      role: 'presentation'\n    });\n    el.appendChild(this.contentEl_);\n    return el;\n  }\n  dispose() {\n    this.contentEl_ = null;\n    this.textNode_ = null;\n    super.dispose();\n  }\n\n  /**\n   * Updates the displayed time according to the `updateContent` function which is defined in the child class.\n   *\n   * @param {Event} [event]\n   *          The `timeupdate`, `ended` or `seeking` (if enableSmoothSeeking is true) event that caused this function to be called.\n   */\n  update(event) {\n    if (!this.player_.options_.enableSmoothSeeking && event.type === 'seeking') {\n      return;\n    }\n    this.updateContent(event);\n  }\n\n  /**\n   * Updates the time display text node with a new time\n   *\n   * @param {number} [time=0] the time to update to\n   *\n   * @private\n   */\n  updateTextNode_(time = 0) {\n    time = formatTime(time);\n    if (this.formattedTime_ === time) {\n      return;\n    }\n    this.formattedTime_ = time;\n    this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', () => {\n      if (!this.contentEl_) {\n        return;\n      }\n      let oldNode = this.textNode_;\n      if (oldNode && this.contentEl_.firstChild !== oldNode) {\n        oldNode = null;\n        log$1.warn('TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.');\n      }\n      this.textNode_ = document$1.createTextNode(this.formattedTime_);\n      if (!this.textNode_) {\n        return;\n      }\n      if (oldNode) {\n        this.contentEl_.replaceChild(this.textNode_, oldNode);\n      } else {\n        this.contentEl_.appendChild(this.textNode_);\n      }\n    });\n  }\n\n  /**\n   * To be filled out in the child class, should update the displayed time\n   * in accordance with the fact that the current time has changed.\n   *\n   * @param {Event} [event]\n   *        The `timeupdate`  event that caused this to run.\n   *\n   * @listens Player#timeupdate\n   */\n  updateContent(event) {}\n}\n\n/**\n * The text that is added to the `TimeDisplay` for screen reader users.\n *\n * @type {string}\n * @private\n */\nTimeDisplay.prototype.labelText_ = 'Time';\n\n/**\n * The text that should display over the `TimeDisplay`s controls. Added to for localization.\n *\n * @type {string}\n * @protected\n *\n * @deprecated in v7; controlText_ is not used in non-active display Components\n */\nTimeDisplay.prototype.controlText_ = 'Time';\nComponent$1.registerComponent('TimeDisplay', TimeDisplay);\n\n/**\n * @file current-time-display.js\n */\n\n/**\n * Displays the current time\n *\n * @extends Component\n */\nclass CurrentTimeDisplay extends TimeDisplay {\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return 'vjs-current-time';\n  }\n\n  /**\n   * Update current time display\n   *\n   * @param {Event} [event]\n   *        The `timeupdate` event that caused this function to run.\n   *\n   * @listens Player#timeupdate\n   */\n  updateContent(event) {\n    // Allows for smooth scrubbing, when player can't keep up.\n    let time;\n    if (this.player_.ended()) {\n      time = this.player_.duration();\n    } else if (event && event.target && typeof event.target.pendingSeekTime === 'function') {\n      time = event.target.pendingSeekTime();\n    } else {\n      time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();\n    }\n    this.updateTextNode_(time);\n  }\n}\n\n/**\n * The text that is added to the `CurrentTimeDisplay` for screen reader users.\n *\n * @type {string}\n * @private\n */\nCurrentTimeDisplay.prototype.labelText_ = 'Current Time';\n\n/**\n * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.\n *\n * @type {string}\n * @protected\n *\n * @deprecated in v7; controlText_ is not used in non-active display Components\n */\nCurrentTimeDisplay.prototype.controlText_ = 'Current Time';\nComponent$1.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);\n\n/**\n * @file duration-display.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * Displays the duration\n *\n * @extends Component\n */\nclass DurationDisplay extends TimeDisplay {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    const updateContent = e => this.updateContent(e);\n\n    // we do not want to/need to throttle duration changes,\n    // as they should always display the changed duration as\n    // it has changed\n    this.on(player, 'durationchange', updateContent);\n\n    // Listen to loadstart because the player duration is reset when a new media element is loaded,\n    // but the durationchange on the user agent will not fire.\n    // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}\n    this.on(player, 'loadstart', updateContent);\n\n    // Also listen for timeupdate (in the parent) and loadedmetadata because removing those\n    // listeners could have broken dependent applications/libraries. These\n    // can likely be removed for 7.0.\n    this.on(player, 'loadedmetadata', updateContent);\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return 'vjs-duration';\n  }\n\n  /**\n   * Update duration time display.\n   *\n   * @param {Event} [event]\n   *        The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused\n   *        this function to be called.\n   *\n   * @listens Player#durationchange\n   * @listens Player#timeupdate\n   * @listens Player#loadedmetadata\n   */\n  updateContent(event) {\n    const duration = this.player_.duration();\n    this.updateTextNode_(duration);\n  }\n}\n\n/**\n * The text that is added to the `DurationDisplay` for screen reader users.\n *\n * @type {string}\n * @private\n */\nDurationDisplay.prototype.labelText_ = 'Duration';\n\n/**\n * The text that should display over the `DurationDisplay`s controls. Added to for localization.\n *\n * @type {string}\n * @protected\n *\n * @deprecated in v7; controlText_ is not used in non-active display Components\n */\nDurationDisplay.prototype.controlText_ = 'Duration';\nComponent$1.registerComponent('DurationDisplay', DurationDisplay);\n\n/**\n * @file time-divider.js\n */\n\n/**\n * The separator between the current time and duration.\n * Can be hidden if it's not needed in the design.\n *\n * @extends Component\n */\nclass TimeDivider extends Component$1 {\n  /**\n   * Create the component's DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    const el = super.createEl('div', {\n      className: 'vjs-time-control vjs-time-divider'\n    }, {\n      // this element and its contents can be hidden from assistive techs since\n      // it is made extraneous by the announcement of the control text\n      // for the current time and duration displays\n      'aria-hidden': true\n    });\n    const div = super.createEl('div');\n    const span = super.createEl('span', {\n      textContent: '/'\n    });\n    div.appendChild(span);\n    el.appendChild(div);\n    return el;\n  }\n}\nComponent$1.registerComponent('TimeDivider', TimeDivider);\n\n/**\n * @file remaining-time-display.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * Displays the time left in the video\n *\n * @extends Component\n */\nclass RemainingTimeDisplay extends TimeDisplay {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.on(player, 'durationchange', e => this.updateContent(e));\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return 'vjs-remaining-time';\n  }\n\n  /**\n   * Create the `Component`'s DOM element with the \"minus\" character prepend to the time\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    const el = super.createEl();\n    if (this.options_.displayNegative !== false) {\n      el.insertBefore(createEl('span', {}, {\n        'aria-hidden': true\n      }, '-'), this.contentEl_);\n    }\n    return el;\n  }\n\n  /**\n   * Update remaining time display.\n   *\n   * @param {Event} [event]\n   *        The `timeupdate` or `durationchange` event that caused this to run.\n   *\n   * @listens Player#timeupdate\n   * @listens Player#durationchange\n   */\n  updateContent(event) {\n    if (typeof this.player_.duration() !== 'number') {\n      return;\n    }\n    let time;\n\n    // @deprecated We should only use remainingTimeDisplay\n    // as of video.js 7\n    if (this.player_.ended()) {\n      time = 0;\n    } else if (this.player_.remainingTimeDisplay) {\n      time = this.player_.remainingTimeDisplay();\n    } else {\n      time = this.player_.remainingTime();\n    }\n    this.updateTextNode_(time);\n  }\n}\n\n/**\n * The text that is added to the `RemainingTimeDisplay` for screen reader users.\n *\n * @type {string}\n * @private\n */\nRemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';\n\n/**\n * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.\n *\n * @type {string}\n * @protected\n *\n * @deprecated in v7; controlText_ is not used in non-active display Components\n */\nRemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';\nComponent$1.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);\n\n/**\n * @file live-display.js\n */\n\n/** @import Player from './player' */\n\n// TODO - Future make it click to snap to live\n\n/**\n * Displays the live indicator when duration is Infinity.\n *\n * @extends Component\n */\nclass LiveDisplay extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.updateShowing();\n    this.on(this.player(), 'durationchange', e => this.updateShowing(e));\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    const el = super.createEl('div', {\n      className: 'vjs-live-control vjs-control'\n    });\n    this.contentEl_ = createEl('div', {\n      className: 'vjs-live-display'\n    }, {\n      'aria-live': 'off'\n    });\n    this.contentEl_.appendChild(createEl('span', {\n      className: 'vjs-control-text',\n      textContent: `${this.localize('Stream Type')}\\u00a0`\n    }));\n    this.contentEl_.appendChild(document$1.createTextNode(this.localize('LIVE')));\n    el.appendChild(this.contentEl_);\n    return el;\n  }\n  dispose() {\n    this.contentEl_ = null;\n    super.dispose();\n  }\n\n  /**\n   * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide\n   * it accordingly\n   *\n   * @param {Event} [event]\n   *        The {@link Player#durationchange} event that caused this function to run.\n   *\n   * @listens Player#durationchange\n   */\n  updateShowing(event) {\n    if (this.player().duration() === Infinity) {\n      this.show();\n    } else {\n      this.hide();\n    }\n  }\n}\nComponent$1.registerComponent('LiveDisplay', LiveDisplay);\n\n/**\n * @file seek-to-live.js\n */\n\n/** @import Player from './player' */\n\n/**\n * Displays the live indicator when duration is Infinity.\n *\n * @extends Component\n */\nclass SeekToLive extends Button {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.updateLiveEdgeStatus();\n    if (this.player_.liveTracker) {\n      this.updateLiveEdgeStatusHandler_ = e => this.updateLiveEdgeStatus(e);\n      this.on(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);\n    }\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    const el = super.createEl('button', {\n      className: 'vjs-seek-to-live-control vjs-control'\n    });\n    this.setIcon('circle', el);\n    this.textEl_ = createEl('span', {\n      className: 'vjs-seek-to-live-text',\n      textContent: this.localize('LIVE')\n    }, {\n      'aria-hidden': 'true'\n    });\n    el.appendChild(this.textEl_);\n    return el;\n  }\n\n  /**\n   * Update the state of this button if we are at the live edge\n   * or not\n   */\n  updateLiveEdgeStatus() {\n    // default to live edge\n    if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {\n      this.setAttribute('aria-disabled', true);\n      this.addClass('vjs-at-live-edge');\n      this.controlText('Seek to live, currently playing live');\n    } else {\n      this.setAttribute('aria-disabled', false);\n      this.removeClass('vjs-at-live-edge');\n      this.controlText('Seek to live, currently behind live');\n    }\n  }\n\n  /**\n   * On click bring us as near to the live point as possible.\n   * This requires that we wait for the next `live-seekable-change`\n   * event which will happen every segment length seconds.\n   */\n  handleClick() {\n    this.player_.liveTracker.seekToLiveEdge();\n  }\n\n  /**\n   * Dispose of the element and stop tracking\n   */\n  dispose() {\n    if (this.player_.liveTracker) {\n      this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);\n    }\n    this.textEl_ = null;\n    super.dispose();\n  }\n}\n/**\n * The text that should display over the `SeekToLive`s control. Added for localization.\n *\n * @type {string}\n * @protected\n */\nSeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';\nComponent$1.registerComponent('SeekToLive', SeekToLive);\n\n/**\n * @file num.js\n * @module num\n */\n\n/**\n * Keep a number between a min and a max value\n *\n * @param {number} number\n *        The number to clamp\n *\n * @param {number} min\n *        The minimum value\n * @param {number} max\n *        The maximum value\n *\n * @return {number}\n *         the clamped number\n */\nfunction clamp(number, min, max) {\n  number = Number(number);\n  return Math.min(max, Math.max(min, isNaN(number) ? min : number));\n}\n\nvar Num = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  clamp: clamp\n});\n\n/**\n * @file slider.js\n */\n\n/** @import Player from '../player' */\n\n/**\n * The base functionality for a slider. Can be vertical or horizontal.\n * For instance the volume bar or the seek bar on a video is a slider.\n *\n * @extends Component\n */\nclass Slider extends Component$1 {\n  /**\n  * Create an instance of this class\n  *\n  * @param {Player} player\n  *        The `Player` that this class should be attached to.\n  *\n  * @param {Object} [options]\n  *        The key/value store of player options.\n  */\n  constructor(player, options) {\n    super(player, options);\n    this.handleMouseDown_ = e => this.handleMouseDown(e);\n    this.handleMouseUp_ = e => this.handleMouseUp(e);\n    this.handleKeyDown_ = e => this.handleKeyDown(e);\n    this.handleClick_ = e => this.handleClick(e);\n    this.handleMouseMove_ = e => this.handleMouseMove(e);\n    this.update_ = e => this.update(e);\n\n    // Set property names to bar to match with the child Slider class is looking for\n    this.bar = this.getChild(this.options_.barName);\n\n    // Set a horizontal or vertical class on the slider depending on the slider type\n    this.vertical(!!this.options_.vertical);\n    this.enable();\n  }\n\n  /**\n   * Are controls are currently enabled for this slider or not.\n   *\n   * @return {boolean}\n   *         true if controls are enabled, false otherwise\n   */\n  enabled() {\n    return this.enabled_;\n  }\n\n  /**\n   * Enable controls for this slider if they are disabled\n   */\n  enable() {\n    if (this.enabled()) {\n      return;\n    }\n    this.on('mousedown', this.handleMouseDown_);\n    this.on('touchstart', this.handleMouseDown_);\n    this.on('keydown', this.handleKeyDown_);\n    this.on('click', this.handleClick_);\n\n    // TODO: deprecated, controlsvisible does not seem to be fired\n    this.on(this.player_, 'controlsvisible', this.update);\n    if (this.playerEvent) {\n      this.on(this.player_, this.playerEvent, this.update);\n    }\n    this.removeClass('disabled');\n    this.setAttribute('tabindex', 0);\n    this.enabled_ = true;\n  }\n\n  /**\n   * Disable controls for this slider if they are enabled\n   */\n  disable() {\n    if (!this.enabled()) {\n      return;\n    }\n    const doc = this.bar.el_.ownerDocument;\n    this.off('mousedown', this.handleMouseDown_);\n    this.off('touchstart', this.handleMouseDown_);\n    this.off('keydown', this.handleKeyDown_);\n    this.off('click', this.handleClick_);\n    this.off(this.player_, 'controlsvisible', this.update_);\n    this.off(doc, 'mousemove', this.handleMouseMove_);\n    this.off(doc, 'mouseup', this.handleMouseUp_);\n    this.off(doc, 'touchmove', this.handleMouseMove_);\n    this.off(doc, 'touchend', this.handleMouseUp_);\n    this.removeAttribute('tabindex');\n    this.addClass('disabled');\n    if (this.playerEvent) {\n      this.off(this.player_, this.playerEvent, this.update);\n    }\n    this.enabled_ = false;\n  }\n\n  /**\n   * Create the `Slider`s DOM element.\n   *\n   * @param {string} type\n   *        Type of element to create.\n   *\n   * @param {Object} [props={}]\n   *        List of properties in Object form.\n   *\n   * @param {Object} [attributes={}]\n   *        list of attributes in Object form.\n   *\n   * @return {Element}\n   *         The element that gets created.\n   */\n  createEl(type, props = {}, attributes = {}) {\n    // Add the slider element class to all sub classes\n    props.className = props.className + ' vjs-slider';\n    props = Object.assign({\n      tabIndex: 0\n    }, props);\n    attributes = Object.assign({\n      'role': 'slider',\n      'aria-valuenow': 0,\n      'aria-valuemin': 0,\n      'aria-valuemax': 100\n    }, attributes);\n    return super.createEl(type, props, attributes);\n  }\n\n  /**\n   * Handle `mousedown` or `touchstart` events on the `Slider`.\n   *\n   * @param {MouseEvent} event\n   *        `mousedown` or `touchstart` event that triggered this function\n   *\n   * @listens mousedown\n   * @listens touchstart\n   * @fires Slider#slideractive\n   */\n  handleMouseDown(event) {\n    const doc = this.bar.el_.ownerDocument;\n    if (event.type === 'mousedown') {\n      event.preventDefault();\n    }\n    // Do not call preventDefault() on touchstart in Chrome\n    // to avoid console warnings. Use a 'touch-action: none' style\n    // instead to prevent unintended scrolling.\n    // https://developers.google.com/web/updates/2017/01/scrolling-intervention\n    if (event.type === 'touchstart' && !IS_CHROME) {\n      event.preventDefault();\n    }\n    blockTextSelection();\n    this.addClass('vjs-sliding');\n    /**\n     * Triggered when the slider is in an active state\n     *\n     * @event Slider#slideractive\n     * @type {MouseEvent}\n     */\n    this.trigger('slideractive');\n    this.on(doc, 'mousemove', this.handleMouseMove_);\n    this.on(doc, 'mouseup', this.handleMouseUp_);\n    this.on(doc, 'touchmove', this.handleMouseMove_);\n    this.on(doc, 'touchend', this.handleMouseUp_);\n    this.handleMouseMove(event, true);\n  }\n\n  /**\n   * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.\n   * The `mousemove` and `touchmove` events will only only trigger this function during\n   * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and\n   * {@link Slider#handleMouseUp}.\n   *\n   * @param {MouseEvent} event\n   *        `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered\n   *        this function\n   * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false.\n   *\n   * @listens mousemove\n   * @listens touchmove\n   */\n  handleMouseMove(event) {}\n\n  /**\n   * Handle `mouseup` or `touchend` events on the `Slider`.\n   *\n   * @param {MouseEvent} event\n   *        `mouseup` or `touchend` event that triggered this function.\n   *\n   * @listens touchend\n   * @listens mouseup\n   * @fires Slider#sliderinactive\n   */\n  handleMouseUp(event) {\n    const doc = this.bar.el_.ownerDocument;\n    unblockTextSelection();\n    this.removeClass('vjs-sliding');\n    /**\n     * Triggered when the slider is no longer in an active state.\n     *\n     * @event Slider#sliderinactive\n     * @type {Event}\n     */\n    this.trigger('sliderinactive');\n    this.off(doc, 'mousemove', this.handleMouseMove_);\n    this.off(doc, 'mouseup', this.handleMouseUp_);\n    this.off(doc, 'touchmove', this.handleMouseMove_);\n    this.off(doc, 'touchend', this.handleMouseUp_);\n    this.update();\n  }\n\n  /**\n   * Update the progress bar of the `Slider`.\n   *\n   * @return {number}\n   *          The percentage of progress the progress bar represents as a\n   *          number from 0 to 1.\n   */\n  update() {\n    // In VolumeBar init we have a setTimeout for update that pops and update\n    // to the end of the execution stack. The player is destroyed before then\n    // update will cause an error\n    // If there's no bar...\n    if (!this.el_ || !this.bar) {\n      return;\n    }\n\n    // clamp progress between 0 and 1\n    // and only round to four decimal places, as we round to two below\n    const progress = this.getProgress();\n    if (progress === this.progress_) {\n      return progress;\n    }\n    this.progress_ = progress;\n    this.requestNamedAnimationFrame('Slider#update', () => {\n      // Set the new bar width or height\n      const sizeKey = this.vertical() ? 'height' : 'width';\n\n      // Convert to a percentage for css value\n      this.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';\n    });\n    return progress;\n  }\n\n  /**\n   * Get the percentage of the bar that should be filled\n   * but clamped and rounded.\n   *\n   * @return {number}\n   *         percentage filled that the slider is\n   */\n  getProgress() {\n    return Number(clamp(this.getPercent(), 0, 1).toFixed(4));\n  }\n\n  /**\n   * Calculate distance for slider\n   *\n   * @param {Event} event\n   *        The event that caused this function to run.\n   *\n   * @return {number}\n   *         The current position of the Slider.\n   *         - position.x for vertical `Slider`s\n   *         - position.y for horizontal `Slider`s\n   */\n  calculateDistance(event) {\n    const position = getPointerPosition(this.el_, event);\n    if (this.vertical()) {\n      return position.y;\n    }\n    return position.x;\n  }\n\n  /**\n   * Handle a `keydown` event on the `Slider`. Watches for left, right, up, and down\n   * arrow keys. This function will only be called when the slider has focus. See\n   * {@link Slider#handleFocus} and {@link Slider#handleBlur}.\n   *\n   * @param {KeyboardEvent} event\n   *        the `keydown` event that caused this function to run.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    const spatialNavOptions = this.options_.playerOptions.spatialNavigation;\n    const spatialNavEnabled = spatialNavOptions && spatialNavOptions.enabled;\n    const horizontalSeek = spatialNavOptions && spatialNavOptions.horizontalSeek;\n    if (spatialNavEnabled) {\n      if (horizontalSeek && event.key === 'ArrowLeft' || !horizontalSeek && event.key === 'ArrowDown') {\n        event.preventDefault();\n        event.stopPropagation();\n        this.stepBack();\n      } else if (horizontalSeek && event.key === 'ArrowRight' || !horizontalSeek && event.key === 'ArrowUp') {\n        event.preventDefault();\n        event.stopPropagation();\n        this.stepForward();\n      } else {\n        if (this.pendingSeekTime()) {\n          this.pendingSeekTime(null);\n          this.userSeek_(this.player_.currentTime());\n        }\n        super.handleKeyDown(event);\n      }\n\n      // Left and Down Arrows\n    } else if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.stepBack();\n\n      // Up and Right Arrows\n    } else if (event.key === 'ArrowUp' || event.key === 'ArrowRight') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.stepForward();\n    } else {\n      // Pass keydown handling up for unsupported keys\n      super.handleKeyDown(event);\n    }\n  }\n\n  /**\n   * Listener for click events on slider, used to prevent clicks\n   *   from bubbling up to parent elements like button menus.\n   *\n   * @param {Object} event\n   *        Event that caused this object to run\n   */\n  handleClick(event) {\n    event.stopPropagation();\n    event.preventDefault();\n  }\n\n  /**\n   * Get/set if slider is horizontal for vertical\n   *\n   * @param {boolean} [bool]\n   *        - true if slider is vertical,\n   *        - false is horizontal\n   *\n   * @return {boolean}\n   *         - true if slider is vertical, and getting\n   *         - false if the slider is horizontal, and getting\n   */\n  vertical(bool) {\n    if (bool === undefined) {\n      return this.vertical_ || false;\n    }\n    this.vertical_ = !!bool;\n    if (this.vertical_) {\n      this.addClass('vjs-slider-vertical');\n    } else {\n      this.addClass('vjs-slider-horizontal');\n    }\n  }\n}\nComponent$1.registerComponent('Slider', Slider);\n\n/**\n * @file load-progress-bar.js\n */\n\n/** @import Player from '../../player' */\n\n// get the percent width of a time compared to the total end\nconst percentify = (time, end) => clamp(time / end * 100, 0, 100).toFixed(2) + '%';\n\n/**\n * Shows loading progress\n *\n * @extends Component\n */\nclass LoadProgressBar extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.partEls_ = [];\n    this.on(player, 'progress', e => this.update(e));\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    const el = super.createEl('div', {\n      className: 'vjs-load-progress'\n    });\n    const wrapper = createEl('span', {\n      className: 'vjs-control-text'\n    });\n    const loadedText = createEl('span', {\n      textContent: this.localize('Loaded')\n    });\n    const separator = document$1.createTextNode(': ');\n    this.percentageEl_ = createEl('span', {\n      className: 'vjs-control-text-loaded-percentage',\n      textContent: '0%'\n    });\n    el.appendChild(wrapper);\n    wrapper.appendChild(loadedText);\n    wrapper.appendChild(separator);\n    wrapper.appendChild(this.percentageEl_);\n    return el;\n  }\n  dispose() {\n    this.partEls_ = null;\n    this.percentageEl_ = null;\n    super.dispose();\n  }\n\n  /**\n   * Update progress bar\n   *\n   * @param {Event} [event]\n   *        The `progress` event that caused this function to run.\n   *\n   * @listens Player#progress\n   */\n  update(event) {\n    this.requestNamedAnimationFrame('LoadProgressBar#update', () => {\n      const liveTracker = this.player_.liveTracker;\n      const buffered = this.player_.buffered();\n      const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();\n      const bufferedEnd = this.player_.bufferedEnd();\n      const children = this.partEls_;\n      const percent = percentify(bufferedEnd, duration);\n      if (this.percent_ !== percent) {\n        // update the width of the progress bar\n        this.el_.style.width = percent;\n        // update the control-text\n        textContent(this.percentageEl_, percent);\n        this.percent_ = percent;\n      }\n\n      // add child elements to represent the individual buffered time ranges\n      for (let i = 0; i < buffered.length; i++) {\n        const start = buffered.start(i);\n        const end = buffered.end(i);\n        let part = children[i];\n        if (!part) {\n          part = this.el_.appendChild(createEl());\n          children[i] = part;\n        }\n\n        //  only update if changed\n        if (part.dataset.start === start && part.dataset.end === end) {\n          continue;\n        }\n        part.dataset.start = start;\n        part.dataset.end = end;\n\n        // set the percent based on the width of the progress bar (bufferedEnd)\n        part.style.left = percentify(start, bufferedEnd);\n        part.style.width = percentify(end - start, bufferedEnd);\n      }\n\n      // remove unused buffered range elements\n      for (let i = children.length; i > buffered.length; i--) {\n        this.el_.removeChild(children[i - 1]);\n      }\n      children.length = buffered.length;\n    });\n  }\n}\nComponent$1.registerComponent('LoadProgressBar', LoadProgressBar);\n\n/**\n * @file time-tooltip.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * Time tooltips display a time above the progress bar.\n *\n * @extends Component\n */\nclass TimeTooltip extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The {@link Player} that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);\n  }\n\n  /**\n   * Create the time tooltip DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-time-tooltip'\n    }, {\n      'aria-hidden': 'true'\n    });\n  }\n\n  /**\n   * Updates the position of the time tooltip relative to the `SeekBar`.\n   *\n   * @param {Object} seekBarRect\n   *        The `ClientRect` for the {@link SeekBar} element.\n   *\n   * @param {number} seekBarPoint\n   *        A number from 0 to 1, representing a horizontal reference point\n   *        from the left edge of the {@link SeekBar}\n   */\n  update(seekBarRect, seekBarPoint, content) {\n    const tooltipRect = findPosition(this.el_);\n    const playerRect = getBoundingClientRect(this.player_.el());\n    const seekBarPointPx = seekBarRect.width * seekBarPoint;\n\n    // do nothing if either rect isn't available\n    // for example, if the player isn't in the DOM for testing\n    if (!playerRect || !tooltipRect) {\n      return;\n    }\n\n    // This is the space left of the `seekBarPoint` available within the bounds\n    // of the player. We calculate any gap between the left edge of the player\n    // and the left edge of the `SeekBar` and add the number of pixels in the\n    // `SeekBar` before hitting the `seekBarPoint`\n    let spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;\n\n    // This is the space right of the `seekBarPoint` available within the bounds\n    // of the player. We calculate the number of pixels from the `seekBarPoint`\n    // to the right edge of the `SeekBar` and add to that any gap between the\n    // right edge of the `SeekBar` and the player.\n    let spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);\n\n    // spaceRightOfPoint is always NaN for mouse time display\n    // because the seekbarRect does not have a right property. This causes\n    // the mouse tool tip to be truncated when it's close to the right edge of the player.\n    // In such cases, we ignore the `playerRect.right - seekBarRect.right` value when calculating.\n    // For the sake of consistency, we ignore seekBarRect.left - playerRect.left for the left edge.\n    if (!spaceRightOfPoint) {\n      spaceRightOfPoint = seekBarRect.width - seekBarPointPx;\n      spaceLeftOfPoint = seekBarPointPx;\n    }\n    // This is the number of pixels by which the tooltip will need to be pulled\n    // further to the right to center it over the `seekBarPoint`.\n    let pullTooltipBy = tooltipRect.width / 2;\n\n    // Adjust the `pullTooltipBy` distance to the left or right depending on\n    // the results of the space calculations above.\n    if (spaceLeftOfPoint < pullTooltipBy) {\n      pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;\n    } else if (spaceRightOfPoint < pullTooltipBy) {\n      pullTooltipBy = spaceRightOfPoint;\n    }\n\n    // Due to the imprecision of decimal/ratio based calculations and varying\n    // rounding behaviors, there are cases where the spacing adjustment is off\n    // by a pixel or two. This adds insurance to these calculations.\n    if (pullTooltipBy < 0) {\n      pullTooltipBy = 0;\n    } else if (pullTooltipBy > tooltipRect.width) {\n      pullTooltipBy = tooltipRect.width;\n    }\n\n    // prevent small width fluctuations within 0.4px from\n    // changing the value below.\n    // This really helps for live to prevent the play\n    // progress time tooltip from jittering\n    pullTooltipBy = Math.round(pullTooltipBy);\n    this.el_.style.right = `-${pullTooltipBy}px`;\n    this.write(content);\n  }\n\n  /**\n   * Write the time to the tooltip DOM element.\n   *\n   * @param {string} content\n   *        The formatted time for the tooltip.\n   */\n  write(content) {\n    textContent(this.el_, content);\n  }\n\n  /**\n   * Updates the position of the time tooltip relative to the `SeekBar`.\n   *\n   * @param {Object} seekBarRect\n   *        The `ClientRect` for the {@link SeekBar} element.\n   *\n   * @param {number} seekBarPoint\n   *        A number from 0 to 1, representing a horizontal reference point\n   *        from the left edge of the {@link SeekBar}\n   *\n   * @param {number} time\n   *        The time to update the tooltip to, not used during live playback\n   *\n   * @param {Function} cb\n   *        A function that will be called during the request animation frame\n   *        for tooltips that need to do additional animations from the default\n   */\n  updateTime(seekBarRect, seekBarPoint, time, cb) {\n    this.requestNamedAnimationFrame('TimeTooltip#updateTime', () => {\n      let content;\n      const duration = this.player_.duration();\n      if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {\n        const liveWindow = this.player_.liveTracker.liveWindow();\n        const secondsBehind = liveWindow - seekBarPoint * liveWindow;\n        content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);\n      } else {\n        content = formatTime(time, duration);\n      }\n      this.update(seekBarRect, seekBarPoint, content);\n      if (cb) {\n        cb();\n      }\n    });\n  }\n}\nComponent$1.registerComponent('TimeTooltip', TimeTooltip);\n\n/**\n * @file play-progress-bar.js\n */\n\n/**\n * Used by {@link SeekBar} to display media playback progress as part of the\n * {@link ProgressControl}.\n *\n * @extends Component\n */\nclass PlayProgressBar extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The {@link Player} that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.setIcon('circle');\n    this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);\n  }\n\n  /**\n   * Create the the DOM element for this class.\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-play-progress vjs-slider-bar'\n    }, {\n      'aria-hidden': 'true'\n    });\n  }\n\n  /**\n   * Enqueues updates to its own DOM as well as the DOM of its\n   * {@link TimeTooltip} child.\n   *\n   * @param {Object} seekBarRect\n   *        The `ClientRect` for the {@link SeekBar} element.\n   *\n   * @param {number} seekBarPoint\n   *        A number from 0 to 1, representing a horizontal reference point\n   *        from the left edge of the {@link SeekBar}\n   *\n   * @param {Event} [event]\n   *        The `timeupdate` event that caused this function to run.\n   */\n  update(seekBarRect, seekBarPoint, event) {\n    const timeTooltip = this.getChild('timeTooltip');\n    if (!timeTooltip) {\n      return;\n    }\n\n    // Combined logic: if an event with a valid pendingSeekTime getter exists, use it.\n    const time = event && event.target && typeof event.target.pendingSeekTime === 'function' ? event.target.pendingSeekTime() : this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();\n    timeTooltip.updateTime(seekBarRect, seekBarPoint, time);\n  }\n}\n\n/**\n * Default options for {@link PlayProgressBar}.\n *\n * @type {Object}\n * @private\n */\nPlayProgressBar.prototype.options_ = {\n  children: []\n};\n\n// Time tooltips should not be added to a player on mobile devices\nif (!IS_IOS && !IS_ANDROID) {\n  PlayProgressBar.prototype.options_.children.push('timeTooltip');\n}\nComponent$1.registerComponent('PlayProgressBar', PlayProgressBar);\n\n/**\n * @file mouse-time-display.js\n */\n\n/**\n * The {@link MouseTimeDisplay} component tracks mouse movement over the\n * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}\n * indicating the time which is represented by a given point in the\n * {@link ProgressControl}.\n *\n * @extends Component\n */\nclass MouseTimeDisplay extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The {@link Player} that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);\n  }\n\n  /**\n   * Create the DOM element for this class.\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-mouse-display'\n    });\n  }\n\n  /**\n   * Enqueues updates to its own DOM as well as the DOM of its\n   * {@link TimeTooltip} child.\n   *\n   * @param {Object} seekBarRect\n   *        The `ClientRect` for the {@link SeekBar} element.\n   *\n   * @param {number} seekBarPoint\n   *        A number from 0 to 1, representing a horizontal reference point\n   *        from the left edge of the {@link SeekBar}\n   */\n  update(seekBarRect, seekBarPoint) {\n    const time = seekBarPoint * this.player_.duration();\n    this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, () => {\n      this.el_.style.left = `${seekBarRect.width * seekBarPoint}px`;\n    });\n  }\n}\n\n/**\n * Default options for `MouseTimeDisplay`\n *\n * @type {Object}\n * @private\n */\nMouseTimeDisplay.prototype.options_ = {\n  children: ['timeTooltip']\n};\nComponent$1.registerComponent('MouseTimeDisplay', MouseTimeDisplay);\n\n/**\n * @file seek-bar.js\n */\n\n/**\n * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}\n * as its `bar`.\n *\n * @extends Slider\n */\nclass SeekBar extends Slider {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   * @param {number} [options.stepSeconds=5]\n   *        The number of seconds to increment on keyboard control\n   * @param {number} [options.pageMultiplier=12]\n   *        The multiplier of stepSeconds that PgUp/PgDown move the timeline.\n   */\n  constructor(player, options) {\n    options = merge$1(SeekBar.prototype.options_, options);\n\n    // Avoid mutating the prototype's `children` array by creating a copy\n    options.children = [...options.children];\n    const shouldDisableSeekWhileScrubbing = player.options_.disableSeekWhileScrubbingOnMobile && (IS_IOS || IS_ANDROID) || player.options_.disableSeekWhileScrubbingOnSTV;\n\n    // Add the TimeTooltip as a child if we are on desktop, or on mobile with `disableSeekWhileScrubbingOnMobile: true`\n    if (!IS_IOS && !IS_ANDROID || shouldDisableSeekWhileScrubbing) {\n      options.children.splice(1, 0, 'mouseTimeDisplay');\n    }\n    super(player, options);\n    this.shouldDisableSeekWhileScrubbing_ = shouldDisableSeekWhileScrubbing;\n    this.pendingSeekTime_ = null;\n    this.setEventHandlers_();\n  }\n\n  /**\n   * Sets the event handlers\n   *\n   * @private\n   */\n  setEventHandlers_() {\n    this.update_ = bind_(this, this.update);\n    this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);\n    this.on(this.player_, ['durationchange', 'timeupdate'], this.update);\n    this.on(this.player_, ['ended'], this.update_);\n    if (this.player_.liveTracker) {\n      this.on(this.player_.liveTracker, 'liveedgechange', this.update);\n    }\n\n    // when playing, let's ensure we smoothly update the play progress bar\n    // via an interval\n    this.updateInterval = null;\n    this.enableIntervalHandler_ = e => this.enableInterval_(e);\n    this.disableIntervalHandler_ = e => this.disableInterval_(e);\n    this.on(this.player_, ['playing'], this.enableIntervalHandler_);\n    this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);\n\n    // we don't need to update the play progress if the document is hidden,\n    // also, this causes the CPU to spike and eventually crash the page on IE11.\n    if ('hidden' in document$1 && 'visibilityState' in document$1) {\n      this.on(document$1, 'visibilitychange', this.toggleVisibility_);\n    }\n  }\n  toggleVisibility_(e) {\n    if (document$1.visibilityState === 'hidden') {\n      this.cancelNamedAnimationFrame('SeekBar#update');\n      this.cancelNamedAnimationFrame('Slider#update');\n      this.disableInterval_(e);\n    } else {\n      if (!this.player_.ended() && !this.player_.paused()) {\n        this.enableInterval_();\n      }\n\n      // we just switched back to the page and someone may be looking, so, update ASAP\n      this.update();\n    }\n  }\n  enableInterval_() {\n    if (this.updateInterval) {\n      return;\n    }\n    this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);\n  }\n  disableInterval_(e) {\n    if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {\n      return;\n    }\n    if (!this.updateInterval) {\n      return;\n    }\n    this.clearInterval(this.updateInterval);\n    this.updateInterval = null;\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-progress-holder'\n    }, {\n      'aria-label': this.localize('Progress Bar')\n    });\n  }\n\n  /**\n   * This function updates the play progress bar and accessibility\n   * attributes to whatever is passed in.\n   *\n   * @param {Event} [event]\n   *        The `timeupdate` or `ended` event that caused this to run.\n   *\n   * @listens Player#timeupdate\n   *\n   * @return {number}\n   *          The current percent at a number from 0-1\n   */\n  update(event) {\n    // ignore updates while the tab is hidden\n    if (document$1.visibilityState === 'hidden') {\n      return;\n    }\n    const percent = super.update();\n    this.requestNamedAnimationFrame('SeekBar#update', () => {\n      const currentTime = this.player_.ended() ? this.player_.duration() : this.getCurrentTime_();\n      const liveTracker = this.player_.liveTracker;\n      let duration = this.player_.duration();\n      if (liveTracker && liveTracker.isLive()) {\n        duration = this.player_.liveTracker.liveCurrentTime();\n      }\n      if (this.percent_ !== percent) {\n        // machine readable value of progress bar (percentage complete)\n        this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));\n        this.percent_ = percent;\n      }\n      if (this.currentTime_ !== currentTime || this.duration_ !== duration) {\n        // human readable value of progress bar (time complete)\n        this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));\n        this.currentTime_ = currentTime;\n        this.duration_ = duration;\n      }\n\n      // update the progress bar time tooltip with the current time\n      if (this.bar) {\n        this.bar.update(getBoundingClientRect(this.el()), this.getProgress(), event);\n      }\n    });\n    return percent;\n  }\n\n  /**\n   * Prevent liveThreshold from causing seeks to seem like they\n   * are not happening from a user perspective.\n   *\n   * @param {number} ct\n   *        current time to seek to\n   */\n  userSeek_(ct) {\n    if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {\n      this.player_.liveTracker.nextSeekedFromUser();\n    }\n    this.player_.currentTime(ct);\n  }\n\n  /**\n   * Get the value of current time but allows for smooth scrubbing,\n   * when player can't keep up.\n   *\n   * @return {number}\n   *         The current time value to display\n   *\n   * @private\n   */\n  getCurrentTime_() {\n    return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();\n  }\n\n  /**\n   * Getter and setter for pendingSeekTime.\n   * Ensures the value is clamped between 0 and duration.\n   *\n   * @param {number|null} [time] - Optional. The new pending seek time, can be a number or null.\n   * @return {number|null} - The current pending seek time.\n   */\n  pendingSeekTime(time) {\n    if (time !== undefined) {\n      if (time !== null) {\n        const duration = this.player_.duration();\n        this.pendingSeekTime_ = Math.max(0, Math.min(time, duration));\n      } else {\n        this.pendingSeekTime_ = null;\n      }\n    }\n    return this.pendingSeekTime_;\n  }\n\n  /**\n   * Get the percentage of media played so far.\n   *\n   * @return {number}\n   *         The percentage of media played so far (0 to 1).\n   */\n  getPercent() {\n    // If we have a pending seek time, we are scrubbing on mobile and should set the slider percent\n    // to reflect the current scrub location.\n    if (this.pendingSeekTime() !== null) {\n      return this.pendingSeekTime() / this.player_.duration();\n    }\n    const currentTime = this.getCurrentTime_();\n    let percent;\n    const liveTracker = this.player_.liveTracker;\n    if (liveTracker && liveTracker.isLive()) {\n      percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();\n\n      // prevent the percent from changing at the live edge\n      if (liveTracker.atLiveEdge()) {\n        percent = 1;\n      }\n    } else {\n      percent = currentTime / this.player_.duration();\n    }\n    return percent;\n  }\n\n  /**\n   * Handle mouse down on seek bar\n   *\n   * @param {MouseEvent} event\n   *        The `mousedown` event that caused this to run.\n   *\n   * @listens mousedown\n   */\n  handleMouseDown(event) {\n    if (!isSingleLeftClick(event)) {\n      return;\n    }\n\n    // Stop event propagation to prevent double fire in progress-control.js\n    event.stopPropagation();\n    this.videoWasPlaying = !this.player_.paused();\n\n    // Don't pause if we are on mobile and `disableSeekWhileScrubbingOnMobile: true`.\n    // In that case, playback should continue while the player scrubs to a new location.\n    if (!this.shouldDisableSeekWhileScrubbing_) {\n      this.player_.pause();\n    }\n    super.handleMouseDown(event);\n  }\n\n  /**\n   * Handle mouse move on seek bar\n   *\n   * @param {MouseEvent} event\n   *        The `mousemove` event that caused this to run.\n   * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false\n   *\n   * @listens mousemove\n   */\n  handleMouseMove(event, mouseDown = false) {\n    if (!isSingleLeftClick(event) || isNaN(this.player_.duration())) {\n      return;\n    }\n    if (!mouseDown && !this.player_.scrubbing()) {\n      this.player_.scrubbing(true);\n    }\n    let newTime;\n    const distance = this.calculateDistance(event);\n    const liveTracker = this.player_.liveTracker;\n    if (!liveTracker || !liveTracker.isLive()) {\n      newTime = distance * this.player_.duration();\n\n      // Don't let video end while scrubbing.\n      if (newTime === this.player_.duration()) {\n        newTime = newTime - 0.1;\n      }\n    } else {\n      if (distance >= 0.99) {\n        liveTracker.seekToLiveEdge();\n        return;\n      }\n      const seekableStart = liveTracker.seekableStart();\n      const seekableEnd = liveTracker.liveCurrentTime();\n      newTime = seekableStart + distance * liveTracker.liveWindow();\n\n      // Don't let video end while scrubbing.\n      if (newTime >= seekableEnd) {\n        newTime = seekableEnd;\n      }\n\n      // Compensate for precision differences so that currentTime is not less\n      // than seekable start\n      if (newTime <= seekableStart) {\n        newTime = seekableStart + 0.1;\n      }\n\n      // On android seekableEnd can be Infinity sometimes,\n      // this will cause newTime to be Infinity, which is\n      // not a valid currentTime.\n      if (newTime === Infinity) {\n        return;\n      }\n    }\n\n    // if on mobile and `disableSeekWhileScrubbingOnMobile: true`, keep track of the desired seek point but we won't initiate the seek until 'touchend'\n    if (this.shouldDisableSeekWhileScrubbing_) {\n      this.pendingSeekTime(newTime);\n    } else {\n      this.userSeek_(newTime);\n    }\n    if (this.player_.options_.enableSmoothSeeking) {\n      this.update();\n    }\n  }\n  enable() {\n    super.enable();\n    const mouseTimeDisplay = this.getChild('mouseTimeDisplay');\n    if (!mouseTimeDisplay) {\n      return;\n    }\n    mouseTimeDisplay.show();\n  }\n  disable() {\n    super.disable();\n    const mouseTimeDisplay = this.getChild('mouseTimeDisplay');\n    if (!mouseTimeDisplay) {\n      return;\n    }\n    mouseTimeDisplay.hide();\n  }\n\n  /**\n   * Handle mouse up on seek bar\n   *\n   * @param {MouseEvent} event\n   *        The `mouseup` event that caused this to run.\n   *\n   * @listens mouseup\n   */\n  handleMouseUp(event) {\n    super.handleMouseUp(event);\n\n    // Stop event propagation to prevent double fire in progress-control.js\n    if (event) {\n      event.stopPropagation();\n    }\n    this.player_.scrubbing(false);\n\n    // If we have a pending seek time, then we have finished scrubbing on mobile and should initiate a seek.\n    if (this.pendingSeekTime() !== null) {\n      this.userSeek_(this.pendingSeekTime());\n      this.pendingSeekTime(null);\n    }\n\n    /**\n     * Trigger timeupdate because we're done seeking and the time has changed.\n     * This is particularly useful for if the player is paused to time the time displays.\n     *\n     * @event Tech#timeupdate\n     * @type {Event}\n     */\n    this.player_.trigger({\n      type: 'timeupdate',\n      target: this,\n      manuallyTriggered: true\n    });\n    if (this.videoWasPlaying) {\n      silencePromise(this.player_.play());\n    } else {\n      // We're done seeking and the time has changed.\n      // If the player is paused, make sure we display the correct time on the seek bar.\n      this.update_();\n    }\n  }\n\n  /**\n   * Handles pending seek time when `disableSeekWhileScrubbingOnSTV` is enabled.\n   *\n   * @param {number} stepAmount - The number of seconds to step (positive for forward, negative for backward).\n   */\n  handlePendingSeek_(stepAmount) {\n    if (!this.player_.paused()) {\n      this.player_.pause();\n    }\n    const currentPos = this.pendingSeekTime() !== null ? this.pendingSeekTime() : this.player_.currentTime();\n    this.pendingSeekTime(currentPos + stepAmount);\n    this.player_.trigger({\n      type: 'timeupdate',\n      target: this,\n      manuallyTriggered: true\n    });\n  }\n\n  /**\n   * Move more quickly fast forward for keyboard-only users\n   */\n  stepForward() {\n    // if `disableSeekWhileScrubbingOnSTV: true`, keep track of the desired seek point but we won't initiate the seek\n    if (this.shouldDisableSeekWhileScrubbing_) {\n      this.handlePendingSeek_(this.options().stepSeconds);\n    } else {\n      this.userSeek_(this.player_.currentTime() + this.options().stepSeconds);\n    }\n  }\n\n  /**\n   * Move more quickly rewind for keyboard-only users\n   */\n  stepBack() {\n    // if `disableSeekWhileScrubbingOnSTV: true`, keep track of the desired seek point but we won't initiate the seek\n    if (this.shouldDisableSeekWhileScrubbing_) {\n      this.handlePendingSeek_(-this.options().stepSeconds);\n    } else {\n      this.userSeek_(this.player_.currentTime() - this.options().stepSeconds);\n    }\n  }\n\n  /**\n   * Toggles the playback state of the player\n   * This gets called when enter or space is used on the seekbar\n   *\n   * @param {KeyboardEvent} event\n   *        The `keydown` event that caused this function to be called\n   *\n   */\n  handleAction(event) {\n    if (this.pendingSeekTime() !== null) {\n      this.userSeek_(this.pendingSeekTime());\n      this.pendingSeekTime(null);\n    }\n    if (this.player_.paused()) {\n      this.player_.play();\n    } else {\n      this.player_.pause();\n    }\n  }\n\n  /**\n   * Called when this SeekBar has focus and a key gets pressed down.\n   * Supports the following keys:\n   *\n   *   Space or Enter key fire a click event\n   *   Home key moves to start of the timeline\n   *   End key moves to end of the timeline\n   *   Digit \"0\" through \"9\" keys move to 0%, 10% ... 80%, 90% of the timeline\n   *   PageDown key moves back a larger step than ArrowDown\n   *   PageUp key moves forward a large step\n   *\n   * @param {KeyboardEvent} event\n   *        The `keydown` event that caused this function to be called.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    const liveTracker = this.player_.liveTracker;\n    if (event.key === ' ' || event.key === 'Enter') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.handleAction(event);\n    } else if (event.key === 'Home') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.userSeek_(0);\n    } else if (event.key === 'End') {\n      event.preventDefault();\n      event.stopPropagation();\n      if (liveTracker && liveTracker.isLive()) {\n        this.userSeek_(liveTracker.liveCurrentTime());\n      } else {\n        this.userSeek_(this.player_.duration());\n      }\n    } else if (/^[0-9]$/.test(event.key)) {\n      event.preventDefault();\n      event.stopPropagation();\n      const gotoFraction = parseInt(event.key, 10) * 0.1;\n      if (liveTracker && liveTracker.isLive()) {\n        this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);\n      } else {\n        this.userSeek_(this.player_.duration() * gotoFraction);\n      }\n    } else if (event.key === 'PageDown') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.userSeek_(this.player_.currentTime() - this.options().stepSeconds * this.options().pageMultiplier);\n    } else if (event.key === 'PageUp') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.userSeek_(this.player_.currentTime() + this.options().stepSeconds * this.options().pageMultiplier);\n    } else {\n      // Pass keydown handling up for unsupported keys\n      super.handleKeyDown(event);\n    }\n  }\n  dispose() {\n    this.disableInterval_();\n    this.off(this.player_, ['durationchange', 'timeupdate'], this.update);\n    this.off(this.player_, ['ended'], this.update_);\n    if (this.player_.liveTracker) {\n      this.off(this.player_.liveTracker, 'liveedgechange', this.update);\n    }\n    this.off(this.player_, ['playing'], this.enableIntervalHandler_);\n    this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);\n\n    // we don't need to update the play progress if the document is hidden,\n    // also, this causes the CPU to spike and eventually crash the page on IE11.\n    if ('hidden' in document$1 && 'visibilityState' in document$1) {\n      this.off(document$1, 'visibilitychange', this.toggleVisibility_);\n    }\n    super.dispose();\n  }\n}\n\n/**\n * Default options for the `SeekBar`\n *\n * @type {Object}\n * @private\n */\nSeekBar.prototype.options_ = {\n  children: ['loadProgressBar', 'playProgressBar'],\n  barName: 'playProgressBar',\n  stepSeconds: 5,\n  pageMultiplier: 12\n};\nComponent$1.registerComponent('SeekBar', SeekBar);\n\n/**\n * @file progress-control.js\n */\n\n/**\n * The Progress Control component contains the seek bar, load progress,\n * and play progress.\n *\n * @extends Component\n */\nclass ProgressControl extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.handleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);\n    this.throttledHandleMouseSeek = throttle(bind_(this, this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);\n    this.handleMouseUpHandler_ = e => this.handleMouseUp(e);\n    this.handleMouseDownHandler_ = e => this.handleMouseDown(e);\n    this.enable();\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-progress-control vjs-control'\n    });\n  }\n\n  /**\n   * When the mouse moves over the `ProgressControl`, the pointer position\n   * gets passed down to the `MouseTimeDisplay` component.\n   *\n   * @param {Event} event\n   *        The `mousemove` event that caused this function to run.\n   *\n   * @listen mousemove\n   */\n  handleMouseMove(event) {\n    const seekBar = this.getChild('seekBar');\n    if (!seekBar) {\n      return;\n    }\n    const playProgressBar = seekBar.getChild('playProgressBar');\n    const mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');\n    if (!playProgressBar && !mouseTimeDisplay) {\n      return;\n    }\n    const seekBarEl = seekBar.el();\n    const seekBarRect = findPosition(seekBarEl);\n    let seekBarPoint = getPointerPosition(seekBarEl, event).x;\n\n    // The default skin has a gap on either side of the `SeekBar`. This means\n    // that it's possible to trigger this behavior outside the boundaries of\n    // the `SeekBar`. This ensures we stay within it at all times.\n    seekBarPoint = clamp(seekBarPoint, 0, 1);\n    if (mouseTimeDisplay) {\n      mouseTimeDisplay.update(seekBarRect, seekBarPoint);\n    }\n    if (playProgressBar) {\n      playProgressBar.update(seekBarRect, seekBar.getProgress());\n    }\n  }\n\n  /**\n   * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.\n   *\n   * @method ProgressControl#throttledHandleMouseSeek\n   * @param {Event} event\n   *        The `mousemove` event that caused this function to run.\n   *\n   * @listen mousemove\n   * @listen touchmove\n   */\n\n  /**\n   * Handle `mousemove` or `touchmove` events on the `ProgressControl`.\n   *\n   * @param {Event} event\n   *        `mousedown` or `touchstart` event that triggered this function\n   *\n   * @listens mousemove\n   * @listens touchmove\n   */\n  handleMouseSeek(event) {\n    const seekBar = this.getChild('seekBar');\n    if (seekBar) {\n      seekBar.handleMouseMove(event);\n    }\n  }\n\n  /**\n   * Are controls are currently enabled for this progress control.\n   *\n   * @return {boolean}\n   *         true if controls are enabled, false otherwise\n   */\n  enabled() {\n    return this.enabled_;\n  }\n\n  /**\n   * Disable all controls on the progress control and its children\n   */\n  disable() {\n    this.children().forEach(child => child.disable && child.disable());\n    if (!this.enabled()) {\n      return;\n    }\n    this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);\n    this.off(this.el_, ['mousemove', 'touchmove'], this.handleMouseMove);\n    this.removeListenersAddedOnMousedownAndTouchstart();\n    this.addClass('disabled');\n    this.enabled_ = false;\n\n    // Restore normal playback state if controls are disabled while scrubbing\n    if (this.player_.scrubbing()) {\n      const seekBar = this.getChild('seekBar');\n      this.player_.scrubbing(false);\n      if (seekBar.videoWasPlaying) {\n        silencePromise(this.player_.play());\n      }\n    }\n  }\n\n  /**\n   * Enable all controls on the progress control and its children\n   */\n  enable() {\n    this.children().forEach(child => child.enable && child.enable());\n    if (this.enabled()) {\n      return;\n    }\n    this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);\n    this.on(this.el_, ['mousemove', 'touchmove'], this.handleMouseMove);\n    this.removeClass('disabled');\n    this.enabled_ = true;\n  }\n\n  /**\n   * Cleanup listeners after the user finishes interacting with the progress controls\n   */\n  removeListenersAddedOnMousedownAndTouchstart() {\n    const doc = this.el_.ownerDocument;\n    this.off(doc, 'mousemove', this.throttledHandleMouseSeek);\n    this.off(doc, 'touchmove', this.throttledHandleMouseSeek);\n    this.off(doc, 'mouseup', this.handleMouseUpHandler_);\n    this.off(doc, 'touchend', this.handleMouseUpHandler_);\n  }\n\n  /**\n   * Handle `mousedown` or `touchstart` events on the `ProgressControl`.\n   *\n   * @param {Event} event\n   *        `mousedown` or `touchstart` event that triggered this function\n   *\n   * @listens mousedown\n   * @listens touchstart\n   */\n  handleMouseDown(event) {\n    const doc = this.el_.ownerDocument;\n    const seekBar = this.getChild('seekBar');\n    if (seekBar) {\n      seekBar.handleMouseDown(event);\n    }\n    this.on(doc, 'mousemove', this.throttledHandleMouseSeek);\n    this.on(doc, 'touchmove', this.throttledHandleMouseSeek);\n    this.on(doc, 'mouseup', this.handleMouseUpHandler_);\n    this.on(doc, 'touchend', this.handleMouseUpHandler_);\n  }\n\n  /**\n   * Handle `mouseup` or `touchend` events on the `ProgressControl`.\n   *\n   * @param {Event} event\n   *        `mouseup` or `touchend` event that triggered this function.\n   *\n   * @listens touchend\n   * @listens mouseup\n   */\n  handleMouseUp(event) {\n    const seekBar = this.getChild('seekBar');\n    if (seekBar) {\n      seekBar.handleMouseUp(event);\n    }\n    this.removeListenersAddedOnMousedownAndTouchstart();\n  }\n}\n\n/**\n * Default options for `ProgressControl`\n *\n * @type {Object}\n * @private\n */\nProgressControl.prototype.options_ = {\n  children: ['seekBar']\n};\nComponent$1.registerComponent('ProgressControl', ProgressControl);\n\n/**\n * @file picture-in-picture-toggle.js\n */\n\n/** @import Player from './player' */\n\n/**\n * Toggle Picture-in-Picture mode\n *\n * @extends Button\n */\nclass PictureInPictureToggle extends Button {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @listens Player#enterpictureinpicture\n   * @listens Player#leavepictureinpicture\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.setIcon('picture-in-picture-enter');\n    this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], e => this.handlePictureInPictureChange(e));\n    this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], e => this.handlePictureInPictureEnabledChange(e));\n    this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], () => this.handlePictureInPictureAudioModeChange());\n\n    // TODO: Deactivate button on player emptied event.\n    this.disable();\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * Displays or hides the button depending on the audio mode detection.\n   * Exits picture-in-picture if it is enabled when switching to audio mode.\n   */\n  handlePictureInPictureAudioModeChange() {\n    // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time\n    const isSourceAudio = this.player_.currentType().substring(0, 5) === 'audio';\n    const isAudioMode = isSourceAudio || this.player_.audioPosterMode() || this.player_.audioOnlyMode();\n    if (!isAudioMode) {\n      this.show();\n      return;\n    }\n    if (this.player_.isInPictureInPicture()) {\n      this.player_.exitPictureInPicture();\n    }\n    this.hide();\n  }\n\n  /**\n   * Enables or disables button based on availability of a Picture-In-Picture mode.\n   *\n   * Enabled if\n   * - `player.options().enableDocumentPictureInPicture` is true and\n   *   window.documentPictureInPicture is available; or\n   * - `player.disablePictureInPicture()` is false and\n   *   element.requestPictureInPicture is available\n   */\n  handlePictureInPictureEnabledChange() {\n    if (document$1.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false || this.player_.options_.enableDocumentPictureInPicture && 'documentPictureInPicture' in window$1) {\n      this.enable();\n    } else {\n      this.disable();\n    }\n  }\n\n  /**\n   * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.\n   *\n   * @param {Event} [event]\n   *        The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be\n   *        called.\n   *\n   * @listens Player#enterpictureinpicture\n   * @listens Player#leavepictureinpicture\n   */\n  handlePictureInPictureChange(event) {\n    if (this.player_.isInPictureInPicture()) {\n      this.setIcon('picture-in-picture-exit');\n      this.controlText('Exit Picture-in-Picture');\n    } else {\n      this.setIcon('picture-in-picture-enter');\n      this.controlText('Picture-in-Picture');\n    }\n    this.handlePictureInPictureEnabledChange();\n  }\n\n  /**\n   * This gets called when an `PictureInPictureToggle` is \"clicked\". See\n   * {@link ClickableComponent} for more detailed information on what a click can be.\n   *\n   * @param {Event} [event]\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    if (!this.player_.isInPictureInPicture()) {\n      this.player_.requestPictureInPicture();\n    } else {\n      this.player_.exitPictureInPicture();\n    }\n  }\n\n  /**\n   * Show the `Component`s element if it is hidden by removing the\n   * 'vjs-hidden' class name from it only in browsers that support the Picture-in-Picture API.\n   */\n  show() {\n    // Does not allow to display the pictureInPictureToggle in browsers that do not support the Picture-in-Picture API, e.g. Firefox.\n    if (typeof document$1.exitPictureInPicture !== 'function') {\n      return;\n    }\n    super.show();\n  }\n}\n\n/**\n * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.\n *\n * @type {string}\n * @protected\n */\nPictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';\nComponent$1.registerComponent('PictureInPictureToggle', PictureInPictureToggle);\n\n/**\n * @file fullscreen-toggle.js\n */\n\n/** @import Player from './player' */\n\n/**\n * Toggle fullscreen video\n *\n * @extends Button\n */\nclass FullscreenToggle extends Button {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.setIcon('fullscreen-enter');\n    this.on(player, 'fullscreenchange', e => this.handleFullscreenChange(e));\n    if (document$1[player.fsApi_.fullscreenEnabled] === false) {\n      this.disable();\n    }\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-fullscreen-control ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * Handles fullscreenchange on the player and change control text accordingly.\n   *\n   * @param {Event} [event]\n   *        The {@link Player#fullscreenchange} event that caused this function to be\n   *        called.\n   *\n   * @listens Player#fullscreenchange\n   */\n  handleFullscreenChange(event) {\n    if (this.player_.isFullscreen()) {\n      this.controlText('Exit Fullscreen');\n      this.setIcon('fullscreen-exit');\n    } else {\n      this.controlText('Fullscreen');\n      this.setIcon('fullscreen-enter');\n    }\n  }\n\n  /**\n   * This gets called when an `FullscreenToggle` is \"clicked\". See\n   * {@link ClickableComponent} for more detailed information on what a click can be.\n   *\n   * @param {Event} [event]\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    if (!this.player_.isFullscreen()) {\n      this.player_.requestFullscreen();\n    } else {\n      this.player_.exitFullscreen();\n    }\n  }\n}\n\n/**\n * The text that should display over the `FullscreenToggle`s controls. Added for localization.\n *\n * @type {string}\n * @protected\n */\nFullscreenToggle.prototype.controlText_ = 'Fullscreen';\nComponent$1.registerComponent('FullscreenToggle', FullscreenToggle);\n\n/** @import Component from '../../component' */\n/** @import Player from '../../player' */\n\n/**\n * Check if volume control is supported and if it isn't hide the\n * `Component` that was passed  using the `vjs-hidden` class.\n *\n * @param {Component} self\n *        The component that should be hidden if volume is unsupported\n *\n * @param {Player} player\n *        A reference to the player\n *\n * @private\n */\nconst checkVolumeSupport = function (self, player) {\n  // hide volume controls when they're not supported by the current tech\n  if (player.tech_ && !player.tech_.featuresVolumeControl) {\n    self.addClass('vjs-hidden');\n  }\n  self.on(player, 'loadstart', function () {\n    if (!player.tech_.featuresVolumeControl) {\n      self.addClass('vjs-hidden');\n    } else {\n      self.removeClass('vjs-hidden');\n    }\n  });\n};\n\n/**\n * @file volume-level.js\n */\n\n/**\n * Shows volume level\n *\n * @extends Component\n */\nclass VolumeLevel extends Component$1 {\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    const el = super.createEl('div', {\n      className: 'vjs-volume-level'\n    });\n    this.setIcon('circle', el);\n    el.appendChild(super.createEl('span', {\n      className: 'vjs-control-text'\n    }));\n    return el;\n  }\n}\nComponent$1.registerComponent('VolumeLevel', VolumeLevel);\n\n/**\n * @file volume-level-tooltip.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * Volume level tooltips display a volume above or side by side the volume bar.\n *\n * @extends Component\n */\nclass VolumeLevelTooltip extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The {@link Player} that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);\n  }\n\n  /**\n   * Create the volume tooltip DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-volume-tooltip'\n    }, {\n      'aria-hidden': 'true'\n    });\n  }\n\n  /**\n   * Updates the position of the tooltip relative to the `VolumeBar` and\n   * its content text.\n   *\n   * @param {Object} rangeBarRect\n   *        The `ClientRect` for the {@link VolumeBar} element.\n   *\n   * @param {number} rangeBarPoint\n   *        A number from 0 to 1, representing a horizontal/vertical reference point\n   *        from the left edge of the {@link VolumeBar}\n   *\n   * @param {boolean} vertical\n   *        Referees to the Volume control position\n   *        in the control bar{@link VolumeControl}\n   *\n   */\n  update(rangeBarRect, rangeBarPoint, vertical, content) {\n    if (!vertical) {\n      const tooltipRect = getBoundingClientRect(this.el_);\n      const playerRect = getBoundingClientRect(this.player_.el());\n      const volumeBarPointPx = rangeBarRect.width * rangeBarPoint;\n      if (!playerRect || !tooltipRect) {\n        return;\n      }\n      const spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;\n      const spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);\n      let pullTooltipBy = tooltipRect.width / 2;\n      if (spaceLeftOfPoint < pullTooltipBy) {\n        pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;\n      } else if (spaceRightOfPoint < pullTooltipBy) {\n        pullTooltipBy = spaceRightOfPoint;\n      }\n      if (pullTooltipBy < 0) {\n        pullTooltipBy = 0;\n      } else if (pullTooltipBy > tooltipRect.width) {\n        pullTooltipBy = tooltipRect.width;\n      }\n      this.el_.style.right = `-${pullTooltipBy}px`;\n    }\n    this.write(`${content}%`);\n  }\n\n  /**\n   * Write the volume to the tooltip DOM element.\n   *\n   * @param {string} content\n   *        The formatted volume for the tooltip.\n   */\n  write(content) {\n    textContent(this.el_, content);\n  }\n\n  /**\n   * Updates the position of the volume tooltip relative to the `VolumeBar`.\n   *\n   * @param {Object} rangeBarRect\n   *        The `ClientRect` for the {@link VolumeBar} element.\n   *\n   * @param {number} rangeBarPoint\n   *        A number from 0 to 1, representing a horizontal/vertical reference point\n   *        from the left edge of the {@link VolumeBar}\n   *\n   * @param {boolean} vertical\n   *        Referees to the Volume control position\n   *        in the control bar{@link VolumeControl}\n   *\n   * @param {number} volume\n   *        The volume level to update the tooltip to\n   *\n   * @param {Function} cb\n   *        A function that will be called during the request animation frame\n   *        for tooltips that need to do additional animations from the default\n   */\n  updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {\n    this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', () => {\n      this.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));\n      if (cb) {\n        cb();\n      }\n    });\n  }\n}\nComponent$1.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);\n\n/**\n * @file mouse-volume-level-display.js\n */\n\n/**\n * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the\n * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}\n * indicating the volume level which is represented by a given point in the\n * {@link VolumeBar}.\n *\n * @extends Component\n */\nclass MouseVolumeLevelDisplay extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The {@link Player} that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);\n  }\n\n  /**\n   * Create the DOM element for this class.\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-mouse-display'\n    });\n  }\n\n  /**\n   * Enquires updates to its own DOM as well as the DOM of its\n   * {@link VolumeLevelTooltip} child.\n   *\n   * @param {Object} rangeBarRect\n   *        The `ClientRect` for the {@link VolumeBar} element.\n   *\n   * @param {number} rangeBarPoint\n   *        A number from 0 to 1, representing a horizontal/vertical reference point\n   *        from the left edge of the {@link VolumeBar}\n   *\n   * @param {boolean} vertical\n   *        Referees to the Volume control position\n   *        in the control bar{@link VolumeControl}\n   *\n   */\n  update(rangeBarRect, rangeBarPoint, vertical) {\n    const volume = 100 * rangeBarPoint;\n    this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, () => {\n      if (vertical) {\n        this.el_.style.bottom = `${rangeBarRect.height * rangeBarPoint}px`;\n      } else {\n        this.el_.style.left = `${rangeBarRect.width * rangeBarPoint}px`;\n      }\n    });\n  }\n}\n\n/**\n * Default options for `MouseVolumeLevelDisplay`\n *\n * @type {Object}\n * @private\n */\nMouseVolumeLevelDisplay.prototype.options_ = {\n  children: ['volumeLevelTooltip']\n};\nComponent$1.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);\n\n/**\n * @file volume-bar.js\n */\n\n/**\n * The bar that contains the volume level and can be clicked on to adjust the level\n *\n * @extends Slider\n */\nclass VolumeBar extends Slider {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.on('slideractive', e => this.updateLastVolume_(e));\n    this.on(player, 'volumechange', e => this.updateARIAAttributes(e));\n    player.ready(() => this.updateARIAAttributes());\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-volume-bar vjs-slider-bar'\n    }, {\n      'aria-label': this.localize('Volume Level'),\n      'aria-live': 'polite'\n    });\n  }\n\n  /**\n   * Handle mouse down on volume bar\n   *\n   * @param {Event} event\n   *        The `mousedown` event that caused this to run.\n   *\n   * @listens mousedown\n   */\n  handleMouseDown(event) {\n    if (!isSingleLeftClick(event)) {\n      return;\n    }\n    super.handleMouseDown(event);\n  }\n\n  /**\n   * Handle movement events on the {@link VolumeMenuButton}.\n   *\n   * @param {Event} event\n   *        The event that caused this function to run.\n   *\n   * @listens mousemove\n   */\n  handleMouseMove(event) {\n    const mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');\n    if (mouseVolumeLevelDisplay) {\n      const volumeBarEl = this.el();\n      const volumeBarRect = getBoundingClientRect(volumeBarEl);\n      const vertical = this.vertical();\n      let volumeBarPoint = getPointerPosition(volumeBarEl, event);\n      volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;\n      // The default skin has a gap on either side of the `VolumeBar`. This means\n      // that it's possible to trigger this behavior outside the boundaries of\n      // the `VolumeBar`. This ensures we stay within it at all times.\n      volumeBarPoint = clamp(volumeBarPoint, 0, 1);\n      mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);\n    }\n    if (!isSingleLeftClick(event)) {\n      return;\n    }\n    this.checkMuted();\n    this.player_.volume(this.calculateDistance(event));\n  }\n\n  /**\n   * If the player is muted unmute it.\n   */\n  checkMuted() {\n    if (this.player_.muted()) {\n      this.player_.muted(false);\n    }\n  }\n\n  /**\n   * Get percent of volume level\n   *\n   * @return {number}\n   *         Volume level percent as a decimal number.\n   */\n  getPercent() {\n    if (this.player_.muted()) {\n      return 0;\n    }\n    return this.player_.volume();\n  }\n\n  /**\n   * Increase volume level for keyboard users\n   */\n  stepForward() {\n    this.checkMuted();\n    this.player_.volume(this.player_.volume() + 0.1);\n  }\n\n  /**\n   * Decrease volume level for keyboard users\n   */\n  stepBack() {\n    this.checkMuted();\n    this.player_.volume(this.player_.volume() - 0.1);\n  }\n\n  /**\n   * Update ARIA accessibility attributes\n   *\n   * @param {Event} [event]\n   *        The `volumechange` event that caused this function to run.\n   *\n   * @listens Player#volumechange\n   */\n  updateARIAAttributes(event) {\n    const ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();\n    this.el_.setAttribute('aria-valuenow', ariaValue);\n    this.el_.setAttribute('aria-valuetext', ariaValue + '%');\n  }\n\n  /**\n   * Returns the current value of the player volume as a percentage\n   *\n   * @private\n   */\n  volumeAsPercentage_() {\n    return Math.round(this.player_.volume() * 100);\n  }\n\n  /**\n   * When user starts dragging the VolumeBar, store the volume and listen for\n   * the end of the drag. When the drag ends, if the volume was set to zero,\n   * set lastVolume to the stored volume.\n   *\n   * @listens slideractive\n   * @private\n   */\n  updateLastVolume_() {\n    const volumeBeforeDrag = this.player_.volume();\n    this.one('sliderinactive', () => {\n      if (this.player_.volume() === 0) {\n        this.player_.lastVolume_(volumeBeforeDrag);\n      }\n    });\n  }\n}\n\n/**\n * Default options for the `VolumeBar`\n *\n * @type {Object}\n * @private\n */\nVolumeBar.prototype.options_ = {\n  children: ['volumeLevel'],\n  barName: 'volumeLevel'\n};\n\n// MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices\nif (!IS_IOS && !IS_ANDROID) {\n  VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');\n}\n\n/**\n * Call the update event for this Slider when this event happens on the player.\n *\n * @type {string}\n */\nVolumeBar.prototype.playerEvent = 'volumechange';\nComponent$1.registerComponent('VolumeBar', VolumeBar);\n\n/**\n * @file volume-control.js\n */\n\n/**\n * The component for controlling the volume level\n *\n * @extends Component\n */\nclass VolumeControl extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options={}]\n   *        The key/value store of player options.\n   */\n  constructor(player, options = {}) {\n    options.vertical = options.vertical || false;\n\n    // Pass the vertical option down to the VolumeBar if\n    // the VolumeBar is turned on.\n    if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {\n      options.volumeBar = options.volumeBar || {};\n      options.volumeBar.vertical = options.vertical;\n    }\n    super(player, options);\n\n    // hide this control if volume support is missing\n    checkVolumeSupport(this, player);\n    this.throttledHandleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);\n    this.handleMouseUpHandler_ = e => this.handleMouseUp(e);\n    this.on('mousedown', e => this.handleMouseDown(e));\n    this.on('touchstart', e => this.handleMouseDown(e));\n    this.on('mousemove', e => this.handleMouseMove(e));\n\n    // while the slider is active (the mouse has been pressed down and\n    // is dragging) or in focus we do not want to hide the VolumeBar\n    this.on(this.volumeBar, ['focus', 'slideractive'], () => {\n      this.volumeBar.addClass('vjs-slider-active');\n      this.addClass('vjs-slider-active');\n      this.trigger('slideractive');\n    });\n    this.on(this.volumeBar, ['blur', 'sliderinactive'], () => {\n      this.volumeBar.removeClass('vjs-slider-active');\n      this.removeClass('vjs-slider-active');\n      this.trigger('sliderinactive');\n    });\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    let orientationClass = 'vjs-volume-horizontal';\n    if (this.options_.vertical) {\n      orientationClass = 'vjs-volume-vertical';\n    }\n    return super.createEl('div', {\n      className: `vjs-volume-control vjs-control ${orientationClass}`\n    });\n  }\n\n  /**\n   * Handle `mousedown` or `touchstart` events on the `VolumeControl`.\n   *\n   * @param {Event} event\n   *        `mousedown` or `touchstart` event that triggered this function\n   *\n   * @listens mousedown\n   * @listens touchstart\n   */\n  handleMouseDown(event) {\n    const doc = this.el_.ownerDocument;\n    this.on(doc, 'mousemove', this.throttledHandleMouseMove);\n    this.on(doc, 'touchmove', this.throttledHandleMouseMove);\n    this.on(doc, 'mouseup', this.handleMouseUpHandler_);\n    this.on(doc, 'touchend', this.handleMouseUpHandler_);\n  }\n\n  /**\n   * Handle `mouseup` or `touchend` events on the `VolumeControl`.\n   *\n   * @param {Event} event\n   *        `mouseup` or `touchend` event that triggered this function.\n   *\n   * @listens touchend\n   * @listens mouseup\n   */\n  handleMouseUp(event) {\n    const doc = this.el_.ownerDocument;\n    this.off(doc, 'mousemove', this.throttledHandleMouseMove);\n    this.off(doc, 'touchmove', this.throttledHandleMouseMove);\n    this.off(doc, 'mouseup', this.handleMouseUpHandler_);\n    this.off(doc, 'touchend', this.handleMouseUpHandler_);\n  }\n\n  /**\n   * Handle `mousedown` or `touchstart` events on the `VolumeControl`.\n   *\n   * @param {Event} event\n   *        `mousedown` or `touchstart` event that triggered this function\n   *\n   * @listens mousedown\n   * @listens touchstart\n   */\n  handleMouseMove(event) {\n    this.volumeBar.handleMouseMove(event);\n  }\n}\n\n/**\n * Default options for the `VolumeControl`\n *\n * @type {Object}\n * @private\n */\nVolumeControl.prototype.options_ = {\n  children: ['volumeBar']\n};\nComponent$1.registerComponent('VolumeControl', VolumeControl);\n\n/** @import Component from '../../component' */\n/** @import Player from '../../player' */\n\n/**\n * Check if muting volume is supported and if it isn't hide the mute toggle\n * button.\n *\n * @param {Component} self\n *        A reference to the mute toggle button\n *\n * @param {Player} player\n *        A reference to the player\n *\n * @private\n */\nconst checkMuteSupport = function (self, player) {\n  // hide mute toggle button if it's not supported by the current tech\n  if (player.tech_ && !player.tech_.featuresMuteControl) {\n    self.addClass('vjs-hidden');\n  }\n  self.on(player, 'loadstart', function () {\n    if (!player.tech_.featuresMuteControl) {\n      self.addClass('vjs-hidden');\n    } else {\n      self.removeClass('vjs-hidden');\n    }\n  });\n};\n\n/**\n * @file mute-toggle.js\n */\n\n/** @import Player from './player' */\n\n/**\n * A button component for muting the audio.\n *\n * @extends Button\n */\nclass MuteToggle extends Button {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n\n    // hide this control if volume support is missing\n    checkMuteSupport(this, player);\n    this.on(player, ['loadstart', 'volumechange'], e => this.update(e));\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-mute-control ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * This gets called when an `MuteToggle` is \"clicked\". See\n   * {@link ClickableComponent} for more detailed information on what a click can be.\n   *\n   * @param {Event} [event]\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    const vol = this.player_.volume();\n    const lastVolume = this.player_.lastVolume_();\n    if (vol === 0) {\n      const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;\n      this.player_.volume(volumeToSet);\n      this.player_.muted(false);\n    } else {\n      this.player_.muted(this.player_.muted() ? false : true);\n    }\n  }\n\n  /**\n   * Update the `MuteToggle` button based on the state of `volume` and `muted`\n   * on the player.\n   *\n   * @param {Event} [event]\n   *        The {@link Player#loadstart} event if this function was called\n   *        through an event.\n   *\n   * @listens Player#loadstart\n   * @listens Player#volumechange\n   */\n  update(event) {\n    this.updateIcon_();\n    this.updateControlText_();\n  }\n\n  /**\n   * Update the appearance of the `MuteToggle` icon.\n   *\n   * Possible states (given `level` variable below):\n   * - 0: crossed out\n   * - 1: zero bars of volume\n   * - 2: one bar of volume\n   * - 3: two bars of volume\n   *\n   * @private\n   */\n  updateIcon_() {\n    const vol = this.player_.volume();\n    let level = 3;\n    this.setIcon('volume-high');\n\n    // in iOS when a player is loaded with muted attribute\n    // and volume is changed with a native mute button\n    // we want to make sure muted state is updated\n    if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {\n      this.player_.muted(this.player_.tech_.el_.muted);\n    }\n    if (vol === 0 || this.player_.muted()) {\n      this.setIcon('volume-mute');\n      level = 0;\n    } else if (vol < 0.33) {\n      this.setIcon('volume-low');\n      level = 1;\n    } else if (vol < 0.67) {\n      this.setIcon('volume-medium');\n      level = 2;\n    }\n    removeClass(this.el_, [0, 1, 2, 3].reduce((str, i) => str + `${i ? ' ' : ''}vjs-vol-${i}`, ''));\n    addClass(this.el_, `vjs-vol-${level}`);\n  }\n\n  /**\n   * If `muted` has changed on the player, update the control text\n   * (`title` attribute on `vjs-mute-control` element and content of\n   * `vjs-control-text` element).\n   *\n   * @private\n   */\n  updateControlText_() {\n    const soundOff = this.player_.muted() || this.player_.volume() === 0;\n    const text = soundOff ? 'Unmute' : 'Mute';\n    if (this.controlText() !== text) {\n      this.controlText(text);\n    }\n  }\n}\n\n/**\n * The text that should display over the `MuteToggle`s controls. Added for localization.\n *\n * @type {string}\n * @protected\n */\nMuteToggle.prototype.controlText_ = 'Mute';\nComponent$1.registerComponent('MuteToggle', MuteToggle);\n\n/**\n * @file volume-control.js\n */\n\n/**\n * A Component to contain the MuteToggle and VolumeControl so that\n * they can work together.\n *\n * @extends Component\n */\nclass VolumePanel extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options={}]\n   *        The key/value store of player options.\n   */\n  constructor(player, options = {}) {\n    if (typeof options.inline !== 'undefined') {\n      options.inline = options.inline;\n    } else {\n      options.inline = true;\n    }\n\n    // pass the inline option down to the VolumeControl as vertical if\n    // the VolumeControl is on.\n    if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {\n      options.volumeControl = options.volumeControl || {};\n      options.volumeControl.vertical = !options.inline;\n    }\n    super(player, options);\n\n    // this handler is used by mouse handler methods below\n    this.handleKeyPressHandler_ = e => this.handleKeyPress(e);\n    this.on(player, ['loadstart'], e => this.volumePanelState_(e));\n    this.on(this.muteToggle, 'keyup', e => this.handleKeyPress(e));\n    this.on(this.volumeControl, 'keyup', e => this.handleVolumeControlKeyUp(e));\n    this.on('keydown', e => this.handleKeyPress(e));\n    this.on('mouseover', e => this.handleMouseOver(e));\n    this.on('mouseout', e => this.handleMouseOut(e));\n\n    // while the slider is active (the mouse has been pressed down and\n    // is dragging) we do not want to hide the VolumeBar\n    this.on(this.volumeControl, ['slideractive'], this.sliderActive_);\n    this.on(this.volumeControl, ['sliderinactive'], this.sliderInactive_);\n  }\n\n  /**\n   * Add vjs-slider-active class to the VolumePanel\n   *\n   * @listens VolumeControl#slideractive\n   * @private\n   */\n  sliderActive_() {\n    this.addClass('vjs-slider-active');\n  }\n\n  /**\n   * Removes vjs-slider-active class to the VolumePanel\n   *\n   * @listens VolumeControl#sliderinactive\n   * @private\n   */\n  sliderInactive_() {\n    this.removeClass('vjs-slider-active');\n  }\n\n  /**\n   * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel\n   * depending on MuteToggle and VolumeControl state\n   *\n   * @listens Player#loadstart\n   * @private\n   */\n  volumePanelState_() {\n    // hide volume panel if neither volume control or mute toggle\n    // are displayed\n    if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {\n      this.addClass('vjs-hidden');\n    }\n\n    // if only mute toggle is visible we don't want\n    // volume panel expanding when hovered or active\n    if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {\n      this.addClass('vjs-mute-toggle-only');\n    }\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    let orientationClass = 'vjs-volume-panel-horizontal';\n    if (!this.options_.inline) {\n      orientationClass = 'vjs-volume-panel-vertical';\n    }\n    return super.createEl('div', {\n      className: `vjs-volume-panel vjs-control ${orientationClass}`\n    });\n  }\n\n  /**\n   * Dispose of the `volume-panel` and all child components.\n   */\n  dispose() {\n    this.handleMouseOut();\n    super.dispose();\n  }\n\n  /**\n   * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes\n   * the volume panel and sets focus on `MuteToggle`.\n   *\n   * @param {Event} event\n   *        The `keyup` event that caused this function to be called.\n   *\n   * @listens keyup\n   */\n  handleVolumeControlKeyUp(event) {\n    if (event.key === 'Escape') {\n      this.muteToggle.focus();\n    }\n  }\n\n  /**\n   * This gets called when a `VolumePanel` gains hover via a `mouseover` event.\n   * Turns on listening for `mouseover` event. When they happen it\n   * calls `this.handleMouseOver`.\n   *\n   * @param {Event} event\n   *        The `mouseover` event that caused this function to be called.\n   *\n   * @listens mouseover\n   */\n  handleMouseOver(event) {\n    this.addClass('vjs-hover');\n    on(document$1, 'keyup', this.handleKeyPressHandler_);\n  }\n\n  /**\n   * This gets called when a `VolumePanel` gains hover via a `mouseout` event.\n   * Turns on listening for `mouseout` event. When they happen it\n   * calls `this.handleMouseOut`.\n   *\n   * @param {Event} event\n   *        The `mouseout` event that caused this function to be called.\n   *\n   * @listens mouseout\n   */\n  handleMouseOut(event) {\n    this.removeClass('vjs-hover');\n    off(document$1, 'keyup', this.handleKeyPressHandler_);\n  }\n\n  /**\n   * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,\n   * looking for ESC, which hides the `VolumeControl`.\n   *\n   * @param {Event} event\n   *        The keypress that triggered this event.\n   *\n   * @listens keydown | keyup\n   */\n  handleKeyPress(event) {\n    if (event.key === 'Escape') {\n      this.handleMouseOut();\n    }\n  }\n}\n\n/**\n * Default options for the `VolumeControl`\n *\n * @type {Object}\n * @private\n */\nVolumePanel.prototype.options_ = {\n  children: ['muteToggle', 'volumeControl']\n};\nComponent$1.registerComponent('VolumePanel', VolumePanel);\n\n/**\n * Button to skip forward a configurable amount of time\n * through a video. Renders in the control bar.\n *\n * e.g. options: {controlBar: {skipButtons: forward: 5}}\n *\n * @extends Button\n */\nclass SkipForward extends Button {\n  constructor(player, options) {\n    super(player, options);\n    this.validOptions = [5, 10, 30];\n    this.skipTime = this.getSkipForwardTime();\n    if (this.skipTime && this.validOptions.includes(this.skipTime)) {\n      this.setIcon(`forward-${this.skipTime}`);\n      this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime.toLocaleString(player.language())]));\n      this.show();\n    } else {\n      this.hide();\n    }\n  }\n  getSkipForwardTime() {\n    const playerOptions = this.options_.playerOptions;\n    return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.forward;\n  }\n  buildCSSClass() {\n    return `vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * On click, skips forward in the duration/seekable range by a configurable amount of seconds.\n   * If the time left in the duration/seekable range is less than the configured 'skip forward' time,\n   * skips to end of duration/seekable range.\n   *\n   * Handle a click on a `SkipForward` button\n   *\n   * @param {EventTarget~Event} event\n   *        The `click` event that caused this function\n   *        to be called\n   */\n  handleClick(event) {\n    if (isNaN(this.player_.duration())) {\n      return;\n    }\n    const currentVideoTime = this.player_.currentTime();\n    const liveTracker = this.player_.liveTracker;\n    const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();\n    let newTime;\n    if (currentVideoTime + this.skipTime <= duration) {\n      newTime = currentVideoTime + this.skipTime;\n    } else {\n      newTime = duration;\n    }\n    this.player_.currentTime(newTime);\n  }\n\n  /**\n   * Update control text on languagechange\n   */\n  handleLanguagechange() {\n    this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));\n  }\n}\nSkipForward.prototype.controlText_ = 'Skip Forward';\nComponent$1.registerComponent('SkipForward', SkipForward);\n\n/**\n * Button to skip backward a configurable amount of time\n * through a video. Renders in the control bar.\n *\n *  * e.g. options: {controlBar: {skipButtons: backward: 5}}\n *\n * @extends Button\n */\nclass SkipBackward extends Button {\n  constructor(player, options) {\n    super(player, options);\n    this.validOptions = [5, 10, 30];\n    this.skipTime = this.getSkipBackwardTime();\n    if (this.skipTime && this.validOptions.includes(this.skipTime)) {\n      this.setIcon(`replay-${this.skipTime}`);\n      this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime.toLocaleString(player.language())]));\n      this.show();\n    } else {\n      this.hide();\n    }\n  }\n  getSkipBackwardTime() {\n    const playerOptions = this.options_.playerOptions;\n    return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.backward;\n  }\n  buildCSSClass() {\n    return `vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * On click, skips backward in the video by a configurable amount of seconds.\n   * If the current time in the video is less than the configured 'skip backward' time,\n   * skips to beginning of video or seekable range.\n   *\n   * Handle a click on a `SkipBackward` button\n   *\n   * @param {EventTarget~Event} event\n   *        The `click` event that caused this function\n   *        to be called\n   */\n  handleClick(event) {\n    const currentVideoTime = this.player_.currentTime();\n    const liveTracker = this.player_.liveTracker;\n    const seekableStart = liveTracker && liveTracker.isLive() && liveTracker.seekableStart();\n    let newTime;\n    if (seekableStart && currentVideoTime - this.skipTime <= seekableStart) {\n      newTime = seekableStart;\n    } else if (currentVideoTime >= this.skipTime) {\n      newTime = currentVideoTime - this.skipTime;\n    } else {\n      newTime = 0;\n    }\n    this.player_.currentTime(newTime);\n  }\n\n  /**\n   * Update control text on languagechange\n   */\n  handleLanguagechange() {\n    this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));\n  }\n}\nSkipBackward.prototype.controlText_ = 'Skip Backward';\nComponent$1.registerComponent('SkipBackward', SkipBackward);\n\n/**\n * @file menu.js\n */\n\n/** @import Player from '../player' */\n\n/**\n * The Menu component is used to build popup menus, including subtitle and\n * captions selection menus.\n *\n * @extends Component\n */\nclass Menu extends Component$1 {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {Player} player\n   *        the player that this component should attach to\n   *\n   * @param {Object} [options]\n   *        Object of option names and values\n   *\n   */\n  constructor(player, options) {\n    super(player, options);\n    if (options) {\n      this.menuButton_ = options.menuButton;\n    }\n    this.focusedChild_ = -1;\n    this.on('keydown', e => this.handleKeyDown(e));\n\n    // All the menu item instances share the same blur handler provided by the menu container.\n    this.boundHandleBlur_ = e => this.handleBlur(e);\n    this.boundHandleTapClick_ = e => this.handleTapClick(e);\n  }\n\n  /**\n   * Add event listeners to the {@link MenuItem}.\n   *\n   * @param {Object} component\n   *        The instance of the `MenuItem` to add listeners to.\n   *\n   */\n  addEventListenerForItem(component) {\n    if (!(component instanceof Component$1)) {\n      return;\n    }\n    this.on(component, 'blur', this.boundHandleBlur_);\n    this.on(component, ['tap', 'click'], this.boundHandleTapClick_);\n  }\n\n  /**\n   * Remove event listeners from the {@link MenuItem}.\n   *\n   * @param {Object} component\n   *        The instance of the `MenuItem` to remove listeners.\n   *\n   */\n  removeEventListenerForItem(component) {\n    if (!(component instanceof Component$1)) {\n      return;\n    }\n    this.off(component, 'blur', this.boundHandleBlur_);\n    this.off(component, ['tap', 'click'], this.boundHandleTapClick_);\n  }\n\n  /**\n   * This method will be called indirectly when the component has been added\n   * before the component adds to the new menu instance by `addItem`.\n   * In this case, the original menu instance will remove the component\n   * by calling `removeChild`.\n   *\n   * @param {Object} component\n   *        The instance of the `MenuItem`\n   */\n  removeChild(component) {\n    if (typeof component === 'string') {\n      component = this.getChild(component);\n    }\n    this.removeEventListenerForItem(component);\n    super.removeChild(component);\n  }\n\n  /**\n   * Add a {@link MenuItem} to the menu.\n   *\n   * @param {Object|string} component\n   *        The name or instance of the `MenuItem` to add.\n   *\n   */\n  addItem(component) {\n    const childComponent = this.addChild(component);\n    if (childComponent) {\n      this.addEventListenerForItem(childComponent);\n    }\n  }\n\n  /**\n   * Create the `Menu`s DOM element.\n   *\n   * @return {Element}\n   *         the element that was created\n   */\n  createEl() {\n    const contentElType = this.options_.contentElType || 'ul';\n    this.contentEl_ = createEl(contentElType, {\n      className: 'vjs-menu-content'\n    });\n    this.contentEl_.setAttribute('role', 'menu');\n    const el = super.createEl('div', {\n      append: this.contentEl_,\n      className: 'vjs-menu'\n    });\n    el.appendChild(this.contentEl_);\n\n    // Prevent clicks from bubbling up. Needed for Menu Buttons,\n    // where a click on the parent is significant\n    on(el, 'click', function (event) {\n      event.preventDefault();\n      event.stopImmediatePropagation();\n    });\n    return el;\n  }\n  dispose() {\n    this.contentEl_ = null;\n    this.boundHandleBlur_ = null;\n    this.boundHandleTapClick_ = null;\n    super.dispose();\n  }\n\n  /**\n   * Called when a `MenuItem` loses focus.\n   *\n   * @param {Event} event\n   *        The `blur` event that caused this function to be called.\n   *\n   * @listens blur\n   */\n  handleBlur(event) {\n    const relatedTarget = event.relatedTarget || document$1.activeElement;\n\n    // Close menu popup when a user clicks outside the menu\n    if (!this.children().some(element => {\n      return element.el() === relatedTarget;\n    })) {\n      const btn = this.menuButton_;\n      if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {\n        btn.unpressButton();\n      }\n    }\n  }\n\n  /**\n   * Called when a `MenuItem` gets clicked or tapped.\n   *\n   * @param {Event} event\n   *        The `click` or `tap` event that caused this function to be called.\n   *\n   * @listens click,tap\n   */\n  handleTapClick(event) {\n    // Unpress the associated MenuButton, and move focus back to it\n    if (this.menuButton_) {\n      this.menuButton_.unpressButton();\n      const childComponents = this.children();\n      if (!Array.isArray(childComponents)) {\n        return;\n      }\n      const foundComponent = childComponents.filter(component => component.el() === event.target)[0];\n      if (!foundComponent) {\n        return;\n      }\n\n      // don't focus menu button if item is a caption settings item\n      // because focus will move elsewhere\n      if (foundComponent.name() !== 'CaptionSettingsMenuItem') {\n        this.menuButton_.focus();\n      }\n    }\n  }\n\n  /**\n   * Handle a `keydown` event on this menu. This listener is added in the constructor.\n   *\n   * @param {KeyboardEvent} event\n   *        A `keydown` event that happened on the menu.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    // Left and Down Arrows\n    if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.stepForward();\n\n      // Up and Right Arrows\n    } else if (event.key === 'ArrowRight' || event.key === 'ArrowUp') {\n      event.preventDefault();\n      event.stopPropagation();\n      this.stepBack();\n    }\n  }\n\n  /**\n   * Move to next (lower) menu item for keyboard users.\n   */\n  stepForward() {\n    let stepChild = 0;\n    if (this.focusedChild_ !== undefined) {\n      stepChild = this.focusedChild_ + 1;\n    }\n    this.focus(stepChild);\n  }\n\n  /**\n   * Move to previous (higher) menu item for keyboard users.\n   */\n  stepBack() {\n    let stepChild = 0;\n    if (this.focusedChild_ !== undefined) {\n      stepChild = this.focusedChild_ - 1;\n    }\n    this.focus(stepChild);\n  }\n\n  /**\n   * Set focus on a {@link MenuItem} in the `Menu`.\n   *\n   * @param {Object|string} [item=0]\n   *        Index of child item set focus on.\n   */\n  focus(item = 0) {\n    const children = this.children().slice();\n    const haveTitle = children.length && children[0].hasClass('vjs-menu-title');\n    if (haveTitle) {\n      children.shift();\n    }\n    if (children.length > 0) {\n      if (item < 0) {\n        item = 0;\n      } else if (item >= children.length) {\n        item = children.length - 1;\n      }\n      this.focusedChild_ = item;\n      children[item].el_.focus();\n    }\n  }\n}\nComponent$1.registerComponent('Menu', Menu);\n\n/**\n * @file menu-button.js\n */\n\n/** @import Player from '../player' */\n\n/**\n * A `MenuButton` class for any popup {@link Menu}.\n *\n * @extends Component\n */\nclass MenuButton extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options={}]\n   *        The key/value store of player options.\n   */\n  constructor(player, options = {}) {\n    super(player, options);\n    this.menuButton_ = new Button(player, options);\n    this.menuButton_.controlText(this.controlText_);\n    this.menuButton_.el_.setAttribute('aria-haspopup', 'true');\n\n    // Add buildCSSClass values to the button, not the wrapper\n    const buttonClass = Button.prototype.buildCSSClass();\n    this.menuButton_.el_.className = this.buildCSSClass() + ' ' + buttonClass;\n    this.menuButton_.removeClass('vjs-control');\n    this.addChild(this.menuButton_);\n    this.update();\n    this.enabled_ = true;\n    const handleClick = e => this.handleClick(e);\n    this.handleMenuKeyUp_ = e => this.handleMenuKeyUp(e);\n    this.on(this.menuButton_, 'tap', handleClick);\n    this.on(this.menuButton_, 'click', handleClick);\n    this.on(this.menuButton_, 'keydown', e => this.handleKeyDown(e));\n    this.on(this.menuButton_, 'mouseenter', () => {\n      this.addClass('vjs-hover');\n      this.menu.show();\n      on(document$1, 'keyup', this.handleMenuKeyUp_);\n    });\n    this.on('mouseleave', e => this.handleMouseLeave(e));\n    this.on('keydown', e => this.handleSubmenuKeyDown(e));\n  }\n\n  /**\n   * Update the menu based on the current state of its items.\n   */\n  update() {\n    const menu = this.createMenu();\n    if (this.menu) {\n      this.menu.dispose();\n      this.removeChild(this.menu);\n    }\n    this.menu = menu;\n    this.addChild(menu);\n\n    /**\n     * Track the state of the menu button\n     *\n     * @type {Boolean}\n     * @private\n     */\n    this.buttonPressed_ = false;\n    this.menuButton_.el_.setAttribute('aria-expanded', 'false');\n    if (this.items && this.items.length <= this.hideThreshold_) {\n      this.hide();\n      this.menu.contentEl_.removeAttribute('role');\n    } else {\n      this.show();\n      this.menu.contentEl_.setAttribute('role', 'menu');\n    }\n  }\n\n  /**\n   * Create the menu and add all items to it.\n   *\n   * @return {Menu}\n   *         The constructed menu\n   */\n  createMenu() {\n    const menu = new Menu(this.player_, {\n      menuButton: this\n    });\n\n    /**\n     * Hide the menu if the number of items is less than or equal to this threshold. This defaults\n     * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list\n     * it here because every time we run `createMenu` we need to reset the value.\n     *\n     * @protected\n     * @type {Number}\n     */\n    this.hideThreshold_ = 0;\n\n    // Add a title list item to the top\n    if (this.options_.title) {\n      const titleEl = createEl('li', {\n        className: 'vjs-menu-title',\n        textContent: toTitleCase$1(this.options_.title),\n        tabIndex: -1\n      });\n      const titleComponent = new Component$1(this.player_, {\n        el: titleEl\n      });\n      menu.addItem(titleComponent);\n    }\n    this.items = this.createItems();\n    if (this.items) {\n      // Add menu items to the menu\n      for (let i = 0; i < this.items.length; i++) {\n        menu.addItem(this.items[i]);\n      }\n    }\n    return menu;\n  }\n\n  /**\n   * Create the list of menu items. Specific to each subclass.\n   *\n   * @abstract\n   */\n  createItems() {}\n\n  /**\n   * Create the `MenuButtons`s DOM element.\n   *\n   * @return {Element}\n   *         The element that gets created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: this.buildWrapperCSSClass()\n    }, {});\n  }\n\n  /**\n   * Overwrites the `setIcon` method from `Component`.\n   * In this case, we want the icon to be appended to the menuButton.\n   *\n   * @param {string} name\n   *         The icon name to be added.\n   */\n  setIcon(name) {\n    super.setIcon(name, this.menuButton_.el_);\n  }\n\n  /**\n   * Allow sub components to stack CSS class names for the wrapper element\n   *\n   * @return {string}\n   *         The constructed wrapper DOM `className`\n   */\n  buildWrapperCSSClass() {\n    let menuButtonClass = 'vjs-menu-button';\n\n    // If the inline option is passed, we want to use different styles altogether.\n    if (this.options_.inline === true) {\n      menuButtonClass += '-inline';\n    } else {\n      menuButtonClass += '-popup';\n    }\n\n    // TODO: Fix the CSS so that this isn't necessary\n    const buttonClass = Button.prototype.buildCSSClass();\n    return `vjs-menu-button ${menuButtonClass} ${buttonClass} ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    let menuButtonClass = 'vjs-menu-button';\n\n    // If the inline option is passed, we want to use different styles altogether.\n    if (this.options_.inline === true) {\n      menuButtonClass += '-inline';\n    } else {\n      menuButtonClass += '-popup';\n    }\n    return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * Get or set the localized control text that will be used for accessibility.\n   *\n   * > NOTE: This will come from the internal `menuButton_` element.\n   *\n   * @param {string} [text]\n   *        Control text for element.\n   *\n   * @param {Element} [el=this.menuButton_.el()]\n   *        Element to set the title on.\n   *\n   * @return {string}\n   *         - The control text when getting\n   */\n  controlText(text, el = this.menuButton_.el()) {\n    return this.menuButton_.controlText(text, el);\n  }\n\n  /**\n   * Dispose of the `menu-button` and all child components.\n   */\n  dispose() {\n    this.handleMouseLeave();\n    super.dispose();\n  }\n\n  /**\n   * Handle a click on a `MenuButton`.\n   * See {@link ClickableComponent#handleClick} for instances where this is called.\n   *\n   * @param {Event} event\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    if (this.buttonPressed_) {\n      this.unpressButton();\n    } else {\n      this.pressButton();\n    }\n  }\n\n  /**\n   * Handle `mouseleave` for `MenuButton`.\n   *\n   * @param {Event} event\n   *        The `mouseleave` event that caused this function to be called.\n   *\n   * @listens mouseleave\n   */\n  handleMouseLeave(event) {\n    this.removeClass('vjs-hover');\n    off(document$1, 'keyup', this.handleMenuKeyUp_);\n  }\n\n  /**\n   * Set the focus to the actual button, not to this element\n   */\n  focus() {\n    this.menuButton_.focus();\n  }\n\n  /**\n   * Remove the focus from the actual button, not this element\n   */\n  blur() {\n    this.menuButton_.blur();\n  }\n\n  /**\n   * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See\n   * {@link ClickableComponent#handleKeyDown} for instances where this is called.\n   *\n   * @param {Event} event\n   *        The `keydown` event that caused this function to be called.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    // Escape or Tab unpress the 'button'\n    if (event.key === 'Escape' || event.key === 'Tab') {\n      if (this.buttonPressed_) {\n        this.unpressButton();\n      }\n\n      // Don't preventDefault for Tab key - we still want to lose focus\n      if (!event.key === 'Tab') {\n        event.preventDefault();\n        // Set focus back to the menu button's button\n        this.menuButton_.focus();\n      }\n      // Up Arrow or Down Arrow also 'press' the button to open the menu\n    } else if (event.key === 'Up' || event.key === 'Down' && !(this.player_.options_.playerOptions.spatialNavigation && this.player_.options_.playerOptions.spatialNavigation.enabled)) {\n      if (!this.buttonPressed_) {\n        event.preventDefault();\n        this.pressButton();\n      }\n    }\n  }\n\n  /**\n   * Handle a `keyup` event on a `MenuButton`. The listener for this is added in\n   * the constructor.\n   *\n   * @param {Event} event\n   *        Key press event\n   *\n   * @listens keyup\n   */\n  handleMenuKeyUp(event) {\n    // Escape hides popup menu\n    if (event.key === 'Escape' || event.key === 'Tab') {\n      this.removeClass('vjs-hover');\n    }\n  }\n\n  /**\n   * This method name now delegates to `handleSubmenuKeyDown`. This means\n   * anyone calling `handleSubmenuKeyPress` will not see their method calls\n   * stop working.\n   *\n   * @param {Event} event\n   *        The event that caused this function to be called.\n   */\n  handleSubmenuKeyPress(event) {\n    this.handleSubmenuKeyDown(event);\n  }\n\n  /**\n   * Handle a `keydown` event on a sub-menu. The listener for this is added in\n   * the constructor.\n   *\n   * @param {Event} event\n   *        Key press event\n   *\n   * @listens keydown\n   */\n  handleSubmenuKeyDown(event) {\n    // Escape or Tab unpress the 'button'\n    if (event.key === 'Escape' || event.key === 'Tab') {\n      if (this.buttonPressed_) {\n        this.unpressButton();\n      }\n      // Don't preventDefault for Tab key - we still want to lose focus\n      if (!event.key === 'Tab') {\n        event.preventDefault();\n        // Set focus back to the menu button's button\n        this.menuButton_.focus();\n      }\n    }\n  }\n\n  /**\n   * Put the current `MenuButton` into a pressed state.\n   */\n  pressButton() {\n    if (this.enabled_) {\n      this.buttonPressed_ = true;\n      this.menu.show();\n      this.menu.lockShowing();\n      this.menuButton_.el_.setAttribute('aria-expanded', 'true');\n\n      // set the focus into the submenu, except on iOS where it is resulting in\n      // undesired scrolling behavior when the player is in an iframe\n      if (IS_IOS && isInFrame()) {\n        // Return early so that the menu isn't focused\n        return;\n      }\n      this.menu.focus();\n    }\n  }\n\n  /**\n   * Take the current `MenuButton` out of a pressed state.\n   */\n  unpressButton() {\n    if (this.enabled_) {\n      this.buttonPressed_ = false;\n      this.menu.unlockShowing();\n      this.menu.hide();\n      this.menuButton_.el_.setAttribute('aria-expanded', 'false');\n    }\n  }\n\n  /**\n   * Disable the `MenuButton`. Don't allow it to be clicked.\n   */\n  disable() {\n    this.unpressButton();\n    this.enabled_ = false;\n    this.addClass('vjs-disabled');\n    this.menuButton_.disable();\n  }\n\n  /**\n   * Enable the `MenuButton`. Allow it to be clicked.\n   */\n  enable() {\n    this.enabled_ = true;\n    this.removeClass('vjs-disabled');\n    this.menuButton_.enable();\n  }\n}\nComponent$1.registerComponent('MenuButton', MenuButton);\n\n/**\n * @file track-button.js\n */\n\n/** @import Player from './player' */\n\n/**\n * The base class for buttons that toggle specific  track types (e.g. subtitles).\n *\n * @extends MenuButton\n */\nclass TrackButton extends MenuButton {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    const tracks = options.tracks;\n    super(player, options);\n    if (this.items.length <= 1) {\n      this.hide();\n    }\n    if (!tracks) {\n      return;\n    }\n    const updateHandler = bind_(this, this.update);\n    tracks.addEventListener('removetrack', updateHandler);\n    tracks.addEventListener('addtrack', updateHandler);\n    tracks.addEventListener('labelchange', updateHandler);\n    this.player_.on('ready', updateHandler);\n    this.player_.on('dispose', function () {\n      tracks.removeEventListener('removetrack', updateHandler);\n      tracks.removeEventListener('addtrack', updateHandler);\n      tracks.removeEventListener('labelchange', updateHandler);\n    });\n  }\n}\nComponent$1.registerComponent('TrackButton', TrackButton);\n\n/**\n * @file menu-item.js\n */\n\n/** @import Player from '../player' */\n\n/**\n * The component for a menu item. `<li>`\n *\n * @extends ClickableComponent\n */\nclass MenuItem extends ClickableComponent {\n  /**\n   * Creates an instance of the this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options={}]\n   *        The key/value store of player options.\n   *\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.selectable = options.selectable;\n    this.isSelected_ = options.selected || false;\n    this.multiSelectable = options.multiSelectable;\n    this.selected(this.isSelected_);\n    if (this.selectable) {\n      if (this.multiSelectable) {\n        this.el_.setAttribute('role', 'menuitemcheckbox');\n      } else {\n        this.el_.setAttribute('role', 'menuitemradio');\n      }\n    } else {\n      this.el_.setAttribute('role', 'menuitem');\n    }\n  }\n\n  /**\n   * Create the `MenuItem's DOM element\n   *\n   * @param {string} [type=li]\n   *        Element's node type, not actually used, always set to `li`.\n   *\n   * @param {Object} [props={}]\n   *        An object of properties that should be set on the element\n   *\n   * @param {Object} [attrs={}]\n   *        An object of attributes that should be set on the element\n   *\n   * @return {Element}\n   *         The element that gets created.\n   */\n  createEl(type, props, attrs) {\n    // The control is textual, not just an icon\n    this.nonIconControl = true;\n    const el = super.createEl('li', Object.assign({\n      className: 'vjs-menu-item',\n      tabIndex: -1\n    }, props), attrs);\n\n    // swap icon with menu item text.\n    const menuItemEl = createEl('span', {\n      className: 'vjs-menu-item-text',\n      textContent: this.localize(this.options_.label)\n    });\n\n    // If using SVG icons, the element with vjs-icon-placeholder will be added separately.\n    if (this.player_.options_.experimentalSvgIcons) {\n      el.appendChild(menuItemEl);\n    } else {\n      el.replaceChild(menuItemEl, el.querySelector('.vjs-icon-placeholder'));\n    }\n    return el;\n  }\n\n  /**\n   * Ignore keys which are used by the menu, but pass any other ones up. See\n   * {@link ClickableComponent#handleKeyDown} for instances where this is called.\n   *\n   * @param {KeyboardEvent} event\n   *        The `keydown` event that caused this function to be called.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    if (!['Tab', 'Escape', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'].includes(event.key)) {\n      // Pass keydown handling up for unused keys\n      super.handleKeyDown(event);\n    }\n  }\n\n  /**\n   * Any click on a `MenuItem` puts it into the selected state.\n   * See {@link ClickableComponent#handleClick} for instances where this is called.\n   *\n   * @param {Event} event\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    this.selected(true);\n  }\n\n  /**\n   * Set the state for this menu item as selected or not.\n   *\n   * @param {boolean} selected\n   *        if the menu item is selected or not\n   */\n  selected(selected) {\n    if (this.selectable) {\n      if (selected) {\n        this.addClass('vjs-selected');\n        this.el_.setAttribute('aria-checked', 'true');\n        // aria-checked isn't fully supported by browsers/screen readers,\n        // so indicate selected state to screen reader in the control text.\n        this.controlText(', selected');\n        this.isSelected_ = true;\n      } else {\n        this.removeClass('vjs-selected');\n        this.el_.setAttribute('aria-checked', 'false');\n        // Indicate un-selected state to screen reader\n        this.controlText('');\n        this.isSelected_ = false;\n      }\n    }\n  }\n}\nComponent$1.registerComponent('MenuItem', MenuItem);\n\n/**\n * @file text-track-menu-item.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The specific menu item type for selecting a language within a text track kind\n *\n * @extends MenuItem\n */\nclass TextTrackMenuItem extends MenuItem {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    const track = options.track;\n    const tracks = player.textTracks();\n\n    // Modify options for parent MenuItem class's init.\n    options.label = track.label || track.language || 'Unknown';\n    options.selected = track.mode === 'showing';\n    super(player, options);\n    this.track = track;\n    // Determine the relevant kind(s) of tracks for this component and filter\n    // out empty kinds.\n    this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);\n    const changeHandler = (...args) => {\n      this.handleTracksChange.apply(this, args);\n    };\n    const selectedLanguageChangeHandler = (...args) => {\n      this.handleSelectedLanguageChange.apply(this, args);\n    };\n    player.on(['loadstart', 'texttrackchange'], changeHandler);\n    tracks.addEventListener('change', changeHandler);\n    tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);\n    this.on('dispose', function () {\n      player.off(['loadstart', 'texttrackchange'], changeHandler);\n      tracks.removeEventListener('change', changeHandler);\n      tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);\n    });\n\n    // iOS7 doesn't dispatch change events to TextTrackLists when an\n    // associated track's mode changes. Without something like\n    // Object.observe() (also not present on iOS7), it's not\n    // possible to detect changes to the mode attribute and polyfill\n    // the change event. As a poor substitute, we manually dispatch\n    // change events whenever the controls modify the mode.\n    if (tracks.onchange === undefined) {\n      let event;\n      this.on(['tap', 'click'], function () {\n        if (typeof window$1.Event !== 'object') {\n          // Android 2.3 throws an Illegal Constructor error for window.Event\n          try {\n            event = new window$1.Event('change');\n          } catch (err) {\n            // continue regardless of error\n          }\n        }\n        if (!event) {\n          event = document$1.createEvent('Event');\n          event.initEvent('change', true, true);\n        }\n        tracks.dispatchEvent(event);\n      });\n    }\n\n    // set the default state based on current tracks\n    this.handleTracksChange();\n  }\n\n  /**\n   * This gets called when an `TextTrackMenuItem` is \"clicked\". See\n   * {@link ClickableComponent} for more detailed information on what a click can be.\n   *\n   * @param {Event} event\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    const referenceTrack = this.track;\n    const tracks = this.player_.textTracks();\n    super.handleClick(event);\n    if (!tracks) {\n      return;\n    }\n    for (let i = 0; i < tracks.length; i++) {\n      const track = tracks[i];\n\n      // If the track from the text tracks list is not of the right kind,\n      // skip it. We do not want to affect tracks of incompatible kind(s).\n      if (this.kinds.indexOf(track.kind) === -1) {\n        continue;\n      }\n\n      // If this text track is the component's track and it is not showing,\n      // set it to showing.\n      if (track === referenceTrack) {\n        if (track.mode !== 'showing') {\n          track.mode = 'showing';\n        }\n\n        // If this text track is not the component's track and it is not\n        // disabled, set it to disabled.\n      } else if (track.mode !== 'disabled') {\n        track.mode = 'disabled';\n      }\n    }\n  }\n\n  /**\n   * Handle text track list change\n   *\n   * @param {Event} event\n   *        The `change` event that caused this function to be called.\n   *\n   * @listens TextTrackList#change\n   */\n  handleTracksChange(event) {\n    const shouldBeSelected = this.track.mode === 'showing';\n\n    // Prevent redundant selected() calls because they may cause\n    // screen readers to read the appended control text unnecessarily\n    if (shouldBeSelected !== this.isSelected_) {\n      this.selected(shouldBeSelected);\n    }\n  }\n  handleSelectedLanguageChange(event) {\n    if (this.track.mode === 'showing') {\n      const selectedLanguage = this.player_.cache_.selectedLanguage;\n\n      // Don't replace the kind of track across the same language\n      if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {\n        return;\n      }\n      this.player_.cache_.selectedLanguage = {\n        enabled: true,\n        language: this.track.language,\n        kind: this.track.kind\n      };\n    }\n  }\n  dispose() {\n    // remove reference to track object on dispose\n    this.track = null;\n    super.dispose();\n  }\n}\nComponent$1.registerComponent('TextTrackMenuItem', TextTrackMenuItem);\n\n/**\n * @file off-text-track-menu-item.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * A special menu item for turning off a specific type of text track\n *\n * @extends TextTrackMenuItem\n */\nclass OffTextTrackMenuItem extends TextTrackMenuItem {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    // Create pseudo track info\n    // Requires options['kind']\n    options.track = {\n      player,\n      // it is no longer necessary to store `kind` or `kinds` on the track itself\n      // since they are now stored in the `kinds` property of all instances of\n      // TextTrackMenuItem, but this will remain for backwards compatibility\n      kind: options.kind,\n      kinds: options.kinds,\n      default: false,\n      mode: 'disabled'\n    };\n    if (!options.kinds) {\n      options.kinds = [options.kind];\n    }\n    if (options.label) {\n      options.track.label = options.label;\n    } else {\n      options.track.label = options.kinds.join(' and ') + ' off';\n    }\n\n    // MenuItem is selectable\n    options.selectable = true;\n    // MenuItem is NOT multiSelectable (i.e. only one can be marked \"selected\" at a time)\n    options.multiSelectable = false;\n    super(player, options);\n  }\n\n  /**\n   * Handle text track change\n   *\n   * @param {Event} event\n   *        The event that caused this function to run\n   */\n  handleTracksChange(event) {\n    const tracks = this.player().textTracks();\n    let shouldBeSelected = true;\n    for (let i = 0, l = tracks.length; i < l; i++) {\n      const track = tracks[i];\n      if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {\n        shouldBeSelected = false;\n        break;\n      }\n    }\n\n    // Prevent redundant selected() calls because they may cause\n    // screen readers to read the appended control text unnecessarily\n    if (shouldBeSelected !== this.isSelected_) {\n      this.selected(shouldBeSelected);\n    }\n  }\n  handleSelectedLanguageChange(event) {\n    const tracks = this.player().textTracks();\n    let allHidden = true;\n    for (let i = 0, l = tracks.length; i < l; i++) {\n      const track = tracks[i];\n      if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {\n        allHidden = false;\n        break;\n      }\n    }\n    if (allHidden) {\n      this.player_.cache_.selectedLanguage = {\n        enabled: false\n      };\n    }\n  }\n\n  /**\n   * Update control text and label on languagechange\n   */\n  handleLanguagechange() {\n    this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.label);\n    super.handleLanguagechange();\n  }\n}\nComponent$1.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);\n\n/**\n * @file text-track-button.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The base class for buttons that toggle specific text track types (e.g. subtitles)\n *\n * @extends MenuButton\n */\nclass TextTrackButton extends TrackButton {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options={}]\n   *        The key/value store of player options.\n   */\n  constructor(player, options = {}) {\n    options.tracks = player.textTracks();\n    super(player, options);\n  }\n\n  /**\n   * Create a menu item for each text track\n   *\n   * @param {TextTrackMenuItem[]} [items=[]]\n   *        Existing array of items to use during creation\n   *\n   * @return {TextTrackMenuItem[]}\n   *         Array of menu items that were created\n   */\n  createItems(items = [], TrackMenuItem = TextTrackMenuItem) {\n    // Label is an override for the [track] off label\n    // USed to localise captions/subtitles\n    let label;\n    if (this.label_) {\n      label = `${this.label_} off`;\n    }\n    // Add an OFF menu item to turn all tracks off\n    items.push(new OffTextTrackMenuItem(this.player_, {\n      kinds: this.kinds_,\n      kind: this.kind_,\n      label\n    }));\n    this.hideThreshold_ += 1;\n    const tracks = this.player_.textTracks();\n    if (!Array.isArray(this.kinds_)) {\n      this.kinds_ = [this.kind_];\n    }\n    for (let i = 0; i < tracks.length; i++) {\n      const track = tracks[i];\n\n      // only add tracks that are of an appropriate kind and have a label\n      if (this.kinds_.indexOf(track.kind) > -1) {\n        const item = new TrackMenuItem(this.player_, {\n          track,\n          kinds: this.kinds_,\n          kind: this.kind_,\n          // MenuItem is selectable\n          selectable: true,\n          // MenuItem is NOT multiSelectable (i.e. only one can be marked \"selected\" at a time)\n          multiSelectable: false\n        });\n        item.addClass(`vjs-${track.kind}-menu-item`);\n        items.push(item);\n      }\n    }\n    return items;\n  }\n}\nComponent$1.registerComponent('TextTrackButton', TextTrackButton);\n\n/**\n * @file chapters-track-menu-item.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The chapter track menu item\n *\n * @extends MenuItem\n */\nclass ChaptersTrackMenuItem extends MenuItem {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    const track = options.track;\n    const cue = options.cue;\n    const currentTime = player.currentTime();\n\n    // Modify options for parent MenuItem class's init.\n    options.selectable = true;\n    options.multiSelectable = false;\n    options.label = cue.text;\n    options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;\n    super(player, options);\n    this.track = track;\n    this.cue = cue;\n  }\n\n  /**\n   * This gets called when an `ChaptersTrackMenuItem` is \"clicked\". See\n   * {@link ClickableComponent} for more detailed information on what a click can be.\n   *\n   * @param {Event} [event]\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    super.handleClick();\n    this.player_.currentTime(this.cue.startTime);\n  }\n}\nComponent$1.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);\n\n/**\n * @file chapters-button.js\n */\n\n/** @import Player from '../../player' */\n/** @import Menu from '../../menu/menu' */\n/** @import TextTrack from '../../tracks/text-track' */\n/** @import TextTrackMenuItem from '../text-track-controls/text-track-menu-item' */\n\n/**\n * The button component for toggling and selecting chapters\n * Chapters act much differently than other text tracks\n * Cues are navigation vs. other tracks of alternative languages\n *\n * @extends TextTrackButton\n */\nclass ChaptersButton extends TextTrackButton {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {Function} [ready]\n   *        The function to call when this function is ready.\n   */\n  constructor(player, options, ready) {\n    super(player, options, ready);\n    this.setIcon('chapters');\n    this.selectCurrentItem_ = () => {\n      this.items.forEach(item => {\n        item.selected(this.track_.activeCues[0] === item.cue);\n      });\n    };\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-chapters-button ${super.buildCSSClass()}`;\n  }\n  buildWrapperCSSClass() {\n    return `vjs-chapters-button ${super.buildWrapperCSSClass()}`;\n  }\n\n  /**\n   * Update the menu based on the current state of its items.\n   *\n   * @param {Event} [event]\n   *        An event that triggered this function to run.\n   *\n   * @listens TextTrackList#addtrack\n   * @listens TextTrackList#removetrack\n   * @listens TextTrackList#change\n   */\n  update(event) {\n    if (event && event.track && event.track.kind !== 'chapters') {\n      return;\n    }\n    const track = this.findChaptersTrack();\n    if (track !== this.track_) {\n      this.setTrack(track);\n      super.update();\n    } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {\n      // Update the menu initially or if the number of cues has changed since set\n      super.update();\n    }\n  }\n\n  /**\n   * Set the currently selected track for the chapters button.\n   *\n   * @param {TextTrack} track\n   *        The new track to select. Nothing will change if this is the currently selected\n   *        track.\n   */\n  setTrack(track) {\n    if (this.track_ === track) {\n      return;\n    }\n    if (!this.updateHandler_) {\n      this.updateHandler_ = this.update.bind(this);\n    }\n\n    // here this.track_ refers to the old track instance\n    if (this.track_) {\n      const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);\n      if (remoteTextTrackEl) {\n        remoteTextTrackEl.removeEventListener('load', this.updateHandler_);\n      }\n      this.track_.removeEventListener('cuechange', this.selectCurrentItem_);\n      this.track_ = null;\n    }\n    this.track_ = track;\n\n    // here this.track_ refers to the new track instance\n    if (this.track_) {\n      this.track_.mode = 'hidden';\n      const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);\n      if (remoteTextTrackEl) {\n        remoteTextTrackEl.addEventListener('load', this.updateHandler_);\n      }\n      this.track_.addEventListener('cuechange', this.selectCurrentItem_);\n    }\n  }\n\n  /**\n   * Find the track object that is currently in use by this ChaptersButton\n   *\n   * @return {TextTrack|undefined}\n   *         The current track or undefined if none was found.\n   */\n  findChaptersTrack() {\n    const tracks = this.player_.textTracks() || [];\n    for (let i = tracks.length - 1; i >= 0; i--) {\n      // We will always choose the last track as our chaptersTrack\n      const track = tracks[i];\n      if (track.kind === this.kind_) {\n        return track;\n      }\n    }\n  }\n\n  /**\n   * Get the caption for the ChaptersButton based on the track label. This will also\n   * use the current tracks localized kind as a fallback if a label does not exist.\n   *\n   * @return {string}\n   *         The tracks current label or the localized track kind.\n   */\n  getMenuCaption() {\n    if (this.track_ && this.track_.label) {\n      return this.track_.label;\n    }\n    return this.localize(toTitleCase$1(this.kind_));\n  }\n\n  /**\n   * Create menu from chapter track\n   *\n   * @return {Menu}\n   *         New menu for the chapter buttons\n   */\n  createMenu() {\n    this.options_.title = this.getMenuCaption();\n    return super.createMenu();\n  }\n\n  /**\n   * Create a menu item for each text track\n   *\n   * @return  {TextTrackMenuItem[]}\n   *         Array of menu items\n   */\n  createItems() {\n    const items = [];\n    if (!this.track_) {\n      return items;\n    }\n    const cues = this.track_.cues;\n    if (!cues) {\n      return items;\n    }\n    for (let i = 0, l = cues.length; i < l; i++) {\n      const cue = cues[i];\n      const mi = new ChaptersTrackMenuItem(this.player_, {\n        track: this.track_,\n        cue\n      });\n      items.push(mi);\n    }\n    return items;\n  }\n}\n\n/**\n * `kind` of TextTrack to look for to associate it with this menu.\n *\n * @type {string}\n * @private\n */\nChaptersButton.prototype.kind_ = 'chapters';\n\n/**\n * The text that should display over the `ChaptersButton`s controls. Added for localization.\n *\n * @type {string}\n * @protected\n */\nChaptersButton.prototype.controlText_ = 'Chapters';\nComponent$1.registerComponent('ChaptersButton', ChaptersButton);\n\n/**\n * @file descriptions-button.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The button component for toggling and selecting descriptions\n *\n * @extends TextTrackButton\n */\nclass DescriptionsButton extends TextTrackButton {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {Function} [ready]\n   *        The function to call when this component is ready.\n   */\n  constructor(player, options, ready) {\n    super(player, options, ready);\n    this.setIcon('audio-description');\n    const tracks = player.textTracks();\n    const changeHandler = bind_(this, this.handleTracksChange);\n    tracks.addEventListener('change', changeHandler);\n    this.on('dispose', function () {\n      tracks.removeEventListener('change', changeHandler);\n    });\n  }\n\n  /**\n   * Handle text track change\n   *\n   * @param {Event} event\n   *        The event that caused this function to run\n   *\n   * @listens TextTrackList#change\n   */\n  handleTracksChange(event) {\n    const tracks = this.player().textTracks();\n    let disabled = false;\n\n    // Check whether a track of a different kind is showing\n    for (let i = 0, l = tracks.length; i < l; i++) {\n      const track = tracks[i];\n      if (track.kind !== this.kind_ && track.mode === 'showing') {\n        disabled = true;\n        break;\n      }\n    }\n\n    // If another track is showing, disable this menu button\n    if (disabled) {\n      this.disable();\n    } else {\n      this.enable();\n    }\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-descriptions-button ${super.buildCSSClass()}`;\n  }\n  buildWrapperCSSClass() {\n    return `vjs-descriptions-button ${super.buildWrapperCSSClass()}`;\n  }\n}\n\n/**\n * `kind` of TextTrack to look for to associate it with this menu.\n *\n * @type {string}\n * @private\n */\nDescriptionsButton.prototype.kind_ = 'descriptions';\n\n/**\n * The text that should display over the `DescriptionsButton`s controls. Added for localization.\n *\n * @type {string}\n * @protected\n */\nDescriptionsButton.prototype.controlText_ = 'Descriptions';\nComponent$1.registerComponent('DescriptionsButton', DescriptionsButton);\n\n/**\n * @file subtitles-button.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The button component for toggling and selecting subtitles\n *\n * @extends TextTrackButton\n */\nclass SubtitlesButton extends TextTrackButton {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {Function} [ready]\n   *        The function to call when this component is ready.\n   */\n  constructor(player, options, ready) {\n    super(player, options, ready);\n    this.setIcon('subtitles');\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-subtitles-button ${super.buildCSSClass()}`;\n  }\n  buildWrapperCSSClass() {\n    return `vjs-subtitles-button ${super.buildWrapperCSSClass()}`;\n  }\n}\n\n/**\n * `kind` of TextTrack to look for to associate it with this menu.\n *\n * @type {string}\n * @private\n */\nSubtitlesButton.prototype.kind_ = 'subtitles';\n\n/**\n * The text that should display over the `SubtitlesButton`s controls. Added for localization.\n *\n * @type {string}\n * @protected\n */\nSubtitlesButton.prototype.controlText_ = 'Subtitles';\nComponent$1.registerComponent('SubtitlesButton', SubtitlesButton);\n\n/**\n * @file caption-settings-menu-item.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The menu item for caption track settings menu\n *\n * @extends TextTrackMenuItem\n */\nclass CaptionSettingsMenuItem extends TextTrackMenuItem {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    options.track = {\n      player,\n      kind: options.kind,\n      label: options.kind + ' settings',\n      selectable: false,\n      default: false,\n      mode: 'disabled'\n    };\n\n    // CaptionSettingsMenuItem has no concept of 'selected'\n    options.selectable = false;\n    options.name = 'CaptionSettingsMenuItem';\n    super(player, options);\n    this.addClass('vjs-texttrack-settings');\n    this.controlText(', opens ' + options.kind + ' settings dialog');\n  }\n\n  /**\n   * This gets called when an `CaptionSettingsMenuItem` is \"clicked\". See\n   * {@link ClickableComponent} for more detailed information on what a click can be.\n   *\n   * @param {Event} [event]\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    this.player().getChild('textTrackSettings').open();\n  }\n\n  /**\n   * Update control text and label on languagechange\n   */\n  handleLanguagechange() {\n    this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.kind + ' settings');\n    super.handleLanguagechange();\n  }\n}\nComponent$1.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);\n\n/**\n * @file captions-button.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The button component for toggling and selecting captions\n *\n * @extends TextTrackButton\n */\nclass CaptionsButton extends TextTrackButton {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {Function} [ready]\n   *        The function to call when this component is ready.\n   */\n  constructor(player, options, ready) {\n    super(player, options, ready);\n    this.setIcon('captions');\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-captions-button ${super.buildCSSClass()}`;\n  }\n  buildWrapperCSSClass() {\n    return `vjs-captions-button ${super.buildWrapperCSSClass()}`;\n  }\n\n  /**\n   * Create caption menu items\n   *\n   * @return {CaptionSettingsMenuItem[]}\n   *         The array of current menu items.\n   */\n  createItems() {\n    const items = [];\n    if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {\n      items.push(new CaptionSettingsMenuItem(this.player_, {\n        kind: this.kind_\n      }));\n      this.hideThreshold_ += 1;\n    }\n    return super.createItems(items);\n  }\n}\n\n/**\n * `kind` of TextTrack to look for to associate it with this menu.\n *\n * @type {string}\n * @private\n */\nCaptionsButton.prototype.kind_ = 'captions';\n\n/**\n * The text that should display over the `CaptionsButton`s controls. Added for localization.\n *\n * @type {string}\n * @protected\n */\nCaptionsButton.prototype.controlText_ = 'Captions';\nComponent$1.registerComponent('CaptionsButton', CaptionsButton);\n\n/**\n * @file subs-caps-menu-item.js\n */\n\n/**\n * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles\n * in the SubsCapsMenu.\n *\n * @extends TextTrackMenuItem\n */\nclass SubsCapsMenuItem extends TextTrackMenuItem {\n  createEl(type, props, attrs) {\n    const el = super.createEl(type, props, attrs);\n    const parentSpan = el.querySelector('.vjs-menu-item-text');\n    if (this.options_.track.kind === 'captions') {\n      if (this.player_.options_.experimentalSvgIcons) {\n        this.setIcon('captions', el);\n      } else {\n        parentSpan.appendChild(createEl('span', {\n          className: 'vjs-icon-placeholder'\n        }, {\n          'aria-hidden': true\n        }));\n      }\n      parentSpan.appendChild(createEl('span', {\n        className: 'vjs-control-text',\n        // space added as the text will visually flow with the\n        // label\n        textContent: ` ${this.localize('Captions')}`\n      }));\n    }\n    return el;\n  }\n}\nComponent$1.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);\n\n/**\n * @file sub-caps-button.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The button component for toggling and selecting captions and/or subtitles\n *\n * @extends TextTrackButton\n */\nclass SubsCapsButton extends TextTrackButton {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {Function} [ready]\n   *        The function to call when this component is ready.\n   */\n  constructor(player, options = {}) {\n    super(player, options);\n\n    // Although North America uses \"captions\" in most cases for\n    // \"captions and subtitles\" other locales use \"subtitles\"\n    this.label_ = 'subtitles';\n    this.setIcon('subtitles');\n    if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(this.player_.language_) > -1) {\n      this.label_ = 'captions';\n      this.setIcon('captions');\n    }\n    this.menuButton_.controlText(toTitleCase$1(this.label_));\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-subs-caps-button ${super.buildCSSClass()}`;\n  }\n  buildWrapperCSSClass() {\n    return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;\n  }\n\n  /**\n   * Create caption/subtitles menu items\n   *\n   * @return {CaptionSettingsMenuItem[]}\n   *         The array of current menu items.\n   */\n  createItems() {\n    let items = [];\n    if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {\n      items.push(new CaptionSettingsMenuItem(this.player_, {\n        kind: this.label_\n      }));\n      this.hideThreshold_ += 1;\n    }\n    items = super.createItems(items, SubsCapsMenuItem);\n    return items;\n  }\n}\n\n/**\n * `kind`s of TextTrack to look for to associate it with this menu.\n *\n * @type {array}\n * @private\n */\nSubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];\n\n/**\n * The text that should display over the `SubsCapsButton`s controls.\n *\n *\n * @type {string}\n * @protected\n */\nSubsCapsButton.prototype.controlText_ = 'Subtitles';\nComponent$1.registerComponent('SubsCapsButton', SubsCapsButton);\n\n/**\n * @file audio-track-menu-item.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * An {@link AudioTrack} {@link MenuItem}\n *\n * @extends MenuItem\n */\nclass AudioTrackMenuItem extends MenuItem {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    const track = options.track;\n    const tracks = player.audioTracks();\n\n    // Modify options for parent MenuItem class's init.\n    options.label = track.label || track.language || 'Unknown';\n    options.selected = track.enabled;\n    super(player, options);\n    this.track = track;\n    this.addClass(`vjs-${track.kind}-menu-item`);\n    const changeHandler = (...args) => {\n      this.handleTracksChange.apply(this, args);\n    };\n    tracks.addEventListener('change', changeHandler);\n    this.on('dispose', () => {\n      tracks.removeEventListener('change', changeHandler);\n    });\n  }\n  createEl(type, props, attrs) {\n    const el = super.createEl(type, props, attrs);\n    const parentSpan = el.querySelector('.vjs-menu-item-text');\n    if (['main-desc', 'descriptions'].indexOf(this.options_.track.kind) >= 0) {\n      parentSpan.appendChild(createEl('span', {\n        className: 'vjs-icon-placeholder'\n      }, {\n        'aria-hidden': true\n      }));\n      parentSpan.appendChild(createEl('span', {\n        className: 'vjs-control-text',\n        textContent: ' ' + this.localize('Descriptions')\n      }));\n    }\n    return el;\n  }\n\n  /**\n   * This gets called when an `AudioTrackMenuItem is \"clicked\". See {@link ClickableComponent}\n   * for more detailed information on what a click can be.\n   *\n   * @param {Event} [event]\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    super.handleClick(event);\n\n    // the audio track list will automatically toggle other tracks\n    // off for us.\n    this.track.enabled = true;\n\n    // when native audio tracks are used, we want to make sure that other tracks are turned off\n    if (this.player_.tech_.featuresNativeAudioTracks) {\n      const tracks = this.player_.audioTracks();\n      for (let i = 0; i < tracks.length; i++) {\n        const track = tracks[i];\n\n        // skip the current track since we enabled it above\n        if (track === this.track) {\n          continue;\n        }\n        track.enabled = track === this.track;\n      }\n    }\n  }\n\n  /**\n   * Handle any {@link AudioTrack} change.\n   *\n   * @param {Event} [event]\n   *        The {@link AudioTrackList#change} event that caused this to run.\n   *\n   * @listens AudioTrackList#change\n   */\n  handleTracksChange(event) {\n    this.selected(this.track.enabled);\n  }\n}\nComponent$1.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);\n\n/**\n * @file audio-track-button.js\n */\n\n/**\n * The base class for buttons that toggle specific {@link AudioTrack} types.\n *\n * @extends TrackButton\n */\nclass AudioTrackButton extends TrackButton {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options={}]\n   *        The key/value store of player options.\n   */\n  constructor(player, options = {}) {\n    options.tracks = player.audioTracks();\n    super(player, options);\n    this.setIcon('audio');\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-audio-button ${super.buildCSSClass()}`;\n  }\n  buildWrapperCSSClass() {\n    return `vjs-audio-button ${super.buildWrapperCSSClass()}`;\n  }\n\n  /**\n   * Create a menu item for each audio track\n   *\n   * @param {AudioTrackMenuItem[]} [items=[]]\n   *        An array of existing menu items to use.\n   *\n   * @return {AudioTrackMenuItem[]}\n   *         An array of menu items\n   */\n  createItems(items = []) {\n    // if there's only one audio track, there no point in showing it\n    this.hideThreshold_ = 1;\n    const tracks = this.player_.audioTracks();\n    for (let i = 0; i < tracks.length; i++) {\n      const track = tracks[i];\n      items.push(new AudioTrackMenuItem(this.player_, {\n        track,\n        // MenuItem is selectable\n        selectable: true,\n        // MenuItem is NOT multiSelectable (i.e. only one can be marked \"selected\" at a time)\n        multiSelectable: false\n      }));\n    }\n    return items;\n  }\n}\n\n/**\n * The text that should display over the `AudioTrackButton`s controls. Added for localization.\n *\n * @type {string}\n * @protected\n */\nAudioTrackButton.prototype.controlText_ = 'Audio Track';\nComponent$1.registerComponent('AudioTrackButton', AudioTrackButton);\n\n/**\n * @file playback-rate-menu-item.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The specific menu item type for selecting a playback rate.\n *\n * @extends MenuItem\n */\nclass PlaybackRateMenuItem extends MenuItem {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    const label = options.rate;\n    const rate = parseFloat(label, 10);\n\n    // Modify options for parent MenuItem class's init.\n    options.label = label;\n    options.selected = rate === player.playbackRate();\n    options.selectable = true;\n    options.multiSelectable = false;\n    super(player, options);\n    this.label = label;\n    this.rate = rate;\n    this.on(player, 'ratechange', e => this.update(e));\n  }\n\n  /**\n   * This gets called when an `PlaybackRateMenuItem` is \"clicked\". See\n   * {@link ClickableComponent} for more detailed information on what a click can be.\n   *\n   * @param {Event} [event]\n   *        The `keydown`, `tap`, or `click` event that caused this function to be\n   *        called.\n   *\n   * @listens tap\n   * @listens click\n   */\n  handleClick(event) {\n    super.handleClick();\n    this.player().playbackRate(this.rate);\n  }\n\n  /**\n   * Update the PlaybackRateMenuItem when the playbackrate changes.\n   *\n   * @param {Event} [event]\n   *        The `ratechange` event that caused this function to run.\n   *\n   * @listens Player#ratechange\n   */\n  update(event) {\n    this.selected(this.player().playbackRate() === this.rate);\n  }\n}\n\n/**\n * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.\n *\n * @type {string}\n * @private\n */\nPlaybackRateMenuItem.prototype.contentElType = 'button';\nComponent$1.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);\n\n/**\n * @file playback-rate-menu-button.js\n */\n\n/** @import Player from '../../player' */\n\n/**\n * The component for controlling the playback rate.\n *\n * @extends MenuButton\n */\nclass PlaybackRateMenuButton extends MenuButton {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.menuButton_.el_.setAttribute('aria-describedby', this.labelElId_);\n    this.updateVisibility();\n    this.updateLabel();\n    this.on(player, 'loadstart', e => this.updateVisibility(e));\n    this.on(player, 'ratechange', e => this.updateLabel(e));\n    this.on(player, 'playbackrateschange', e => this.handlePlaybackRateschange(e));\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    const el = super.createEl();\n    this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;\n    this.labelEl_ = createEl('div', {\n      className: 'vjs-playback-rate-value',\n      id: this.labelElId_,\n      textContent: '1x'\n    });\n    el.appendChild(this.labelEl_);\n    return el;\n  }\n  dispose() {\n    this.labelEl_ = null;\n    super.dispose();\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-playback-rate ${super.buildCSSClass()}`;\n  }\n  buildWrapperCSSClass() {\n    return `vjs-playback-rate ${super.buildWrapperCSSClass()}`;\n  }\n\n  /**\n   * Create the list of menu items. Specific to each subclass.\n   *\n   */\n  createItems() {\n    const rates = this.playbackRates();\n    const items = [];\n    for (let i = rates.length - 1; i >= 0; i--) {\n      items.push(new PlaybackRateMenuItem(this.player(), {\n        rate: rates[i] + 'x'\n      }));\n    }\n    return items;\n  }\n\n  /**\n   * On playbackrateschange, update the menu to account for the new items.\n   *\n   * @listens Player#playbackrateschange\n   */\n  handlePlaybackRateschange(event) {\n    this.update();\n  }\n\n  /**\n   * Get possible playback rates\n   *\n   * @return {Array}\n   *         All possible playback rates\n   */\n  playbackRates() {\n    const player = this.player();\n    return player.playbackRates && player.playbackRates() || [];\n  }\n\n  /**\n   * Get whether playback rates is supported by the tech\n   * and an array of playback rates exists\n   *\n   * @return {boolean}\n   *         Whether changing playback rate is supported\n   */\n  playbackRateSupported() {\n    return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;\n  }\n\n  /**\n   * Hide playback rate controls when they're no playback rate options to select\n   *\n   * @param {Event} [event]\n   *        The event that caused this function to run.\n   *\n   * @listens Player#loadstart\n   */\n  updateVisibility(event) {\n    if (this.playbackRateSupported()) {\n      this.removeClass('vjs-hidden');\n    } else {\n      this.addClass('vjs-hidden');\n    }\n  }\n\n  /**\n   * Update button label when rate changed\n   *\n   * @param {Event} [event]\n   *        The event that caused this function to run.\n   *\n   * @listens Player#ratechange\n   */\n  updateLabel(event) {\n    if (this.playbackRateSupported()) {\n      this.labelEl_.textContent = this.player().playbackRate() + 'x';\n    }\n  }\n}\n\n/**\n * The text that should display over the `PlaybackRateMenuButton`s controls.\n *\n * Added for localization.\n *\n * @type {string}\n * @protected\n */\nPlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';\nComponent$1.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);\n\n/**\n * @file spacer.js\n */\n\n/**\n * Just an empty spacer element that can be used as an append point for plugins, etc.\n * Also can be used to create space between elements when necessary.\n *\n * @extends Component\n */\nclass Spacer extends Component$1 {\n  /**\n  * Builds the default DOM `className`.\n  *\n  * @return {string}\n  *         The DOM `className` for this object.\n  */\n  buildCSSClass() {\n    return `vjs-spacer ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl(tag = 'div', props = {}, attributes = {}) {\n    if (!props.className) {\n      props.className = this.buildCSSClass();\n    }\n    return super.createEl(tag, props, attributes);\n  }\n}\nComponent$1.registerComponent('Spacer', Spacer);\n\n/**\n * @file custom-control-spacer.js\n */\n\n/**\n * Spacer specifically meant to be used as an insertion point for new plugins, etc.\n *\n * @extends Spacer\n */\nclass CustomControlSpacer extends Spacer {\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   */\n  buildCSSClass() {\n    return `vjs-custom-control-spacer ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: this.buildCSSClass(),\n      // No-flex/table-cell mode requires there be some content\n      // in the cell to fill the remaining space of the table.\n      textContent: '\\u00a0'\n    });\n  }\n}\nComponent$1.registerComponent('CustomControlSpacer', CustomControlSpacer);\n\n/**\n * @file control-bar.js\n */\n\n/**\n * Container of main controls.\n *\n * @extends Component\n */\nclass ControlBar extends Component$1 {\n  /**\n   * Create the `Component`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    return super.createEl('div', {\n      className: 'vjs-control-bar',\n      dir: 'ltr'\n    });\n  }\n}\n\n/**\n * Default options for `ControlBar`\n *\n * @type {Object}\n * @private\n */\nControlBar.prototype.options_ = {\n  children: ['playToggle', 'skipBackward', 'skipForward', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'pictureInPictureToggle', 'fullscreenToggle']\n};\nComponent$1.registerComponent('ControlBar', ControlBar);\n\n/**\n * @file error-display.js\n */\n\n/** @import Player from './player' */\n\n/**\n * A display that indicates an error has occurred. This means that the video\n * is unplayable.\n *\n * @extends ModalDialog\n */\nclass ErrorDisplay extends ModalDialog {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param  {Player} player\n   *         The `Player` that this class should be attached to.\n   *\n   * @param  {Object} [options]\n   *         The key/value store of player options.\n   */\n  constructor(player, options) {\n    super(player, options);\n    this.on(player, 'error', e => {\n      this.open(e);\n    });\n  }\n\n  /**\n   * Builds the default DOM `className`.\n   *\n   * @return {string}\n   *         The DOM `className` for this object.\n   *\n   * @deprecated Since version 5.\n   */\n  buildCSSClass() {\n    return `vjs-error-display ${super.buildCSSClass()}`;\n  }\n\n  /**\n   * Gets the localized error message based on the `Player`s error.\n   *\n   * @return {string}\n   *         The `Player`s error message localized or an empty string.\n   */\n  content() {\n    const error = this.player().error();\n    return error ? this.localize(error.message) : '';\n  }\n}\n\n/**\n * The default options for an `ErrorDisplay`.\n *\n * @private\n */\nErrorDisplay.prototype.options_ = Object.assign({}, ModalDialog.prototype.options_, {\n  pauseOnOpen: false,\n  fillAlways: true,\n  temporary: false,\n  uncloseable: true\n});\nComponent$1.registerComponent('ErrorDisplay', ErrorDisplay);\n\n/** @import Player from './player' */\n/** @import { ContentDescriptor } from  '../utils/dom' */\n\n/**\n * Creates DOM element of 'select' & its options.\n *\n * @extends Component\n */\nclass TextTrackSelect extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {ContentDescriptor} [options.content=undefined]\n   *        Provide customized content for this modal.\n   *\n   * @param {string} [options.legendId]\n   *        A text with part of an string to create atribute of aria-labelledby.\n   *\n   * @param {string} [options.id]\n   *        A text with part of an string to create atribute of aria-labelledby.\n   *\n   * @param {Array} [options.SelectOptions]\n   *        Array that contains the value & textContent of for each of the\n   *        options elements.\n   */\n  constructor(player, options = {}) {\n    super(player, options);\n    this.el_.setAttribute('aria-labelledby', this.selectLabelledbyIds);\n  }\n\n  /**\n   * Create the `TextTrackSelect`'s DOM element\n   *\n   * @return {Element}\n   *         The DOM element that gets created.\n   */\n  createEl() {\n    this.selectLabelledbyIds = [this.options_.legendId, this.options_.labelId].join(' ').trim();\n\n    // Create select & inner options\n    const selectoptions = createEl('select', {\n      id: this.options_.id\n    }, {}, this.options_.SelectOptions.map(optionText => {\n      // Constructs an id for the <option>.\n      // For the colour settings that have two <selects> with a <label> each, generates an id based off the label value\n      // For font size/family and edge style with one <select> and no <label>, generates an id with a guid\n      const optionId = (this.options_.labelId ? this.options_.labelId : `vjs-track-option-${newGUID()}`) + '-' + optionText[1].replace(/\\W+/g, '');\n      const option = createEl('option', {\n        id: optionId,\n        value: this.localize(optionText[0]),\n        textContent: this.localize(optionText[1])\n      });\n      option.setAttribute('aria-labelledby', `${this.selectLabelledbyIds} ${optionId}`);\n      return option;\n    }));\n    return selectoptions;\n  }\n}\nComponent$1.registerComponent('TextTrackSelect', TextTrackSelect);\n\n/** @import Player from './player' */\n/** @import { ContentDescriptor } from '../utils/dom' */\n\n/**\n * Creates fieldset section of 'TextTrackSettings'.\n * Manganes two versions of fieldsets, one for type of 'colors'\n * & the other for 'font', Component adds diferent DOM elements\n * to that fieldset  depending on the type.\n *\n * @extends Component\n */\nclass TextTrackFieldset extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {ContentDescriptor} [options.content=undefined]\n   *        Provide customized content for this modal.\n   *\n   * @param {string} [options.legendId]\n   *        A text with part of an string to create atribute of aria-labelledby.\n   *        It passes to 'TextTrackSelect'.\n   *\n   * @param {string} [options.id]\n   *        A text with part of an string to create atribute of aria-labelledby.\n   *        It passes to 'TextTrackSelect'.\n   *\n   * @param {string} [options.legendText]\n   *        A text to use as the text content of the legend element.\n   *\n   * @param {Array} [options.selects]\n   *        Array that contains the selects that are use to create 'selects'\n   *        components.\n   *\n   * @param {Array} [options.SelectOptions]\n   *        Array that contains the value & textContent of for each of the\n   *        options elements, it passes to 'TextTrackSelect'.\n   *\n   * @param {string} [options.type]\n   *        Conditions if some DOM elements will be added to the fieldset\n   *        component.\n   *\n   * @param {Object} [options.selectConfigs]\n   *        Object with the following properties that are the selects configurations:\n   *        backgroundColor, backgroundOpacity, color, edgeStyle, fontFamily,\n   *        fontPercent, textOpacity, windowColor, windowOpacity.\n   *        These properties are use to configure the 'TextTrackSelect' Component.\n   */\n  constructor(player, options = {}) {\n    super(player, options);\n\n    // Add Components & DOM Elements\n    const legendElement = createEl('legend', {\n      textContent: this.localize(this.options_.legendText),\n      id: this.options_.legendId\n    });\n    this.el().appendChild(legendElement);\n    const selects = this.options_.selects;\n\n    // Iterate array of selects to create 'selects' components\n    for (const i of selects) {\n      const selectConfig = this.options_.selectConfigs[i];\n      const selectClassName = selectConfig.className;\n      const id = selectConfig.id.replace('%s', this.options_.id_);\n      let span = null;\n      const guid = `vjs_select_${newGUID()}`;\n\n      // Conditionally create span to add on the component\n      if (this.options_.type === 'colors') {\n        span = createEl('span', {\n          className: selectClassName\n        });\n        const label = createEl('label', {\n          id,\n          className: 'vjs-label',\n          textContent: this.localize(selectConfig.label)\n        });\n        label.setAttribute('for', guid);\n        span.appendChild(label);\n      }\n      const textTrackSelect = new TextTrackSelect(player, {\n        SelectOptions: selectConfig.options,\n        legendId: this.options_.legendId,\n        id: guid,\n        labelId: id\n      });\n      this.addChild(textTrackSelect);\n\n      // Conditionally append to 'select' component to conditionally created span\n      if (this.options_.type === 'colors') {\n        span.appendChild(textTrackSelect.el());\n        this.el().appendChild(span);\n      }\n    }\n  }\n\n  /**\n   * Create the `TextTrackFieldset`'s DOM element\n   *\n   * @return {Element}\n   *         The DOM element that gets created.\n   */\n  createEl() {\n    const el = createEl('fieldset', {\n      // Prefixing classes of elements within a player with \"vjs-\"\n      // is a convention used in Video.js.\n      className: this.options_.className\n    });\n    return el;\n  }\n}\nComponent$1.registerComponent('TextTrackFieldset', TextTrackFieldset);\n\n/** @import Player from './player' */\n/** @import { ContentDescriptor } from  '../utils/dom' */\n\n/**\n * The component 'TextTrackSettingsColors' displays a set of 'fieldsets'\n * using the component 'TextTrackFieldset'.\n *\n * @extends Component\n */\nclass TextTrackSettingsColors extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {ContentDescriptor} [options.content=undefined]\n   *        Provide customized content for this modal.\n   *\n   * @param {Array} [options.fieldSets]\n   *        Array that contains the configurations for the selects.\n   *\n   * @param {Object} [options.selectConfigs]\n   *        Object with the following properties that are the select confugations:\n   *        backgroundColor, backgroundOpacity, color, edgeStyle, fontFamily,\n   *        fontPercent, textOpacity, windowColor, windowOpacity.\n   *        it passes to 'TextTrackFieldset'.\n   */\n  constructor(player, options = {}) {\n    super(player, options);\n    const id_ = this.options_.textTrackComponentid;\n\n    // createElFgColor_\n    const ElFgColorFieldset = new TextTrackFieldset(player, {\n      id_,\n      legendId: `captions-text-legend-${id_}`,\n      legendText: this.localize('Text'),\n      className: 'vjs-fg vjs-track-setting',\n      selects: this.options_.fieldSets[0],\n      selectConfigs: this.options_.selectConfigs,\n      type: 'colors'\n    });\n    this.addChild(ElFgColorFieldset);\n\n    // createElBgColor_\n    const ElBgColorFieldset = new TextTrackFieldset(player, {\n      id_,\n      legendId: `captions-background-${id_}`,\n      legendText: this.localize('Text Background'),\n      className: 'vjs-bg vjs-track-setting',\n      selects: this.options_.fieldSets[1],\n      selectConfigs: this.options_.selectConfigs,\n      type: 'colors'\n    });\n    this.addChild(ElBgColorFieldset);\n\n    // createElWinColor_\n    const ElWinColorFieldset = new TextTrackFieldset(player, {\n      id_,\n      legendId: `captions-window-${id_}`,\n      legendText: this.localize('Caption Area Background'),\n      className: 'vjs-window vjs-track-setting',\n      selects: this.options_.fieldSets[2],\n      selectConfigs: this.options_.selectConfigs,\n      type: 'colors'\n    });\n    this.addChild(ElWinColorFieldset);\n  }\n\n  /**\n   * Create the `TextTrackSettingsColors`'s DOM element\n   *\n   * @return {Element}\n   *         The DOM element that gets created.\n   */\n  createEl() {\n    const el = createEl('div', {\n      className: 'vjs-track-settings-colors'\n    });\n    return el;\n  }\n}\nComponent$1.registerComponent('TextTrackSettingsColors', TextTrackSettingsColors);\n\n/** @import Player from './player' */\n/** @import { ContentDescriptor } from  '../utils/dom' */\n\n/**\n * The component 'TextTrackSettingsFont' displays a set of 'fieldsets'\n * using the component 'TextTrackFieldset'.\n *\n * @extends Component\n */\nclass TextTrackSettingsFont extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {ContentDescriptor} [options.content=undefined]\n   *        Provide customized content for this modal.\n   *\n   * @param {Array} [options.fieldSets]\n   *        Array that contains the configurations for the selects.\n   *\n   * @param {Object} [options.selectConfigs]\n   *        Object with the following properties that are the select confugations:\n   *        backgroundColor, backgroundOpacity, color, edgeStyle, fontFamily,\n   *        fontPercent, textOpacity, windowColor, windowOpacity.\n   *        it passes to 'TextTrackFieldset'.\n   */\n  constructor(player, options = {}) {\n    super(player, options);\n    const id_ = this.options_.textTrackComponentid;\n    const ElFgColorFieldset = new TextTrackFieldset(player, {\n      id_,\n      legendId: `captions-font-size-${id_}`,\n      legendText: 'Font Size',\n      className: 'vjs-font-percent vjs-track-setting',\n      selects: this.options_.fieldSets[0],\n      selectConfigs: this.options_.selectConfigs,\n      type: 'font'\n    });\n    this.addChild(ElFgColorFieldset);\n    const ElBgColorFieldset = new TextTrackFieldset(player, {\n      id_,\n      legendId: `captions-edge-style-${id_}`,\n      legendText: this.localize('Text Edge Style'),\n      className: 'vjs-edge-style vjs-track-setting',\n      selects: this.options_.fieldSets[1],\n      selectConfigs: this.options_.selectConfigs,\n      type: 'font'\n    });\n    this.addChild(ElBgColorFieldset);\n    const ElWinColorFieldset = new TextTrackFieldset(player, {\n      id_,\n      legendId: `captions-font-family-${id_}`,\n      legendText: this.localize('Font Family'),\n      className: 'vjs-font-family vjs-track-setting',\n      selects: this.options_.fieldSets[2],\n      selectConfigs: this.options_.selectConfigs,\n      type: 'font'\n    });\n    this.addChild(ElWinColorFieldset);\n  }\n\n  /**\n   * Create the `TextTrackSettingsFont`'s DOM element\n   *\n   * @return {Element}\n   *         The DOM element that gets created.\n   */\n  createEl() {\n    const el = createEl('div', {\n      className: 'vjs-track-settings-font'\n    });\n    return el;\n  }\n}\nComponent$1.registerComponent('TextTrackSettingsFont', TextTrackSettingsFont);\n\n/**\n * Buttons of reset & done that modal 'TextTrackSettings'\n * uses as part of its content.\n *\n * 'Reset': Resets all settings on 'TextTrackSettings'.\n * 'Done': Closes 'TextTrackSettings' modal.\n *\n * @extends Component\n */\nclass TrackSettingsControls extends Component$1 {\n  constructor(player, options = {}) {\n    super(player, options);\n\n    // Create DOM elements\n    const resetButton = new Button(player, {\n      controlText: this.localize('restore all settings to the default values'),\n      className: 'vjs-default-button'\n    });\n    resetButton.el().classList.remove('vjs-control', 'vjs-button');\n    resetButton.el().textContent = this.localize('Reset');\n    this.addChild(resetButton);\n    const doneText = this.localize('Done');\n    const doneButton = new Button(player, {\n      controlText: doneText,\n      className: 'vjs-done-button'\n    });\n\n    // Remove unrequired style classes\n    doneButton.el().classList.remove('vjs-control', 'vjs-button');\n    doneButton.el().textContent = doneText;\n    this.addChild(doneButton);\n  }\n\n  /**\n   * Create the `TrackSettingsControls`'s DOM element\n   *\n   * @return {Element}\n   *         The DOM element that gets created.\n   */\n  createEl() {\n    const el = createEl('div', {\n      className: 'vjs-track-settings-controls'\n    });\n    return el;\n  }\n}\nComponent$1.registerComponent('TrackSettingsControls', TrackSettingsControls);\n\n/**\n * @file text-track-settings.js\n */\n\n/** @import Player from '../player' */\n\nconst LOCAL_STORAGE_KEY$1 = 'vjs-text-track-settings';\nconst COLOR_BLACK = ['#000', 'Black'];\nconst COLOR_BLUE = ['#00F', 'Blue'];\nconst COLOR_CYAN = ['#0FF', 'Cyan'];\nconst COLOR_GREEN = ['#0F0', 'Green'];\nconst COLOR_MAGENTA = ['#F0F', 'Magenta'];\nconst COLOR_RED = ['#F00', 'Red'];\nconst COLOR_WHITE = ['#FFF', 'White'];\nconst COLOR_YELLOW = ['#FF0', 'Yellow'];\nconst OPACITY_OPAQUE = ['1', 'Opaque'];\nconst OPACITY_SEMI = ['0.5', 'Semi-Transparent'];\nconst OPACITY_TRANS = ['0', 'Transparent'];\n\n// Configuration for the various <select> elements in the DOM of this component.\n//\n// Possible keys include:\n//\n// `default`:\n//   The default option index. Only needs to be provided if not zero.\n// `parser`:\n//   A function which is used to parse the value from the selected option in\n//   a customized way.\n// `selector`:\n//   The selector used to find the associated <select> element.\nconst selectConfigs = {\n  backgroundColor: {\n    selector: '.vjs-bg-color > select',\n    id: 'captions-background-color-%s',\n    label: 'Color',\n    options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN],\n    className: 'vjs-bg-color'\n  },\n  backgroundOpacity: {\n    selector: '.vjs-bg-opacity > select',\n    id: 'captions-background-opacity-%s',\n    label: 'Opacity',\n    options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS],\n    className: 'vjs-bg-opacity vjs-opacity'\n  },\n  color: {\n    selector: '.vjs-text-color > select',\n    id: 'captions-foreground-color-%s',\n    label: 'Color',\n    options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN],\n    className: 'vjs-text-color'\n  },\n  edgeStyle: {\n    selector: '.vjs-edge-style > select',\n    id: '',\n    label: 'Text Edge Style',\n    options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Drop shadow']]\n  },\n  fontFamily: {\n    selector: '.vjs-font-family > select',\n    id: '',\n    label: 'Font Family',\n    options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]\n  },\n  fontPercent: {\n    selector: '.vjs-font-percent > select',\n    id: '',\n    label: 'Font Size',\n    options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']],\n    default: 2,\n    parser: v => v === '1.00' ? null : Number(v)\n  },\n  textOpacity: {\n    selector: '.vjs-text-opacity > select',\n    id: 'captions-foreground-opacity-%s',\n    label: 'Opacity',\n    options: [OPACITY_OPAQUE, OPACITY_SEMI],\n    className: 'vjs-text-opacity vjs-opacity'\n  },\n  // Options for this object are defined below.\n  windowColor: {\n    selector: '.vjs-window-color > select',\n    id: 'captions-window-color-%s',\n    label: 'Color',\n    className: 'vjs-window-color'\n  },\n  // Options for this object are defined below.\n  windowOpacity: {\n    selector: '.vjs-window-opacity > select',\n    id: 'captions-window-opacity-%s',\n    label: 'Opacity',\n    options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE],\n    className: 'vjs-window-opacity vjs-opacity'\n  }\n};\nselectConfigs.windowColor.options = selectConfigs.backgroundColor.options;\n\n/**\n * Get the actual value of an option.\n *\n * @param  {string} value\n *         The value to get\n *\n * @param  {Function} [parser]\n *         Optional function to adjust the value.\n *\n * @return {*}\n *         - Will be `undefined` if no value exists\n *         - Will be `undefined` if the given value is \"none\".\n *         - Will be the actual value otherwise.\n *\n * @private\n */\nfunction parseOptionValue(value, parser) {\n  if (parser) {\n    value = parser(value);\n  }\n  if (value && value !== 'none') {\n    return value;\n  }\n}\n\n/**\n * Gets the value of the selected <option> element within a <select> element.\n *\n * @param  {Element} el\n *         the element to look in\n *\n * @param  {Function} [parser]\n *         Optional function to adjust the value.\n *\n * @return {*}\n *         - Will be `undefined` if no value exists\n *         - Will be `undefined` if the given value is \"none\".\n *         - Will be the actual value otherwise.\n *\n * @private\n */\nfunction getSelectedOptionValue(el, parser) {\n  const value = el.options[el.options.selectedIndex].value;\n  return parseOptionValue(value, parser);\n}\n\n/**\n * Sets the selected <option> element within a <select> element based on a\n * given value.\n *\n * @param {Element} el\n *        The element to look in.\n *\n * @param {string} value\n *        the property to look on.\n *\n * @param {Function} [parser]\n *        Optional function to adjust the value before comparing.\n *\n * @private\n */\nfunction setSelectedOption(el, value, parser) {\n  if (!value) {\n    return;\n  }\n  for (let i = 0; i < el.options.length; i++) {\n    if (parseOptionValue(el.options[i].value, parser) === value) {\n      el.selectedIndex = i;\n      break;\n    }\n  }\n}\n\n/**\n * Manipulate Text Tracks settings.\n *\n * @extends ModalDialog\n */\nclass TextTrackSettings extends ModalDialog {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *         The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *         The key/value store of player options.\n   */\n  constructor(player, options) {\n    options.temporary = false;\n    super(player, options);\n    this.updateDisplay = this.updateDisplay.bind(this);\n\n    // fill the modal and pretend we have opened it\n    this.fill();\n    this.hasBeenOpened_ = this.hasBeenFilled_ = true;\n    this.renderModalComponents(player);\n    this.endDialog = createEl('p', {\n      className: 'vjs-control-text',\n      textContent: this.localize('End of dialog window.')\n    });\n    this.el().appendChild(this.endDialog);\n    this.setDefaults();\n\n    // Grab `persistTextTrackSettings` from the player options if not passed in child options\n    if (options.persistTextTrackSettings === undefined) {\n      this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;\n    }\n    this.bindFunctionsToSelectsAndButtons();\n    if (this.options_.persistTextTrackSettings) {\n      this.restoreSettings();\n    }\n  }\n  renderModalComponents(player) {\n    const textTrackSettingsColors = new TextTrackSettingsColors(player, {\n      textTrackComponentid: this.id_,\n      selectConfigs,\n      fieldSets: [['color', 'textOpacity'], ['backgroundColor', 'backgroundOpacity'], ['windowColor', 'windowOpacity']]\n    });\n    this.addChild(textTrackSettingsColors);\n    const textTrackSettingsFont = new TextTrackSettingsFont(player, {\n      textTrackComponentid: this.id_,\n      selectConfigs,\n      fieldSets: [['fontPercent'], ['edgeStyle'], ['fontFamily']]\n    });\n    this.addChild(textTrackSettingsFont);\n    const trackSettingsControls = new TrackSettingsControls(player);\n    this.addChild(trackSettingsControls);\n  }\n  bindFunctionsToSelectsAndButtons() {\n    this.on(this.$('.vjs-done-button'), ['click', 'tap'], () => {\n      this.saveSettings();\n      this.close();\n    });\n    this.on(this.$('.vjs-default-button'), ['click', 'tap'], () => {\n      this.setDefaults();\n      this.updateDisplay();\n    });\n    each(selectConfigs, config => {\n      this.on(this.$(config.selector), 'change', this.updateDisplay);\n    });\n  }\n  dispose() {\n    this.endDialog = null;\n    super.dispose();\n  }\n  label() {\n    return this.localize('Caption Settings Dialog');\n  }\n  description() {\n    return this.localize('Beginning of dialog window. Escape will cancel and close the window.');\n  }\n  buildCSSClass() {\n    return super.buildCSSClass() + ' vjs-text-track-settings';\n  }\n\n  /**\n   * Gets an object of text track settings (or null).\n   *\n   * @return {Object}\n   *         An object with config values parsed from the DOM or localStorage.\n   */\n  getValues() {\n    return reduce(selectConfigs, (accum, config, key) => {\n      const value = getSelectedOptionValue(this.$(config.selector), config.parser);\n      if (value !== undefined) {\n        accum[key] = value;\n      }\n      return accum;\n    }, {});\n  }\n\n  /**\n   * Sets text track settings from an object of values.\n   *\n   * @param {Object} values\n   *        An object with config values parsed from the DOM or localStorage.\n   */\n  setValues(values) {\n    each(selectConfigs, (config, key) => {\n      setSelectedOption(this.$(config.selector), values[key], config.parser);\n    });\n  }\n\n  /**\n   * Sets all `<select>` elements to their default values.\n   */\n  setDefaults() {\n    each(selectConfigs, config => {\n      const index = config.hasOwnProperty('default') ? config.default : 0;\n      this.$(config.selector).selectedIndex = index;\n    });\n  }\n\n  /**\n   * Restore texttrack settings from localStorage\n   */\n  restoreSettings() {\n    let values;\n    try {\n      values = JSON.parse(window$1.localStorage.getItem(LOCAL_STORAGE_KEY$1));\n    } catch (err) {\n      log$1.warn(err);\n    }\n    if (values) {\n      this.setValues(values);\n    }\n  }\n\n  /**\n   * Save text track settings to localStorage\n   */\n  saveSettings() {\n    if (!this.options_.persistTextTrackSettings) {\n      return;\n    }\n    const values = this.getValues();\n    try {\n      if (Object.keys(values).length) {\n        window$1.localStorage.setItem(LOCAL_STORAGE_KEY$1, JSON.stringify(values));\n      } else {\n        window$1.localStorage.removeItem(LOCAL_STORAGE_KEY$1);\n      }\n    } catch (err) {\n      log$1.warn(err);\n    }\n  }\n\n  /**\n   * Update display of text track settings\n   */\n  updateDisplay() {\n    const ttDisplay = this.player_.getChild('textTrackDisplay');\n    if (ttDisplay) {\n      ttDisplay.updateDisplay();\n    }\n  }\n\n  /**\n   * Repopulate dialog with new localizations on languagechange\n   */\n  handleLanguagechange() {\n    this.fill();\n    this.renderModalComponents(this.player_);\n    this.bindFunctionsToSelectsAndButtons();\n  }\n}\nComponent$1.registerComponent('TextTrackSettings', TextTrackSettings);\n\n/**\n * @file resize-manager.js\n */\n\n/**\n * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.\n *\n * It'll either create an iframe and use a debounced resize handler on it or use the new {@link https://wicg.github.io/ResizeObserver/|ResizeObserver}.\n *\n * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.\n * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.\n *\n * @example <caption>How to disable the resize manager</caption>\n * const player = videojs('#vid', {\n *   resizeManager: false\n * });\n *\n * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}\n *\n * @extends Component\n */\nclass ResizeManager extends Component$1 {\n  /**\n   * Create the ResizeManager.\n   *\n   * @param {Object} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of ResizeManager options.\n   *\n   * @param {Object} [options.ResizeObserver]\n   *        A polyfill for ResizeObserver can be passed in here.\n   *        If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.\n   */\n  constructor(player, options) {\n    let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window$1.ResizeObserver;\n\n    // if `null` was passed, we want to disable the ResizeObserver\n    if (options.ResizeObserver === null) {\n      RESIZE_OBSERVER_AVAILABLE = false;\n    }\n\n    // Only create an element when ResizeObserver isn't available\n    const options_ = merge$1({\n      createEl: !RESIZE_OBSERVER_AVAILABLE,\n      reportTouchActivity: false\n    }, options);\n    super(player, options_);\n    this.ResizeObserver = options.ResizeObserver || window$1.ResizeObserver;\n    this.loadListener_ = null;\n    this.resizeObserver_ = null;\n    this.debouncedHandler_ = debounce$1(() => {\n      this.resizeHandler();\n    }, 100, false, this);\n    if (RESIZE_OBSERVER_AVAILABLE) {\n      this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);\n      this.resizeObserver_.observe(player.el());\n    } else {\n      this.loadListener_ = () => {\n        if (!this.el_ || !this.el_.contentWindow) {\n          return;\n        }\n        const debouncedHandler_ = this.debouncedHandler_;\n        let unloadListener_ = this.unloadListener_ = function () {\n          off(this, 'resize', debouncedHandler_);\n          off(this, 'unload', unloadListener_);\n          unloadListener_ = null;\n        };\n\n        // safari and edge can unload the iframe before resizemanager dispose\n        // we have to dispose of event handlers correctly before that happens\n        on(this.el_.contentWindow, 'unload', unloadListener_);\n        on(this.el_.contentWindow, 'resize', debouncedHandler_);\n      };\n      this.one('load', this.loadListener_);\n    }\n  }\n  createEl() {\n    return super.createEl('iframe', {\n      className: 'vjs-resize-manager',\n      tabIndex: -1,\n      title: this.localize('No content')\n    }, {\n      'aria-hidden': 'true'\n    });\n  }\n\n  /**\n   * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver\n   *\n   * @fires Player#playerresize\n   */\n  resizeHandler() {\n    /**\n     * Called when the player size has changed\n     *\n     * @event Player#playerresize\n     * @type {Event}\n     */\n    // make sure player is still around to trigger\n    // prevents this from causing an error after dispose\n    if (!this.player_ || !this.player_.trigger) {\n      return;\n    }\n    this.player_.trigger('playerresize');\n  }\n  dispose() {\n    if (this.debouncedHandler_) {\n      this.debouncedHandler_.cancel();\n    }\n    if (this.resizeObserver_) {\n      if (this.player_.el()) {\n        this.resizeObserver_.unobserve(this.player_.el());\n      }\n      this.resizeObserver_.disconnect();\n    }\n    if (this.loadListener_) {\n      this.off('load', this.loadListener_);\n    }\n    if (this.el_ && this.el_.contentWindow && this.unloadListener_) {\n      this.unloadListener_.call(this.el_.contentWindow);\n    }\n    this.ResizeObserver = null;\n    this.resizeObserver = null;\n    this.debouncedHandler_ = null;\n    this.loadListener_ = null;\n    super.dispose();\n  }\n}\nComponent$1.registerComponent('ResizeManager', ResizeManager);\n\n/** @import Player from './player' */\n\nconst defaults$1 = {\n  trackingThreshold: 20,\n  liveTolerance: 15\n};\n\n/*\n  track when we are at the live edge, and other helpers for live playback */\n\n/**\n * A class for checking live current time and determining when the player\n * is at or behind the live edge.\n */\nclass LiveTracker extends Component$1 {\n  /**\n   * Creates an instance of this class.\n   *\n   * @param {Player} player\n   *        The `Player` that this class should be attached to.\n   *\n   * @param {Object} [options]\n   *        The key/value store of player options.\n   *\n   * @param {number} [options.trackingThreshold=20]\n   *        Number of seconds of live window (seekableEnd - seekableStart) that\n   *        media needs to have before the liveui will be shown.\n   *\n   * @param {number} [options.liveTolerance=15]\n   *        Number of seconds behind live that we have to be\n   *        before we will be considered non-live. Note that this will only\n   *        be used when playing at the live edge. This allows large seekable end\n   *        changes to not effect whether we are live or not.\n   */\n  constructor(player, options) {\n    // LiveTracker does not need an element\n    const options_ = merge$1(defaults$1, options, {\n      createEl: false\n    });\n    super(player, options_);\n    this.trackLiveHandler_ = () => this.trackLive_();\n    this.handlePlay_ = e => this.handlePlay(e);\n    this.handleFirstTimeupdate_ = e => this.handleFirstTimeupdate(e);\n    this.handleSeeked_ = e => this.handleSeeked(e);\n    this.seekToLiveEdge_ = e => this.seekToLiveEdge(e);\n    this.reset_();\n    this.on(this.player_, 'durationchange', e => this.handleDurationchange(e));\n    // we should try to toggle tracking on canplay as native playback engines, like Safari\n    // may not have the proper values for things like seekableEnd until then\n    this.on(this.player_, 'canplay', () => this.toggleTracking());\n  }\n\n  /**\n   * all the functionality for tracking when seek end changes\n   * and for tracking how far past seek end we should be\n   */\n  trackLive_() {\n    const seekable = this.player_.seekable();\n\n    // skip undefined seekable\n    if (!seekable || !seekable.length) {\n      return;\n    }\n    const newTime = Number(window$1.performance.now().toFixed(4));\n    const deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;\n    this.lastTime_ = newTime;\n    this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;\n    const liveCurrentTime = this.liveCurrentTime();\n    const currentTime = this.player_.currentTime();\n\n    // we are behind live if any are true\n    // 1. the player is paused\n    // 2. the user seeked to a location 2 seconds away from live\n    // 3. the difference between live and current time is greater\n    //    liveTolerance which defaults to 15s\n    let isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;\n\n    // we cannot be behind if\n    // 1. until we have not seen a timeupdate yet\n    // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari\n    if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {\n      isBehind = false;\n    }\n    if (isBehind !== this.behindLiveEdge_) {\n      this.behindLiveEdge_ = isBehind;\n      this.trigger('liveedgechange');\n    }\n  }\n\n  /**\n   * handle a durationchange event on the player\n   * and start/stop tracking accordingly.\n   */\n  handleDurationchange() {\n    this.toggleTracking();\n  }\n\n  /**\n   * start/stop tracking\n   */\n  toggleTracking() {\n    if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {\n      if (this.player_.options_.liveui) {\n        this.player_.addClass('vjs-liveui');\n      }\n      this.startTracking();\n    } else {\n      this.player_.removeClass('vjs-liveui');\n      this.stopTracking();\n    }\n  }\n\n  /**\n   * start tracking live playback\n   */\n  startTracking() {\n    if (this.isTracking()) {\n      return;\n    }\n\n    // If we haven't seen a timeupdate, we need to check whether playback\n    // began before this component started tracking. This can happen commonly\n    // when using autoplay.\n    if (!this.timeupdateSeen_) {\n      this.timeupdateSeen_ = this.player_.hasStarted();\n    }\n    this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);\n    this.trackLive_();\n    this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);\n    if (!this.timeupdateSeen_) {\n      this.one(this.player_, 'play', this.handlePlay_);\n      this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);\n    } else {\n      this.on(this.player_, 'seeked', this.handleSeeked_);\n    }\n  }\n\n  /**\n   * handle the first timeupdate on the player if it wasn't already playing\n   * when live tracker started tracking.\n   */\n  handleFirstTimeupdate() {\n    this.timeupdateSeen_ = true;\n    this.on(this.player_, 'seeked', this.handleSeeked_);\n  }\n\n  /**\n   * Keep track of what time a seek starts, and listen for seeked\n   * to find where a seek ends.\n   */\n  handleSeeked() {\n    const timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());\n    this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;\n    this.nextSeekedFromUser_ = false;\n    this.trackLive_();\n  }\n\n  /**\n   * handle the first play on the player, and make sure that we seek\n   * right to the live edge.\n   */\n  handlePlay() {\n    this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);\n  }\n\n  /**\n   * Stop tracking, and set all internal variables to\n   * their initial value.\n   */\n  reset_() {\n    this.lastTime_ = -1;\n    this.pastSeekEnd_ = 0;\n    this.lastSeekEnd_ = -1;\n    this.behindLiveEdge_ = true;\n    this.timeupdateSeen_ = false;\n    this.seekedBehindLive_ = false;\n    this.nextSeekedFromUser_ = false;\n    this.clearInterval(this.trackingInterval_);\n    this.trackingInterval_ = null;\n    this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);\n    this.off(this.player_, 'seeked', this.handleSeeked_);\n    this.off(this.player_, 'play', this.handlePlay_);\n    this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);\n    this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);\n  }\n\n  /**\n   * The next seeked event is from the user. Meaning that any seek\n   * > 2s behind live will be considered behind live for real and\n   * liveTolerance will be ignored.\n   */\n  nextSeekedFromUser() {\n    this.nextSeekedFromUser_ = true;\n  }\n\n  /**\n   * stop tracking live playback\n   */\n  stopTracking() {\n    if (!this.isTracking()) {\n      return;\n    }\n    this.reset_();\n    this.trigger('liveedgechange');\n  }\n\n  /**\n   * A helper to get the player seekable end\n   * so that we don't have to null check everywhere\n   *\n   * @return {number}\n   *         The furthest seekable end or Infinity.\n   */\n  seekableEnd() {\n    const seekable = this.player_.seekable();\n    const seekableEnds = [];\n    let i = seekable ? seekable.length : 0;\n    while (i--) {\n      seekableEnds.push(seekable.end(i));\n    }\n\n    // grab the furthest seekable end after sorting, or if there are none\n    // default to Infinity\n    return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;\n  }\n\n  /**\n   * A helper to get the player seekable start\n   * so that we don't have to null check everywhere\n   *\n   * @return {number}\n   *         The earliest seekable start or 0.\n   */\n  seekableStart() {\n    const seekable = this.player_.seekable();\n    const seekableStarts = [];\n    let i = seekable ? seekable.length : 0;\n    while (i--) {\n      seekableStarts.push(seekable.start(i));\n    }\n\n    // grab the first seekable start after sorting, or if there are none\n    // default to 0\n    return seekableStarts.length ? seekableStarts.sort()[0] : 0;\n  }\n\n  /**\n   * Get the live time window aka\n   * the amount of time between seekable start and\n   * live current time.\n   *\n   * @return {number}\n   *         The amount of seconds that are seekable in\n   *         the live video.\n   */\n  liveWindow() {\n    const liveCurrentTime = this.liveCurrentTime();\n\n    // if liveCurrenTime is Infinity then we don't have a liveWindow at all\n    if (liveCurrentTime === Infinity) {\n      return 0;\n    }\n    return liveCurrentTime - this.seekableStart();\n  }\n\n  /**\n   * Determines if the player is live, only checks if this component\n   * is tracking live playback or not\n   *\n   * @return {boolean}\n   *         Whether liveTracker is tracking\n   */\n  isLive() {\n    return this.isTracking();\n  }\n\n  /**\n   * Determines if currentTime is at the live edge and won't fall behind\n   * on each seekableendchange\n   *\n   * @return {boolean}\n   *         Whether playback is at the live edge\n   */\n  atLiveEdge() {\n    return !this.behindLiveEdge();\n  }\n\n  /**\n   * get what we expect the live current time to be\n   *\n   * @return {number}\n   *         The expected live current time\n   */\n  liveCurrentTime() {\n    return this.pastSeekEnd() + this.seekableEnd();\n  }\n\n  /**\n   * The number of seconds that have occurred after seekable end\n   * changed. This will be reset to 0 once seekable end changes.\n   *\n   * @return {number}\n   *         Seconds past the current seekable end\n   */\n  pastSeekEnd() {\n    const seekableEnd = this.seekableEnd();\n    if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {\n      this.pastSeekEnd_ = 0;\n    }\n    this.lastSeekEnd_ = seekableEnd;\n    return this.pastSeekEnd_;\n  }\n\n  /**\n   * If we are currently behind the live edge, aka currentTime will be\n   * behind on a seekableendchange\n   *\n   * @return {boolean}\n   *         If we are behind the live edge\n   */\n  behindLiveEdge() {\n    return this.behindLiveEdge_;\n  }\n\n  /**\n   * Whether live tracker is currently tracking or not.\n   */\n  isTracking() {\n    return typeof this.trackingInterval_ === 'number';\n  }\n\n  /**\n   * Seek to the live edge if we are behind the live edge\n   */\n  seekToLiveEdge() {\n    this.seekedBehindLive_ = false;\n    if (this.atLiveEdge()) {\n      return;\n    }\n    this.nextSeekedFromUser_ = false;\n    this.player_.currentTime(this.liveCurrentTime());\n  }\n\n  /**\n   * Dispose of liveTracker\n   */\n  dispose() {\n    this.stopTracking();\n    super.dispose();\n  }\n}\nComponent$1.registerComponent('LiveTracker', LiveTracker);\n\n/**\n * Displays an element over the player which contains an optional title and\n * description for the current content.\n *\n * Much of the code for this component originated in the now obsolete\n * videojs-dock plugin: https://github.com/brightcove/videojs-dock/\n *\n * @extends Component\n */\nclass TitleBar extends Component$1 {\n  constructor(player, options) {\n    super(player, options);\n    this.on('statechanged', e => this.updateDom_());\n    this.updateDom_();\n  }\n\n  /**\n   * Create the `TitleBar`'s DOM element\n   *\n   * @return {Element}\n   *         The element that was created.\n   */\n  createEl() {\n    this.els = {\n      title: createEl('div', {\n        className: 'vjs-title-bar-title',\n        id: `vjs-title-bar-title-${newGUID()}`\n      }),\n      description: createEl('div', {\n        className: 'vjs-title-bar-description',\n        id: `vjs-title-bar-description-${newGUID()}`\n      })\n    };\n    return createEl('div', {\n      className: 'vjs-title-bar'\n    }, {}, values(this.els));\n  }\n\n  /**\n   * Updates the DOM based on the component's state object.\n   */\n  updateDom_() {\n    const tech = this.player_.tech_;\n    const techEl = tech && tech.el_;\n    const techAriaAttrs = {\n      title: 'aria-labelledby',\n      description: 'aria-describedby'\n    };\n    ['title', 'description'].forEach(k => {\n      const value = this.state[k];\n      const el = this.els[k];\n      const techAriaAttr = techAriaAttrs[k];\n      emptyEl(el);\n      if (value) {\n        textContent(el, value);\n      }\n\n      // If there is a tech element available, update its ARIA attributes\n      // according to whether a title and/or description have been provided.\n      if (techEl) {\n        techEl.removeAttribute(techAriaAttr);\n        if (value) {\n          techEl.setAttribute(techAriaAttr, el.id);\n        }\n      }\n    });\n    if (this.state.title || this.state.description) {\n      this.show();\n    } else {\n      this.hide();\n    }\n  }\n\n  /**\n   * Update the contents of the title bar component with new title and\n   * description text.\n   *\n   * If both title and description are missing, the title bar will be hidden.\n   *\n   * If either title or description are present, the title bar will be visible.\n   *\n   * NOTE: Any previously set value will be preserved. To unset a previously\n   * set value, you must pass an empty string or null.\n   *\n   * For example:\n   *\n   * ```\n   * update({title: 'foo', description: 'bar'}) // title: 'foo', description: 'bar'\n   * update({description: 'bar2'}) // title: 'foo', description: 'bar2'\n   * update({title: ''}) // title: '', description: 'bar2'\n   * update({title: 'foo', description: null}) // title: 'foo', description: null\n   * ```\n   *\n   * @param  {Object} [options={}]\n   *         An options object. When empty, the title bar will be hidden.\n   *\n   * @param  {string} [options.title]\n   *         A title to display in the title bar.\n   *\n   * @param  {string} [options.description]\n   *         A description to display in the title bar.\n   */\n  update(options) {\n    this.setState(options);\n  }\n\n  /**\n   * Dispose the component.\n   */\n  dispose() {\n    const tech = this.player_.tech_;\n    const techEl = tech && tech.el_;\n    if (techEl) {\n      techEl.removeAttribute('aria-labelledby');\n      techEl.removeAttribute('aria-describedby');\n    }\n    super.dispose();\n    this.els = null;\n  }\n}\nComponent$1.registerComponent('TitleBar', TitleBar);\n\n/** @import Player from './player' */\n\n/**\n * @typedef {object} TransientButtonOptions\n * @property {string} [controlText] Control text, usually visible for these buttons\n * @property {number} [initialDisplay=4000] Time in ms that button should initially remain visible\n * @property {Array<'top'|'neartop'|'bottom'|'left'|'right'>} [position] Array of position strings to add basic styles for positioning\n * @property {string} [className] Class(es) to add\n * @property {boolean} [takeFocus=false] Whether element sohuld take focus when shown\n * @property {Function} [clickHandler] Function called on button activation\n */\n\n/** @type {TransientButtonOptions} */\nconst defaults = {\n  initialDisplay: 4000,\n  position: [],\n  takeFocus: false\n};\n\n/**\n * A floating transient button.\n * It's recommended to insert these buttons _before_ the control bar with the this argument to `addChild`\n * for a logical tab order.\n *\n * @example\n * ```\n * player.addChild(\n *   'TransientButton',\n *   options,\n *   player.children().indexOf(player.getChild(\"ControlBar\"))\n * )\n * ```\n *\n * @extends Button\n */\nclass TransientButton extends Button {\n  /**\n   * TransientButton constructor\n   *\n   * @param {Player} player The button's player\n   * @param {TransientButtonOptions} options Options for the transient button\n   */\n  constructor(player, options) {\n    options = merge$1(defaults, options);\n    super(player, options);\n    this.controlText(options.controlText);\n    this.hide();\n\n    // When shown, the float button will be visible even if the user is inactive.\n    // Clear this if there is any interaction.\n    this.on(this.player_, ['useractive', 'userinactive'], e => {\n      this.removeClass('force-display');\n    });\n  }\n\n  /**\n   * Return CSS class including position classes\n   *\n   * @return {string} CSS class list\n   */\n  buildCSSClass() {\n    return `vjs-transient-button focus-visible ${this.options_.position.map(c => `vjs-${c}`).join(' ')}`;\n  }\n\n  /**\n   * Create the button element\n   *\n   * @return {HTMLButtonElement} The button element\n   */\n  createEl() {\n    /** @type HTMLButtonElement */\n    const el = createEl('button', {}, {\n      type: 'button',\n      class: this.buildCSSClass()\n    }, createEl('span'));\n    this.controlTextEl_ = el.querySelector('span');\n    return el;\n  }\n\n  /**\n   * Show the button. The button will remain visible for the `initialDisplay` time, default 4s,\n   * and when there is user activity.\n   */\n  show() {\n    super.show();\n    this.addClass('force-display');\n    if (this.options_.takeFocus) {\n      this.el().focus({\n        preventScroll: true\n      });\n    }\n    this.forceDisplayTimeout = this.player_.setTimeout(() => {\n      this.removeClass('force-display');\n    }, this.options_.initialDisplay);\n  }\n\n  /**\n   * Hide the display, even if during the `initialDisplay` time.\n   */\n  hide() {\n    this.removeClass('force-display');\n    super.hide();\n  }\n\n  /**\n   * Dispose the component\n   */\n  dispose() {\n    this.player_.clearTimeout(this.forceDisplayTimeout);\n    super.dispose();\n  }\n}\nComponent$1.registerComponent('TransientButton', TransientButton);\n\n/** @import Html5 from './html5' */\n\n/**\n * This function is used to fire a sourceset when there is something\n * similar to `mediaEl.load()` being called. It will try to find the source via\n * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`\n * with the source that was found or empty string if we cannot know. If it cannot\n * find a source then `sourceset` will not be fired.\n *\n * @param {Html5} tech\n *        The tech object that sourceset was setup on\n *\n * @return {boolean}\n *         returns false if the sourceset was not fired and true otherwise.\n */\nconst sourcesetLoad = tech => {\n  const el = tech.el();\n\n  // if `el.src` is set, that source will be loaded.\n  if (el.hasAttribute('src')) {\n    tech.triggerSourceset(el.src);\n    return true;\n  }\n\n  /**\n   * Since there isn't a src property on the media element, source elements will be used for\n   * implementing the source selection algorithm. This happens asynchronously and\n   * for most cases were there is more than one source we cannot tell what source will\n   * be loaded, without re-implementing the source selection algorithm. At this time we are not\n   * going to do that. There are three special cases that we do handle here though:\n   *\n   * 1. If there are no sources, do not fire `sourceset`.\n   * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`\n   * 3. If there is more than one `<source>` but all of them have the same `src` url.\n   *    That will be our src.\n   */\n  const sources = tech.$$('source');\n  const srcUrls = [];\n  let src = '';\n\n  // if there are no sources, do not fire sourceset\n  if (!sources.length) {\n    return false;\n  }\n\n  // only count valid/non-duplicate source elements\n  for (let i = 0; i < sources.length; i++) {\n    const url = sources[i].src;\n    if (url && srcUrls.indexOf(url) === -1) {\n      srcUrls.push(url);\n    }\n  }\n\n  // there were no valid sources\n  if (!srcUrls.length) {\n    return false;\n  }\n\n  // there is only one valid source element url\n  // use that\n  if (srcUrls.length === 1) {\n    src = srcUrls[0];\n  }\n  tech.triggerSourceset(src);\n  return true;\n};\n\n/**\n * our implementation of an `innerHTML` descriptor for browsers\n * that do not have one.\n */\nconst innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {\n  get() {\n    return this.cloneNode(true).innerHTML;\n  },\n  set(v) {\n    // make a dummy node to use innerHTML on\n    const dummy = document$1.createElement(this.nodeName.toLowerCase());\n\n    // set innerHTML to the value provided\n    dummy.innerHTML = v;\n\n    // make a document fragment to hold the nodes from dummy\n    const docFrag = document$1.createDocumentFragment();\n\n    // copy all of the nodes created by the innerHTML on dummy\n    // to the document fragment\n    while (dummy.childNodes.length) {\n      docFrag.appendChild(dummy.childNodes[0]);\n    }\n\n    // remove content\n    this.innerText = '';\n\n    // now we add all of that html in one by appending the\n    // document fragment. This is how innerHTML does it.\n    window$1.Element.prototype.appendChild.call(this, docFrag);\n\n    // then return the result that innerHTML's setter would\n    return this.innerHTML;\n  }\n});\n\n/**\n * Get a property descriptor given a list of priorities and the\n * property to get.\n */\nconst getDescriptor = (priority, prop) => {\n  let descriptor = {};\n  for (let i = 0; i < priority.length; i++) {\n    descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);\n    if (descriptor && descriptor.set && descriptor.get) {\n      break;\n    }\n  }\n  descriptor.enumerable = true;\n  descriptor.configurable = true;\n  return descriptor;\n};\nconst getInnerHTMLDescriptor = tech => getDescriptor([tech.el(), window$1.HTMLMediaElement.prototype, window$1.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');\n\n/**\n * Patches browser internal functions so that we can tell synchronously\n * if a `<source>` was appended to the media element. For some reason this\n * causes a `sourceset` if the the media element is ready and has no source.\n * This happens when:\n * - The page has just loaded and the media element does not have a source.\n * - The media element was emptied of all sources, then `load()` was called.\n *\n * It does this by patching the following functions/properties when they are supported:\n *\n * - `append()` - can be used to add a `<source>` element to the media element\n * - `appendChild()` - can be used to add a `<source>` element to the media element\n * - `insertAdjacentHTML()` -  can be used to add a `<source>` element to the media element\n * - `innerHTML` -  can be used to add a `<source>` element to the media element\n *\n * @param {Html5} tech\n *        The tech object that sourceset is being setup on.\n */\nconst firstSourceWatch = function (tech) {\n  const el = tech.el();\n\n  // make sure firstSourceWatch isn't setup twice.\n  if (el.resetSourceWatch_) {\n    return;\n  }\n  const old = {};\n  const innerDescriptor = getInnerHTMLDescriptor(tech);\n  const appendWrapper = appendFn => (...args) => {\n    const retval = appendFn.apply(el, args);\n    sourcesetLoad(tech);\n    return retval;\n  };\n  ['append', 'appendChild', 'insertAdjacentHTML'].forEach(k => {\n    if (!el[k]) {\n      return;\n    }\n\n    // store the old function\n    old[k] = el[k];\n\n    // call the old function with a sourceset if a source\n    // was loaded\n    el[k] = appendWrapper(old[k]);\n  });\n  Object.defineProperty(el, 'innerHTML', merge$1(innerDescriptor, {\n    set: appendWrapper(innerDescriptor.set)\n  }));\n  el.resetSourceWatch_ = () => {\n    el.resetSourceWatch_ = null;\n    Object.keys(old).forEach(k => {\n      el[k] = old[k];\n    });\n    Object.defineProperty(el, 'innerHTML', innerDescriptor);\n  };\n\n  // on the first sourceset, we need to revert our changes\n  tech.one('sourceset', el.resetSourceWatch_);\n};\n\n/**\n * our implementation of a `src` descriptor for browsers\n * that do not have one\n */\nconst srcDescriptorPolyfill = Object.defineProperty({}, 'src', {\n  get() {\n    if (this.hasAttribute('src')) {\n      return getAbsoluteURL(window$1.Element.prototype.getAttribute.call(this, 'src'));\n    }\n    return '';\n  },\n  set(v) {\n    window$1.Element.prototype.setAttribute.call(this, 'src', v);\n    return v;\n  }\n});\nconst getSrcDescriptor = tech => getDescriptor([tech.el(), window$1.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');\n\n/**\n * setup `sourceset` handling on the `Html5` tech. This function\n * patches the following element properties/functions:\n *\n * - `src` - to determine when `src` is set\n * - `setAttribute()` - to determine when `src` is set\n * - `load()` - this re-triggers the source selection algorithm, and can\n *              cause a sourceset.\n *\n * If there is no source when we are adding `sourceset` support or during a `load()`\n * we also patch the functions listed in `firstSourceWatch`.\n *\n * @param {Html5} tech\n *        The tech to patch\n */\nconst setupSourceset = function (tech) {\n  if (!tech.featuresSourceset) {\n    return;\n  }\n  const el = tech.el();\n\n  // make sure sourceset isn't setup twice.\n  if (el.resetSourceset_) {\n    return;\n  }\n  const srcDescriptor = getSrcDescriptor(tech);\n  const oldSetAttribute = el.setAttribute;\n  const oldLoad = el.load;\n  Object.defineProperty(el, 'src', merge$1(srcDescriptor, {\n    set: v => {\n      const retval = srcDescriptor.set.call(el, v);\n\n      // we use the getter here to get the actual value set on src\n      tech.triggerSourceset(el.src);\n      return retval;\n    }\n  }));\n  el.setAttribute = (n, v) => {\n    const retval = oldSetAttribute.call(el, n, v);\n    if (/src/i.test(n)) {\n      tech.triggerSourceset(el.src);\n    }\n    return retval;\n  };\n  el.load = () => {\n    const retval = oldLoad.call(el);\n\n    // if load was called, but there was no source to fire\n    // sourceset on. We have to watch for a source append\n    // as that can trigger a `sourceset` when the media element\n    // has no source\n    if (!sourcesetLoad(tech)) {\n      tech.triggerSourceset('');\n      firstSourceWatch(tech);\n    }\n    return retval;\n  };\n  if (el.currentSrc) {\n    tech.triggerSourceset(el.currentSrc);\n  } else if (!sourcesetLoad(tech)) {\n    firstSourceWatch(tech);\n  }\n  el.resetSourceset_ = () => {\n    el.resetSourceset_ = null;\n    el.load = oldLoad;\n    el.setAttribute = oldSetAttribute;\n    Object.defineProperty(el, 'src', srcDescriptor);\n    if (el.resetSourceWatch_) {\n      el.resetSourceWatch_();\n    }\n  };\n};\n\n/**\n * @file html5.js\n */\n\n/**\n * HTML5 Media Controller - Wrapper for HTML5 Media API\n *\n * @mixes Tech~SourceHandlerAdditions\n * @extends Tech\n */\nclass Html5 extends Tech {\n  /**\n  * Create an instance of this Tech.\n  *\n  * @param {Object} [options]\n  *        The key/value store of player options.\n  *\n  * @param {Function} [ready]\n  *        Callback function to call when the `HTML5` Tech is ready.\n  */\n  constructor(options, ready) {\n    super(options, ready);\n    const source = options.source;\n    let crossoriginTracks = false;\n    this.featuresVideoFrameCallback = this.featuresVideoFrameCallback && this.el_.tagName === 'VIDEO';\n\n    // Set the source if one is provided\n    // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)\n    // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source\n    // anyway so the error gets fired.\n    if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {\n      this.setSource(source);\n    } else {\n      this.handleLateInit_(this.el_);\n    }\n\n    // setup sourceset after late sourceset/init\n    if (options.enableSourceset) {\n      this.setupSourcesetHandling_();\n    }\n    this.isScrubbing_ = false;\n    if (this.el_.hasChildNodes()) {\n      const nodes = this.el_.childNodes;\n      let nodesLength = nodes.length;\n      const removeNodes = [];\n      while (nodesLength--) {\n        const node = nodes[nodesLength];\n        const nodeName = node.nodeName.toLowerCase();\n        if (nodeName === 'track') {\n          if (!this.featuresNativeTextTracks) {\n            // Empty video tag tracks so the built-in player doesn't use them also.\n            // This may not be fast enough to stop HTML5 browsers from reading the tags\n            // so we'll need to turn off any default tracks if we're manually doing\n            // captions and subtitles. videoElement.textTracks\n            removeNodes.push(node);\n          } else {\n            // store HTMLTrackElement and TextTrack to remote list\n            this.remoteTextTrackEls().addTrackElement_(node);\n            this.remoteTextTracks().addTrack(node.track);\n            this.textTracks().addTrack(node.track);\n            if (!crossoriginTracks && !this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {\n              crossoriginTracks = true;\n            }\n          }\n        }\n      }\n      for (let i = 0; i < removeNodes.length; i++) {\n        this.el_.removeChild(removeNodes[i]);\n      }\n    }\n    this.proxyNativeTracks_();\n    if (this.featuresNativeTextTracks && crossoriginTracks) {\n      log$1.warn('Text Tracks are being loaded from another origin but the crossorigin attribute isn\\'t used.\\n' + 'This may prevent text tracks from loading.');\n    }\n\n    // prevent iOS Safari from disabling metadata text tracks during native playback\n    this.restoreMetadataTracksInIOSNativePlayer_();\n\n    // Determine if native controls should be used\n    // Our goal should be to get the custom controls on mobile solid everywhere\n    // so we can remove this all together. Right now this will block custom\n    // controls on touch enabled laptops like the Chrome Pixel\n    if ((TOUCH_ENABLED || IS_IPHONE) && options.nativeControlsForTouch === true) {\n      this.setControls(true);\n    }\n\n    // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`\n    // into a `fullscreenchange` event\n    this.proxyWebkitFullscreen_();\n    this.triggerReady();\n  }\n\n  /**\n   * Dispose of `HTML5` media element and remove all tracks.\n   */\n  dispose() {\n    if (this.el_ && this.el_.resetSourceset_) {\n      this.el_.resetSourceset_();\n    }\n    Html5.disposeMediaElement(this.el_);\n    this.options_ = null;\n\n    // tech will handle clearing of the emulated track list\n    super.dispose();\n  }\n\n  /**\n   * Modify the media element so that we can detect when\n   * the source is changed. Fires `sourceset` just after the source has changed\n   */\n  setupSourcesetHandling_() {\n    setupSourceset(this);\n  }\n\n  /**\n   * When a captions track is enabled in the iOS Safari native player, all other\n   * tracks are disabled (including metadata tracks), which nulls all of their\n   * associated cue points. This will restore metadata tracks to their pre-fullscreen\n   * state in those cases so that cue points are not needlessly lost.\n   *\n   * @private\n   */\n  restoreMetadataTracksInIOSNativePlayer_() {\n    const textTracks = this.textTracks();\n    let metadataTracksPreFullscreenState;\n\n    // captures a snapshot of every metadata track's current state\n    const takeMetadataTrackSnapshot = () => {\n      metadataTracksPreFullscreenState = [];\n      for (let i = 0; i < textTracks.length; i++) {\n        const track = textTracks[i];\n        if (track.kind === 'metadata') {\n          metadataTracksPreFullscreenState.push({\n            track,\n            storedMode: track.mode\n          });\n        }\n      }\n    };\n\n    // snapshot each metadata track's initial state, and update the snapshot\n    // each time there is a track 'change' event\n    takeMetadataTrackSnapshot();\n    textTracks.addEventListener('change', takeMetadataTrackSnapshot);\n    this.on('dispose', () => textTracks.removeEventListener('change', takeMetadataTrackSnapshot));\n    const restoreTrackMode = () => {\n      for (let i = 0; i < metadataTracksPreFullscreenState.length; i++) {\n        const storedTrack = metadataTracksPreFullscreenState[i];\n        if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {\n          storedTrack.track.mode = storedTrack.storedMode;\n        }\n      }\n      // we only want this handler to be executed on the first 'change' event\n      textTracks.removeEventListener('change', restoreTrackMode);\n    };\n\n    // when we enter fullscreen playback, stop updating the snapshot and\n    // restore all track modes to their pre-fullscreen state\n    this.on('webkitbeginfullscreen', () => {\n      textTracks.removeEventListener('change', takeMetadataTrackSnapshot);\n\n      // remove the listener before adding it just in case it wasn't previously removed\n      textTracks.removeEventListener('change', restoreTrackMode);\n      textTracks.addEventListener('change', restoreTrackMode);\n    });\n\n    // start updating the snapshot again after leaving fullscreen\n    this.on('webkitendfullscreen', () => {\n      // remove the listener before adding it just in case it wasn't previously removed\n      textTracks.removeEventListener('change', takeMetadataTrackSnapshot);\n      textTracks.addEventListener('change', takeMetadataTrackSnapshot);\n\n      // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback\n      textTracks.removeEventListener('change', restoreTrackMode);\n    });\n  }\n\n  /**\n   * Attempt to force override of tracks for the given type\n   *\n   * @param {string} type - Track type to override, possible values include 'Audio',\n   * 'Video', and 'Text'.\n   * @param {boolean} override - If set to true native audio/video will be overridden,\n   * otherwise native audio/video will potentially be used.\n   * @private\n   */\n  overrideNative_(type, override) {\n    // If there is no behavioral change don't add/remove listeners\n    if (override !== this[`featuresNative${type}Tracks`]) {\n      return;\n    }\n    const lowerCaseType = type.toLowerCase();\n    if (this[`${lowerCaseType}TracksListeners_`]) {\n      Object.keys(this[`${lowerCaseType}TracksListeners_`]).forEach(eventName => {\n        const elTracks = this.el()[`${lowerCaseType}Tracks`];\n        elTracks.removeEventListener(eventName, this[`${lowerCaseType}TracksListeners_`][eventName]);\n      });\n    }\n    this[`featuresNative${type}Tracks`] = !override;\n    this[`${lowerCaseType}TracksListeners_`] = null;\n    this.proxyNativeTracksForType_(lowerCaseType);\n  }\n\n  /**\n   * Attempt to force override of native audio tracks.\n   *\n   * @param {boolean} override - If set to true native audio will be overridden,\n   * otherwise native audio will potentially be used.\n   */\n  overrideNativeAudioTracks(override) {\n    this.overrideNative_('Audio', override);\n  }\n\n  /**\n   * Attempt to force override of native video tracks.\n   *\n   * @param {boolean} override - If set to true native video will be overridden,\n   * otherwise native video will potentially be used.\n   */\n  overrideNativeVideoTracks(override) {\n    this.overrideNative_('Video', override);\n  }\n\n  /**\n   * Proxy native track list events for the given type to our track\n   * lists if the browser we are playing in supports that type of track list.\n   *\n   * @param {string} name - Track type; values include 'audio', 'video', and 'text'\n   * @private\n   */\n  proxyNativeTracksForType_(name) {\n    const props = NORMAL[name];\n    const elTracks = this.el()[props.getterName];\n    const techTracks = this[props.getterName]();\n    if (!this[`featuresNative${props.capitalName}Tracks`] || !elTracks || !elTracks.addEventListener) {\n      return;\n    }\n    const listeners = {\n      change: e => {\n        const event = {\n          type: 'change',\n          target: techTracks,\n          currentTarget: techTracks,\n          srcElement: techTracks\n        };\n        techTracks.trigger(event);\n\n        // if we are a text track change event, we should also notify the\n        // remote text track list. This can potentially cause a false positive\n        // if we were to get a change event on a non-remote track and\n        // we triggered the event on the remote text track list which doesn't\n        // contain that track. However, best practices mean looping through the\n        // list of tracks and searching for the appropriate mode value, so,\n        // this shouldn't pose an issue\n        if (name === 'text') {\n          this[REMOTE.remoteText.getterName]().trigger(event);\n        }\n      },\n      addtrack(e) {\n        techTracks.addTrack(e.track);\n      },\n      removetrack(e) {\n        techTracks.removeTrack(e.track);\n      }\n    };\n    const removeOldTracks = function () {\n      const removeTracks = [];\n      for (let i = 0; i < techTracks.length; i++) {\n        let found = false;\n        for (let j = 0; j < elTracks.length; j++) {\n          if (elTracks[j] === techTracks[i]) {\n            found = true;\n            break;\n          }\n        }\n        if (!found) {\n          removeTracks.push(techTracks[i]);\n        }\n      }\n      while (removeTracks.length) {\n        techTracks.removeTrack(removeTracks.shift());\n      }\n    };\n    this[props.getterName + 'Listeners_'] = listeners;\n    Object.keys(listeners).forEach(eventName => {\n      const listener = listeners[eventName];\n      elTracks.addEventListener(eventName, listener);\n      this.on('dispose', e => elTracks.removeEventListener(eventName, listener));\n    });\n\n    // Remove (native) tracks that are not used anymore\n    this.on('loadstart', removeOldTracks);\n    this.on('dispose', e => this.off('loadstart', removeOldTracks));\n  }\n\n  /**\n   * Proxy all native track list events to our track lists if the browser we are playing\n   * in supports that type of track list.\n   *\n   * @private\n   */\n  proxyNativeTracks_() {\n    NORMAL.names.forEach(name => {\n      this.proxyNativeTracksForType_(name);\n    });\n  }\n\n  /**\n   * Create the `Html5` Tech's DOM element.\n   *\n   * @return {Element}\n   *         The element that gets created.\n   */\n  createEl() {\n    let el = this.options_.tag;\n\n    // Check if this browser supports moving the element into the box.\n    // On the iPhone video will break if you move the element,\n    // So we have to create a brand new element.\n    // If we ingested the player div, we do not need to move the media element.\n    if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {\n      // If the original tag is still there, clone and remove it.\n      if (el) {\n        const clone = el.cloneNode(true);\n        if (el.parentNode) {\n          el.parentNode.insertBefore(clone, el);\n        }\n        Html5.disposeMediaElement(el);\n        el = clone;\n      } else {\n        el = document$1.createElement('video');\n\n        // determine if native controls should be used\n        const tagAttributes = this.options_.tag && getAttributes(this.options_.tag);\n        const attributes = merge$1({}, tagAttributes);\n        if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {\n          delete attributes.controls;\n        }\n        setAttributes(el, Object.assign(attributes, {\n          id: this.options_.techId,\n          class: 'vjs-tech'\n        }));\n      }\n      el.playerId = this.options_.playerId;\n    }\n    if (typeof this.options_.preload !== 'undefined') {\n      setAttribute(el, 'preload', this.options_.preload);\n    }\n    if (this.options_.disablePictureInPicture !== undefined) {\n      el.disablePictureInPicture = this.options_.disablePictureInPicture;\n    }\n\n    // Update specific tag settings, in case they were overridden\n    // `autoplay` has to be *last* so that `muted` and `playsinline` are present\n    // when iOS/Safari or other browsers attempt to autoplay.\n    const settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];\n    for (let i = 0; i < settingsAttrs.length; i++) {\n      const attr = settingsAttrs[i];\n      const value = this.options_[attr];\n      if (typeof value !== 'undefined') {\n        if (value) {\n          setAttribute(el, attr, attr);\n        } else {\n          removeAttribute(el, attr);\n        }\n        el[attr] = value;\n      }\n    }\n    return el;\n  }\n\n  /**\n   * This will be triggered if the loadstart event has already fired, before videojs was\n   * ready. Two known examples of when this can happen are:\n   * 1. If we're loading the playback object after it has started loading\n   * 2. The media is already playing the (often with autoplay on) then\n   *\n   * This function will fire another loadstart so that videojs can catchup.\n   *\n   * @fires Tech#loadstart\n   *\n   * @return {undefined}\n   *         returns nothing.\n   */\n  handleLateInit_(el) {\n    if (el.networkState === 0 || el.networkState === 3) {\n      // The video element hasn't started loading the source yet\n      // or didn't find a source\n      return;\n    }\n    if (el.readyState === 0) {\n      // NetworkState is set synchronously BUT loadstart is fired at the\n      // end of the current stack, usually before setInterval(fn, 0).\n      // So at this point we know loadstart may have already fired or is\n      // about to fire, and either way the player hasn't seen it yet.\n      // We don't want to fire loadstart prematurely here and cause a\n      // double loadstart so we'll wait and see if it happens between now\n      // and the next loop, and fire it if not.\n      // HOWEVER, we also want to make sure it fires before loadedmetadata\n      // which could also happen between now and the next loop, so we'll\n      // watch for that also.\n      let loadstartFired = false;\n      const setLoadstartFired = function () {\n        loadstartFired = true;\n      };\n      this.on('loadstart', setLoadstartFired);\n      const triggerLoadstart = function () {\n        // We did miss the original loadstart. Make sure the player\n        // sees loadstart before loadedmetadata\n        if (!loadstartFired) {\n          this.trigger('loadstart');\n        }\n      };\n      this.on('loadedmetadata', triggerLoadstart);\n      this.ready(function () {\n        this.off('loadstart', setLoadstartFired);\n        this.off('loadedmetadata', triggerLoadstart);\n        if (!loadstartFired) {\n          // We did miss the original native loadstart. Fire it now.\n          this.trigger('loadstart');\n        }\n      });\n      return;\n    }\n\n    // From here on we know that loadstart already fired and we missed it.\n    // The other readyState events aren't as much of a problem if we double\n    // them, so not going to go to as much trouble as loadstart to prevent\n    // that unless we find reason to.\n    const eventsToTrigger = ['loadstart'];\n\n    // loadedmetadata: newly equal to HAVE_METADATA (1) or greater\n    eventsToTrigger.push('loadedmetadata');\n\n    // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater\n    if (el.readyState >= 2) {\n      eventsToTrigger.push('loadeddata');\n    }\n\n    // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater\n    if (el.readyState >= 3) {\n      eventsToTrigger.push('canplay');\n    }\n\n    // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)\n    if (el.readyState >= 4) {\n      eventsToTrigger.push('canplaythrough');\n    }\n\n    // We still need to give the player time to add event listeners\n    this.ready(function () {\n      eventsToTrigger.forEach(function (type) {\n        this.trigger(type);\n      }, this);\n    });\n  }\n\n  /**\n   * Set whether we are scrubbing or not.\n   * This is used to decide whether we should use `fastSeek` or not.\n   * `fastSeek` is used to provide trick play on Safari browsers.\n   *\n   * @param {boolean} isScrubbing\n   *                  - true for we are currently scrubbing\n   *                  - false for we are no longer scrubbing\n   */\n  setScrubbing(isScrubbing) {\n    this.isScrubbing_ = isScrubbing;\n  }\n\n  /**\n   * Get whether we are scrubbing or not.\n   *\n   * @return {boolean} isScrubbing\n   *                  - true for we are currently scrubbing\n   *                  - false for we are no longer scrubbing\n   */\n  scrubbing() {\n    return this.isScrubbing_;\n  }\n\n  /**\n   * Set current time for the `HTML5` tech.\n   *\n   * @param {number} seconds\n   *        Set the current time of the media to this.\n   */\n  setCurrentTime(seconds) {\n    try {\n      if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {\n        this.el_.fastSeek(seconds);\n      } else {\n        this.el_.currentTime = seconds;\n      }\n    } catch (e) {\n      log$1(e, 'Video is not ready. (Video.js)');\n      // this.warning(VideoJS.warnings.videoNotReady);\n    }\n  }\n\n  /**\n   * Get the current duration of the HTML5 media element.\n   *\n   * @return {number}\n   *         The duration of the media or 0 if there is no duration.\n   */\n  duration() {\n    // Android Chrome will report duration as Infinity for VOD HLS until after\n    // playback has started, which triggers the live display erroneously.\n    // Return NaN if playback has not started and trigger a durationupdate once\n    // the duration can be reliably known.\n    if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {\n      // Wait for the first `timeupdate` with currentTime > 0 - there may be\n      // several with 0\n      const checkProgress = () => {\n        if (this.el_.currentTime > 0) {\n          // Trigger durationchange for genuinely live video\n          if (this.el_.duration === Infinity) {\n            this.trigger('durationchange');\n          }\n          this.off('timeupdate', checkProgress);\n        }\n      };\n      this.on('timeupdate', checkProgress);\n      return NaN;\n    }\n    return this.el_.duration || NaN;\n  }\n\n  /**\n   * Get the current width of the HTML5 media element.\n   *\n   * @return {number}\n   *         The width of the HTML5 media element.\n   */\n  width() {\n    return this.el_.offsetWidth;\n  }\n\n  /**\n   * Get the current height of the HTML5 media element.\n   *\n   * @return {number}\n   *         The height of the HTML5 media element.\n   */\n  height() {\n    return this.el_.offsetHeight;\n  }\n\n  /**\n   * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into\n   * `fullscreenchange` event.\n   *\n   * @private\n   * @fires fullscreenchange\n   * @listens webkitendfullscreen\n   * @listens webkitbeginfullscreen\n   * @listens webkitbeginfullscreen\n   */\n  proxyWebkitFullscreen_() {\n    if (!('webkitDisplayingFullscreen' in this.el_)) {\n      return;\n    }\n    const endFn = function () {\n      this.trigger('fullscreenchange', {\n        isFullscreen: false\n      });\n      // Safari will sometimes set controls on the videoelement when existing fullscreen.\n      if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {\n        this.el_.controls = false;\n      }\n    };\n    const beginFn = function () {\n      if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {\n        this.one('webkitendfullscreen', endFn);\n        this.trigger('fullscreenchange', {\n          isFullscreen: true,\n          // set a flag in case another tech triggers fullscreenchange\n          nativeIOSFullscreen: true\n        });\n      }\n    };\n    this.on('webkitbeginfullscreen', beginFn);\n    this.on('dispose', () => {\n      this.off('webkitbeginfullscreen', beginFn);\n      this.off('webkitendfullscreen', endFn);\n    });\n  }\n\n  /**\n   * Check if fullscreen is supported on the video el.\n   *\n   * @return {boolean}\n   *         - True if fullscreen is supported.\n   *         - False if fullscreen is not supported.\n   */\n  supportsFullScreen() {\n    return typeof this.el_.webkitEnterFullScreen === 'function';\n  }\n\n  /**\n   * Request that the `HTML5` Tech enter fullscreen.\n   */\n  enterFullScreen() {\n    const video = this.el_;\n    if (video.paused && video.networkState <= video.HAVE_METADATA) {\n      // attempt to prime the video element for programmatic access\n      // this isn't necessary on the desktop but shouldn't hurt\n      silencePromise(this.el_.play());\n\n      // playing and pausing synchronously during the transition to fullscreen\n      // can get iOS ~6.1 devices into a play/pause loop\n      this.setTimeout(function () {\n        video.pause();\n        try {\n          video.webkitEnterFullScreen();\n        } catch (e) {\n          this.trigger('fullscreenerror', e);\n        }\n      }, 0);\n    } else {\n      try {\n        video.webkitEnterFullScreen();\n      } catch (e) {\n        this.trigger('fullscreenerror', e);\n      }\n    }\n  }\n\n  /**\n   * Request that the `HTML5` Tech exit fullscreen.\n   */\n  exitFullScreen() {\n    if (!this.el_.webkitDisplayingFullscreen) {\n      this.trigger('fullscreenerror', new Error('The video is not fullscreen'));\n      return;\n    }\n    this.el_.webkitExitFullScreen();\n  }\n\n  /**\n   * Create a floating video window always on top of other windows so that users may\n   * continue consuming media while they interact with other content sites, or\n   * applications on their device.\n   *\n   * @see [Spec]{@link https://wicg.github.io/picture-in-picture}\n   *\n   * @return {Promise}\n   *         A promise with a Picture-in-Picture window.\n   */\n  requestPictureInPicture() {\n    return this.el_.requestPictureInPicture();\n  }\n\n  /**\n   * Native requestVideoFrameCallback if supported by browser/tech, or fallback\n   * Don't use rVCF on Safari when DRM is playing, as it doesn't fire\n   * Needs to be checked later than the constructor\n   * This will be a false positive for clear sources loaded after a Fairplay source\n   *\n   * @param {function} cb function to call\n   * @return {number} id of request\n   */\n  requestVideoFrameCallback(cb) {\n    if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {\n      return this.el_.requestVideoFrameCallback(cb);\n    }\n    return super.requestVideoFrameCallback(cb);\n  }\n\n  /**\n   * Native or fallback requestVideoFrameCallback\n   *\n   * @param {number} id request id to cancel\n   */\n  cancelVideoFrameCallback(id) {\n    if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {\n      this.el_.cancelVideoFrameCallback(id);\n    } else {\n      super.cancelVideoFrameCallback(id);\n    }\n  }\n\n  /**\n   * A getter/setter for the `Html5` Tech's source object.\n   * > Note: Please use {@link Html5#setSource}\n   *\n   * @param {Tech~SourceObject} [src]\n   *        The source object you want to set on the `HTML5` techs element.\n   *\n   * @return {Tech~SourceObject|undefined}\n   *         - The current source object when a source is not passed in.\n   *         - undefined when setting\n   *\n   * @deprecated Since version 5.\n   */\n  src(src) {\n    if (src === undefined) {\n      return this.el_.src;\n    }\n\n    // Setting src through `src` instead of `setSrc` will be deprecated\n    this.setSrc(src);\n  }\n\n  /**\n   * Add a <source> element to the <video> element.\n   *\n   * @param {string} srcUrl\n   *        The URL of the video source.\n   *\n   * @param {string} [mimeType]\n   *        The MIME type of the video source. Optional but recommended.\n   *\n   * @return {boolean}\n   *         Returns true if the source element was successfully added, false otherwise.\n   */\n  addSourceElement(srcUrl, mimeType) {\n    if (!srcUrl) {\n      log$1.error('Invalid source URL.');\n      return false;\n    }\n    const sourceAttributes = {\n      src: srcUrl\n    };\n    if (mimeType) {\n      sourceAttributes.type = mimeType;\n    }\n    const sourceElement = createEl('source', {}, sourceAttributes);\n    this.el_.appendChild(sourceElement);\n    return true;\n  }\n\n  /**\n   * Remove a <source> element from the <video> element by its URL.\n   *\n   * @param {string} srcUrl\n   *        The URL of the source to remove.\n   *\n   * @return {boolean}\n   *         Returns true if the source element was successfully removed, false otherwise.\n   */\n  removeSourceElement(srcUrl) {\n    if (!srcUrl) {\n      log$1.error('Source URL is required to remove the source element.');\n      return false;\n    }\n    const sourceElements = this.el_.querySelectorAll('source');\n    for (const sourceElement of sourceElements) {\n      if (sourceElement.src === srcUrl) {\n        this.el_.removeChild(sourceElement);\n        return true;\n      }\n    }\n    log$1.warn(`No matching source element found with src: ${srcUrl}`);\n    return false;\n  }\n\n  /**\n   * Reset the tech by removing all sources and then calling\n   * {@link Html5.resetMediaElement}.\n   */\n  reset() {\n    Html5.resetMediaElement(this.el_);\n  }\n\n  /**\n   * Get the current source on the `HTML5` Tech. Falls back to returning the source from\n   * the HTML5 media element.\n   *\n   * @return {Tech~SourceObject}\n   *         The current source object from the HTML5 tech. With a fallback to the\n   *         elements source.\n   */\n  currentSrc() {\n    if (this.currentSource_) {\n      return this.currentSource_.src;\n    }\n    return this.el_.currentSrc;\n  }\n\n  /**\n   * Set controls attribute for the HTML5 media Element.\n   *\n   * @param {string} val\n   *        Value to set the controls attribute to\n   */\n  setControls(val) {\n    this.el_.controls = !!val;\n  }\n\n  /**\n   * Create and returns a remote {@link TextTrack} object.\n   *\n   * @param {string} kind\n   *        `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)\n   *\n   * @param {string} [label]\n   *        Label to identify the text track\n   *\n   * @param {string} [language]\n   *        Two letter language abbreviation\n   *\n   * @return {TextTrack}\n   *         The TextTrack that gets created.\n   */\n  addTextTrack(kind, label, language) {\n    if (!this.featuresNativeTextTracks) {\n      return super.addTextTrack(kind, label, language);\n    }\n    return this.el_.addTextTrack(kind, label, language);\n  }\n\n  /**\n   * Creates either native TextTrack or an emulated TextTrack depending\n   * on the value of `featuresNativeTextTracks`\n   *\n   * @param {Object} options\n   *        The object should contain the options to initialize the TextTrack with.\n   *\n   * @param {string} [options.kind]\n   *        `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).\n   *\n   * @param {string} [options.label]\n   *        Label to identify the text track\n   *\n   * @param {string} [options.language]\n   *        Two letter language abbreviation.\n   *\n   * @param {boolean} [options.default]\n   *        Default this track to on.\n   *\n   * @param {string} [options.id]\n   *        The internal id to assign this track.\n   *\n   * @param {string} [options.src]\n   *        A source url for the track.\n   *\n   * @return {HTMLTrackElement}\n   *         The track element that gets created.\n   */\n  createRemoteTextTrack(options) {\n    if (!this.featuresNativeTextTracks) {\n      return super.createRemoteTextTrack(options);\n    }\n    const htmlTrackElement = document$1.createElement('track');\n    if (options.kind) {\n      htmlTrackElement.kind = options.kind;\n    }\n    if (options.label) {\n      htmlTrackElement.label = options.label;\n    }\n    if (options.language || options.srclang) {\n      htmlTrackElement.srclang = options.language || options.srclang;\n    }\n    if (options.default) {\n      htmlTrackElement.default = options.default;\n    }\n    if (options.id) {\n      htmlTrackElement.id = options.id;\n    }\n    if (options.src) {\n      htmlTrackElement.src = options.src;\n    }\n    return htmlTrackElement;\n  }\n\n  /**\n   * Creates a remote text track object and returns an html track element.\n   *\n   * @param {Object} options The object should contain values for\n   * kind, language, label, and src (location of the WebVTT file)\n   * @param {boolean} [manualCleanup=false] if set to true, the TextTrack\n   * will not be removed from the TextTrackList and HtmlTrackElementList\n   * after a source change\n   * @return {HTMLTrackElement} An Html Track Element.\n   * This can be an emulated {@link HTMLTrackElement} or a native one.\n   *\n   */\n  addRemoteTextTrack(options, manualCleanup) {\n    const htmlTrackElement = super.addRemoteTextTrack(options, manualCleanup);\n    if (this.featuresNativeTextTracks) {\n      this.el().appendChild(htmlTrackElement);\n    }\n    return htmlTrackElement;\n  }\n\n  /**\n   * Remove remote `TextTrack` from `TextTrackList` object\n   *\n   * @param {TextTrack} track\n   *        `TextTrack` object to remove\n   */\n  removeRemoteTextTrack(track) {\n    super.removeRemoteTextTrack(track);\n    if (this.featuresNativeTextTracks) {\n      const tracks = this.$$('track');\n      let i = tracks.length;\n      while (i--) {\n        if (track === tracks[i] || track === tracks[i].track) {\n          this.el().removeChild(tracks[i]);\n        }\n      }\n    }\n  }\n\n  /**\n   * Gets available media playback quality metrics as specified by the W3C's Media\n   * Playback Quality API.\n   *\n   * @see [Spec]{@link https://wicg.github.io/media-playback-quality}\n   *\n   * @return {Object}\n   *         An object with supported media playback quality metrics\n   */\n  getVideoPlaybackQuality() {\n    if (typeof this.el().getVideoPlaybackQuality === 'function') {\n      return this.el().getVideoPlaybackQuality();\n    }\n    const videoPlaybackQuality = {};\n    if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {\n      videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;\n      videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;\n    }\n    if (window$1.performance) {\n      videoPlaybackQuality.creationTime = window$1.performance.now();\n    }\n    return videoPlaybackQuality;\n  }\n}\n\n/* HTML5 Support Testing ---------------------------------------------------- */\n\n/**\n * Element for testing browser HTML5 media capabilities\n *\n * @type {Element}\n * @constant\n * @private\n */\ndefineLazyProperty(Html5, 'TEST_VID', function () {\n  if (!isReal()) {\n    return;\n  }\n  const video = document$1.createElement('video');\n  const track = document$1.createElement('track');\n  track.kind = 'captions';\n  track.srclang = 'en';\n  track.label = 'English';\n  video.appendChild(track);\n  return video;\n});\n\n/**\n * Check if HTML5 media is supported by this browser/device.\n *\n * @return {boolean}\n *         - True if HTML5 media is supported.\n *         - False if HTML5 media is not supported.\n */\nHtml5.isSupported = function () {\n  // IE with no Media Player is a LIAR! (#984)\n  try {\n    Html5.TEST_VID.volume = 0.5;\n  } catch (e) {\n    return false;\n  }\n  return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);\n};\n\n/**\n * Check if the tech can support the given type\n *\n * @param {string} type\n *        The mimetype to check\n * @return {string} 'probably', 'maybe', or '' (empty string)\n */\nHtml5.canPlayType = function (type) {\n  return Html5.TEST_VID.canPlayType(type);\n};\n\n/**\n * Check if the tech can support the given source\n *\n * @param {Object} srcObj\n *        The source object\n * @param {Object} options\n *        The options passed to the tech\n * @return {string} 'probably', 'maybe', or '' (empty string)\n */\nHtml5.canPlaySource = function (srcObj, options) {\n  return Html5.canPlayType(srcObj.type);\n};\n\n/**\n * Check if the volume can be changed in this browser/device.\n * Volume cannot be changed in a lot of mobile devices.\n * Specifically, it can't be changed from 1 on iOS.\n *\n * @return {boolean}\n *         - True if volume can be controlled\n *         - False otherwise\n */\nHtml5.canControlVolume = function () {\n  // IE will error if Windows Media Player not installed #3315\n  try {\n    const volume = Html5.TEST_VID.volume;\n    Html5.TEST_VID.volume = volume / 2 + 0.1;\n    const canControl = volume !== Html5.TEST_VID.volume;\n\n    // With the introduction of iOS 15, there are cases where the volume is read as\n    // changed but reverts back to its original state at the start of the next tick.\n    // To determine whether volume can be controlled on iOS,\n    // a timeout is set and the volume is checked asynchronously.\n    // Since `features` doesn't currently work asynchronously, the value is manually set.\n    if (canControl && IS_IOS) {\n      window$1.setTimeout(() => {\n        if (Html5 && Html5.prototype) {\n          Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;\n        }\n      });\n\n      // default iOS to false, which will be updated in the timeout above.\n      return false;\n    }\n    return canControl;\n  } catch (e) {\n    return false;\n  }\n};\n\n/**\n * Check if the volume can be muted in this browser/device.\n * Some devices, e.g. iOS, don't allow changing volume\n * but permits muting/unmuting.\n *\n * @return {boolean}\n *      - True if volume can be muted\n *      - False otherwise\n */\nHtml5.canMuteVolume = function () {\n  try {\n    const muted = Html5.TEST_VID.muted;\n\n    // in some versions of iOS muted property doesn't always\n    // work, so we want to set both property and attribute\n    Html5.TEST_VID.muted = !muted;\n    if (Html5.TEST_VID.muted) {\n      setAttribute(Html5.TEST_VID, 'muted', 'muted');\n    } else {\n      removeAttribute(Html5.TEST_VID, 'muted', 'muted');\n    }\n    return muted !== Html5.TEST_VID.muted;\n  } catch (e) {\n    return false;\n  }\n};\n\n/**\n * Check if the playback rate can be changed in this browser/device.\n *\n * @return {boolean}\n *         - True if playback rate can be controlled\n *         - False otherwise\n */\nHtml5.canControlPlaybackRate = function () {\n  // Playback rate API is implemented in Android Chrome, but doesn't do anything\n  // https://github.com/videojs/video.js/issues/3180\n  if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {\n    return false;\n  }\n  // IE will error if Windows Media Player not installed #3315\n  try {\n    const playbackRate = Html5.TEST_VID.playbackRate;\n    Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;\n    return playbackRate !== Html5.TEST_VID.playbackRate;\n  } catch (e) {\n    return false;\n  }\n};\n\n/**\n * Check if we can override a video/audio elements attributes, with\n * Object.defineProperty.\n *\n * @return {boolean}\n *         - True if builtin attributes can be overridden\n *         - False otherwise\n */\nHtml5.canOverrideAttributes = function () {\n  // if we cannot overwrite the src/innerHTML property, there is no support\n  // iOS 7 safari for instance cannot do this.\n  try {\n    const noop = () => {};\n    Object.defineProperty(document$1.createElement('video'), 'src', {\n      get: noop,\n      set: noop\n    });\n    Object.defineProperty(document$1.createElement('audio'), 'src', {\n      get: noop,\n      set: noop\n    });\n    Object.defineProperty(document$1.createElement('video'), 'innerHTML', {\n      get: noop,\n      set: noop\n    });\n    Object.defineProperty(document$1.createElement('audio'), 'innerHTML', {\n      get: noop,\n      set: noop\n    });\n  } catch (e) {\n    return false;\n  }\n  return true;\n};\n\n/**\n * Check to see if native `TextTrack`s are supported by this browser/device.\n *\n * @return {boolean}\n *         - True if native `TextTrack`s are supported.\n *         - False otherwise\n */\nHtml5.supportsNativeTextTracks = function () {\n  return IS_ANY_SAFARI || IS_IOS && IS_CHROME;\n};\n\n/**\n * Check to see if native `VideoTrack`s are supported by this browser/device\n *\n * @return {boolean}\n *        - True if native `VideoTrack`s are supported.\n *        - False otherwise\n */\nHtml5.supportsNativeVideoTracks = function () {\n  return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);\n};\n\n/**\n * Check to see if native `AudioTrack`s are supported by this browser/device\n *\n * @return {boolean}\n *        - True if native `AudioTrack`s are supported.\n *        - False otherwise\n */\nHtml5.supportsNativeAudioTracks = function () {\n  return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);\n};\n\n/**\n * An array of events available on the Html5 tech.\n *\n * @private\n * @type {Array}\n */\nHtml5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'resize', 'volumechange'];\n\n/**\n * Boolean indicating whether the `Tech` supports volume control.\n *\n * @type {boolean}\n * @default {@link Html5.canControlVolume}\n */\n/**\n * Boolean indicating whether the `Tech` supports muting volume.\n *\n * @type {boolean}\n * @default {@link Html5.canMuteVolume}\n */\n\n/**\n * Boolean indicating whether the `Tech` supports changing the speed at which the media\n * plays. Examples:\n *   - Set player to play 2x (twice) as fast\n *   - Set player to play 0.5x (half) as fast\n *\n * @type {boolean}\n * @default {@link Html5.canControlPlaybackRate}\n */\n\n/**\n * Boolean indicating whether the `Tech` supports the `sourceset` event.\n *\n * @type {boolean}\n * @default\n */\n/**\n * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.\n *\n * @type {boolean}\n * @default {@link Html5.supportsNativeTextTracks}\n */\n/**\n * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.\n *\n * @type {boolean}\n * @default {@link Html5.supportsNativeVideoTracks}\n */\n/**\n * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.\n *\n * @type {boolean}\n * @default {@link Html5.supportsNativeAudioTracks}\n */\n[['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function ([key, fn]) {\n  defineLazyProperty(Html5.prototype, key, () => Html5[fn](), true);\n});\nHtml5.prototype.featuresVolumeControl = Html5.canControlVolume();\n\n/**\n * Boolean indicating whether the `HTML5` tech currently supports the media element\n * moving in the DOM. iOS breaks if you move the media element, so this is set this to\n * false there. Everywhere else this should be true.\n *\n * @type {boolean}\n * @default\n */\nHtml5.prototype.movingMediaElementInDOM = !IS_IOS;\n\n// TODO: Previous comment: No longer appears to be used. Can probably be removed.\n//       Is this true?\n/**\n * Boolean indicating whether the `HTML5` tech currently supports automatic media resize\n * when going into fullscreen.\n *\n * @type {boolean}\n * @default\n */\nHtml5.prototype.featuresFullscreenResize = true;\n\n/**\n * Boolean indicating whether the `HTML5` tech currently supports the progress event.\n * If this is false, manual `progress` events will be triggered instead.\n *\n * @type {boolean}\n * @default\n */\nHtml5.prototype.featuresProgressEvents = true;\n\n/**\n * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.\n * If this is false, manual `timeupdate` events will be triggered instead.\n *\n * @default\n */\nHtml5.prototype.featuresTimeupdateEvents = true;\n\n/**\n * Whether the HTML5 el supports `requestVideoFrameCallback`\n *\n * @type {boolean}\n */\nHtml5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);\nHtml5.disposeMediaElement = function (el) {\n  if (!el) {\n    return;\n  }\n  if (el.parentNode) {\n    el.parentNode.removeChild(el);\n  }\n\n  // remove any child track or source nodes to prevent their loading\n  while (el.hasChildNodes()) {\n    el.removeChild(el.firstChild);\n  }\n\n  // remove any src reference. not setting `src=''` because that causes a warning\n  // in firefox\n  el.removeAttribute('src');\n\n  // force the media element to update its loading state by calling load()\n  // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)\n  if (typeof el.load === 'function') {\n    // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)\n    (function () {\n      try {\n        el.load();\n      } catch (e) {\n        // not supported\n      }\n    })();\n  }\n};\nHtml5.resetMediaElement = function (el) {\n  if (!el) {\n    return;\n  }\n  const sources = el.querySelectorAll('source');\n  let i = sources.length;\n  while (i--) {\n    el.removeChild(sources[i]);\n  }\n\n  // remove any src reference.\n  // not setting `src=''` because that throws an error\n  el.removeAttribute('src');\n  if (typeof el.load === 'function') {\n    // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)\n    (function () {\n      try {\n        el.load();\n      } catch (e) {\n        // satisfy linter\n      }\n    })();\n  }\n};\n\n/* Native HTML5 element property wrapping ----------------------------------- */\n// Wrap native boolean attributes with getters that check both property and attribute\n// The list is as followed:\n// muted, defaultMuted, autoplay, controls, loop, playsinline\n[\n/**\n * Get the value of `muted` from the media element. `muted` indicates\n * that the volume for the media should be set to silent. This does not actually change\n * the `volume` attribute.\n *\n * @method Html5#muted\n * @return {boolean}\n *         - True if the value of `volume` should be ignored and the audio set to silent.\n *         - False if the value of `volume` should be used.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}\n */\n'muted',\n/**\n * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates\n * whether the media should start muted or not. Only changes the default state of the\n * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the\n * current state.\n *\n * @method Html5#defaultMuted\n * @return {boolean}\n *         - The value of `defaultMuted` from the media element.\n *         - True indicates that the media should start muted.\n *         - False indicates that the media should not start muted\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}\n */\n'defaultMuted',\n/**\n * Get the value of `autoplay` from the media element. `autoplay` indicates\n * that the media should start to play as soon as the page is ready.\n *\n * @method Html5#autoplay\n * @return {boolean}\n *         - The value of `autoplay` from the media element.\n *         - True indicates that the media should start as soon as the page loads.\n *         - False indicates that the media should not start as soon as the page loads.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}\n */\n'autoplay',\n/**\n * Get the value of `controls` from the media element. `controls` indicates\n * whether the native media controls should be shown or hidden.\n *\n * @method Html5#controls\n * @return {boolean}\n *         - The value of `controls` from the media element.\n *         - True indicates that native controls should be showing.\n *         - False indicates that native controls should be hidden.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}\n */\n'controls',\n/**\n * Get the value of `loop` from the media element. `loop` indicates\n * that the media should return to the start of the media and continue playing once\n * it reaches the end.\n *\n * @method Html5#loop\n * @return {boolean}\n *         - The value of `loop` from the media element.\n *         - True indicates that playback should seek back to start once\n *           the end of a media is reached.\n *         - False indicates that playback should not loop back to the start when the\n *           end of the media is reached.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}\n */\n'loop',\n/**\n * Get the value of `playsinline` from the media element. `playsinline` indicates\n * to the browser that non-fullscreen playback is preferred when fullscreen\n * playback is the native default, such as in iOS Safari.\n *\n * @method Html5#playsinline\n * @return {boolean}\n *         - The value of `playsinline` from the media element.\n *         - True indicates that the media should play inline.\n *         - False indicates that the media should not play inline.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}\n */\n'playsinline'].forEach(function (prop) {\n  Html5.prototype[prop] = function () {\n    return this.el_[prop] || this.el_.hasAttribute(prop);\n  };\n});\n\n// Wrap native boolean attributes with setters that set both property and attribute\n// The list is as followed:\n// setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline\n// setControls is special-cased above\n[\n/**\n * Set the value of `muted` on the media element. `muted` indicates that the current\n * audio level should be silent.\n *\n * @method Html5#setMuted\n * @param {boolean} muted\n *        - True if the audio should be set to silent\n *        - False otherwise\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}\n */\n'muted',\n/**\n * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current\n * audio level should be silent, but will only effect the muted level on initial playback..\n *\n * @method Html5.prototype.setDefaultMuted\n * @param {boolean} defaultMuted\n *        - True if the audio should be set to silent\n *        - False otherwise\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}\n */\n'defaultMuted',\n/**\n * Set the value of `autoplay` on the media element. `autoplay` indicates\n * that the media should start to play as soon as the page is ready.\n *\n * @method Html5#setAutoplay\n * @param {boolean} autoplay\n *         - True indicates that the media should start as soon as the page loads.\n *         - False indicates that the media should not start as soon as the page loads.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}\n */\n'autoplay',\n/**\n * Set the value of `loop` on the media element. `loop` indicates\n * that the media should return to the start of the media and continue playing once\n * it reaches the end.\n *\n * @method Html5#setLoop\n * @param {boolean} loop\n *         - True indicates that playback should seek back to start once\n *           the end of a media is reached.\n *         - False indicates that playback should not loop back to the start when the\n *           end of the media is reached.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}\n */\n'loop',\n/**\n * Set the value of `playsinline` from the media element. `playsinline` indicates\n * to the browser that non-fullscreen playback is preferred when fullscreen\n * playback is the native default, such as in iOS Safari.\n *\n * @method Html5#setPlaysinline\n * @param {boolean} playsinline\n *         - True indicates that the media should play inline.\n *         - False indicates that the media should not play inline.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}\n */\n'playsinline'].forEach(function (prop) {\n  Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {\n    this.el_[prop] = v;\n    if (v) {\n      this.el_.setAttribute(prop, prop);\n    } else {\n      this.el_.removeAttribute(prop);\n    }\n  };\n});\n\n// Wrap native properties with a getter\n// The list is as followed\n// paused, currentTime, buffered, volume, poster, preload, error, seeking\n// seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture\n// played, networkState, readyState, videoWidth, videoHeight, crossOrigin\n[\n/**\n * Get the value of `paused` from the media element. `paused` indicates whether the media element\n * is currently paused or not.\n *\n * @method Html5#paused\n * @return {boolean}\n *         The value of `paused` from the media element.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}\n */\n'paused',\n/**\n * Get the value of `currentTime` from the media element. `currentTime` indicates\n * the current second that the media is at in playback.\n *\n * @method Html5#currentTime\n * @return {number}\n *         The value of `currentTime` from the media element.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}\n */\n'currentTime',\n/**\n * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`\n * object that represents the parts of the media that are already downloaded and\n * available for playback.\n *\n * @method Html5#buffered\n * @return {TimeRange}\n *         The value of `buffered` from the media element.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}\n */\n'buffered',\n/**\n * Get the value of `volume` from the media element. `volume` indicates\n * the current playback volume of audio for a media. `volume` will be a value from 0\n * (silent) to 1 (loudest and default).\n *\n * @method Html5#volume\n * @return {number}\n *         The value of `volume` from the media element. Value will be between 0-1.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}\n */\n'volume',\n/**\n * Get the value of `poster` from the media element. `poster` indicates\n * that the url of an image file that can/will be shown when no media data is available.\n *\n * @method Html5#poster\n * @return {string}\n *         The value of `poster` from the media element. Value will be a url to an\n *         image.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}\n */\n'poster',\n/**\n * Get the value of `preload` from the media element. `preload` indicates\n * what should download before the media is interacted with. It can have the following\n * values:\n * - none: nothing should be downloaded\n * - metadata: poster and the first few frames of the media may be downloaded to get\n *   media dimensions and other metadata\n * - auto: allow the media and metadata for the media to be downloaded before\n *    interaction\n *\n * @method Html5#preload\n * @return {string}\n *         The value of `preload` from the media element. Will be 'none', 'metadata',\n *         or 'auto'.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}\n */\n'preload',\n/**\n * Get the value of the `error` from the media element. `error` indicates any\n * MediaError that may have occurred during playback. If error returns null there is no\n * current error.\n *\n * @method Html5#error\n * @return {MediaError|null}\n *         The value of `error` from the media element. Will be `MediaError` if there\n *         is a current error and null otherwise.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}\n */\n'error',\n/**\n * Get the value of `seeking` from the media element. `seeking` indicates whether the\n * media is currently seeking to a new position or not.\n *\n * @method Html5#seeking\n * @return {boolean}\n *         - The value of `seeking` from the media element.\n *         - True indicates that the media is currently seeking to a new position.\n *         - False indicates that the media is not seeking to a new position at this time.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}\n */\n'seeking',\n/**\n * Get the value of `seekable` from the media element. `seekable` returns a\n * `TimeRange` object indicating ranges of time that can currently be `seeked` to.\n *\n * @method Html5#seekable\n * @return {TimeRange}\n *         The value of `seekable` from the media element. A `TimeRange` object\n *         indicating the current ranges of time that can be seeked to.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}\n */\n'seekable',\n/**\n * Get the value of `ended` from the media element. `ended` indicates whether\n * the media has reached the end or not.\n *\n * @method Html5#ended\n * @return {boolean}\n *         - The value of `ended` from the media element.\n *         - True indicates that the media has ended.\n *         - False indicates that the media has not ended.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}\n */\n'ended',\n/**\n * Get the value of `playbackRate` from the media element. `playbackRate` indicates\n * the rate at which the media is currently playing back. Examples:\n *   - if playbackRate is set to 2, media will play twice as fast.\n *   - if playbackRate is set to 0.5, media will play half as fast.\n *\n * @method Html5#playbackRate\n * @return {number}\n *         The value of `playbackRate` from the media element. A number indicating\n *         the current playback speed of the media, where 1 is normal speed.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}\n */\n'playbackRate',\n/**\n * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates\n * the rate at which the media is currently playing back. This value will not indicate the current\n * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.\n *\n * Examples:\n *   - if defaultPlaybackRate is set to 2, media will play twice as fast.\n *   - if defaultPlaybackRate is set to 0.5, media will play half as fast.\n *\n * @method Html5.prototype.defaultPlaybackRate\n * @return {number}\n *         The value of `defaultPlaybackRate` from the media element. A number indicating\n *         the current playback speed of the media, where 1 is normal speed.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}\n */\n'defaultPlaybackRate',\n/**\n * Get the value of 'disablePictureInPicture' from the video element.\n *\n * @method Html5#disablePictureInPicture\n * @return {boolean} value\n *         - The value of `disablePictureInPicture` from the video element.\n *         - True indicates that the video can't be played in Picture-In-Picture mode\n *         - False indicates that the video can be played in Picture-In-Picture mode\n *\n * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}\n */\n'disablePictureInPicture',\n/**\n * Get the value of `played` from the media element. `played` returns a `TimeRange`\n * object representing points in the media timeline that have been played.\n *\n * @method Html5#played\n * @return {TimeRange}\n *         The value of `played` from the media element. A `TimeRange` object indicating\n *         the ranges of time that have been played.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}\n */\n'played',\n/**\n * Get the value of `networkState` from the media element. `networkState` indicates\n * the current network state. It returns an enumeration from the following list:\n * - 0: NETWORK_EMPTY\n * - 1: NETWORK_IDLE\n * - 2: NETWORK_LOADING\n * - 3: NETWORK_NO_SOURCE\n *\n * @method Html5#networkState\n * @return {number}\n *         The value of `networkState` from the media element. This will be a number\n *         from the list in the description.\n *\n * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}\n */\n'networkState',\n/**\n * Get the value of `readyState` from the media element. `readyState` indicates\n * the current state of the media element. It returns an enumeration from the\n * following list:\n * - 0: HAVE_NOTHING\n * - 1: HAVE_METADATA\n * - 2: HAVE_CURRENT_DATA\n * - 3: HAVE_FUTURE_DATA\n * - 4: HAVE_ENOUGH_DATA\n *\n * @method Html5#readyState\n * @return {number}\n *         The value of `readyState` from the media element. This will be a number\n *         from the list in the description.\n *\n * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}\n */\n'readyState',\n/**\n * Get the value of `videoWidth` from the video element. `videoWidth` indicates\n * the current width of the video in css pixels.\n *\n * @method Html5#videoWidth\n * @return {number}\n *         The value of `videoWidth` from the video element. This will be a number\n *         in css pixels.\n *\n * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}\n */\n'videoWidth',\n/**\n * Get the value of `videoHeight` from the video element. `videoHeight` indicates\n * the current height of the video in css pixels.\n *\n * @method Html5#videoHeight\n * @return {number}\n *         The value of `videoHeight` from the video element. This will be a number\n *         in css pixels.\n *\n * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}\n */\n'videoHeight',\n/**\n * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates\n * to the browser that should sent the cookies along with the requests for the\n * different assets/playlists\n *\n * @method Html5#crossOrigin\n * @return {string}\n *         - anonymous indicates that the media should not sent cookies.\n *         - use-credentials indicates that the media should sent cookies along the requests.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}\n */\n'crossOrigin'].forEach(function (prop) {\n  Html5.prototype[prop] = function () {\n    return this.el_[prop];\n  };\n});\n\n// Wrap native properties with a setter in this format:\n// set + toTitleCase(name)\n// The list is as follows:\n// setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,\n// setDisablePictureInPicture, setCrossOrigin\n[\n/**\n * Set the value of `volume` on the media element. `volume` indicates the current\n * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and\n * so on.\n *\n * @method Html5#setVolume\n * @param {number} percentAsDecimal\n *        The volume percent as a decimal. Valid range is from 0-1.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}\n */\n'volume',\n/**\n * Set the value of `src` on the media element. `src` indicates the current\n * {@link Tech~SourceObject} for the media.\n *\n * @method Html5#setSrc\n * @param {Tech~SourceObject} src\n *        The source object to set as the current source.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}\n */\n'src',\n/**\n * Set the value of `poster` on the media element. `poster` is the url to\n * an image file that can/will be shown when no media data is available.\n *\n * @method Html5#setPoster\n * @param {string} poster\n *        The url to an image that should be used as the `poster` for the media\n *        element.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}\n */\n'poster',\n/**\n * Set the value of `preload` on the media element. `preload` indicates\n * what should download before the media is interacted with. It can have the following\n * values:\n * - none: nothing should be downloaded\n * - metadata: poster and the first few frames of the media may be downloaded to get\n *   media dimensions and other metadata\n * - auto: allow the media and metadata for the media to be downloaded before\n *    interaction\n *\n * @method Html5#setPreload\n * @param {string} preload\n *         The value of `preload` to set on the media element. Must be 'none', 'metadata',\n *         or 'auto'.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}\n */\n'preload',\n/**\n * Set the value of `playbackRate` on the media element. `playbackRate` indicates\n * the rate at which the media should play back. Examples:\n *   - if playbackRate is set to 2, media will play twice as fast.\n *   - if playbackRate is set to 0.5, media will play half as fast.\n *\n * @method Html5#setPlaybackRate\n * @return {number}\n *         The value of `playbackRate` from the media element. A number indicating\n *         the current playback speed of the media, where 1 is normal speed.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}\n */\n'playbackRate',\n/**\n * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates\n * the rate at which the media should play back upon initial startup. Changing this value\n * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.\n *\n * Example Values:\n *   - if playbackRate is set to 2, media will play twice as fast.\n *   - if playbackRate is set to 0.5, media will play half as fast.\n *\n * @method Html5.prototype.setDefaultPlaybackRate\n * @return {number}\n *         The value of `defaultPlaybackRate` from the media element. A number indicating\n *         the current playback speed of the media, where 1 is normal speed.\n *\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}\n */\n'defaultPlaybackRate',\n/**\n * Prevents the browser from suggesting a Picture-in-Picture context menu\n * or to request Picture-in-Picture automatically in some cases.\n *\n * @method Html5#setDisablePictureInPicture\n * @param {boolean} value\n *         The true value will disable Picture-in-Picture mode.\n *\n * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}\n */\n'disablePictureInPicture',\n/**\n * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates\n * to the browser that should sent the cookies along with the requests for the\n * different assets/playlists\n *\n * @method Html5#setCrossOrigin\n * @param {string} crossOrigin\n *         - anonymous indicates that the media should not sent cookies.\n *         - use-credentials indicates that the media should sent cookies along the requests.\n *\n * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}\n */\n'crossOrigin'].forEach(function (prop) {\n  Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {\n    this.el_[prop] = v;\n  };\n});\n\n// wrap native functions with a function\n// The list is as follows:\n// pause, load, play\n[\n/**\n * A wrapper around the media elements `pause` function. This will call the `HTML5`\n * media elements `pause` function.\n *\n * @method Html5#pause\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}\n */\n'pause',\n/**\n * A wrapper around the media elements `load` function. This will call the `HTML5`s\n * media element `load` function.\n *\n * @method Html5#load\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}\n */\n'load',\n/**\n * A wrapper around the media elements `play` function. This will call the `HTML5`s\n * media element `play` function.\n *\n * @method Html5#play\n * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}\n */\n'play'].forEach(function (prop) {\n  Html5.prototype[prop] = function () {\n    return this.el_[prop]();\n  };\n});\nTech.withSourceHandlers(Html5);\n\n/**\n * Native source handler for Html5, simply passes the source to the media element.\n *\n * @property {Tech~SourceObject} source\n *        The source object\n *\n * @property {Html5} tech\n *        The instance of the HTML5 tech.\n */\nHtml5.nativeSourceHandler = {};\n\n/**\n * Check if the media element can play the given mime type.\n *\n * @param {string} type\n *        The mimetype to check\n *\n * @return {string}\n *         'probably', 'maybe', or '' (empty string)\n */\nHtml5.nativeSourceHandler.canPlayType = function (type) {\n  // IE without MediaPlayer throws an error (#519)\n  try {\n    return Html5.TEST_VID.canPlayType(type);\n  } catch (e) {\n    return '';\n  }\n};\n\n/**\n * Check if the media element can handle a source natively.\n *\n * @param {Tech~SourceObject} source\n *         The source object\n *\n * @param {Object} [options]\n *         Options to be passed to the tech.\n *\n * @return {string}\n *         'probably', 'maybe', or '' (empty string).\n */\nHtml5.nativeSourceHandler.canHandleSource = function (source, options) {\n  // If a type was provided we should rely on that\n  if (source.type) {\n    return Html5.nativeSourceHandler.canPlayType(source.type);\n\n    // If no type, fall back to checking 'video/[EXTENSION]'\n  } else if (source.src) {\n    const ext = getFileExtension(source.src);\n    return Html5.nativeSourceHandler.canPlayType(`video/${ext}`);\n  }\n  return '';\n};\n\n/**\n * Pass the source to the native media element.\n *\n * @param {Tech~SourceObject} source\n *        The source object\n *\n * @param {Html5} tech\n *        The instance of the Html5 tech\n *\n * @param {Object} [options]\n *        The options to pass to the source\n */\nHtml5.nativeSourceHandler.handleSource = function (source, tech, options) {\n  tech.setSrc(source.src);\n};\n\n/**\n * A noop for the native dispose function, as cleanup is not needed.\n */\nHtml5.nativeSourceHandler.dispose = function () {};\n\n// Register the native source handler\nHtml5.registerSourceHandler(Html5.nativeSourceHandler);\nTech.registerTech('Html5', Html5);\n\n/**\n * @file player.js\n */\n\n/** @import AudioTrackList from './tracks/audio-track-list' */\n/** @import HtmlTrackElement from './tracks/html-track-element' */\n/** @import HtmlTrackElementList from './tracks/html-track-element-list' */\n/** @import TextTrackList from './tracks/text-track-list' */\n/** @import { TimeRange } from './utils/time' */\n/** @import VideoTrackList from './tracks/video-track-list' */\n\n/**\n * @callback PlayerReadyCallback\n * @this     {Player}\n * @returns  {void}\n */\n\n// The following tech events are simply re-triggered\n// on the player when they happen\nconst TECH_EVENTS_RETRIGGER = [\n/**\n * Fired while the user agent is downloading media data.\n *\n * @event Player#progress\n * @type {Event}\n */\n/**\n * Retrigger the `progress` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechProgress_\n * @fires Player#progress\n * @listens Tech#progress\n */\n'progress',\n/**\n * Fires when the loading of an audio/video is aborted.\n *\n * @event Player#abort\n * @type {Event}\n */\n/**\n * Retrigger the `abort` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechAbort_\n * @fires Player#abort\n * @listens Tech#abort\n */\n'abort',\n/**\n * Fires when the browser is intentionally not getting media data.\n *\n * @event Player#suspend\n * @type {Event}\n */\n/**\n * Retrigger the `suspend` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechSuspend_\n * @fires Player#suspend\n * @listens Tech#suspend\n */\n'suspend',\n/**\n * Fires when the current playlist is empty.\n *\n * @event Player#emptied\n * @type {Event}\n */\n/**\n * Retrigger the `emptied` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechEmptied_\n * @fires Player#emptied\n * @listens Tech#emptied\n */\n'emptied',\n/**\n * Fires when the browser is trying to get media data, but data is not available.\n *\n * @event Player#stalled\n * @type {Event}\n */\n/**\n * Retrigger the `stalled` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechStalled_\n * @fires Player#stalled\n * @listens Tech#stalled\n */\n'stalled',\n/**\n * Fires when the browser has loaded meta data for the audio/video.\n *\n * @event Player#loadedmetadata\n * @type {Event}\n */\n/**\n * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechLoadedmetadata_\n * @fires Player#loadedmetadata\n * @listens Tech#loadedmetadata\n */\n'loadedmetadata',\n/**\n * Fires when the browser has loaded the current frame of the audio/video.\n *\n * @event Player#loadeddata\n * @type {event}\n */\n/**\n * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechLoaddeddata_\n * @fires Player#loadeddata\n * @listens Tech#loadeddata\n */\n'loadeddata',\n/**\n * Fires when the current playback position has changed.\n *\n * @event Player#timeupdate\n * @type {event}\n */\n/**\n * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechTimeUpdate_\n * @fires Player#timeupdate\n * @listens Tech#timeupdate\n */\n'timeupdate',\n/**\n * Fires when the video's intrinsic dimensions change\n *\n * @event Player#resize\n * @type {event}\n */\n/**\n * Retrigger the `resize` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechResize_\n * @fires Player#resize\n * @listens Tech#resize\n */\n'resize',\n/**\n * Fires when the volume has been changed\n *\n * @event Player#volumechange\n * @type {event}\n */\n/**\n * Retrigger the `volumechange` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechVolumechange_\n * @fires Player#volumechange\n * @listens Tech#volumechange\n */\n'volumechange',\n/**\n * Fires when the text track has been changed\n *\n * @event Player#texttrackchange\n * @type {event}\n */\n/**\n * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.\n *\n * @private\n * @method Player#handleTechTexttrackchange_\n * @fires Player#texttrackchange\n * @listens Tech#texttrackchange\n */\n'texttrackchange'];\n\n// events to queue when playback rate is zero\n// this is a hash for the sole purpose of mapping non-camel-cased event names\n// to camel-cased function names\nconst TECH_EVENTS_QUEUE = {\n  canplay: 'CanPlay',\n  canplaythrough: 'CanPlayThrough',\n  playing: 'Playing',\n  seeked: 'Seeked'\n};\nconst BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];\nconst BREAKPOINT_CLASSES = {};\n\n// grep: vjs-layout-tiny\n// grep: vjs-layout-x-small\n// grep: vjs-layout-small\n// grep: vjs-layout-medium\n// grep: vjs-layout-large\n// grep: vjs-layout-x-large\n// grep: vjs-layout-huge\nBREAKPOINT_ORDER.forEach(k => {\n  const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;\n  BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;\n});\nconst DEFAULT_BREAKPOINTS = {\n  tiny: 210,\n  xsmall: 320,\n  small: 425,\n  medium: 768,\n  large: 1440,\n  xlarge: 2560,\n  huge: Infinity\n};\n\n/**\n * An instance of the `Player` class is created when any of the Video.js setup methods\n * are used to initialize a video.\n *\n * After an instance has been created it can be accessed globally in three ways:\n * 1. By calling `videojs.getPlayer('example_video_1');`\n * 2. By calling `videojs('example_video_1');` (not recommended)\n * 2. By using it directly via `videojs.players.example_video_1;`\n *\n * @extends Component\n * @global\n */\nclass Player extends Component$1 {\n  /**\n   * Create an instance of this class.\n   *\n   * @param {Element} tag\n   *        The original video DOM element used for configuring options.\n   *\n   * @param {Object} [options]\n   *        Object of option names and values.\n   *\n   * @param {PlayerReadyCallback} [ready]\n   *        Ready callback function.\n   */\n  constructor(tag, options, ready) {\n    // Make sure tag ID exists\n    // also here.. probably better\n    tag.id = tag.id || options.id || `vjs_video_${newGUID()}`;\n\n    // Set Options\n    // The options argument overrides options set in the video tag\n    // which overrides globally set options.\n    // This latter part coincides with the load order\n    // (tag must exist before Player)\n    options = Object.assign(Player.getTagSettings(tag), options);\n\n    // Delay the initialization of children because we need to set up\n    // player properties first, and can't use `this` before `super()`\n    options.initChildren = false;\n\n    // Same with creating the element\n    options.createEl = false;\n\n    // don't auto mixin the evented mixin\n    options.evented = false;\n\n    // we don't want the player to report touch activity on itself\n    // see enableTouchActivity in Component\n    options.reportTouchActivity = false;\n\n    // If language is not set, get the closest lang attribute\n    if (!options.language) {\n      const closest = tag.closest('[lang]');\n      if (closest) {\n        options.language = closest.getAttribute('lang');\n      }\n    }\n\n    // Run base component initializing with new options\n    super(null, options, ready);\n\n    // Create bound methods for document listeners.\n    this.boundDocumentFullscreenChange_ = e => this.documentFullscreenChange_(e);\n    this.boundFullWindowOnEscKey_ = e => this.fullWindowOnEscKey(e);\n    this.boundUpdateStyleEl_ = e => this.updateStyleEl_(e);\n    this.boundApplyInitTime_ = e => this.applyInitTime_(e);\n    this.boundUpdateCurrentBreakpoint_ = e => this.updateCurrentBreakpoint_(e);\n    this.boundHandleTechClick_ = e => this.handleTechClick_(e);\n    this.boundHandleTechDoubleClick_ = e => this.handleTechDoubleClick_(e);\n    this.boundHandleTechTouchStart_ = e => this.handleTechTouchStart_(e);\n    this.boundHandleTechTouchMove_ = e => this.handleTechTouchMove_(e);\n    this.boundHandleTechTouchEnd_ = e => this.handleTechTouchEnd_(e);\n    this.boundHandleTechTap_ = e => this.handleTechTap_(e);\n    this.boundUpdatePlayerHeightOnAudioOnlyMode_ = e => this.updatePlayerHeightOnAudioOnlyMode_(e);\n\n    // default isFullscreen_ to false\n    this.isFullscreen_ = false;\n\n    // create logger\n    this.log = createLogger(this.id_);\n\n    // Hold our own reference to fullscreen api so it can be mocked in tests\n    this.fsApi_ = FullscreenApi;\n\n    // Tracks when a tech changes the poster\n    this.isPosterFromTech_ = false;\n\n    // Holds callback info that gets queued when playback rate is zero\n    // and a seek is happening\n    this.queuedCallbacks_ = [];\n\n    // Turn off API access because we're loading a new tech that might load asynchronously\n    this.isReady_ = false;\n\n    // Init state hasStarted_\n    this.hasStarted_ = false;\n\n    // Init state userActive_\n    this.userActive_ = false;\n\n    // Init debugEnabled_\n    this.debugEnabled_ = false;\n\n    // Init state audioOnlyMode_\n    this.audioOnlyMode_ = false;\n\n    // Init state audioPosterMode_\n    this.audioPosterMode_ = false;\n\n    // Init state audioOnlyCache_\n    this.audioOnlyCache_ = {\n      controlBarHeight: null,\n      playerHeight: null,\n      hiddenChildren: []\n    };\n\n    // if the global option object was accidentally blown away by\n    // someone, bail early with an informative error\n    if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {\n      throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');\n    }\n\n    // Store the original tag used to set options\n    this.tag = tag;\n\n    // Store the tag attributes used to restore html5 element\n    this.tagAttributes = tag && getAttributes(tag);\n\n    // Update current language\n    this.language(this.options_.language);\n\n    // Update Supported Languages\n    if (options.languages) {\n      // Normalise player option languages to lowercase\n      const languagesToLower = {};\n      Object.getOwnPropertyNames(options.languages).forEach(function (name) {\n        languagesToLower[name.toLowerCase()] = options.languages[name];\n      });\n      this.languages_ = languagesToLower;\n    } else {\n      this.languages_ = Player.prototype.options_.languages;\n    }\n    this.resetCache_();\n\n    // Set poster\n    /** @type string */\n    this.poster_ = options.poster || '';\n\n    // Set controls\n    /** @type {boolean} */\n    this.controls_ = !!options.controls;\n\n    // Original tag settings stored in options\n    // now remove immediately so native controls don't flash.\n    // May be turned back on by HTML5 tech if nativeControlsForTouch is true\n    tag.controls = false;\n    tag.removeAttribute('controls');\n    this.changingSrc_ = false;\n    this.playCallbacks_ = [];\n    this.playTerminatedQueue_ = [];\n\n    // the attribute overrides the option\n    if (tag.hasAttribute('autoplay')) {\n      this.autoplay(true);\n    } else {\n      // otherwise use the setter to validate and\n      // set the correct value.\n      this.autoplay(this.options_.autoplay);\n    }\n\n    // check plugins\n    if (options.plugins) {\n      Object.keys(options.plugins).forEach(name => {\n        if (typeof this[name] !== 'function') {\n          throw new Error(`plugin \"${name}\" does not exist`);\n        }\n      });\n    }\n\n    /*\n     * Store the internal state of scrubbing\n     *\n     * @private\n     * @return {Boolean} True if the user is scrubbing\n     */\n    this.scrubbing_ = false;\n    this.el_ = this.createEl();\n\n    // Make this an evented object and use `el_` as its event bus.\n    evented(this, {\n      eventBusKey: 'el_'\n    });\n\n    // listen to document and player fullscreenchange handlers so we receive those events\n    // before a user can receive them so we can update isFullscreen appropriately.\n    // make sure that we listen to fullscreenchange events before everything else to make sure that\n    // our isFullscreen method is updated properly for internal components as well as external.\n    if (this.fsApi_.requestFullscreen) {\n      on(document$1, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);\n      this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);\n    }\n    if (this.fluid_) {\n      this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);\n    }\n    // We also want to pass the original player options to each component and plugin\n    // as well so they don't need to reach back into the player for options later.\n    // We also need to do another copy of this.options_ so we don't end up with\n    // an infinite loop.\n    const playerOptionsCopy = merge$1(this.options_);\n\n    // Load plugins\n    if (options.plugins) {\n      Object.keys(options.plugins).forEach(name => {\n        this[name](options.plugins[name]);\n      });\n    }\n\n    // Enable debug mode to fire debugon event for all plugins.\n    if (options.debug) {\n      this.debug(true);\n    }\n    this.options_.playerOptions = playerOptionsCopy;\n    this.middleware_ = [];\n    this.playbackRates(options.playbackRates);\n    if (options.experimentalSvgIcons) {\n      // Add SVG Sprite to the DOM\n      const parser = new window$1.DOMParser();\n      const parsedSVG = parser.parseFromString(icons, 'image/svg+xml');\n      const errorNode = parsedSVG.querySelector('parsererror');\n      if (errorNode) {\n        log$1.warn('Failed to load SVG Icons. Falling back to Font Icons.');\n        this.options_.experimentalSvgIcons = null;\n      } else {\n        const sprite = parsedSVG.documentElement;\n        sprite.style.display = 'none';\n        this.el_.appendChild(sprite);\n        this.addClass('vjs-svg-icons-enabled');\n      }\n    }\n    this.initChildren();\n\n    // Set isAudio based on whether or not an audio tag was used\n    this.isAudio(tag.nodeName.toLowerCase() === 'audio');\n\n    // Update controls className. Can't do this when the controls are initially\n    // set because the element doesn't exist yet.\n    if (this.controls()) {\n      this.addClass('vjs-controls-enabled');\n    } else {\n      this.addClass('vjs-controls-disabled');\n    }\n\n    // Set ARIA label and region role depending on player type\n    this.el_.setAttribute('role', 'region');\n    if (this.isAudio()) {\n      this.el_.setAttribute('aria-label', this.localize('Audio Player'));\n    } else {\n      this.el_.setAttribute('aria-label', this.localize('Video Player'));\n    }\n    if (this.isAudio()) {\n      this.addClass('vjs-audio');\n    }\n\n    // Check if spatial navigation is enabled in the options.\n    // If enabled, instantiate the SpatialNavigation class.\n    if (options.spatialNavigation && options.spatialNavigation.enabled) {\n      this.spatialNavigation = new SpatialNavigation(this);\n      this.addClass('vjs-spatial-navigation-enabled');\n    }\n\n    // TODO: Make this smarter. Toggle user state between touching/mousing\n    // using events, since devices can have both touch and mouse events.\n    // TODO: Make this check be performed again when the window switches between monitors\n    // (See https://github.com/videojs/video.js/issues/5683)\n    if (TOUCH_ENABLED) {\n      this.addClass('vjs-touch-enabled');\n    }\n\n    // iOS Safari has broken hover handling\n    if (!IS_IOS) {\n      this.addClass('vjs-workinghover');\n    }\n\n    // Make player easily findable by ID\n    Player.players[this.id_] = this;\n\n    // Add a major version class to aid css in plugins\n    const majorVersion = version$6.split('.')[0];\n    this.addClass(`vjs-v${majorVersion}`);\n\n    // When the player is first initialized, trigger activity so components\n    // like the control bar show themselves if needed\n    this.userActive(true);\n    this.reportUserActivity();\n    this.one('play', e => this.listenForUserActivity_(e));\n    this.on('keydown', e => this.handleKeyDown(e));\n    this.on('languagechange', e => this.handleLanguagechange(e));\n    this.breakpoints(this.options_.breakpoints);\n    this.responsive(this.options_.responsive);\n\n    // Calling both the audio mode methods after the player is fully\n    // setup to be able to listen to the events triggered by them\n    this.on('ready', () => {\n      // Calling the audioPosterMode method first so that\n      // the audioOnlyMode can take precedence when both options are set to true\n      this.audioPosterMode(this.options_.audioPosterMode);\n      this.audioOnlyMode(this.options_.audioOnlyMode);\n    });\n  }\n\n  /**\n   * Destroys the video player and does any necessary cleanup.\n   *\n   * This is especially helpful if you are dynamically adding and removing videos\n   * to/from the DOM.\n   *\n   * @fires Player#dispose\n   */\n  dispose() {\n    /**\n     * Called when the player is being disposed of.\n     *\n     * @event Player#dispose\n     * @type {Event}\n     */\n    this.trigger('dispose');\n    // prevent dispose from being called twice\n    this.off('dispose');\n\n    // Make sure all player-specific document listeners are unbound. This is\n    off(document$1, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);\n    off(document$1, 'keydown', this.boundFullWindowOnEscKey_);\n    if (this.styleEl_ && this.styleEl_.parentNode) {\n      this.styleEl_.parentNode.removeChild(this.styleEl_);\n      this.styleEl_ = null;\n    }\n\n    // Kill reference to this player\n    Player.players[this.id_] = null;\n    if (this.tag && this.tag.player) {\n      this.tag.player = null;\n    }\n    if (this.el_ && this.el_.player) {\n      this.el_.player = null;\n    }\n    if (this.tech_) {\n      this.tech_.dispose();\n      this.isPosterFromTech_ = false;\n      this.poster_ = '';\n    }\n    if (this.playerElIngest_) {\n      this.playerElIngest_ = null;\n    }\n    if (this.tag) {\n      this.tag = null;\n    }\n    clearCacheForPlayer(this);\n\n    // remove all event handlers for track lists\n    // all tracks and track listeners are removed on\n    // tech dispose\n    ALL.names.forEach(name => {\n      const props = ALL[name];\n      const list = this[props.getterName]();\n\n      // if it is not a native list\n      // we have to manually remove event listeners\n      if (list && list.off) {\n        list.off();\n      }\n    });\n\n    // the actual .el_ is removed here, or replaced if\n    super.dispose({\n      restoreEl: this.options_.restoreEl\n    });\n  }\n\n  /**\n   * Create the `Player`'s DOM element.\n   *\n   * @return {Element}\n   *         The DOM element that gets created.\n   */\n  createEl() {\n    let tag = this.tag;\n    let el;\n    let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');\n    const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';\n    if (playerElIngest) {\n      el = this.el_ = tag.parentNode;\n    } else if (!divEmbed) {\n      el = this.el_ = super.createEl('div');\n    }\n\n    // Copy over all the attributes from the tag, including ID and class\n    // ID will now reference player box, not the video tag\n    const attrs = getAttributes(tag);\n    if (divEmbed) {\n      el = this.el_ = tag;\n      tag = this.tag = document$1.createElement('video');\n      while (el.children.length) {\n        tag.appendChild(el.firstChild);\n      }\n      if (!hasClass(el, 'video-js')) {\n        addClass(el, 'video-js');\n      }\n      el.appendChild(tag);\n      playerElIngest = this.playerElIngest_ = el;\n      // move properties over from our custom `video-js` element\n      // to our new `video` element. This will move things like\n      // `src` or `controls` that were set via js before the player\n      // was initialized.\n      Object.keys(el).forEach(k => {\n        try {\n          tag[k] = el[k];\n        } catch (e) {\n          // we got a a property like outerHTML which we can't actually copy, ignore it\n        }\n      });\n    }\n\n    // set tabindex to -1 to remove the video element from the focus order\n    tag.setAttribute('tabindex', '-1');\n    attrs.tabindex = '-1';\n\n    // Workaround for #4583 on Chrome (on Windows) with JAWS.\n    // See https://github.com/FreedomScientific/VFO-standards-support/issues/78\n    // Note that we can't detect if JAWS is being used, but this ARIA attribute\n    // doesn't change behavior of Chrome if JAWS is not being used\n    if (IS_CHROME && IS_WINDOWS) {\n      tag.setAttribute('role', 'application');\n      attrs.role = 'application';\n    }\n\n    // Remove width/height attrs from tag so CSS can make it 100% width/height\n    tag.removeAttribute('width');\n    tag.removeAttribute('height');\n    if ('width' in attrs) {\n      delete attrs.width;\n    }\n    if ('height' in attrs) {\n      delete attrs.height;\n    }\n    Object.getOwnPropertyNames(attrs).forEach(function (attr) {\n      // don't copy over the class attribute to the player element when we're in a div embed\n      // the class is already set up properly in the divEmbed case\n      // and we want to make sure that the `video-js` class doesn't get lost\n      if (!(divEmbed && attr === 'class')) {\n        el.setAttribute(attr, attrs[attr]);\n      }\n      if (divEmbed) {\n        tag.setAttribute(attr, attrs[attr]);\n      }\n    });\n\n    // Update tag id/class for use as HTML5 playback tech\n    // Might think we should do this after embedding in container so .vjs-tech class\n    // doesn't flash 100% width/height, but class only applies with .video-js parent\n    tag.playerId = tag.id;\n    tag.id += '_html5_api';\n    tag.className = 'vjs-tech';\n\n    // Make player findable on elements\n    tag.player = el.player = this;\n    // Default state of video is paused\n    this.addClass('vjs-paused');\n    const deviceClassNames = ['IS_SMART_TV', 'IS_TIZEN', 'IS_WEBOS', 'IS_ANDROID', 'IS_IPAD', 'IS_IPHONE', 'IS_CHROMECAST_RECEIVER'].filter(key => browser[key]).map(key => {\n      return 'vjs-device-' + key.substring(3).toLowerCase().replace(/\\_/g, '-');\n    });\n    this.addClass(...deviceClassNames);\n\n    // Add a style element in the player that we'll use to set the width/height\n    // of the player in a way that's still overridable by CSS, just like the\n    // video element\n    if (window$1.VIDEOJS_NO_DYNAMIC_STYLE !== true) {\n      this.styleEl_ = createStyleElement('vjs-styles-dimensions');\n      const defaultsStyleEl = $('.vjs-styles-defaults');\n      const head = $('head');\n      head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);\n    }\n    this.fill_ = false;\n    this.fluid_ = false;\n\n    // Pass in the width/height/aspectRatio options which will update the style el\n    this.width(this.options_.width);\n    this.height(this.options_.height);\n    this.fill(this.options_.fill);\n    this.fluid(this.options_.fluid);\n    this.aspectRatio(this.options_.aspectRatio);\n    // support both crossOrigin and crossorigin to reduce confusion and issues around the name\n    this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);\n\n    // Hide any links within the video/audio tag,\n    // because IE doesn't hide them completely from screen readers.\n    const links = tag.getElementsByTagName('a');\n    for (let i = 0; i < links.length; i++) {\n      const linkEl = links.item(i);\n      addClass(linkEl, 'vjs-hidden');\n      linkEl.setAttribute('hidden', 'hidden');\n    }\n\n    // insertElFirst seems to cause the networkState to flicker from 3 to 2, so\n    // keep track of the original for later so we can know if the source originally failed\n    tag.initNetworkState_ = tag.networkState;\n\n    // Wrap video tag in div (el/box) container\n    if (tag.parentNode && !playerElIngest) {\n      tag.parentNode.insertBefore(el, tag);\n    }\n\n    // insert the tag as the first child of the player element\n    // then manually add it to the children array so that this.addChild\n    // will work properly for other components\n    //\n    // Breaks iPhone, fixed in HTML5 setup.\n    prependTo(tag, el);\n    this.children_.unshift(tag);\n\n    // Set lang attr on player to ensure CSS :lang() in consistent with player\n    // if it's been set to something different to the doc\n    this.el_.setAttribute('lang', this.language_);\n    this.el_.setAttribute('translate', 'no');\n    this.el_ = el;\n    return el;\n  }\n\n  /**\n   * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this\n   * sets the `crossOrigin` property on the `<video>` tag to control the CORS\n   * behavior.\n   *\n   * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}\n   *\n   * @param {string|null} [value]\n   *        The value to set the `Player`'s crossOrigin to. If an argument is\n   *        given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.\n   *\n   * @return {string|null|undefined}\n   *         - The current crossOrigin value of the `Player` when getting.\n   *         - undefined when setting\n   */\n  crossOrigin(value) {\n    // `null` can be set to unset a value\n    if (typeof value === 'undefined') {\n      return this.techGet_('crossOrigin');\n    }\n    if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {\n      log$1.warn(`crossOrigin must be null,  \"anonymous\" or \"use-credentials\", given \"${value}\"`);\n      return;\n    }\n    this.techCall_('setCrossOrigin', value);\n    if (this.posterImage) {\n      this.posterImage.crossOrigin(value);\n    }\n    return;\n  }\n\n  /**\n   * A getter/setter for the `Player`'s width. Returns the player's configured value.\n   * To get the current width use `currentWidth()`.\n   *\n   * @param {number|string} [value]\n   *        CSS value to set the `Player`'s width to.\n   *\n   * @return {number|undefined}\n   *         - The current width of the `Player` when getting.\n   *         - Nothing when setting\n   */\n  width(value) {\n    return this.dimension('width', value);\n  }\n\n  /**\n   * A getter/setter for the `Player`'s height. Returns the player's configured value.\n   * To get the current height use `currentheight()`.\n   *\n   * @param {number|string} [value]\n   *        CSS value to set the `Player`'s height to.\n   *\n   * @return {number|undefined}\n   *         - The current height of the `Player` when getting.\n   *         - Nothing when setting\n   */\n  height(value) {\n    return this.dimension('height', value);\n  }\n\n  /**\n   * A getter/setter for the `Player`'s width & height.\n   *\n   * @param {string} dimension\n   *        This string can be:\n   *        - 'width'\n   *        - 'height'\n   *\n   * @param {number|string} [value]\n   *        Value for dimension specified in the first argument.\n   *\n   * @return {number}\n   *         The dimension arguments value when getting (width/height).\n   */\n  dimension(dimension, value) {\n    const privDimension = dimension + '_';\n    if (value === undefined) {\n      return this[privDimension] || 0;\n    }\n    if (value === '' || value === 'auto') {\n      // If an empty string is given, reset the dimension to be automatic\n      this[privDimension] = undefined;\n      this.updateStyleEl_();\n      return;\n    }\n    const parsedVal = parseFloat(value);\n    if (isNaN(parsedVal)) {\n      log$1.error(`Improper value \"${value}\" supplied for for ${dimension}`);\n      return;\n    }\n    this[privDimension] = parsedVal;\n    this.updateStyleEl_();\n  }\n\n  /**\n   * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.\n   *\n   * Turning this on will turn off fill mode.\n   *\n   * @param {boolean} [bool]\n   *        - A value of true adds the class.\n   *        - A value of false removes the class.\n   *        - No value will be a getter.\n   *\n   * @return {boolean|undefined}\n   *         - The value of fluid when getting.\n   *         - `undefined` when setting.\n   */\n  fluid(bool) {\n    if (bool === undefined) {\n      return !!this.fluid_;\n    }\n    this.fluid_ = !!bool;\n    if (isEvented(this)) {\n      this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);\n    }\n    if (bool) {\n      this.addClass('vjs-fluid');\n      this.fill(false);\n      addEventedCallback(this, () => {\n        this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);\n      });\n    } else {\n      this.removeClass('vjs-fluid');\n    }\n    this.updateStyleEl_();\n  }\n\n  /**\n   * A getter/setter/toggler for the vjs-fill `className` on the `Player`.\n   *\n   * Turning this on will turn off fluid mode.\n   *\n   * @param {boolean} [bool]\n   *        - A value of true adds the class.\n   *        - A value of false removes the class.\n   *        - No value will be a getter.\n   *\n   * @return {boolean|undefined}\n   *         - The value of fluid when getting.\n   *         - `undefined` when setting.\n   */\n  fill(bool) {\n    if (bool === undefined) {\n      return !!this.fill_;\n    }\n    this.fill_ = !!bool;\n    if (bool) {\n      this.addClass('vjs-fill');\n      this.fluid(false);\n    } else {\n      this.removeClass('vjs-fill');\n    }\n  }\n\n  /**\n   * Get/Set the aspect ratio\n   *\n   * @param {string} [ratio]\n   *        Aspect ratio for player\n   *\n   * @return {string|undefined}\n   *         returns the current aspect ratio when getting\n   */\n\n  /**\n   * A getter/setter for the `Player`'s aspect ratio.\n   *\n   * @param {string} [ratio]\n   *        The value to set the `Player`'s aspect ratio to.\n   *\n   * @return {string|undefined}\n   *         - The current aspect ratio of the `Player` when getting.\n   *         - undefined when setting\n   */\n  aspectRatio(ratio) {\n    if (ratio === undefined) {\n      return this.aspectRatio_;\n    }\n\n    // Check for width:height format\n    if (!/^\\d+\\:\\d+$/.test(ratio)) {\n      throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');\n    }\n    this.aspectRatio_ = ratio;\n\n    // We're assuming if you set an aspect ratio you want fluid mode,\n    // because in fixed mode you could calculate width and height yourself.\n    this.fluid(true);\n    this.updateStyleEl_();\n  }\n\n  /**\n   * Update styles of the `Player` element (height, width and aspect ratio).\n   *\n   * @private\n   * @listens Tech#loadedmetadata\n   */\n  updateStyleEl_() {\n    if (window$1.VIDEOJS_NO_DYNAMIC_STYLE === true) {\n      const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;\n      const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;\n      const techEl = this.tech_ && this.tech_.el();\n      if (techEl) {\n        if (width >= 0) {\n          techEl.width = width;\n        }\n        if (height >= 0) {\n          techEl.height = height;\n        }\n      }\n      return;\n    }\n    let width;\n    let height;\n    let aspectRatio;\n    let idClass;\n\n    // The aspect ratio is either used directly or to calculate width and height.\n    if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {\n      // Use any aspectRatio that's been specifically set\n      aspectRatio = this.aspectRatio_;\n    } else if (this.videoWidth() > 0) {\n      // Otherwise try to get the aspect ratio from the video metadata\n      aspectRatio = this.videoWidth() + ':' + this.videoHeight();\n    } else {\n      // Or use a default. The video element's is 2:1, but 16:9 is more common.\n      aspectRatio = '16:9';\n    }\n\n    // Get the ratio as a decimal we can use to calculate dimensions\n    const ratioParts = aspectRatio.split(':');\n    const ratioMultiplier = ratioParts[1] / ratioParts[0];\n    if (this.width_ !== undefined) {\n      // Use any width that's been specifically set\n      width = this.width_;\n    } else if (this.height_ !== undefined) {\n      // Or calculate the width from the aspect ratio if a height has been set\n      width = this.height_ / ratioMultiplier;\n    } else {\n      // Or use the video's metadata, or use the video el's default of 300\n      width = this.videoWidth() || 300;\n    }\n    if (this.height_ !== undefined) {\n      // Use any height that's been specifically set\n      height = this.height_;\n    } else {\n      // Otherwise calculate the height from the ratio and the width\n      height = width * ratioMultiplier;\n    }\n\n    // Ensure the CSS class is valid by starting with an alpha character\n    if (/^[^a-zA-Z]/.test(this.id())) {\n      idClass = 'dimensions-' + this.id();\n    } else {\n      idClass = this.id() + '-dimensions';\n    }\n\n    // Ensure the right class is still on the player for the style element\n    this.addClass(idClass);\n    setTextContent(this.styleEl_, `\n      .${idClass} {\n        width: ${width}px;\n        height: ${height}px;\n      }\n\n      .${idClass}.vjs-fluid:not(.vjs-audio-only-mode) {\n        padding-top: ${ratioMultiplier * 100}%;\n      }\n    `);\n  }\n\n  /**\n   * Load/Create an instance of playback {@link Tech} including element\n   * and API methods. Then append the `Tech` element in `Player` as a child.\n   *\n   * @param {string} techName\n   *        name of the playback technology\n   *\n   * @param {string} source\n   *        video source\n   *\n   * @private\n   */\n  loadTech_(techName, source) {\n    // Pause and remove current playback technology\n    if (this.tech_) {\n      this.unloadTech_();\n    }\n    const titleTechName = toTitleCase$1(techName);\n    const camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);\n\n    // get rid of the HTML5 video tag as soon as we are using another tech\n    if (titleTechName !== 'Html5' && this.tag) {\n      Tech.getTech('Html5').disposeMediaElement(this.tag);\n      this.tag.player = null;\n      this.tag = null;\n    }\n    this.techName_ = titleTechName;\n\n    // Turn off API access because we're loading a new tech that might load asynchronously\n    this.isReady_ = false;\n    let autoplay = this.autoplay();\n\n    // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech\n    // because the player is going to handle autoplay on `loadstart`\n    if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {\n      autoplay = false;\n    }\n\n    // Grab tech-specific options from player options and add source and parent element to use.\n    const techOptions = {\n      source,\n      autoplay,\n      'nativeControlsForTouch': this.options_.nativeControlsForTouch,\n      'playerId': this.id(),\n      'techId': `${this.id()}_${camelTechName}_api`,\n      'playsinline': this.options_.playsinline,\n      'preload': this.options_.preload,\n      'loop': this.options_.loop,\n      'disablePictureInPicture': this.options_.disablePictureInPicture,\n      'muted': this.options_.muted,\n      'poster': this.poster(),\n      'language': this.language(),\n      'playerElIngest': this.playerElIngest_ || false,\n      'vtt.js': this.options_['vtt.js'],\n      'canOverridePoster': !!this.options_.techCanOverridePoster,\n      'enableSourceset': this.options_.enableSourceset\n    };\n    ALL.names.forEach(name => {\n      const props = ALL[name];\n      techOptions[props.getterName] = this[props.privateName];\n    });\n    Object.assign(techOptions, this.options_[titleTechName]);\n    Object.assign(techOptions, this.options_[camelTechName]);\n    Object.assign(techOptions, this.options_[techName.toLowerCase()]);\n    if (this.tag) {\n      techOptions.tag = this.tag;\n    }\n    if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {\n      techOptions.startTime = this.cache_.currentTime;\n    }\n\n    // Initialize tech instance\n    const TechClass = Tech.getTech(techName);\n    if (!TechClass) {\n      throw new Error(`No Tech named '${titleTechName}' exists! '${titleTechName}' should be registered using videojs.registerTech()'`);\n    }\n    this.tech_ = new TechClass(techOptions);\n\n    // player.triggerReady is always async, so don't need this to be async\n    this.tech_.ready(bind_(this, this.handleTechReady_), true);\n    textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);\n\n    // Listen to all HTML5-defined events and trigger them on the player\n    TECH_EVENTS_RETRIGGER.forEach(event => {\n      this.on(this.tech_, event, e => this[`handleTech${toTitleCase$1(event)}_`](e));\n    });\n    Object.keys(TECH_EVENTS_QUEUE).forEach(event => {\n      this.on(this.tech_, event, eventObj => {\n        if (this.tech_.playbackRate() === 0 && this.tech_.seeking()) {\n          this.queuedCallbacks_.push({\n            callback: this[`handleTech${TECH_EVENTS_QUEUE[event]}_`].bind(this),\n            event: eventObj\n          });\n          return;\n        }\n        this[`handleTech${TECH_EVENTS_QUEUE[event]}_`](eventObj);\n      });\n    });\n    this.on(this.tech_, 'loadstart', e => this.handleTechLoadStart_(e));\n    this.on(this.tech_, 'sourceset', e => this.handleTechSourceset_(e));\n    this.on(this.tech_, 'waiting', e => this.handleTechWaiting_(e));\n    this.on(this.tech_, 'ended', e => this.handleTechEnded_(e));\n    this.on(this.tech_, 'seeking', e => this.handleTechSeeking_(e));\n    this.on(this.tech_, 'play', e => this.handleTechPlay_(e));\n    this.on(this.tech_, 'pause', e => this.handleTechPause_(e));\n    this.on(this.tech_, 'durationchange', e => this.handleTechDurationChange_(e));\n    this.on(this.tech_, 'fullscreenchange', (e, data) => this.handleTechFullscreenChange_(e, data));\n    this.on(this.tech_, 'fullscreenerror', (e, err) => this.handleTechFullscreenError_(e, err));\n    this.on(this.tech_, 'enterpictureinpicture', e => this.handleTechEnterPictureInPicture_(e));\n    this.on(this.tech_, 'leavepictureinpicture', e => this.handleTechLeavePictureInPicture_(e));\n    this.on(this.tech_, 'error', e => this.handleTechError_(e));\n    this.on(this.tech_, 'posterchange', e => this.handleTechPosterChange_(e));\n    this.on(this.tech_, 'textdata', e => this.handleTechTextData_(e));\n    this.on(this.tech_, 'ratechange', e => this.handleTechRateChange_(e));\n    this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);\n    this.usingNativeControls(this.techGet_('controls'));\n    if (this.controls() && !this.usingNativeControls()) {\n      this.addTechControlsListeners_();\n    }\n\n    // Add the tech element in the DOM if it was not already there\n    // Make sure to not insert the original video element if using Html5\n    if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {\n      prependTo(this.tech_.el(), this.el());\n    }\n\n    // Get rid of the original video tag reference after the first tech is loaded\n    if (this.tag) {\n      this.tag.player = null;\n      this.tag = null;\n    }\n  }\n\n  /**\n   * Unload and dispose of the current playback {@link Tech}.\n   *\n   * @private\n   */\n  unloadTech_() {\n    // Save the current text tracks so that we can reuse the same text tracks with the next tech\n    ALL.names.forEach(name => {\n      const props = ALL[name];\n      this[props.privateName] = this[props.getterName]();\n    });\n    this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);\n    this.isReady_ = false;\n    this.tech_.dispose();\n    this.tech_ = false;\n    if (this.isPosterFromTech_) {\n      this.poster_ = '';\n      this.trigger('posterchange');\n    }\n    this.isPosterFromTech_ = false;\n  }\n\n  /**\n   * Return a reference to the current {@link Tech}.\n   * It will print a warning by default about the danger of using the tech directly\n   * but any argument that is passed in will silence the warning.\n   *\n   * @param {*} [safety]\n   *        Anything passed in to silence the warning\n   *\n   * @return {Tech}\n   *         The Tech\n   */\n  tech(safety) {\n    if (safety === undefined) {\n      log$1.warn('Using the tech directly can be dangerous. I hope you know what you\\'re doing.\\n' + 'See https://github.com/videojs/video.js/issues/2617 for more info.\\n');\n    }\n    return this.tech_;\n  }\n\n  /**\n   * An object that contains Video.js version.\n   *\n   * @typedef {Object} PlayerVersion\n   *\n   * @property {string} 'video.js' - Video.js version\n   */\n\n  /**\n   * Returns an object with Video.js version.\n   *\n   * @return {PlayerVersion}\n   *          An object with Video.js version.\n   */\n  version() {\n    return {\n      'video.js': version$6\n    };\n  }\n\n  /**\n   * Set up click and touch listeners for the playback element\n   *\n   * - On desktops: a click on the video itself will toggle playback\n   * - On mobile devices: a click on the video toggles controls\n   *   which is done by toggling the user state between active and\n   *   inactive\n   * - A tap can signal that a user has become active or has become inactive\n   *   e.g. a quick tap on an iPhone movie should reveal the controls. Another\n   *   quick tap should hide them again (signaling the user is in an inactive\n   *   viewing state)\n   * - In addition to this, we still want the user to be considered inactive after\n   *   a few seconds of inactivity.\n   *\n   * > Note: the only part of iOS interaction we can't mimic with this setup\n   * is a touch and hold on the video element counting as activity in order to\n   * keep the controls showing, but that shouldn't be an issue. A touch and hold\n   * on any controls will still keep the user active\n   *\n   * @private\n   */\n  addTechControlsListeners_() {\n    // Make sure to remove all the previous listeners in case we are called multiple times.\n    this.removeTechControlsListeners_();\n    this.on(this.tech_, 'click', this.boundHandleTechClick_);\n    this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);\n\n    // If the controls were hidden we don't want that to change without a tap event\n    // so we'll check if the controls were already showing before reporting user\n    // activity\n    this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);\n    this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);\n    this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);\n\n    // The tap listener needs to come after the touchend listener because the tap\n    // listener cancels out any reportedUserActivity when setting userActive(false)\n    this.on(this.tech_, 'tap', this.boundHandleTechTap_);\n  }\n\n  /**\n   * Remove the listeners used for click and tap controls. This is needed for\n   * toggling to controls disabled, where a tap/touch should do nothing.\n   *\n   * @private\n   */\n  removeTechControlsListeners_() {\n    // We don't want to just use `this.off()` because there might be other needed\n    // listeners added by techs that extend this.\n    this.off(this.tech_, 'tap', this.boundHandleTechTap_);\n    this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);\n    this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);\n    this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);\n    this.off(this.tech_, 'click', this.boundHandleTechClick_);\n    this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);\n  }\n\n  /**\n   * Player waits for the tech to be ready\n   *\n   * @private\n   */\n  handleTechReady_() {\n    this.triggerReady();\n\n    // Keep the same volume as before\n    if (this.cache_.volume) {\n      this.techCall_('setVolume', this.cache_.volume);\n    }\n\n    // Look if the tech found a higher resolution poster while loading\n    this.handleTechPosterChange_();\n\n    // Update the duration if available\n    this.handleTechDurationChange_();\n  }\n\n  /**\n   * Retrigger the `loadstart` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#loadstart\n   * @listens Tech#loadstart\n   * @private\n   */\n  handleTechLoadStart_() {\n    // TODO: Update to use `emptied` event instead. See #1277.\n\n    this.removeClass('vjs-ended', 'vjs-seeking');\n\n    // reset the error state\n    this.error(null);\n\n    // Update the duration\n    this.handleTechDurationChange_();\n    if (!this.paused()) {\n      /**\n       * Fired when the user agent begins looking for media data\n       *\n       * @event Player#loadstart\n       * @type {Event}\n       */\n      this.trigger('loadstart');\n    } else {\n      // reset the hasStarted state\n      this.hasStarted(false);\n      this.trigger('loadstart');\n    }\n\n    // autoplay happens after loadstart for the browser,\n    // so we mimic that behavior\n    this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());\n  }\n\n  /**\n   * Handle autoplay string values, rather than the typical boolean\n   * values that should be handled by the tech. Note that this is not\n   * part of any specification. Valid values and what they do can be\n   * found on the autoplay getter at Player#autoplay()\n   */\n  manualAutoplay_(type) {\n    if (!this.tech_ || typeof type !== 'string') {\n      return;\n    }\n\n    // Save original muted() value, set muted to true, and attempt to play().\n    // On promise rejection, restore muted from saved value\n    const resolveMuted = () => {\n      const previouslyMuted = this.muted();\n      this.muted(true);\n      const restoreMuted = () => {\n        this.muted(previouslyMuted);\n      };\n\n      // restore muted on play terminatation\n      this.playTerminatedQueue_.push(restoreMuted);\n      const mutedPromise = this.play();\n      if (!isPromise(mutedPromise)) {\n        return;\n      }\n      return mutedPromise.catch(err => {\n        restoreMuted();\n        throw new Error(`Rejection at manualAutoplay. Restoring muted value. ${err ? err : ''}`);\n      });\n    };\n    let promise;\n\n    // if muted defaults to true\n    // the only thing we can do is call play\n    if (type === 'any' && !this.muted()) {\n      promise = this.play();\n      if (isPromise(promise)) {\n        promise = promise.catch(resolveMuted);\n      }\n    } else if (type === 'muted' && !this.muted()) {\n      promise = resolveMuted();\n    } else {\n      promise = this.play();\n    }\n    if (!isPromise(promise)) {\n      return;\n    }\n    return promise.then(() => {\n      this.trigger({\n        type: 'autoplay-success',\n        autoplay: type\n      });\n    }).catch(() => {\n      this.trigger({\n        type: 'autoplay-failure',\n        autoplay: type\n      });\n    });\n  }\n\n  /**\n   * Update the internal source caches so that we return the correct source from\n   * `src()`, `currentSource()`, and `currentSources()`.\n   *\n   * > Note: `currentSources` will not be updated if the source that is passed in exists\n   *         in the current `currentSources` cache.\n   *\n   *\n   * @param {Tech~SourceObject} srcObj\n   *        A string or object source to update our caches to.\n   */\n  updateSourceCaches_(srcObj = '') {\n    let src = srcObj;\n    let type = '';\n    if (typeof src !== 'string') {\n      src = srcObj.src;\n      type = srcObj.type;\n    }\n\n    // make sure all the caches are set to default values\n    // to prevent null checking\n    this.cache_.source = this.cache_.source || {};\n    this.cache_.sources = this.cache_.sources || [];\n\n    // try to get the type of the src that was passed in\n    if (src && !type) {\n      type = findMimetype(this, src);\n    }\n\n    // update `currentSource` cache always\n    this.cache_.source = merge$1({}, srcObj, {\n      src,\n      type\n    });\n    const matchingSources = this.cache_.sources.filter(s => s.src && s.src === src);\n    const sourceElSources = [];\n    const sourceEls = this.$$('source');\n    const matchingSourceEls = [];\n    for (let i = 0; i < sourceEls.length; i++) {\n      const sourceObj = getAttributes(sourceEls[i]);\n      sourceElSources.push(sourceObj);\n      if (sourceObj.src && sourceObj.src === src) {\n        matchingSourceEls.push(sourceObj.src);\n      }\n    }\n\n    // if we have matching source els but not matching sources\n    // the current source cache is not up to date\n    if (matchingSourceEls.length && !matchingSources.length) {\n      this.cache_.sources = sourceElSources;\n      // if we don't have matching source or source els set the\n      // sources cache to the `currentSource` cache\n    } else if (!matchingSources.length) {\n      this.cache_.sources = [this.cache_.source];\n    }\n\n    // update the tech `src` cache\n    this.cache_.src = src;\n  }\n\n  /**\n   * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}\n   * causing the media element to reload.\n   *\n   * It will fire for the initial source and each subsequent source.\n   * This event is a custom event from Video.js and is triggered by the {@link Tech}.\n   *\n   * The event object for this event contains a `src` property that will contain the source\n   * that was available when the event was triggered. This is generally only necessary if Video.js\n   * is switching techs while the source was being changed.\n   *\n   * It is also fired when `load` is called on the player (or media element)\n   * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}\n   * says that the resource selection algorithm needs to be aborted and restarted.\n   * In this case, it is very likely that the `src` property will be set to the\n   * empty string `\"\"` to indicate we do not know what the source will be but\n   * that it is changing.\n   *\n   * *This event is currently still experimental and may change in minor releases.*\n   * __To use this, pass `enableSourceset` option to the player.__\n   *\n   * @event Player#sourceset\n   * @type {Event}\n   * @prop {string} src\n   *                The source url available when the `sourceset` was triggered.\n   *                It will be an empty string if we cannot know what the source is\n   *                but know that the source will change.\n   */\n  /**\n   * Retrigger the `sourceset` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#sourceset\n   * @listens Tech#sourceset\n   * @private\n   */\n  handleTechSourceset_(event) {\n    // only update the source cache when the source\n    // was not updated using the player api\n    if (!this.changingSrc_) {\n      let updateSourceCaches = src => this.updateSourceCaches_(src);\n      const playerSrc = this.currentSource().src;\n      const eventSrc = event.src;\n\n      // if we have a playerSrc that is not a blob, and a tech src that is a blob\n      if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {\n        // if both the tech source and the player source were updated we assume\n        // something like @videojs/http-streaming did the sourceset and skip updating the source cache.\n        if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {\n          updateSourceCaches = () => {};\n        }\n      }\n\n      // update the source to the initial source right away\n      // in some cases this will be empty string\n      updateSourceCaches(eventSrc);\n\n      // if the `sourceset` `src` was an empty string\n      // wait for a `loadstart` to update the cache to `currentSrc`.\n      // If a sourceset happens before a `loadstart`, we reset the state\n      if (!event.src) {\n        this.tech_.any(['sourceset', 'loadstart'], e => {\n          // if a sourceset happens before a `loadstart` there\n          // is nothing to do as this `handleTechSourceset_`\n          // will be called again and this will be handled there.\n          if (e.type === 'sourceset') {\n            return;\n          }\n          const techSrc = this.techGet_('currentSrc');\n          this.lastSource_.tech = techSrc;\n          this.updateSourceCaches_(techSrc);\n        });\n      }\n    }\n    this.lastSource_ = {\n      player: this.currentSource().src,\n      tech: event.src\n    };\n    this.trigger({\n      src: event.src,\n      type: 'sourceset'\n    });\n  }\n\n  /**\n   * Add/remove the vjs-has-started class\n   *\n   *\n   * @param {boolean} request\n   *        - true: adds the class\n   *        - false: remove the class\n   *\n   * @return {boolean}\n   *         the boolean value of hasStarted_\n   */\n  hasStarted(request) {\n    if (request === undefined) {\n      // act as getter, if we have no request to change\n      return this.hasStarted_;\n    }\n    if (request === this.hasStarted_) {\n      return;\n    }\n    this.hasStarted_ = request;\n    if (this.hasStarted_) {\n      this.addClass('vjs-has-started');\n    } else {\n      this.removeClass('vjs-has-started');\n    }\n  }\n\n  /**\n   * Fired whenever the media begins or resumes playback\n   *\n   * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}\n   * @fires Player#play\n   * @listens Tech#play\n   * @private\n   */\n  handleTechPlay_() {\n    this.removeClass('vjs-ended', 'vjs-paused');\n    this.addClass('vjs-playing');\n\n    // hide the poster when the user hits play\n    this.hasStarted(true);\n    /**\n     * Triggered whenever an {@link Tech#play} event happens. Indicates that\n     * playback has started or resumed.\n     *\n     * @event Player#play\n     * @type {Event}\n     */\n    this.trigger('play');\n  }\n\n  /**\n   * Retrigger the `ratechange` event that was triggered by the {@link Tech}.\n   *\n   * If there were any events queued while the playback rate was zero, fire\n   * those events now.\n   *\n   * @private\n   * @method Player#handleTechRateChange_\n   * @fires Player#ratechange\n   * @listens Tech#ratechange\n   */\n  handleTechRateChange_() {\n    if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {\n      this.queuedCallbacks_.forEach(queued => queued.callback(queued.event));\n      this.queuedCallbacks_ = [];\n    }\n    this.cache_.lastPlaybackRate = this.tech_.playbackRate();\n    /**\n     * Fires when the playing speed of the audio/video is changed\n     *\n     * @event Player#ratechange\n     * @type {event}\n     */\n    this.trigger('ratechange');\n  }\n\n  /**\n   * Retrigger the `waiting` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#waiting\n   * @listens Tech#waiting\n   * @private\n   */\n  handleTechWaiting_() {\n    this.addClass('vjs-waiting');\n    /**\n     * A readyState change on the DOM element has caused playback to stop.\n     *\n     * @event Player#waiting\n     * @type {Event}\n     */\n    this.trigger('waiting');\n\n    // Browsers may emit a timeupdate event after a waiting event. In order to prevent\n    // premature removal of the waiting class, wait for the time to change.\n    const timeWhenWaiting = this.currentTime();\n    const timeUpdateListener = () => {\n      if (timeWhenWaiting !== this.currentTime()) {\n        this.removeClass('vjs-waiting');\n        this.off('timeupdate', timeUpdateListener);\n      }\n    };\n    this.on('timeupdate', timeUpdateListener);\n  }\n\n  /**\n   * Retrigger the `canplay` event that was triggered by the {@link Tech}.\n   * > Note: This is not consistent between browsers. See #1351\n   *\n   * @fires Player#canplay\n   * @listens Tech#canplay\n   * @private\n   */\n  handleTechCanPlay_() {\n    this.removeClass('vjs-waiting');\n    /**\n     * The media has a readyState of HAVE_FUTURE_DATA or greater.\n     *\n     * @event Player#canplay\n     * @type {Event}\n     */\n    this.trigger('canplay');\n  }\n\n  /**\n   * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#canplaythrough\n   * @listens Tech#canplaythrough\n   * @private\n   */\n  handleTechCanPlayThrough_() {\n    this.removeClass('vjs-waiting');\n    /**\n     * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the\n     * entire media file can be played without buffering.\n     *\n     * @event Player#canplaythrough\n     * @type {Event}\n     */\n    this.trigger('canplaythrough');\n  }\n\n  /**\n   * Retrigger the `playing` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#playing\n   * @listens Tech#playing\n   * @private\n   */\n  handleTechPlaying_() {\n    this.removeClass('vjs-waiting');\n    /**\n     * The media is no longer blocked from playback, and has started playing.\n     *\n     * @event Player#playing\n     * @type {Event}\n     */\n    this.trigger('playing');\n  }\n\n  /**\n   * Retrigger the `seeking` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#seeking\n   * @listens Tech#seeking\n   * @private\n   */\n  handleTechSeeking_() {\n    this.addClass('vjs-seeking');\n    /**\n     * Fired whenever the player is jumping to a new time\n     *\n     * @event Player#seeking\n     * @type {Event}\n     */\n    this.trigger('seeking');\n  }\n\n  /**\n   * Retrigger the `seeked` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#seeked\n   * @listens Tech#seeked\n   * @private\n   */\n  handleTechSeeked_() {\n    this.removeClass('vjs-seeking', 'vjs-ended');\n    /**\n     * Fired when the player has finished jumping to a new time\n     *\n     * @event Player#seeked\n     * @type {Event}\n     */\n    this.trigger('seeked');\n  }\n\n  /**\n   * Retrigger the `pause` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#pause\n   * @listens Tech#pause\n   * @private\n   */\n  handleTechPause_() {\n    this.removeClass('vjs-playing');\n    this.addClass('vjs-paused');\n    /**\n     * Fired whenever the media has been paused\n     *\n     * @event Player#pause\n     * @type {Event}\n     */\n    this.trigger('pause');\n  }\n\n  /**\n   * Retrigger the `ended` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#ended\n   * @listens Tech#ended\n   * @private\n   */\n  handleTechEnded_() {\n    this.addClass('vjs-ended');\n    this.removeClass('vjs-waiting');\n    if (this.options_.loop) {\n      this.currentTime(0);\n      this.play();\n    } else if (!this.paused()) {\n      this.pause();\n    }\n\n    /**\n     * Fired when the end of the media resource is reached (currentTime == duration)\n     *\n     * @event Player#ended\n     * @type {Event}\n     */\n    this.trigger('ended');\n  }\n\n  /**\n   * Fired when the duration of the media resource is first known or changed\n   *\n   * @listens Tech#durationchange\n   * @private\n   */\n  handleTechDurationChange_() {\n    this.duration(this.techGet_('duration'));\n  }\n\n  /**\n   * Handle a click on the media element to play/pause\n   *\n   * @param {Event} event\n   *        the event that caused this function to trigger\n   *\n   * @listens Tech#click\n   * @private\n   */\n  handleTechClick_(event) {\n    // When controls are disabled a click should not toggle playback because\n    // the click is considered a control\n    if (!this.controls_) {\n      return;\n    }\n    if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {\n      if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {\n        this.options_.userActions.click.call(this, event);\n      } else if (this.paused()) {\n        silencePromise(this.play());\n      } else {\n        this.pause();\n      }\n    }\n  }\n\n  /**\n   * Handle a double-click on the media element to enter/exit fullscreen,\n   * or exit documentPictureInPicture mode\n   *\n   * @param {Event} event\n   *        the event that caused this function to trigger\n   *\n   * @listens Tech#dblclick\n   * @private\n   */\n  handleTechDoubleClick_(event) {\n    if (!this.controls_) {\n      return;\n    }\n\n    // we do not want to toggle fullscreen state\n    // when double-clicking inside a control bar or a modal\n    const inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), el => el.contains(event.target));\n    if (!inAllowedEls) {\n      /*\n       * options.userActions.doubleClick\n       *\n       * If `undefined` or `true`, double-click toggles fullscreen if controls are present\n       * Set to `false` to disable double-click handling\n       * Set to a function to substitute an external double-click handler\n       */\n      if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {\n        if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {\n          this.options_.userActions.doubleClick.call(this, event);\n        } else if (this.isInPictureInPicture() && !document$1.pictureInPictureElement) {\n          // Checking the presence of `window.documentPictureInPicture.window` complicates\n          // tests, checking `document.pictureInPictureElement` also works. It wouldn't\n          // be null in regular picture in picture.\n          // Exit picture in picture mode. This gesture can't trigger pip on the main window.\n          this.exitPictureInPicture();\n        } else if (this.isFullscreen()) {\n          this.exitFullscreen();\n        } else {\n          this.requestFullscreen();\n        }\n      }\n    }\n  }\n\n  /**\n   * Handle a tap on the media element. It will toggle the user\n   * activity state, which hides and shows the controls.\n   *\n   * @listens Tech#tap\n   * @private\n   */\n  handleTechTap_() {\n    this.userActive(!this.userActive());\n  }\n\n  /**\n   * Handle touch to start\n   *\n   * @listens Tech#touchstart\n   * @private\n   */\n  handleTechTouchStart_() {\n    this.userWasActive = this.userActive();\n  }\n\n  /**\n   * Handle touch to move\n   *\n   * @listens Tech#touchmove\n   * @private\n   */\n  handleTechTouchMove_() {\n    if (this.userWasActive) {\n      this.reportUserActivity();\n    }\n  }\n\n  /**\n   * Handle touch to end\n   *\n   * @param {Event} event\n   *        the touchend event that triggered\n   *        this function\n   *\n   * @listens Tech#touchend\n   * @private\n   */\n  handleTechTouchEnd_(event) {\n    // Stop the mouse events from also happening\n    if (event.cancelable) {\n      event.preventDefault();\n    }\n  }\n\n  /**\n   * @private\n   */\n  toggleFullscreenClass_() {\n    if (this.isFullscreen()) {\n      this.addClass('vjs-fullscreen');\n    } else {\n      this.removeClass('vjs-fullscreen');\n    }\n  }\n\n  /**\n   * when the document fschange event triggers it calls this\n   */\n  documentFullscreenChange_(e) {\n    const targetPlayer = e.target.player;\n\n    // if another player was fullscreen\n    // do a null check for targetPlayer because older firefox's would put document as e.target\n    if (targetPlayer && targetPlayer !== this) {\n      return;\n    }\n    const el = this.el();\n    let isFs = document$1[this.fsApi_.fullscreenElement] === el;\n    if (!isFs && el.matches) {\n      isFs = el.matches(':' + this.fsApi_.fullscreen);\n    }\n    this.isFullscreen(isFs);\n  }\n\n  /**\n   * Handle Tech Fullscreen Change\n   *\n   * @param {Event} event\n   *        the fullscreenchange event that triggered this function\n   *\n   * @param {Object} data\n   *        the data that was sent with the event\n   *\n   * @private\n   * @listens Tech#fullscreenchange\n   * @fires Player#fullscreenchange\n   */\n  handleTechFullscreenChange_(event, data) {\n    if (data) {\n      if (data.nativeIOSFullscreen) {\n        this.addClass('vjs-ios-native-fs');\n        this.tech_.one('webkitendfullscreen', () => {\n          this.removeClass('vjs-ios-native-fs');\n        });\n      }\n      this.isFullscreen(data.isFullscreen);\n    }\n  }\n  handleTechFullscreenError_(event, err) {\n    this.trigger('fullscreenerror', err);\n  }\n\n  /**\n   * @private\n   */\n  togglePictureInPictureClass_() {\n    if (this.isInPictureInPicture()) {\n      this.addClass('vjs-picture-in-picture');\n    } else {\n      this.removeClass('vjs-picture-in-picture');\n    }\n  }\n\n  /**\n   * Handle Tech Enter Picture-in-Picture.\n   *\n   * @param {Event} event\n   *        the enterpictureinpicture event that triggered this function\n   *\n   * @private\n   * @listens Tech#enterpictureinpicture\n   */\n  handleTechEnterPictureInPicture_(event) {\n    this.isInPictureInPicture(true);\n  }\n\n  /**\n   * Handle Tech Leave Picture-in-Picture.\n   *\n   * @param {Event} event\n   *        the leavepictureinpicture event that triggered this function\n   *\n   * @private\n   * @listens Tech#leavepictureinpicture\n   */\n  handleTechLeavePictureInPicture_(event) {\n    this.isInPictureInPicture(false);\n  }\n\n  /**\n   * Fires when an error occurred during the loading of an audio/video.\n   *\n   * @private\n   * @listens Tech#error\n   */\n  handleTechError_() {\n    const error = this.tech_.error();\n    if (error) {\n      this.error(error);\n    }\n  }\n\n  /**\n   * Retrigger the `textdata` event that was triggered by the {@link Tech}.\n   *\n   * @fires Player#textdata\n   * @listens Tech#textdata\n   * @private\n   */\n  handleTechTextData_() {\n    let data = null;\n    if (arguments.length > 1) {\n      data = arguments[1];\n    }\n\n    /**\n     * Fires when we get a textdata event from tech\n     *\n     * @event Player#textdata\n     * @type {Event}\n     */\n    this.trigger('textdata', data);\n  }\n\n  /**\n   * Get object for cached values.\n   *\n   * @return {Object}\n   *         get the current object cache\n   */\n  getCache() {\n    return this.cache_;\n  }\n\n  /**\n   * Resets the internal cache object.\n   *\n   * Using this function outside the player constructor or reset method may\n   * have unintended side-effects.\n   *\n   * @private\n   */\n  resetCache_() {\n    this.cache_ = {\n      // Right now, the currentTime is not _really_ cached because it is always\n      // retrieved from the tech (see: currentTime). However, for completeness,\n      // we set it to zero here to ensure that if we do start actually caching\n      // it, we reset it along with everything else.\n      currentTime: 0,\n      initTime: 0,\n      inactivityTimeout: this.options_.inactivityTimeout,\n      duration: NaN,\n      lastVolume: 1,\n      lastPlaybackRate: this.defaultPlaybackRate(),\n      media: null,\n      src: '',\n      source: {},\n      sources: [],\n      playbackRates: [],\n      volume: 1\n    };\n  }\n\n  /**\n   * Pass values to the playback tech\n   *\n   * @param {string} [method]\n   *        the method to call\n   *\n   * @param {Object} [arg]\n   *        the argument to pass\n   *\n   * @private\n   */\n  techCall_(method, arg) {\n    // If it's not ready yet, call method when it is\n\n    this.ready(function () {\n      if (method in allowedSetters) {\n        return set(this.middleware_, this.tech_, method, arg);\n      } else if (method in allowedMediators) {\n        return mediate(this.middleware_, this.tech_, method, arg);\n      }\n      try {\n        if (this.tech_) {\n          this.tech_[method](arg);\n        }\n      } catch (e) {\n        log$1(e);\n        throw e;\n      }\n    }, true);\n  }\n\n  /**\n   * Mediate attempt to call playback tech method\n   * and return the value of the method called.\n   *\n   * @param {string} method\n   *        Tech method\n   *\n   * @return {*}\n   *         Value returned by the tech method called, undefined if tech\n   *         is not ready or tech method is not present\n   *\n   * @private\n   */\n  techGet_(method) {\n    if (!this.tech_ || !this.tech_.isReady_) {\n      return;\n    }\n    if (method in allowedGetters) {\n      return get(this.middleware_, this.tech_, method);\n    } else if (method in allowedMediators) {\n      return mediate(this.middleware_, this.tech_, method);\n    }\n\n    // Log error when playback tech object is present but method\n    // is undefined or unavailable\n    try {\n      return this.tech_[method]();\n    } catch (e) {\n      // When building additional tech libs, an expected method may not be defined yet\n      if (this.tech_[method] === undefined) {\n        log$1(`Video.js: ${method} method not defined for ${this.techName_} playback technology.`, e);\n        throw e;\n      }\n\n      // When a method isn't available on the object it throws a TypeError\n      if (e.name === 'TypeError') {\n        log$1(`Video.js: ${method} unavailable on ${this.techName_} playback technology element.`, e);\n        this.tech_.isReady_ = false;\n        throw e;\n      }\n\n      // If error unknown, just log and throw\n      log$1(e);\n      throw e;\n    }\n  }\n\n  /**\n   * Attempt to begin playback at the first opportunity.\n   *\n   * @return {Promise|undefined}\n   *         Returns a promise if the browser supports Promises (or one\n   *         was passed in as an option). This promise will be resolved on\n   *         the return value of play. If this is undefined it will fulfill the\n   *         promise chain otherwise the promise chain will be fulfilled when\n   *         the promise from play is fulfilled.\n   */\n  play() {\n    return new Promise(resolve => {\n      this.play_(resolve);\n    });\n  }\n\n  /**\n   * The actual logic for play, takes a callback that will be resolved on the\n   * return value of play. This allows us to resolve to the play promise if there\n   * is one on modern browsers.\n   *\n   * @private\n   * @param {Function} [callback]\n   *        The callback that should be called when the techs play is actually called\n   */\n  play_(callback = silencePromise) {\n    this.playCallbacks_.push(callback);\n    const isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));\n    const isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS);\n\n    // treat calls to play_ somewhat like the `one` event function\n    if (this.waitToPlay_) {\n      this.off(['ready', 'loadstart'], this.waitToPlay_);\n      this.waitToPlay_ = null;\n    }\n\n    // if the player/tech is not ready or the src itself is not ready\n    // queue up a call to play on `ready` or `loadstart`\n    if (!this.isReady_ || !isSrcReady) {\n      this.waitToPlay_ = e => {\n        this.play_();\n      };\n      this.one(['ready', 'loadstart'], this.waitToPlay_);\n\n      // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod\n      // in that case, we need to prime the video element by calling load so it'll be ready in time\n      if (!isSrcReady && isSafariOrIOS) {\n        this.load();\n      }\n      return;\n    }\n\n    // If the player/tech is ready and we have a source, we can attempt playback.\n    const val = this.techGet_('play');\n\n    // For native playback, reset the progress bar if we get a play call from a replay.\n    const isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');\n    if (isNativeReplay) {\n      this.resetProgressBar_();\n    }\n    // play was terminated if the returned value is null\n    if (val === null) {\n      this.runPlayTerminatedQueue_();\n    } else {\n      this.runPlayCallbacks_(val);\n    }\n  }\n\n  /**\n   * These functions will be run when if play is terminated. If play\n   * runPlayCallbacks_ is run these function will not be run. This allows us\n   * to differentiate between a terminated play and an actual call to play.\n   */\n  runPlayTerminatedQueue_() {\n    const queue = this.playTerminatedQueue_.slice(0);\n    this.playTerminatedQueue_ = [];\n    queue.forEach(function (q) {\n      q();\n    });\n  }\n\n  /**\n   * When a callback to play is delayed we have to run these\n   * callbacks when play is actually called on the tech. This function\n   * runs the callbacks that were delayed and accepts the return value\n   * from the tech.\n   *\n   * @param {undefined|Promise} val\n   *        The return value from the tech.\n   */\n  runPlayCallbacks_(val) {\n    const callbacks = this.playCallbacks_.slice(0);\n    this.playCallbacks_ = [];\n    // clear play terminatedQueue since we finished a real play\n    this.playTerminatedQueue_ = [];\n    callbacks.forEach(function (cb) {\n      cb(val);\n    });\n  }\n\n  /**\n   * Pause the video playback\n   */\n  pause() {\n    this.techCall_('pause');\n  }\n\n  /**\n   * Check if the player is paused or has yet to play\n   *\n   * @return {boolean}\n   *         - false: if the media is currently playing\n   *         - true: if media is not currently playing\n   */\n  paused() {\n    // The initial state of paused should be true (in Safari it's actually false)\n    return this.techGet_('paused') === false ? false : true;\n  }\n\n  /**\n   * Get a TimeRange object representing the current ranges of time that the user\n   * has played.\n   *\n   * @return {TimeRange}\n   *         A time range object that represents all the increments of time that have\n   *         been played.\n   */\n  played() {\n    return this.techGet_('played') || createTimeRanges$1(0, 0);\n  }\n\n  /**\n   * Sets or returns whether or not the user is \"scrubbing\". Scrubbing is\n   * when the user has clicked the progress bar handle and is\n   * dragging it along the progress bar.\n   *\n   * @param {boolean} [isScrubbing]\n   *        whether the user is or is not scrubbing\n   *\n   * @return {boolean|undefined}\n   *         - The value of scrubbing when getting\n   *         - Nothing when setting\n   */\n  scrubbing(isScrubbing) {\n    if (typeof isScrubbing === 'undefined') {\n      return this.scrubbing_;\n    }\n    this.scrubbing_ = !!isScrubbing;\n    this.techCall_('setScrubbing', this.scrubbing_);\n    if (isScrubbing) {\n      this.addClass('vjs-scrubbing');\n    } else {\n      this.removeClass('vjs-scrubbing');\n    }\n  }\n\n  /**\n   * Get or set the current time (in seconds)\n   *\n   * @param {number|string} [seconds]\n   *        The time to seek to in seconds\n   *\n   * @return {number|undefined}\n   *         - the current time in seconds when getting\n   *         - Nothing when setting\n   */\n  currentTime(seconds) {\n    if (seconds === undefined) {\n      // cache last currentTime and return. default to 0 seconds\n      //\n      // Caching the currentTime is meant to prevent a massive amount of reads on the tech's\n      // currentTime when scrubbing, but may not provide much performance benefit after all.\n      // Should be tested. Also something has to read the actual current time or the cache will\n      // never get updated.\n      this.cache_.currentTime = this.techGet_('currentTime') || 0;\n      return this.cache_.currentTime;\n    }\n    if (seconds < 0) {\n      seconds = 0;\n    }\n    if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {\n      this.cache_.initTime = seconds;\n      this.off('canplay', this.boundApplyInitTime_);\n      this.one('canplay', this.boundApplyInitTime_);\n      return;\n    }\n    this.techCall_('setCurrentTime', seconds);\n    this.cache_.initTime = 0;\n    if (isFinite(seconds)) {\n      this.cache_.currentTime = Number(seconds);\n    }\n  }\n\n  /**\n   * Apply the value of initTime stored in cache as currentTime.\n   *\n   * @private\n   */\n  applyInitTime_() {\n    this.currentTime(this.cache_.initTime);\n  }\n\n  /**\n   * Normally gets the length in time of the video in seconds;\n   * in all but the rarest use cases an argument will NOT be passed to the method\n   *\n   * > **NOTE**: The video must have started loading before the duration can be\n   * known, and depending on preload behaviour may not be known until the video starts\n   * playing.\n   *\n   * @fires Player#durationchange\n   *\n   * @param {number} [seconds]\n   *        The duration of the video to set in seconds\n   *\n   * @return {number|undefined}\n   *         - The duration of the video in seconds when getting\n   *         - Nothing when setting\n   */\n  duration(seconds) {\n    if (seconds === undefined) {\n      // return NaN if the duration is not known\n      return this.cache_.duration !== undefined ? this.cache_.duration : NaN;\n    }\n    seconds = parseFloat(seconds);\n\n    // Standardize on Infinity for signaling video is live\n    if (seconds < 0) {\n      seconds = Infinity;\n    }\n    if (seconds !== this.cache_.duration) {\n      // Cache the last set value for optimized scrubbing\n      this.cache_.duration = seconds;\n      if (seconds === Infinity) {\n        this.addClass('vjs-live');\n      } else {\n        this.removeClass('vjs-live');\n      }\n      if (!isNaN(seconds)) {\n        // Do not fire durationchange unless the duration value is known.\n        // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}\n\n        /**\n         * @event Player#durationchange\n         * @type {Event}\n         */\n        this.trigger('durationchange');\n      }\n    }\n  }\n\n  /**\n   * Calculates how much time is left in the video. Not part\n   * of the native video API.\n   *\n   * @return {number}\n   *         The time remaining in seconds\n   */\n  remainingTime() {\n    return this.duration() - this.currentTime();\n  }\n\n  /**\n   * A remaining time function that is intended to be used when\n   * the time is to be displayed directly to the user.\n   *\n   * @return {number}\n   *         The rounded time remaining in seconds\n   */\n  remainingTimeDisplay() {\n    return Math.floor(this.duration()) - Math.floor(this.currentTime());\n  }\n\n  //\n  // Kind of like an array of portions of the video that have been downloaded.\n\n  /**\n   * Get a TimeRange object with an array of the times of the video\n   * that have been downloaded. If you just want the percent of the\n   * video that's been downloaded, use bufferedPercent.\n   *\n   * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}\n   *\n   * @return {TimeRange}\n   *         A mock {@link TimeRanges} object (following HTML spec)\n   */\n  buffered() {\n    let buffered = this.techGet_('buffered');\n    if (!buffered || !buffered.length) {\n      buffered = createTimeRanges$1(0, 0);\n    }\n    return buffered;\n  }\n\n  /**\n   * Get the TimeRanges of the media that are currently available\n   * for seeking to.\n   *\n   * @see [Seekable Spec]{@link https://html.spec.whatwg.org/multipage/media.html#dom-media-seekable}\n   *\n   * @return {TimeRange}\n   *         A mock {@link TimeRanges} object (following HTML spec)\n   */\n  seekable() {\n    let seekable = this.techGet_('seekable');\n    if (!seekable || !seekable.length) {\n      seekable = createTimeRanges$1(0, 0);\n    }\n    return seekable;\n  }\n\n  /**\n   * Returns whether the player is in the \"seeking\" state.\n   *\n   * @return {boolean} True if the player is in the seeking state, false if not.\n   */\n  seeking() {\n    return this.techGet_('seeking');\n  }\n\n  /**\n   * Returns whether the player is in the \"ended\" state.\n   *\n   * @return {boolean} True if the player is in the ended state, false if not.\n   */\n  ended() {\n    return this.techGet_('ended');\n  }\n\n  /**\n   * Returns the current state of network activity for the element, from\n   * the codes in the list below.\n   * - NETWORK_EMPTY (numeric value 0)\n   *   The element has not yet been initialised. All attributes are in\n   *   their initial states.\n   * - NETWORK_IDLE (numeric value 1)\n   *   The element's resource selection algorithm is active and has\n   *   selected a resource, but it is not actually using the network at\n   *   this time.\n   * - NETWORK_LOADING (numeric value 2)\n   *   The user agent is actively trying to download data.\n   * - NETWORK_NO_SOURCE (numeric value 3)\n   *   The element's resource selection algorithm is active, but it has\n   *   not yet found a resource to use.\n   *\n   * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states\n   * @return {number} the current network activity state\n   */\n  networkState() {\n    return this.techGet_('networkState');\n  }\n\n  /**\n   * Returns a value that expresses the current state of the element\n   * with respect to rendering the current playback position, from the\n   * codes in the list below.\n   * - HAVE_NOTHING (numeric value 0)\n   *   No information regarding the media resource is available.\n   * - HAVE_METADATA (numeric value 1)\n   *   Enough of the resource has been obtained that the duration of the\n   *   resource is available.\n   * - HAVE_CURRENT_DATA (numeric value 2)\n   *   Data for the immediate current playback position is available.\n   * - HAVE_FUTURE_DATA (numeric value 3)\n   *   Data for the immediate current playback position is available, as\n   *   well as enough data for the user agent to advance the current\n   *   playback position in the direction of playback.\n   * - HAVE_ENOUGH_DATA (numeric value 4)\n   *   The user agent estimates that enough data is available for\n   *   playback to proceed uninterrupted.\n   *\n   * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate\n   * @return {number} the current playback rendering state\n   */\n  readyState() {\n    return this.techGet_('readyState');\n  }\n\n  /**\n   * Get the percent (as a decimal) of the video that's been downloaded.\n   * This method is not a part of the native HTML video API.\n   *\n   * @return {number}\n   *         A decimal between 0 and 1 representing the percent\n   *         that is buffered 0 being 0% and 1 being 100%\n   */\n  bufferedPercent() {\n    return bufferedPercent(this.buffered(), this.duration());\n  }\n\n  /**\n   * Get the ending time of the last buffered time range\n   * This is used in the progress bar to encapsulate all time ranges.\n   *\n   * @return {number}\n   *         The end of the last buffered time range\n   */\n  bufferedEnd() {\n    const buffered = this.buffered();\n    const duration = this.duration();\n    let end = buffered.end(buffered.length - 1);\n    if (end > duration) {\n      end = duration;\n    }\n    return end;\n  }\n\n  /**\n   * Get or set the current volume of the media\n   *\n   * @param  {number} [percentAsDecimal]\n   *         The new volume as a decimal percent:\n   *         - 0 is muted/0%/off\n   *         - 1.0 is 100%/full\n   *         - 0.5 is half volume or 50%\n   *\n   * @return {number|undefined}\n   *         The current volume as a percent when getting\n   */\n  volume(percentAsDecimal) {\n    let vol;\n    if (percentAsDecimal !== undefined) {\n      // Force value to between 0 and 1\n      vol = Math.max(0, Math.min(1, percentAsDecimal));\n      this.cache_.volume = vol;\n      this.techCall_('setVolume', vol);\n      if (vol > 0) {\n        this.lastVolume_(vol);\n      }\n      return;\n    }\n\n    // Default to 1 when returning current volume.\n    vol = parseFloat(this.techGet_('volume'));\n    return isNaN(vol) ? 1 : vol;\n  }\n\n  /**\n   * Get the current muted state, or turn mute on or off\n   *\n   * @param {boolean} [muted]\n   *        - true to mute\n   *        - false to unmute\n   *\n   * @return {boolean|undefined}\n   *         - true if mute is on and getting\n   *         - false if mute is off and getting\n   *         - nothing if setting\n   */\n  muted(muted) {\n    if (muted !== undefined) {\n      this.techCall_('setMuted', muted);\n      return;\n    }\n    return this.techGet_('muted') || false;\n  }\n\n  /**\n   * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted\n   * indicates the state of muted on initial playback.\n   *\n   * ```js\n   *   var myPlayer = videojs('some-player-id');\n   *\n   *   myPlayer.src(\"http://www.example.com/path/to/video.mp4\");\n   *\n   *   // get, should be false\n   *   console.log(myPlayer.defaultMuted());\n   *   // set to true\n   *   myPlayer.defaultMuted(true);\n   *   // get should be true\n   *   console.log(myPlayer.defaultMuted());\n   * ```\n   *\n   * @param {boolean} [defaultMuted]\n   *        - true to mute\n   *        - false to unmute\n   *\n   * @return {boolean|undefined}\n   *         - true if defaultMuted is on and getting\n   *         - false if defaultMuted is off and getting\n   *         - Nothing when setting\n   */\n  defaultMuted(defaultMuted) {\n    if (defaultMuted !== undefined) {\n      this.techCall_('setDefaultMuted', defaultMuted);\n    }\n    return this.techGet_('defaultMuted') || false;\n  }\n\n  /**\n   * Get the last volume, or set it\n   *\n   * @param  {number} [percentAsDecimal]\n   *         The new last volume as a decimal percent:\n   *         - 0 is muted/0%/off\n   *         - 1.0 is 100%/full\n   *         - 0.5 is half volume or 50%\n   *\n   * @return {number|undefined}\n   *         - The current value of lastVolume as a percent when getting\n   *         - Nothing when setting\n   *\n   * @private\n   */\n  lastVolume_(percentAsDecimal) {\n    if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {\n      this.cache_.lastVolume = percentAsDecimal;\n      return;\n    }\n    return this.cache_.lastVolume;\n  }\n\n  /**\n   * Check if current tech can support native fullscreen\n   * (e.g. with built in controls like iOS)\n   *\n   * @return {boolean}\n   *         if native fullscreen is supported\n   */\n  supportsFullScreen() {\n    return this.techGet_('supportsFullScreen') || false;\n  }\n\n  /**\n   * Check if the player is in fullscreen mode or tell the player that it\n   * is or is not in fullscreen mode.\n   *\n   * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official\n   * property and instead document.fullscreenElement is used. But isFullscreen is\n   * still a valuable property for internal player workings.\n   *\n   * @param  {boolean} [isFS]\n   *         Set the players current fullscreen state\n   *\n   * @return {boolean|undefined}\n   *         - true if fullscreen is on and getting\n   *         - false if fullscreen is off and getting\n   *         - Nothing when setting\n   */\n  isFullscreen(isFS) {\n    if (isFS !== undefined) {\n      const oldValue = this.isFullscreen_;\n      this.isFullscreen_ = Boolean(isFS);\n\n      // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange\n      // this is the only place where we trigger fullscreenchange events for older browsers\n      // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well\n      if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {\n        /**\n           * @event Player#fullscreenchange\n           * @type {Event}\n           */\n        this.trigger('fullscreenchange');\n      }\n      this.toggleFullscreenClass_();\n      return;\n    }\n    return this.isFullscreen_;\n  }\n\n  /**\n   * Increase the size of the video to full screen\n   * In some browsers, full screen is not supported natively, so it enters\n   * \"full window mode\", where the video fills the browser window.\n   * In browsers and devices that support native full screen, sometimes the\n   * browser's default controls will be shown, and not the Video.js custom skin.\n   * This includes most mobile devices (iOS, Android) and older versions of\n   * Safari.\n   *\n   * @param  {Object} [fullscreenOptions]\n   *         Override the player fullscreen options\n   *\n   * @fires Player#fullscreenchange\n   */\n  requestFullscreen(fullscreenOptions) {\n    if (this.isInPictureInPicture()) {\n      this.exitPictureInPicture();\n    }\n    const self = this;\n    return new Promise((resolve, reject) => {\n      function offHandler() {\n        self.off('fullscreenerror', errorHandler);\n        self.off('fullscreenchange', changeHandler);\n      }\n      function changeHandler() {\n        offHandler();\n        resolve();\n      }\n      function errorHandler(e, err) {\n        offHandler();\n        reject(err);\n      }\n      self.one('fullscreenchange', changeHandler);\n      self.one('fullscreenerror', errorHandler);\n      const promise = self.requestFullscreenHelper_(fullscreenOptions);\n      if (promise) {\n        promise.then(offHandler, offHandler);\n        promise.then(resolve, reject);\n      }\n    });\n  }\n  requestFullscreenHelper_(fullscreenOptions) {\n    let fsOptions;\n\n    // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.\n    // Use defaults or player configured option unless passed directly to this method.\n    if (!this.fsApi_.prefixed) {\n      fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};\n      if (fullscreenOptions !== undefined) {\n        fsOptions = fullscreenOptions;\n      }\n    }\n\n    // This method works as follows:\n    // 1. if a fullscreen api is available, use it\n    //   1. call requestFullscreen with potential options\n    //   2. if we got a promise from above, use it to update isFullscreen()\n    // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.\n    //   This is particularly used for iPhone, older iPads, and non-safari browser on iOS.\n    // 3. otherwise, use \"fullWindow\" mode\n    if (this.fsApi_.requestFullscreen) {\n      const promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);\n\n      // Even on browsers with promise support this may not return a promise\n      if (promise) {\n        promise.then(() => this.isFullscreen(true), () => this.isFullscreen(false));\n      }\n      return promise;\n    } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {\n      // we can't take the video.js controls fullscreen but we can go fullscreen\n      // with native controls\n      this.techCall_('enterFullScreen');\n    } else {\n      // fullscreen isn't supported so we'll just stretch the video element to\n      // fill the viewport\n      this.enterFullWindow();\n    }\n  }\n\n  /**\n   * Return the video to its normal size after having been in full screen mode\n   *\n   * @fires Player#fullscreenchange\n   */\n  exitFullscreen() {\n    const self = this;\n    return new Promise((resolve, reject) => {\n      function offHandler() {\n        self.off('fullscreenerror', errorHandler);\n        self.off('fullscreenchange', changeHandler);\n      }\n      function changeHandler() {\n        offHandler();\n        resolve();\n      }\n      function errorHandler(e, err) {\n        offHandler();\n        reject(err);\n      }\n      self.one('fullscreenchange', changeHandler);\n      self.one('fullscreenerror', errorHandler);\n      const promise = self.exitFullscreenHelper_();\n      if (promise) {\n        promise.then(offHandler, offHandler);\n        // map the promise to our resolve/reject methods\n        promise.then(resolve, reject);\n      }\n    });\n  }\n  exitFullscreenHelper_() {\n    if (this.fsApi_.requestFullscreen) {\n      const promise = document$1[this.fsApi_.exitFullscreen]();\n\n      // Even on browsers with promise support this may not return a promise\n      if (promise) {\n        // we're splitting the promise here, so, we want to catch the\n        // potential error so that this chain doesn't have unhandled errors\n        silencePromise(promise.then(() => this.isFullscreen(false)));\n      }\n      return promise;\n    } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {\n      this.techCall_('exitFullScreen');\n    } else {\n      this.exitFullWindow();\n    }\n  }\n\n  /**\n   * When fullscreen isn't supported we can stretch the\n   * video container to as wide as the browser will let us.\n   *\n   * @fires Player#enterFullWindow\n   */\n  enterFullWindow() {\n    this.isFullscreen(true);\n    this.isFullWindow = true;\n\n    // Storing original doc overflow value to return to when fullscreen is off\n    this.docOrigOverflow = document$1.documentElement.style.overflow;\n\n    // Add listener for esc key to exit fullscreen\n    on(document$1, 'keydown', this.boundFullWindowOnEscKey_);\n\n    // Hide any scroll bars\n    document$1.documentElement.style.overflow = 'hidden';\n\n    // Apply fullscreen styles\n    addClass(document$1.body, 'vjs-full-window');\n\n    /**\n     * @event Player#enterFullWindow\n     * @type {Event}\n     */\n    this.trigger('enterFullWindow');\n  }\n\n  /**\n   * Check for call to either exit full window or\n   * full screen on ESC key\n   *\n   * @param {string} event\n   *        Event to check for key press\n   */\n  fullWindowOnEscKey(event) {\n    if (event.key === 'Escape') {\n      if (this.isFullscreen() === true) {\n        if (!this.isFullWindow) {\n          this.exitFullscreen();\n        } else {\n          this.exitFullWindow();\n        }\n      }\n    }\n  }\n\n  /**\n   * Exit full window\n   *\n   * @fires Player#exitFullWindow\n   */\n  exitFullWindow() {\n    this.isFullscreen(false);\n    this.isFullWindow = false;\n    off(document$1, 'keydown', this.boundFullWindowOnEscKey_);\n\n    // Unhide scroll bars.\n    document$1.documentElement.style.overflow = this.docOrigOverflow;\n\n    // Remove fullscreen styles\n    removeClass(document$1.body, 'vjs-full-window');\n\n    // Resize the box, controller, and poster to original sizes\n    // this.positionAll();\n    /**\n     * @event Player#exitFullWindow\n     * @type {Event}\n     */\n    this.trigger('exitFullWindow');\n  }\n\n  /**\n   * Get or set disable Picture-in-Picture mode.\n   *\n   * @param {boolean} [value]\n   *                  - true will disable Picture-in-Picture mode\n   *                  - false will enable Picture-in-Picture mode\n   */\n  disablePictureInPicture(value) {\n    if (value === undefined) {\n      return this.techGet_('disablePictureInPicture');\n    }\n    this.techCall_('setDisablePictureInPicture', value);\n    this.options_.disablePictureInPicture = value;\n    this.trigger('disablepictureinpicturechanged');\n  }\n\n  /**\n   * Check if the player is in Picture-in-Picture mode or tell the player that it\n   * is or is not in Picture-in-Picture mode.\n   *\n   * @param  {boolean} [isPiP]\n   *         Set the players current Picture-in-Picture state\n   *\n   * @return {boolean|undefined}\n   *         - true if Picture-in-Picture is on and getting\n   *         - false if Picture-in-Picture is off and getting\n   *         - nothing if setting\n   */\n  isInPictureInPicture(isPiP) {\n    if (isPiP !== undefined) {\n      this.isInPictureInPicture_ = !!isPiP;\n      this.togglePictureInPictureClass_();\n      return;\n    }\n    return !!this.isInPictureInPicture_;\n  }\n\n  /**\n   * Create a floating video window always on top of other windows so that users may\n   * continue consuming media while they interact with other content sites, or\n   * applications on their device.\n   *\n   * This can use document picture-in-picture or element picture in picture\n   *\n   * Set `enableDocumentPictureInPicture` to `true` to use docPiP on a supported browser\n   * Else set `disablePictureInPicture` to `false` to disable elPiP on a supported browser\n   *\n   *\n   * @see [Spec]{@link https://w3c.github.io/picture-in-picture/}\n   * @see [Spec]{@link https://wicg.github.io/document-picture-in-picture/}\n   *\n   * @fires Player#enterpictureinpicture\n   *\n   * @return {Promise}\n   *         A promise with a Picture-in-Picture window.\n   */\n  requestPictureInPicture() {\n    if (this.options_.enableDocumentPictureInPicture && window$1.documentPictureInPicture) {\n      const pipContainer = document$1.createElement(this.el().tagName);\n      pipContainer.classList = this.el().classList;\n      pipContainer.classList.add('vjs-pip-container');\n      if (this.posterImage) {\n        pipContainer.appendChild(this.posterImage.el().cloneNode(true));\n      }\n      if (this.titleBar) {\n        pipContainer.appendChild(this.titleBar.el().cloneNode(true));\n      }\n      pipContainer.appendChild(createEl('p', {\n        className: 'vjs-pip-text'\n      }, {}, this.localize('Playing in picture-in-picture')));\n      return window$1.documentPictureInPicture.requestWindow({\n        // The aspect ratio won't be correct, Chrome bug https://crbug.com/1407629\n        width: this.videoWidth(),\n        height: this.videoHeight()\n      }).then(pipWindow => {\n        copyStyleSheetsToWindow(pipWindow);\n        this.el_.parentNode.insertBefore(pipContainer, this.el_);\n        pipWindow.document.body.appendChild(this.el_);\n        pipWindow.document.body.classList.add('vjs-pip-window');\n        this.player_.isInPictureInPicture(true);\n        this.player_.trigger({\n          type: 'enterpictureinpicture',\n          pipWindow\n        });\n\n        // Listen for the PiP closing event to move the video back.\n        pipWindow.addEventListener('pagehide', event => {\n          const pipVideo = event.target.querySelector('.video-js');\n          pipContainer.parentNode.replaceChild(pipVideo, pipContainer);\n          this.player_.isInPictureInPicture(false);\n          this.player_.trigger('leavepictureinpicture');\n        });\n        return pipWindow;\n      });\n    }\n    if ('pictureInPictureEnabled' in document$1 && this.disablePictureInPicture() === false) {\n      /**\n       * This event fires when the player enters picture in picture mode\n       *\n       * @event Player#enterpictureinpicture\n       * @type {Event}\n       */\n      return this.techGet_('requestPictureInPicture');\n    }\n    return Promise.reject('No PiP mode is available');\n  }\n\n  /**\n   * Exit Picture-in-Picture mode.\n   *\n   * @see [Spec]{@link https://wicg.github.io/picture-in-picture}\n   *\n   * @fires Player#leavepictureinpicture\n   *\n   * @return {Promise}\n   *         A promise.\n   */\n  exitPictureInPicture() {\n    if (window$1.documentPictureInPicture && window$1.documentPictureInPicture.window) {\n      // With documentPictureInPicture, Player#leavepictureinpicture is fired in the pagehide handler\n      window$1.documentPictureInPicture.window.close();\n      return Promise.resolve();\n    }\n    if ('pictureInPictureEnabled' in document$1) {\n      /**\n       * This event fires when the player leaves picture in picture mode\n       *\n       * @event Player#leavepictureinpicture\n       * @type {Event}\n       */\n      return document$1.exitPictureInPicture();\n    }\n  }\n\n  /**\n   * Called when this Player has focus and a key gets pressed down, or when\n   * any Component of this player receives a key press that it doesn't handle.\n   * This allows player-wide hotkeys (either as defined below, or optionally\n   * by an external function).\n   *\n   * @param {KeyboardEvent} event\n   *        The `keydown` event that caused this function to be called.\n   *\n   * @listens keydown\n   */\n  handleKeyDown(event) {\n    const {\n      userActions\n    } = this.options_;\n\n    // Bail out if hotkeys are not configured.\n    if (!userActions || !userActions.hotkeys) {\n      return;\n    }\n\n    // Function that determines whether or not to exclude an element from\n    // hotkeys handling.\n    const excludeElement = el => {\n      const tagName = el.tagName.toLowerCase();\n\n      // The first and easiest test is for `contenteditable` elements.\n      if (el.isContentEditable) {\n        return true;\n      }\n\n      // Inputs matching these types will still trigger hotkey handling as\n      // they are not text inputs.\n      const allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];\n      if (tagName === 'input') {\n        return allowedInputTypes.indexOf(el.type) === -1;\n      }\n\n      // The final test is by tag name. These tags will be excluded entirely.\n      const excludedTags = ['textarea'];\n      return excludedTags.indexOf(tagName) !== -1;\n    };\n\n    // Bail out if the user is focused on an interactive form element.\n    if (excludeElement(this.el_.ownerDocument.activeElement)) {\n      return;\n    }\n    if (typeof userActions.hotkeys === 'function') {\n      userActions.hotkeys.call(this, event);\n    } else {\n      this.handleHotkeys(event);\n    }\n  }\n\n  /**\n   * Called when this Player receives a hotkey keydown event.\n   * Supported player-wide hotkeys are:\n   *\n   *   f          - toggle fullscreen\n   *   m          - toggle mute\n   *   k or Space - toggle play/pause\n   *\n   * @param {Event} event\n   *        The `keydown` event that caused this function to be called.\n   */\n  handleHotkeys(event) {\n    const hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};\n\n    // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set\n    const {\n      fullscreenKey = keydownEvent => event.key.toLowerCase() === 'f',\n      muteKey = keydownEvent => event.key.toLowerCase() === 'm',\n      playPauseKey = keydownEvent => event.key.toLowerCase() === 'k' || event.key.toLowerCase() === ' '\n    } = hotkeys;\n    if (fullscreenKey.call(this, event)) {\n      event.preventDefault();\n      event.stopPropagation();\n      const FSToggle = Component$1.getComponent('FullscreenToggle');\n      if (document$1[this.fsApi_.fullscreenEnabled] !== false) {\n        FSToggle.prototype.handleClick.call(this, event);\n      }\n    } else if (muteKey.call(this, event)) {\n      event.preventDefault();\n      event.stopPropagation();\n      const MuteToggle = Component$1.getComponent('MuteToggle');\n      MuteToggle.prototype.handleClick.call(this, event);\n    } else if (playPauseKey.call(this, event)) {\n      event.preventDefault();\n      event.stopPropagation();\n      const PlayToggle = Component$1.getComponent('PlayToggle');\n      PlayToggle.prototype.handleClick.call(this, event);\n    }\n  }\n\n  /**\n   * Check whether the player can play a given mimetype\n   *\n   * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype\n   *\n   * @param {string} type\n   *        The mimetype to check\n   *\n   * @return {string}\n   *         'probably', 'maybe', or '' (empty string)\n   */\n  canPlayType(type) {\n    let can;\n\n    // Loop through each playback technology in the options order\n    for (let i = 0, j = this.options_.techOrder; i < j.length; i++) {\n      const techName = j[i];\n      let tech = Tech.getTech(techName);\n\n      // Support old behavior of techs being registered as components.\n      // Remove once that deprecated behavior is removed.\n      if (!tech) {\n        tech = Component$1.getComponent(techName);\n      }\n\n      // Check if the current tech is defined before continuing\n      if (!tech) {\n        log$1.error(`The \"${techName}\" tech is undefined. Skipped browser support check for that tech.`);\n        continue;\n      }\n\n      // Check if the browser supports this technology\n      if (tech.isSupported()) {\n        can = tech.canPlayType(type);\n        if (can) {\n          return can;\n        }\n      }\n    }\n    return '';\n  }\n\n  /**\n   * Select source based on tech-order or source-order\n   * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,\n   * defaults to tech-order selection\n   *\n   * @param {Array} sources\n   *        The sources for a media asset\n   *\n   * @return {Object|boolean}\n   *         Object of source and tech order or false\n   */\n  selectSource(sources) {\n    // Get only the techs specified in `techOrder` that exist and are supported by the\n    // current platform\n    const techs = this.options_.techOrder.map(techName => {\n      return [techName, Tech.getTech(techName)];\n    }).filter(([techName, tech]) => {\n      // Check if the current tech is defined before continuing\n      if (tech) {\n        // Check if the browser supports this technology\n        return tech.isSupported();\n      }\n      log$1.error(`The \"${techName}\" tech is undefined. Skipped browser support check for that tech.`);\n      return false;\n    });\n\n    // Iterate over each `innerArray` element once per `outerArray` element and execute\n    // `tester` with both. If `tester` returns a non-falsy value, exit early and return\n    // that value.\n    const findFirstPassingTechSourcePair = function (outerArray, innerArray, tester) {\n      let found;\n      outerArray.some(outerChoice => {\n        return innerArray.some(innerChoice => {\n          found = tester(outerChoice, innerChoice);\n          if (found) {\n            return true;\n          }\n        });\n      });\n      return found;\n    };\n    let foundSourceAndTech;\n    const flip = fn => (a, b) => fn(b, a);\n    const finder = ([techName, tech], source) => {\n      if (tech.canPlaySource(source, this.options_[techName.toLowerCase()])) {\n        return {\n          source,\n          tech: techName\n        };\n      }\n    };\n\n    // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources\n    // to select from them based on their priority.\n    if (this.options_.sourceOrder) {\n      // Source-first ordering\n      foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));\n    } else {\n      // Tech-first ordering\n      foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);\n    }\n    return foundSourceAndTech || false;\n  }\n\n  /**\n   * Executes source setting and getting logic\n   *\n   * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]\n   *        A SourceObject, an array of SourceObjects, or a string referencing\n   *        a URL to a media source. It is _highly recommended_ that an object\n   *        or array of objects is used here, so that source selection\n   *        algorithms can take the `type` into account.\n   *\n   *        If not provided, this method acts as a getter.\n   * @param {boolean} [isRetry]\n   *        Indicates whether this is being called internally as a result of a retry\n   *\n   * @return {string|undefined}\n   *         If the `source` argument is missing, returns the current source\n   *         URL. Otherwise, returns nothing/undefined.\n   */\n  handleSrc_(source, isRetry) {\n    // getter usage\n    if (typeof source === 'undefined') {\n      return this.cache_.src || '';\n    }\n\n    // Reset retry behavior for new source\n    if (this.resetRetryOnError_) {\n      this.resetRetryOnError_();\n    }\n\n    // filter out invalid sources and turn our source into\n    // an array of source objects\n    const sources = filterSource(source);\n\n    // if a source was passed in then it is invalid because\n    // it was filtered to a zero length Array. So we have to\n    // show an error\n    if (!sources.length) {\n      this.setTimeout(function () {\n        this.error({\n          code: 4,\n          message: this.options_.notSupportedMessage\n        });\n      }, 0);\n      return;\n    }\n\n    // initial sources\n    this.changingSrc_ = true;\n\n    // Only update the cached source list if we are not retrying a new source after error,\n    // since in that case we want to include the failed source(s) in the cache\n    if (!isRetry) {\n      this.cache_.sources = sources;\n    }\n    this.updateSourceCaches_(sources[0]);\n\n    // middlewareSource is the source after it has been changed by middleware\n    setSource(this, sources[0], (middlewareSource, mws) => {\n      this.middleware_ = mws;\n\n      // since sourceSet is async we have to update the cache again after we select a source since\n      // the source that is selected could be out of order from the cache update above this callback.\n      if (!isRetry) {\n        this.cache_.sources = sources;\n      }\n      this.updateSourceCaches_(middlewareSource);\n      const err = this.src_(middlewareSource);\n      if (err) {\n        if (sources.length > 1) {\n          return this.handleSrc_(sources.slice(1));\n        }\n        this.changingSrc_ = false;\n\n        // We need to wrap this in a timeout to give folks a chance to add error event handlers\n        this.setTimeout(function () {\n          this.error({\n            code: 4,\n            message: this.options_.notSupportedMessage\n          });\n        }, 0);\n\n        // we could not find an appropriate tech, but let's still notify the delegate that this is it\n        // this needs a better comment about why this is needed\n        this.triggerReady();\n        return;\n      }\n      setTech(mws, this.tech_);\n    });\n\n    // Try another available source if this one fails before playback.\n    if (sources.length > 1) {\n      const retry = () => {\n        // Remove the error modal\n        this.error(null);\n        this.handleSrc_(sources.slice(1), true);\n      };\n      const stopListeningForErrors = () => {\n        this.off('error', retry);\n      };\n      this.one('error', retry);\n      this.one('playing', stopListeningForErrors);\n      this.resetRetryOnError_ = () => {\n        this.off('error', retry);\n        this.off('playing', stopListeningForErrors);\n      };\n    }\n  }\n\n  /**\n   * Get or set the video source.\n   *\n   * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]\n   *        A SourceObject, an array of SourceObjects, or a string referencing\n   *        a URL to a media source. It is _highly recommended_ that an object\n   *        or array of objects is used here, so that source selection\n   *        algorithms can take the `type` into account.\n   *\n   *        If not provided, this method acts as a getter.\n   *\n   * @return {string|undefined}\n   *         If the `source` argument is missing, returns the current source\n   *         URL. Otherwise, returns nothing/undefined.\n   */\n  src(source) {\n    return this.handleSrc_(source, false);\n  }\n\n  /**\n   * Set the source object on the tech, returns a boolean that indicates whether\n   * there is a tech that can play the source or not\n   *\n   * @param {Tech~SourceObject} source\n   *        The source object to set on the Tech\n   *\n   * @return {boolean}\n   *         - True if there is no Tech to playback this source\n   *         - False otherwise\n   *\n   * @private\n   */\n  src_(source) {\n    const sourceTech = this.selectSource([source]);\n    if (!sourceTech) {\n      return true;\n    }\n    if (!titleCaseEquals(sourceTech.tech, this.techName_)) {\n      this.changingSrc_ = true;\n      // load this technology with the chosen source\n      this.loadTech_(sourceTech.tech, sourceTech.source);\n      this.tech_.ready(() => {\n        this.changingSrc_ = false;\n      });\n      return false;\n    }\n\n    // wait until the tech is ready to set the source\n    // and set it synchronously if possible (#2326)\n    this.ready(function () {\n      // The setSource tech method was added with source handlers\n      // so older techs won't support it\n      // We need to check the direct prototype for the case where subclasses\n      // of the tech do not support source handlers\n      if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {\n        this.techCall_('setSource', source);\n      } else {\n        this.techCall_('src', source.src);\n      }\n      this.changingSrc_ = false;\n    }, true);\n    return false;\n  }\n\n  /**\n   * Add a <source> element to the <video> element.\n   *\n   * @param {string} srcUrl\n   *        The URL of the video source.\n   *\n   * @param {string} [mimeType]\n   *        The MIME type of the video source. Optional but recommended.\n   *\n   * @return {boolean}\n   *         Returns true if the source element was successfully added, false otherwise.\n   */\n  addSourceElement(srcUrl, mimeType) {\n    if (!this.tech_) {\n      return false;\n    }\n    return this.tech_.addSourceElement(srcUrl, mimeType);\n  }\n\n  /**\n   * Remove a <source> element from the <video> element by its URL.\n   *\n   * @param {string} srcUrl\n   *        The URL of the source to remove.\n   *\n   * @return {boolean}\n   *         Returns true if the source element was successfully removed, false otherwise.\n   */\n  removeSourceElement(srcUrl) {\n    if (!this.tech_) {\n      return false;\n    }\n    return this.tech_.removeSourceElement(srcUrl);\n  }\n\n  /**\n   * Begin loading the src data.\n   */\n  load() {\n    // Workaround to use the load method with the VHS.\n    // Does not cover the case when the load method is called directly from the mediaElement.\n    if (this.tech_ && this.tech_.vhs) {\n      this.src(this.currentSource());\n      return;\n    }\n    this.techCall_('load');\n  }\n\n  /**\n   * Reset the player. Loads the first tech in the techOrder,\n   * removes all the text tracks in the existing `tech`,\n   * and calls `reset` on the `tech`.\n   */\n  reset() {\n    if (this.paused()) {\n      this.doReset_();\n    } else {\n      const playPromise = this.play();\n      silencePromise(playPromise.then(() => this.doReset_()));\n    }\n  }\n  doReset_() {\n    if (this.tech_) {\n      this.tech_.clearTracks('text');\n    }\n    this.removeClass('vjs-playing');\n    this.addClass('vjs-paused');\n    this.resetCache_();\n    this.poster('');\n    this.loadTech_(this.options_.techOrder[0], null);\n    this.techCall_('reset');\n    this.resetControlBarUI_();\n    this.error(null);\n    if (this.titleBar) {\n      this.titleBar.update({\n        title: undefined,\n        description: undefined\n      });\n    }\n    if (isEvented(this)) {\n      this.trigger('playerreset');\n    }\n  }\n\n  /**\n   * Reset Control Bar's UI by calling sub-methods that reset\n   * all of Control Bar's components\n   */\n  resetControlBarUI_() {\n    this.resetProgressBar_();\n    this.resetPlaybackRate_();\n    this.resetVolumeBar_();\n  }\n\n  /**\n   * Reset tech's progress so progress bar is reset in the UI\n   */\n  resetProgressBar_() {\n    this.currentTime(0);\n    const {\n      currentTimeDisplay,\n      durationDisplay,\n      progressControl,\n      remainingTimeDisplay\n    } = this.controlBar || {};\n    const {\n      seekBar\n    } = progressControl || {};\n    if (currentTimeDisplay) {\n      currentTimeDisplay.updateContent();\n    }\n    if (durationDisplay) {\n      durationDisplay.updateContent();\n    }\n    if (remainingTimeDisplay) {\n      remainingTimeDisplay.updateContent();\n    }\n    if (seekBar) {\n      seekBar.update();\n      if (seekBar.loadProgressBar) {\n        seekBar.loadProgressBar.update();\n      }\n    }\n  }\n\n  /**\n   * Reset Playback ratio\n   */\n  resetPlaybackRate_() {\n    this.playbackRate(this.defaultPlaybackRate());\n    this.handleTechRateChange_();\n  }\n\n  /**\n   * Reset Volume bar\n   */\n  resetVolumeBar_() {\n    this.volume(1.0);\n    this.trigger('volumechange');\n  }\n\n  /**\n   * Returns all of the current source objects.\n   *\n   * @return {Tech~SourceObject[]}\n   *         The current source objects\n   */\n  currentSources() {\n    const source = this.currentSource();\n    const sources = [];\n\n    // assume `{}` or `{ src }`\n    if (Object.keys(source).length !== 0) {\n      sources.push(source);\n    }\n    return this.cache_.sources || sources;\n  }\n\n  /**\n   * Returns the current source object.\n   *\n   * @return {Tech~SourceObject}\n   *         The current source object\n   */\n  currentSource() {\n    return this.cache_.source || {};\n  }\n\n  /**\n   * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4\n   * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.\n   *\n   * @return {string}\n   *         The current source\n   */\n  currentSrc() {\n    return this.currentSource() && this.currentSource().src || '';\n  }\n\n  /**\n   * Get the current source type e.g. video/mp4\n   * This can allow you rebuild the current source object so that you could load the same\n   * source and tech later\n   *\n   * @return {string}\n   *         The source MIME type\n   */\n  currentType() {\n    return this.currentSource() && this.currentSource().type || '';\n  }\n\n  /**\n   * Get or set the preload attribute\n   *\n   * @param {'none'|'auto'|'metadata'} [value]\n   *        Preload mode to pass to tech\n   *\n   * @return {string|undefined}\n   *         - The preload attribute value when getting\n   *         - Nothing when setting\n   */\n  preload(value) {\n    if (value !== undefined) {\n      this.techCall_('setPreload', value);\n      this.options_.preload = value;\n      return;\n    }\n    return this.techGet_('preload');\n  }\n\n  /**\n   * Get or set the autoplay option. When this is a boolean it will\n   * modify the attribute on the tech. When this is a string the attribute on\n   * the tech will be removed and `Player` will handle autoplay on loadstarts.\n   *\n   * @param {boolean|'play'|'muted'|'any'} [value]\n   *        - true: autoplay using the browser behavior\n   *        - false: do not autoplay\n   *        - 'play': call play() on every loadstart\n   *        - 'muted': call muted() then play() on every loadstart\n   *        - 'any': call play() on every loadstart. if that fails call muted() then play().\n   *        - *: values other than those listed here will be set `autoplay` to true\n   *\n   * @return {boolean|string|undefined}\n   *         - The current value of autoplay when getting\n   *         - Nothing when setting\n   */\n  autoplay(value) {\n    // getter usage\n    if (value === undefined) {\n      return this.options_.autoplay || false;\n    }\n    let techAutoplay;\n\n    // if the value is a valid string set it to that, or normalize `true` to 'play', if need be\n    if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {\n      this.options_.autoplay = value;\n      this.manualAutoplay_(typeof value === 'string' ? value : 'play');\n      techAutoplay = false;\n\n      // any falsy value sets autoplay to false in the browser,\n      // lets do the same\n    } else if (!value) {\n      this.options_.autoplay = false;\n\n      // any other value (ie truthy) sets autoplay to true\n    } else {\n      this.options_.autoplay = true;\n    }\n    techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay;\n\n    // if we don't have a tech then we do not queue up\n    // a setAutoplay call on tech ready. We do this because the\n    // autoplay option will be passed in the constructor and we\n    // do not need to set it twice\n    if (this.tech_) {\n      this.techCall_('setAutoplay', techAutoplay);\n    }\n  }\n\n  /**\n   * Set or unset the playsinline attribute.\n   * Playsinline tells the browser that non-fullscreen playback is preferred.\n   *\n   * @param {boolean} [value]\n   *        - true means that we should try to play inline by default\n   *        - false means that we should use the browser's default playback mode,\n   *          which in most cases is inline. iOS Safari is a notable exception\n   *          and plays fullscreen by default.\n   *\n   * @return {string|undefined}\n   *         - the current value of playsinline\n   *         - Nothing when setting\n   *\n   * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}\n   */\n  playsinline(value) {\n    if (value !== undefined) {\n      this.techCall_('setPlaysinline', value);\n      this.options_.playsinline = value;\n    }\n    return this.techGet_('playsinline');\n  }\n\n  /**\n   * Get or set the loop attribute on the video element.\n   *\n   * @param {boolean} [value]\n   *        - true means that we should loop the video\n   *        - false means that we should not loop the video\n   *\n   * @return {boolean|undefined}\n   *         - The current value of loop when getting\n   *         - Nothing when setting\n   */\n  loop(value) {\n    if (value !== undefined) {\n      this.techCall_('setLoop', value);\n      this.options_.loop = value;\n      return;\n    }\n    return this.techGet_('loop');\n  }\n\n  /**\n   * Get or set the poster image source url\n   *\n   * @fires Player#posterchange\n   *\n   * @param {string} [src]\n   *        Poster image source URL\n   *\n   * @return {string|undefined}\n   *         - The current value of poster when getting\n   *         - Nothing when setting\n   */\n  poster(src) {\n    if (src === undefined) {\n      return this.poster_;\n    }\n\n    // The correct way to remove a poster is to set as an empty string\n    // other falsey values will throw errors\n    if (!src) {\n      src = '';\n    }\n    if (src === this.poster_) {\n      return;\n    }\n\n    // update the internal poster variable\n    this.poster_ = src;\n\n    // update the tech's poster\n    this.techCall_('setPoster', src);\n    this.isPosterFromTech_ = false;\n\n    // alert components that the poster has been set\n    /**\n     * This event fires when the poster image is changed on the player.\n     *\n     * @event Player#posterchange\n     * @type {Event}\n     */\n    this.trigger('posterchange');\n  }\n\n  /**\n   * Some techs (e.g. YouTube) can provide a poster source in an\n   * asynchronous way. We want the poster component to use this\n   * poster source so that it covers up the tech's controls.\n   * (YouTube's play button). However we only want to use this\n   * source if the player user hasn't set a poster through\n   * the normal APIs.\n   *\n   * @fires Player#posterchange\n   * @listens Tech#posterchange\n   * @private\n   */\n  handleTechPosterChange_() {\n    if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {\n      const newPoster = this.tech_.poster() || '';\n      if (newPoster !== this.poster_) {\n        this.poster_ = newPoster;\n        this.isPosterFromTech_ = true;\n\n        // Let components know the poster has changed\n        this.trigger('posterchange');\n      }\n    }\n  }\n\n  /**\n   * Get or set whether or not the controls are showing.\n   *\n   * @fires Player#controlsenabled\n   *\n   * @param {boolean} [bool]\n   *        - true to turn controls on\n   *        - false to turn controls off\n   *\n   * @return {boolean|undefined}\n   *         - The current value of controls when getting\n   *         - Nothing when setting\n   */\n  controls(bool) {\n    if (bool === undefined) {\n      return !!this.controls_;\n    }\n    bool = !!bool;\n\n    // Don't trigger a change event unless it actually changed\n    if (this.controls_ === bool) {\n      return;\n    }\n    this.controls_ = bool;\n    if (this.usingNativeControls()) {\n      this.techCall_('setControls', bool);\n    }\n    if (this.controls_) {\n      this.removeClass('vjs-controls-disabled');\n      this.addClass('vjs-controls-enabled');\n      /**\n       * @event Player#controlsenabled\n       * @type {Event}\n       */\n      this.trigger('controlsenabled');\n      if (!this.usingNativeControls()) {\n        this.addTechControlsListeners_();\n      }\n    } else {\n      this.removeClass('vjs-controls-enabled');\n      this.addClass('vjs-controls-disabled');\n      /**\n       * @event Player#controlsdisabled\n       * @type {Event}\n       */\n      this.trigger('controlsdisabled');\n      if (!this.usingNativeControls()) {\n        this.removeTechControlsListeners_();\n      }\n    }\n  }\n\n  /**\n   * Toggle native controls on/off. Native controls are the controls built into\n   * devices (e.g. default iPhone controls) or other techs\n   * (e.g. Vimeo Controls)\n   * **This should only be set by the current tech, because only the tech knows\n   * if it can support native controls**\n   *\n   * @fires Player#usingnativecontrols\n   * @fires Player#usingcustomcontrols\n   *\n   * @param {boolean} [bool]\n   *        - true to turn native controls on\n   *        - false to turn native controls off\n   *\n   * @return {boolean|undefined}\n   *         - The current value of native controls when getting\n   *         - Nothing when setting\n   */\n  usingNativeControls(bool) {\n    if (bool === undefined) {\n      return !!this.usingNativeControls_;\n    }\n    bool = !!bool;\n\n    // Don't trigger a change event unless it actually changed\n    if (this.usingNativeControls_ === bool) {\n      return;\n    }\n    this.usingNativeControls_ = bool;\n    if (this.usingNativeControls_) {\n      this.addClass('vjs-using-native-controls');\n\n      /**\n       * player is using the native device controls\n       *\n       * @event Player#usingnativecontrols\n       * @type {Event}\n       */\n      this.trigger('usingnativecontrols');\n    } else {\n      this.removeClass('vjs-using-native-controls');\n\n      /**\n       * player is using the custom HTML controls\n       *\n       * @event Player#usingcustomcontrols\n       * @type {Event}\n       */\n      this.trigger('usingcustomcontrols');\n    }\n  }\n\n  /**\n   * Set or get the current MediaError\n   *\n   * @fires Player#error\n   *\n   * @param  {MediaError|string|number} [err]\n   *         A MediaError or a string/number to be turned\n   *         into a MediaError\n   *\n   * @return {MediaError|null|undefined}\n   *         - The current MediaError when getting (or null)\n   *         - Nothing when setting\n   */\n  error(err) {\n    if (err === undefined) {\n      return this.error_ || null;\n    }\n\n    // allow hooks to modify error object\n    hooks('beforeerror').forEach(hookFunction => {\n      const newErr = hookFunction(this, err);\n      if (!(isObject(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {\n        this.log.error('please return a value that MediaError expects in beforeerror hooks');\n        return;\n      }\n      err = newErr;\n    });\n\n    // Suppress the first error message for no compatible source until\n    // user interaction\n    if (this.options_.suppressNotSupportedError && err && err.code === 4) {\n      const triggerSuppressedError = function () {\n        this.error(err);\n      };\n      this.options_.suppressNotSupportedError = false;\n      this.any(['click', 'touchstart'], triggerSuppressedError);\n      this.one('loadstart', function () {\n        this.off(['click', 'touchstart'], triggerSuppressedError);\n      });\n      return;\n    }\n\n    // restoring to default\n    if (err === null) {\n      this.error_ = null;\n      this.removeClass('vjs-error');\n      if (this.errorDisplay) {\n        this.errorDisplay.close();\n      }\n      return;\n    }\n    this.error_ = new MediaError(err);\n\n    // add the vjs-error classname to the player\n    this.addClass('vjs-error');\n\n    // log the name of the error type and any message\n    // IE11 logs \"[object object]\" and required you to expand message to see error object\n    log$1.error(`(CODE:${this.error_.code} ${MediaError.errorTypes[this.error_.code]})`, this.error_.message, this.error_);\n\n    /**\n     * @event Player#error\n     * @type {Event}\n     */\n    this.trigger('error');\n\n    // notify hooks of the per player error\n    hooks('error').forEach(hookFunction => hookFunction(this, this.error_));\n    return;\n  }\n\n  /**\n   * Report user activity\n   *\n   * @param {Object} event\n   *        Event object\n   */\n  reportUserActivity(event) {\n    this.userActivity_ = true;\n  }\n\n  /**\n   * Get/set if user is active\n   *\n   * @fires Player#useractive\n   * @fires Player#userinactive\n   *\n   * @param {boolean} [bool]\n   *        - true if the user is active\n   *        - false if the user is inactive\n   *\n   * @return {boolean|undefined}\n   *         - The current value of userActive when getting\n   *         - Nothing when setting\n   */\n  userActive(bool) {\n    if (bool === undefined) {\n      return this.userActive_;\n    }\n    bool = !!bool;\n    if (bool === this.userActive_) {\n      return;\n    }\n    this.userActive_ = bool;\n    if (this.userActive_) {\n      this.userActivity_ = true;\n      this.removeClass('vjs-user-inactive');\n      this.addClass('vjs-user-active');\n      /**\n       * @event Player#useractive\n       * @type {Event}\n       */\n      this.trigger('useractive');\n      return;\n    }\n\n    // Chrome/Safari/IE have bugs where when you change the cursor it can\n    // trigger a mousemove event. This causes an issue when you're hiding\n    // the cursor when the user is inactive, and a mousemove signals user\n    // activity. Making it impossible to go into inactive mode. Specifically\n    // this happens in fullscreen when we really need to hide the cursor.\n    //\n    // When this gets resolved in ALL browsers it can be removed\n    // https://code.google.com/p/chromium/issues/detail?id=103041\n    if (this.tech_) {\n      this.tech_.one('mousemove', function (e) {\n        e.stopPropagation();\n        e.preventDefault();\n      });\n    }\n    this.userActivity_ = false;\n    this.removeClass('vjs-user-active');\n    this.addClass('vjs-user-inactive');\n    /**\n     * @event Player#userinactive\n     * @type {Event}\n     */\n    this.trigger('userinactive');\n  }\n\n  /**\n   * Listen for user activity based on timeout value\n   *\n   * @private\n   */\n  listenForUserActivity_() {\n    let mouseInProgress;\n    let lastMoveX;\n    let lastMoveY;\n    const handleActivity = bind_(this, this.reportUserActivity);\n    const handleMouseMove = function (e) {\n      // #1068 - Prevent mousemove spamming\n      // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970\n      if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {\n        lastMoveX = e.screenX;\n        lastMoveY = e.screenY;\n        handleActivity();\n      }\n    };\n    const handleMouseDown = function () {\n      handleActivity();\n      // For as long as the they are touching the device or have their mouse down,\n      // we consider them active even if they're not moving their finger or mouse.\n      // So we want to continue to update that they are active\n      this.clearInterval(mouseInProgress);\n      // Setting userActivity=true now and setting the interval to the same time\n      // as the activityCheck interval (250) should ensure we never miss the\n      // next activityCheck\n      mouseInProgress = this.setInterval(handleActivity, 250);\n    };\n    const handleMouseUpAndMouseLeave = function (event) {\n      handleActivity();\n      // Stop the interval that maintains activity if the mouse/touch is down\n      this.clearInterval(mouseInProgress);\n    };\n\n    // Any mouse movement will be considered user activity\n    this.on('mousedown', handleMouseDown);\n    this.on('mousemove', handleMouseMove);\n    this.on('mouseup', handleMouseUpAndMouseLeave);\n    this.on('mouseleave', handleMouseUpAndMouseLeave);\n    const controlBar = this.getChild('controlBar');\n\n    // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)\n    // controlBar would no longer be hidden by default timeout.\n    if (controlBar && !IS_IOS && !IS_ANDROID) {\n      controlBar.on('mouseenter', function (event) {\n        if (this.player().options_.inactivityTimeout !== 0) {\n          this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;\n        }\n        this.player().options_.inactivityTimeout = 0;\n      });\n      controlBar.on('mouseleave', function (event) {\n        this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;\n      });\n    }\n\n    // Listen for keyboard navigation\n    // Shouldn't need to use inProgress interval because of key repeat\n    this.on('keydown', handleActivity);\n    this.on('keyup', handleActivity);\n\n    // Run an interval every 250 milliseconds instead of stuffing everything into\n    // the mousemove/touchmove function itself, to prevent performance degradation.\n    // `this.reportUserActivity` simply sets this.userActivity_ to true, which\n    // then gets picked up by this loop\n    // http://ejohn.org/blog/learning-from-twitter/\n    let inactivityTimeout;\n\n    /** @this Player */\n    const activityCheck = function () {\n      // Check to see if mouse/touch activity has happened\n      if (!this.userActivity_) {\n        return;\n      }\n\n      // Reset the activity tracker\n      this.userActivity_ = false;\n\n      // If the user state was inactive, set the state to active\n      this.userActive(true);\n\n      // Clear any existing inactivity timeout to start the timer over\n      this.clearTimeout(inactivityTimeout);\n      const timeout = this.options_.inactivityTimeout;\n      if (timeout <= 0) {\n        return;\n      }\n\n      // In <timeout> milliseconds, if no more activity has occurred the\n      // user will be considered inactive\n      inactivityTimeout = this.setTimeout(function () {\n        // Protect against the case where the inactivityTimeout can trigger just\n        // before the next user activity is picked up by the activity check loop\n        // causing a flicker\n        if (!this.userActivity_) {\n          this.userActive(false);\n        }\n      }, timeout);\n    };\n    this.setInterval(activityCheck, 250);\n  }\n\n  /**\n   * Gets or sets the current playback rate. A playback rate of\n   * 1.0 represents normal speed and 0.5 would indicate half-speed\n   * playback, for instance.\n   *\n   * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate\n   *\n   * @param {number} [rate]\n   *       New playback rate to set.\n   *\n   * @return {number|undefined}\n   *         - The current playback rate when getting or 1.0\n   *         - Nothing when setting\n   */\n  playbackRate(rate) {\n    if (rate !== undefined) {\n      // NOTE: this.cache_.lastPlaybackRate is set from the tech handler\n      // that is registered above\n      this.techCall_('setPlaybackRate', rate);\n      return;\n    }\n    if (this.tech_ && this.tech_.featuresPlaybackRate) {\n      return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');\n    }\n    return 1.0;\n  }\n\n  /**\n   * Gets or sets the current default playback rate. A default playback rate of\n   * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.\n   * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not\n   * not the current playbackRate.\n   *\n   * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate\n   *\n   * @param {number} [rate]\n   *       New default playback rate to set.\n   *\n   * @return {number|undefined}\n   *         - The default playback rate when getting or 1.0\n   *         - Nothing when setting\n   */\n  defaultPlaybackRate(rate) {\n    if (rate !== undefined) {\n      return this.techCall_('setDefaultPlaybackRate', rate);\n    }\n    if (this.tech_ && this.tech_.featuresPlaybackRate) {\n      return this.techGet_('defaultPlaybackRate');\n    }\n    return 1.0;\n  }\n\n  /**\n   * Gets or sets the audio flag\n   *\n   * @param {boolean} [bool]\n   *        - true signals that this is an audio player\n   *        - false signals that this is not an audio player\n   *\n   * @return {boolean|undefined}\n   *         - The current value of isAudio when getting\n   *         - Nothing when setting\n   */\n  isAudio(bool) {\n    if (bool !== undefined) {\n      this.isAudio_ = !!bool;\n      return;\n    }\n    return !!this.isAudio_;\n  }\n  updatePlayerHeightOnAudioOnlyMode_() {\n    const controlBar = this.getChild('ControlBar');\n    if (!controlBar || this.audioOnlyCache_.controlBarHeight === controlBar.currentHeight()) {\n      return;\n    }\n    this.audioOnlyCache_.controlBarHeight = controlBar.currentHeight();\n    this.height(this.audioOnlyCache_.controlBarHeight);\n  }\n  enableAudioOnlyUI_() {\n    // Update styling immediately to show the control bar so we can get its height\n    this.addClass('vjs-audio-only-mode');\n    const playerChildren = this.children();\n    const controlBar = this.getChild('ControlBar');\n    const controlBarHeight = controlBar && controlBar.currentHeight();\n\n    // Hide all player components except the control bar. Control bar components\n    // needed only for video are hidden with CSS\n    playerChildren.forEach(child => {\n      if (child === controlBar) {\n        return;\n      }\n      if (child.el_ && !child.hasClass('vjs-hidden')) {\n        child.hide();\n        this.audioOnlyCache_.hiddenChildren.push(child);\n      }\n    });\n    this.audioOnlyCache_.playerHeight = this.currentHeight();\n    this.audioOnlyCache_.controlBarHeight = controlBarHeight;\n    this.on('playerresize', this.boundUpdatePlayerHeightOnAudioOnlyMode_);\n\n    // Set the player height the same as the control bar\n    this.height(controlBarHeight);\n    this.trigger('audioonlymodechange');\n  }\n  disableAudioOnlyUI_() {\n    this.removeClass('vjs-audio-only-mode');\n    this.off('playerresize', this.boundUpdatePlayerHeightOnAudioOnlyMode_);\n\n    // Show player components that were previously hidden\n    this.audioOnlyCache_.hiddenChildren.forEach(child => child.show());\n\n    // Reset player height\n    this.height(this.audioOnlyCache_.playerHeight);\n    this.trigger('audioonlymodechange');\n  }\n\n  /**\n   * Get the current audioOnlyMode state or set audioOnlyMode to true or false.\n   *\n   * Setting this to `true` will hide all player components except the control bar,\n   * as well as control bar components needed only for video.\n   *\n   * @param {boolean} [value]\n   *         The value to set audioOnlyMode to.\n   *\n   * @return {Promise|boolean}\n   *        A Promise is returned when setting the state, and a boolean when getting\n   *        the present state\n   */\n  audioOnlyMode(value) {\n    if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {\n      return this.audioOnlyMode_;\n    }\n    this.audioOnlyMode_ = value;\n\n    // Enable Audio Only Mode\n    if (value) {\n      const exitPromises = [];\n\n      // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.\n      if (this.isInPictureInPicture()) {\n        exitPromises.push(this.exitPictureInPicture());\n      }\n      if (this.isFullscreen()) {\n        exitPromises.push(this.exitFullscreen());\n      }\n      if (this.audioPosterMode()) {\n        exitPromises.push(this.audioPosterMode(false));\n      }\n      return Promise.all(exitPromises).then(() => this.enableAudioOnlyUI_());\n    }\n\n    // Disable Audio Only Mode\n    return Promise.resolve().then(() => this.disableAudioOnlyUI_());\n  }\n  enablePosterModeUI_() {\n    // Hide the video element and show the poster image to enable posterModeUI\n    const tech = this.tech_ && this.tech_;\n    tech.hide();\n    this.addClass('vjs-audio-poster-mode');\n    this.trigger('audiopostermodechange');\n  }\n  disablePosterModeUI_() {\n    // Show the video element and hide the poster image to disable posterModeUI\n    const tech = this.tech_ && this.tech_;\n    tech.show();\n    this.removeClass('vjs-audio-poster-mode');\n    this.trigger('audiopostermodechange');\n  }\n\n  /**\n   * Get the current audioPosterMode state or set audioPosterMode to true or false\n   *\n   * @param {boolean} [value]\n   *         The value to set audioPosterMode to.\n   *\n   * @return {Promise|boolean}\n   *         A Promise is returned when setting the state, and a boolean when getting\n   *        the present state\n   */\n  audioPosterMode(value) {\n    if (typeof value !== 'boolean' || value === this.audioPosterMode_) {\n      return this.audioPosterMode_;\n    }\n    this.audioPosterMode_ = value;\n    if (value) {\n      if (this.audioOnlyMode()) {\n        const audioOnlyModePromise = this.audioOnlyMode(false);\n        return audioOnlyModePromise.then(() => {\n          // enable audio poster mode after audio only mode is disabled\n          this.enablePosterModeUI_();\n        });\n      }\n      return Promise.resolve().then(() => {\n        // enable audio poster mode\n        this.enablePosterModeUI_();\n      });\n    }\n    return Promise.resolve().then(() => {\n      // disable audio poster mode\n      this.disablePosterModeUI_();\n    });\n  }\n\n  /**\n   * A helper method for adding a {@link TextTrack} to our\n   * {@link TextTrackList}.\n   *\n   * In addition to the W3C settings we allow adding additional info through options.\n   *\n   * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack\n   *\n   * @param {string} [kind]\n   *        the kind of TextTrack you are adding\n   *\n   * @param {string} [label]\n   *        the label to give the TextTrack label\n   *\n   * @param {string} [language]\n   *        the language to set on the TextTrack\n   *\n   * @return {TextTrack|undefined}\n   *         the TextTrack that was added or undefined\n   *         if there is no tech\n   */\n  addTextTrack(kind, label, language) {\n    if (this.tech_) {\n      return this.tech_.addTextTrack(kind, label, language);\n    }\n  }\n\n  /**\n   * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.\n   *\n   * @param {Object} options\n   *        Options to pass to {@link HTMLTrackElement} during creation. See\n   *        {@link HTMLTrackElement} for object properties that you should use.\n   *\n   * @param {boolean} [manualCleanup=false] if set to true, the TextTrack will not be removed\n   *                                        from the TextTrackList and HtmlTrackElementList\n   *                                        after a source change\n   *\n   * @return {HtmlTrackElement}\n   *         the HTMLTrackElement that was created and added\n   *         to the HtmlTrackElementList and the remote\n   *         TextTrackList\n   *\n   */\n  addRemoteTextTrack(options, manualCleanup) {\n    if (this.tech_) {\n      return this.tech_.addRemoteTextTrack(options, manualCleanup);\n    }\n  }\n\n  /**\n   * Remove a remote {@link TextTrack} from the respective\n   * {@link TextTrackList} and {@link HtmlTrackElementList}.\n   *\n   * @param {Object} track\n   *        Remote {@link TextTrack} to remove\n   *\n   * @return {undefined}\n   *         does not return anything\n   */\n  removeRemoteTextTrack(obj = {}) {\n    let {\n      track\n    } = obj;\n    if (!track) {\n      track = obj;\n    }\n\n    // destructure the input into an object with a track argument, defaulting to arguments[0]\n    // default the whole argument to an empty object if nothing was passed in\n\n    if (this.tech_) {\n      return this.tech_.removeRemoteTextTrack(track);\n    }\n  }\n\n  /**\n   * Gets available media playback quality metrics as specified by the W3C's Media\n   * Playback Quality API.\n   *\n   * @see [Spec]{@link https://wicg.github.io/media-playback-quality}\n   *\n   * @return {Object|undefined}\n   *         An object with supported media playback quality metrics or undefined if there\n   *         is no tech or the tech does not support it.\n   */\n  getVideoPlaybackQuality() {\n    return this.techGet_('getVideoPlaybackQuality');\n  }\n\n  /**\n   * Get video width\n   *\n   * @return {number}\n   *         current video width\n   */\n  videoWidth() {\n    return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;\n  }\n\n  /**\n   * Get video height\n   *\n   * @return {number}\n   *         current video height\n   */\n  videoHeight() {\n    return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;\n  }\n\n  /**\n   * Set or get the player's language code.\n   *\n   * Changing the language will trigger\n   * [languagechange]{@link Player#event:languagechange}\n   * which Components can use to update control text.\n   * ClickableComponent will update its control text by default on\n   * [languagechange]{@link Player#event:languagechange}.\n   *\n   * @fires Player#languagechange\n   *\n   * @param {string} [code]\n   *        the language code to set the player to\n   *\n   * @return {string|undefined}\n   *         - The current language code when getting\n   *         - Nothing when setting\n   */\n  language(code) {\n    if (code === undefined) {\n      return this.language_;\n    }\n    if (this.language_ !== String(code).toLowerCase()) {\n      this.language_ = String(code).toLowerCase();\n\n      // during first init, it's possible some things won't be evented\n      if (isEvented(this)) {\n        /**\n        * fires when the player language change\n        *\n        * @event Player#languagechange\n        * @type {Event}\n        */\n        this.trigger('languagechange');\n      }\n    }\n  }\n\n  /**\n   * Get the player's language dictionary\n   * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time\n   * Languages specified directly in the player options have precedence\n   *\n   * @return {Array}\n   *         An array of of supported languages\n   */\n  languages() {\n    return merge$1(Player.prototype.options_.languages, this.languages_);\n  }\n\n  /**\n   * returns a JavaScript object representing the current track\n   * information. **DOES not return it as JSON**\n   *\n   * @return {Object}\n   *         Object representing the current of track info\n   */\n  toJSON() {\n    const options = merge$1(this.options_);\n    const tracks = options.tracks;\n    options.tracks = [];\n    for (let i = 0; i < tracks.length; i++) {\n      let track = tracks[i];\n\n      // deep merge tracks and null out player so no circular references\n      track = merge$1(track);\n      track.player = undefined;\n      options.tracks[i] = track;\n    }\n    return options;\n  }\n\n  /**\n   * Creates a simple modal dialog (an instance of the {@link ModalDialog}\n   * component) that immediately overlays the player with arbitrary\n   * content and removes itself when closed.\n   *\n   * @param {string|Function|Element|Array|null} content\n   *        Same as {@link ModalDialog#content}'s param of the same name.\n   *        The most straight-forward usage is to provide a string or DOM\n   *        element.\n   *\n   * @param {Object} [options]\n   *        Extra options which will be passed on to the {@link ModalDialog}.\n   *\n   * @return {ModalDialog}\n   *         the {@link ModalDialog} that was created\n   */\n  createModal(content, options) {\n    options = options || {};\n    options.content = content || '';\n    const modal = new ModalDialog(this, options);\n    this.addChild(modal);\n    modal.on('dispose', () => {\n      this.removeChild(modal);\n    });\n    modal.open();\n    return modal;\n  }\n\n  /**\n   * Change breakpoint classes when the player resizes.\n   *\n   * @private\n   */\n  updateCurrentBreakpoint_() {\n    if (!this.responsive()) {\n      return;\n    }\n    const currentBreakpoint = this.currentBreakpoint();\n    const currentWidth = this.currentWidth();\n    for (let i = 0; i < BREAKPOINT_ORDER.length; i++) {\n      const candidateBreakpoint = BREAKPOINT_ORDER[i];\n      const maxWidth = this.breakpoints_[candidateBreakpoint];\n      if (currentWidth <= maxWidth) {\n        // The current breakpoint did not change, nothing to do.\n        if (currentBreakpoint === candidateBreakpoint) {\n          return;\n        }\n\n        // Only remove a class if there is a current breakpoint.\n        if (currentBreakpoint) {\n          this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);\n        }\n        this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);\n        this.breakpoint_ = candidateBreakpoint;\n        break;\n      }\n    }\n  }\n\n  /**\n   * Removes the current breakpoint.\n   *\n   * @private\n   */\n  removeCurrentBreakpoint_() {\n    const className = this.currentBreakpointClass();\n    this.breakpoint_ = '';\n    if (className) {\n      this.removeClass(className);\n    }\n  }\n\n  /**\n   * Get or set breakpoints on the player.\n   *\n   * Calling this method with an object or `true` will remove any previous\n   * custom breakpoints and start from the defaults again.\n   *\n   * @param  {Object|boolean} [breakpoints]\n   *         If an object is given, it can be used to provide custom\n   *         breakpoints. If `true` is given, will set default breakpoints.\n   *         If this argument is not given, will simply return the current\n   *         breakpoints.\n   *\n   * @param  {number} [breakpoints.tiny]\n   *         The maximum width for the \"vjs-layout-tiny\" class.\n   *\n   * @param  {number} [breakpoints.xsmall]\n   *         The maximum width for the \"vjs-layout-x-small\" class.\n   *\n   * @param  {number} [breakpoints.small]\n   *         The maximum width for the \"vjs-layout-small\" class.\n   *\n   * @param  {number} [breakpoints.medium]\n   *         The maximum width for the \"vjs-layout-medium\" class.\n   *\n   * @param  {number} [breakpoints.large]\n   *         The maximum width for the \"vjs-layout-large\" class.\n   *\n   * @param  {number} [breakpoints.xlarge]\n   *         The maximum width for the \"vjs-layout-x-large\" class.\n   *\n   * @param  {number} [breakpoints.huge]\n   *         The maximum width for the \"vjs-layout-huge\" class.\n   *\n   * @return {Object}\n   *         An object mapping breakpoint names to maximum width values.\n   */\n  breakpoints(breakpoints) {\n    // Used as a getter.\n    if (breakpoints === undefined) {\n      return Object.assign(this.breakpoints_);\n    }\n    this.breakpoint_ = '';\n    this.breakpoints_ = Object.assign({}, DEFAULT_BREAKPOINTS, breakpoints);\n\n    // When breakpoint definitions change, we need to update the currently\n    // selected breakpoint.\n    this.updateCurrentBreakpoint_();\n\n    // Clone the breakpoints before returning.\n    return Object.assign(this.breakpoints_);\n  }\n\n  /**\n   * Get or set a flag indicating whether or not this player should adjust\n   * its UI based on its dimensions.\n   *\n   * @param  {boolean} [value]\n   *         Should be `true` if the player should adjust its UI based on its\n   *         dimensions; otherwise, should be `false`.\n   *\n   * @return {boolean|undefined}\n   *         Will be `true` if this player should adjust its UI based on its\n   *         dimensions; otherwise, will be `false`.\n   *         Nothing if setting\n   */\n  responsive(value) {\n    // Used as a getter.\n    if (value === undefined) {\n      return this.responsive_;\n    }\n    value = Boolean(value);\n    const current = this.responsive_;\n\n    // Nothing changed.\n    if (value === current) {\n      return;\n    }\n\n    // The value actually changed, set it.\n    this.responsive_ = value;\n\n    // Start listening for breakpoints and set the initial breakpoint if the\n    // player is now responsive.\n    if (value) {\n      this.on('playerresize', this.boundUpdateCurrentBreakpoint_);\n      this.updateCurrentBreakpoint_();\n\n      // Stop listening for breakpoints if the player is no longer responsive.\n    } else {\n      this.off('playerresize', this.boundUpdateCurrentBreakpoint_);\n      this.removeCurrentBreakpoint_();\n    }\n    return value;\n  }\n\n  /**\n   * Get current breakpoint name, if any.\n   *\n   * @return {string}\n   *         If there is currently a breakpoint set, returns a the key from the\n   *         breakpoints object matching it. Otherwise, returns an empty string.\n   */\n  currentBreakpoint() {\n    return this.breakpoint_;\n  }\n\n  /**\n   * Get the current breakpoint class name.\n   *\n   * @return {string}\n   *         The matching class name (e.g. `\"vjs-layout-tiny\"` or\n   *         `\"vjs-layout-large\"`) for the current breakpoint. Empty string if\n   *         there is no current breakpoint.\n   */\n  currentBreakpointClass() {\n    return BREAKPOINT_CLASSES[this.breakpoint_] || '';\n  }\n\n  /**\n   * An object that describes a single piece of media.\n   *\n   * Properties that are not part of this type description will be retained; so,\n   * this can be viewed as a generic metadata storage mechanism as well.\n   *\n   * @see      {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}\n   * @typedef  {Object} Player~MediaObject\n   *\n   * @property {string} [album]\n   *           Unused, except if this object is passed to the `MediaSession`\n   *           API.\n   *\n   * @property {string} [artist]\n   *           Unused, except if this object is passed to the `MediaSession`\n   *           API.\n   *\n   * @property {Object[]} [artwork]\n   *           Unused, except if this object is passed to the `MediaSession`\n   *           API. If not specified, will be populated via the `poster`, if\n   *           available.\n   *\n   * @property {string} [poster]\n   *           URL to an image that will display before playback.\n   *\n   * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]\n   *           A single source object, an array of source objects, or a string\n   *           referencing a URL to a media source. It is _highly recommended_\n   *           that an object or array of objects is used here, so that source\n   *           selection algorithms can take the `type` into account.\n   *\n   * @property {string} [title]\n   *           Unused, except if this object is passed to the `MediaSession`\n   *           API.\n   *\n   * @property {Object[]} [textTracks]\n   *           An array of objects to be used to create text tracks, following\n   *           the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.\n   *           For ease of removal, these will be created as \"remote\" text\n   *           tracks and set to automatically clean up on source changes.\n   *\n   *           These objects may have properties like `src`, `kind`, `label`,\n   *           and `language`, see {@link Tech#createRemoteTextTrack}.\n   */\n\n  /**\n   * Populate the player using a {@link Player~MediaObject|MediaObject}.\n   *\n   * @param  {Player~MediaObject} media\n   *         A media object.\n   *\n   * @param  {Function} ready\n   *         A callback to be called when the player is ready.\n   */\n  loadMedia(media, ready) {\n    if (!media || typeof media !== 'object') {\n      return;\n    }\n    const crossOrigin = this.crossOrigin();\n    this.reset();\n\n    // Clone the media object so it cannot be mutated from outside.\n    this.cache_.media = merge$1(media);\n    const {\n      artist,\n      artwork,\n      description,\n      poster,\n      src,\n      textTracks,\n      title\n    } = this.cache_.media;\n\n    // If `artwork` is not given, create it using `poster`.\n    if (!artwork && poster) {\n      this.cache_.media.artwork = [{\n        src: poster,\n        type: getMimetype(poster)\n      }];\n    }\n    if (crossOrigin) {\n      this.crossOrigin(crossOrigin);\n    }\n    if (src) {\n      this.src(src);\n    }\n    if (poster) {\n      this.poster(poster);\n    }\n    if (Array.isArray(textTracks)) {\n      textTracks.forEach(tt => this.addRemoteTextTrack(tt, false));\n    }\n    if (this.titleBar) {\n      this.titleBar.update({\n        title,\n        description: description || artist || ''\n      });\n    }\n    this.ready(ready);\n  }\n\n  /**\n   * Get a clone of the current {@link Player~MediaObject} for this player.\n   *\n   * If the `loadMedia` method has not been used, will attempt to return a\n   * {@link Player~MediaObject} based on the current state of the player.\n   *\n   * @return {Player~MediaObject}\n   */\n  getMedia() {\n    if (!this.cache_.media) {\n      const poster = this.poster();\n      const src = this.currentSources();\n      const textTracks = Array.prototype.map.call(this.remoteTextTracks(), tt => ({\n        kind: tt.kind,\n        label: tt.label,\n        language: tt.language,\n        src: tt.src\n      }));\n      const media = {\n        src,\n        textTracks\n      };\n      if (poster) {\n        media.poster = poster;\n        media.artwork = [{\n          src: media.poster,\n          type: getMimetype(media.poster)\n        }];\n      }\n      return media;\n    }\n    return merge$1(this.cache_.media);\n  }\n\n  /**\n   * Gets tag settings\n   *\n   * @param {Element} tag\n   *        The player tag\n   *\n   * @return {Object}\n   *         An object containing all of the settings\n   *         for a player tag\n   */\n  static getTagSettings(tag) {\n    const baseOptions = {\n      sources: [],\n      tracks: []\n    };\n    const tagOptions = getAttributes(tag);\n    const dataSetup = tagOptions['data-setup'];\n    if (hasClass(tag, 'vjs-fill')) {\n      tagOptions.fill = true;\n    }\n    if (hasClass(tag, 'vjs-fluid')) {\n      tagOptions.fluid = true;\n    }\n\n    // Check if data-setup attr exists.\n    if (dataSetup !== null) {\n      // Parse options JSON\n      try {\n        // If empty string, make it a parsable json object.\n        Object.assign(tagOptions, JSON.parse(dataSetup || '{}'));\n      } catch (e) {\n        log$1.error('data-setup', e);\n      }\n    }\n    Object.assign(baseOptions, tagOptions);\n\n    // Get tag children settings\n    if (tag.hasChildNodes()) {\n      const children = tag.childNodes;\n      for (let i = 0, j = children.length; i < j; i++) {\n        const child = children[i];\n        // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/\n        const childName = child.nodeName.toLowerCase();\n        if (childName === 'source') {\n          baseOptions.sources.push(getAttributes(child));\n        } else if (childName === 'track') {\n          baseOptions.tracks.push(getAttributes(child));\n        }\n      }\n    }\n    return baseOptions;\n  }\n\n  /**\n   * Set debug mode to enable/disable logs at info level.\n   *\n   * @param {boolean} enabled\n   * @fires Player#debugon\n   * @fires Player#debugoff\n   * @return {boolean|undefined}\n   */\n  debug(enabled) {\n    if (enabled === undefined) {\n      return this.debugEnabled_;\n    }\n    if (enabled) {\n      this.trigger('debugon');\n      this.previousLogLevel_ = this.log.level;\n      this.log.level('debug');\n      this.debugEnabled_ = true;\n    } else {\n      this.trigger('debugoff');\n      this.log.level(this.previousLogLevel_);\n      this.previousLogLevel_ = undefined;\n      this.debugEnabled_ = false;\n    }\n  }\n\n  /**\n   * Set or get current playback rates.\n   * Takes an array and updates the playback rates menu with the new items.\n   * Pass in an empty array to hide the menu.\n   * Values other than arrays are ignored.\n   *\n   * @fires Player#playbackrateschange\n   * @param {number[]} [newRates]\n   *                   The new rates that the playback rates menu should update to.\n   *                   An empty array will hide the menu\n   * @return {number[]} When used as a getter will return the current playback rates\n   */\n  playbackRates(newRates) {\n    if (newRates === undefined) {\n      return this.cache_.playbackRates;\n    }\n\n    // ignore any value that isn't an array\n    if (!Array.isArray(newRates)) {\n      return;\n    }\n\n    // ignore any arrays that don't only contain numbers\n    if (!newRates.every(rate => typeof rate === 'number')) {\n      return;\n    }\n    this.cache_.playbackRates = newRates;\n\n    /**\n    * fires when the playback rates in a player are changed\n    *\n    * @event Player#playbackrateschange\n    * @type {Event}\n    */\n    this.trigger('playbackrateschange');\n  }\n\n  /**\n   * Reports whether or not a player has a plugin available.\n   *\n   * This does not report whether or not the plugin has ever been initialized\n   * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.\n   *\n   * @method hasPlugin\n   * @param  {string}  name\n   *         The name of a plugin.\n   *\n   * @return {boolean}\n   *         Whether or not this player has the requested plugin available.\n   */\n\n  /**\n   * Reports whether or not a player is using a plugin by name.\n   *\n   * For basic plugins, this only reports whether the plugin has _ever_ been\n   * initialized on this player.\n   *\n   * @method Player#usingPlugin\n   * @param  {string} name\n   *         The name of a plugin.\n   *\n   * @return {boolean}\n   *         Whether or not this player is using the requested plugin.\n   */\n}\n\n/**\n * Get the {@link VideoTrackList}\n *\n * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist\n *\n * @return {VideoTrackList}\n *         the current video track list\n *\n * @method Player.prototype.videoTracks\n */\nPlayer.prototype.videoTracks = () => {};\n\n/**\n * Get the {@link AudioTrackList}\n *\n * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist\n *\n * @return {AudioTrackList}\n *         the current audio track list\n *\n * @method Player.prototype.audioTracks\n */\nPlayer.prototype.audioTracks = () => {};\n\n/**\n * Get the {@link TextTrackList}\n *\n * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks\n *\n * @return {TextTrackList}\n *         the current text track list\n *\n * @method Player.prototype.textTracks\n */\nPlayer.prototype.textTracks = () => {};\n\n/**\n * Get the remote {@link TextTrackList}\n *\n * @return {TextTrackList}\n *         The current remote text track list\n *\n * @method Player.prototype.remoteTextTracks\n */\nPlayer.prototype.remoteTextTracks = () => {};\n\n/**\n * Get the remote {@link HtmlTrackElementList} tracks.\n *\n * @return {HtmlTrackElementList}\n *         The current remote text track element list\n *\n * @method Player.prototype.remoteTextTrackEls\n */\nPlayer.prototype.remoteTextTrackEls = () => {};\nALL.names.forEach(function (name) {\n  const props = ALL[name];\n  Player.prototype[props.getterName] = function () {\n    if (this.tech_) {\n      return this.tech_[props.getterName]();\n    }\n\n    // if we have not yet loadTech_, we create {video,audio,text}Tracks_\n    // these will be passed to the tech during loading\n    this[props.privateName] = this[props.privateName] || new props.ListClass();\n    return this[props.privateName];\n  };\n});\n\n/**\n * Get or set the `Player`'s crossorigin option. For the HTML5 player, this\n * sets the `crossOrigin` property on the `<video>` tag to control the CORS\n * behavior.\n *\n * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}\n *\n * @param {string} [value]\n *        The value to set the `Player`'s crossorigin to. If an argument is\n *        given, must be one of `anonymous` or `use-credentials`.\n *\n * @return {string|undefined}\n *         - The current crossorigin value of the `Player` when getting.\n *         - undefined when setting\n */\nPlayer.prototype.crossorigin = Player.prototype.crossOrigin;\n\n/**\n * Global enumeration of players.\n *\n * The keys are the player IDs and the values are either the {@link Player}\n * instance or `null` for disposed players.\n *\n * @type {Object}\n */\nPlayer.players = {};\nconst navigator = window$1.navigator;\n\n/*\n * Player instance options, surfaced using options\n * options = Player.prototype.options_\n * Make changes in options, not here.\n *\n * @type {Object}\n * @private\n */\nPlayer.prototype.options_ = {\n  // Default order of fallback technology\n  techOrder: Tech.defaultTechOrder_,\n  html5: {},\n  // enable sourceset by default\n  enableSourceset: true,\n  // default inactivity timeout\n  inactivityTimeout: 2000,\n  // default playback rates\n  playbackRates: [],\n  // Add playback rate selection by adding rates\n  // 'playbackRates': [0.5, 1, 1.5, 2],\n  liveui: false,\n  // Included control sets\n  children: ['mediaLoader', 'posterImage', 'titleBar', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],\n  language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',\n  // locales and their language translations\n  languages: {},\n  // Default message to show when a video cannot be played.\n  notSupportedMessage: 'No compatible source was found for this media.',\n  normalizeAutoplay: false,\n  fullscreen: {\n    options: {\n      navigationUI: 'hide'\n    }\n  },\n  breakpoints: {},\n  responsive: false,\n  audioOnlyMode: false,\n  audioPosterMode: false,\n  spatialNavigation: {\n    enabled: false,\n    horizontalSeek: false\n  },\n  // Default smooth seeking to false\n  enableSmoothSeeking: false,\n  disableSeekWhileScrubbingOnMobile: false,\n  disableSeekWhileScrubbingOnSTV: false\n};\nTECH_EVENTS_RETRIGGER.forEach(function (event) {\n  Player.prototype[`handleTech${toTitleCase$1(event)}_`] = function () {\n    return this.trigger(event);\n  };\n});\n\n/**\n * Fired when the player has initial duration and dimension information\n *\n * @event Player#loadedmetadata\n * @type {Event}\n */\n\n/**\n * Fired when the player has downloaded data at the current playback position\n *\n * @event Player#loadeddata\n * @type {Event}\n */\n\n/**\n * Fired when the current playback position has changed *\n * During playback this is fired every 15-250 milliseconds, depending on the\n * playback technology in use.\n *\n * @event Player#timeupdate\n * @type {Event}\n */\n\n/**\n * Fired when the volume changes\n *\n * @event Player#volumechange\n * @type {Event}\n */\n\nComponent$1.registerComponent('Player', Player);\n\n/**\n * @file plugin.js\n */\n\n/**\n * The base plugin name.\n *\n * @private\n * @constant\n * @type {string}\n */\nconst BASE_PLUGIN_NAME = 'plugin';\n\n/**\n * The key on which a player's active plugins cache is stored.\n *\n * @private\n * @constant\n * @type     {string}\n */\nconst PLUGIN_CACHE_KEY = 'activePlugins_';\n\n/**\n * Stores registered plugins in a private space.\n *\n * @private\n * @type    {Object}\n */\nconst pluginStorage = {};\n\n/**\n * Reports whether or not a plugin has been registered.\n *\n * @private\n * @param   {string} name\n *          The name of a plugin.\n *\n * @return {boolean}\n *          Whether or not the plugin has been registered.\n */\nconst pluginExists = name => pluginStorage.hasOwnProperty(name);\n\n/**\n * Get a single registered plugin by name.\n *\n * @private\n * @param   {string} name\n *          The name of a plugin.\n *\n * @return {typeof Plugin|Function|undefined}\n *          The plugin (or undefined).\n */\nconst getPlugin = name => pluginExists(name) ? pluginStorage[name] : undefined;\n\n/**\n * Marks a plugin as \"active\" on a player.\n *\n * Also, ensures that the player has an object for tracking active plugins.\n *\n * @private\n * @param   {Player} player\n *          A Video.js player instance.\n *\n * @param   {string} name\n *          The name of a plugin.\n */\nconst markPluginAsActive = (player, name) => {\n  player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};\n  player[PLUGIN_CACHE_KEY][name] = true;\n};\n\n/**\n * Triggers a pair of plugin setup events.\n *\n * @private\n * @param  {Player} player\n *         A Video.js player instance.\n *\n * @param  {PluginEventHash} hash\n *         A plugin event hash.\n *\n * @param  {boolean} [before]\n *         If true, prefixes the event name with \"before\". In other words,\n *         use this to trigger \"beforepluginsetup\" instead of \"pluginsetup\".\n */\nconst triggerSetupEvent = (player, hash, before) => {\n  const eventName = (before ? 'before' : '') + 'pluginsetup';\n  player.trigger(eventName, hash);\n  player.trigger(eventName + ':' + hash.name, hash);\n};\n\n/**\n * Takes a basic plugin function and returns a wrapper function which marks\n * on the player that the plugin has been activated.\n *\n * @private\n * @param   {string} name\n *          The name of the plugin.\n *\n * @param   {Function} plugin\n *          The basic plugin.\n *\n * @return {Function}\n *          A wrapper function for the given plugin.\n */\nconst createBasicPlugin = function (name, plugin) {\n  const basicPluginWrapper = function () {\n    // We trigger the \"beforepluginsetup\" and \"pluginsetup\" events on the player\n    // regardless, but we want the hash to be consistent with the hash provided\n    // for advanced plugins.\n    //\n    // The only potentially counter-intuitive thing here is the `instance` in\n    // the \"pluginsetup\" event is the value returned by the `plugin` function.\n    triggerSetupEvent(this, {\n      name,\n      plugin,\n      instance: null\n    }, true);\n    const instance = plugin.apply(this, arguments);\n    markPluginAsActive(this, name);\n    triggerSetupEvent(this, {\n      name,\n      plugin,\n      instance\n    });\n    return instance;\n  };\n  Object.keys(plugin).forEach(function (prop) {\n    basicPluginWrapper[prop] = plugin[prop];\n  });\n  return basicPluginWrapper;\n};\n\n/**\n * Takes a plugin sub-class and returns a factory function for generating\n * instances of it.\n *\n * This factory function will replace itself with an instance of the requested\n * sub-class of Plugin.\n *\n * @private\n * @param   {string} name\n *          The name of the plugin.\n *\n * @param   {Plugin} PluginSubClass\n *          The advanced plugin.\n *\n * @return {Function}\n */\nconst createPluginFactory = (name, PluginSubClass) => {\n  // Add a `name` property to the plugin prototype so that each plugin can\n  // refer to itself by name.\n  PluginSubClass.prototype.name = name;\n  return function (...args) {\n    triggerSetupEvent(this, {\n      name,\n      plugin: PluginSubClass,\n      instance: null\n    }, true);\n    const instance = new PluginSubClass(...[this, ...args]);\n\n    // The plugin is replaced by a function that returns the current instance.\n    this[name] = () => instance;\n    triggerSetupEvent(this, instance.getEventHash());\n    return instance;\n  };\n};\n\n/**\n * Parent class for all advanced plugins.\n *\n * @mixes   module:evented~EventedMixin\n * @mixes   module:stateful~StatefulMixin\n * @fires   Player#beforepluginsetup\n * @fires   Player#beforepluginsetup:$name\n * @fires   Player#pluginsetup\n * @fires   Player#pluginsetup:$name\n * @listens Player#dispose\n * @throws  {Error}\n *          If attempting to instantiate the base {@link Plugin} class\n *          directly instead of via a sub-class.\n */\nclass Plugin {\n  /**\n   * Creates an instance of this class.\n   *\n   * Sub-classes should call `super` to ensure plugins are properly initialized.\n   *\n   * @param {Player} player\n   *        A Video.js player instance.\n   */\n  constructor(player) {\n    if (this.constructor === Plugin) {\n      throw new Error('Plugin must be sub-classed; not directly instantiated.');\n    }\n    this.player = player;\n    if (!this.log) {\n      this.log = this.player.log.createLogger(this.name);\n    }\n\n    // Make this object evented, but remove the added `trigger` method so we\n    // use the prototype version instead.\n    evented(this);\n    delete this.trigger;\n    stateful(this, this.constructor.defaultState);\n    markPluginAsActive(player, this.name);\n\n    // Auto-bind the dispose method so we can use it as a listener and unbind\n    // it later easily.\n    this.dispose = this.dispose.bind(this);\n\n    // If the player is disposed, dispose the plugin.\n    player.on('dispose', this.dispose);\n  }\n\n  /**\n   * Get the version of the plugin that was set on <pluginName>.VERSION\n   */\n  version() {\n    return this.constructor.VERSION;\n  }\n\n  /**\n   * Each event triggered by plugins includes a hash of additional data with\n   * conventional properties.\n   *\n   * This returns that object or mutates an existing hash.\n   *\n   * @param   {Object} [hash={}]\n   *          An object to be used as event an event hash.\n   *\n   * @return {PluginEventHash}\n   *          An event hash object with provided properties mixed-in.\n   */\n  getEventHash(hash = {}) {\n    hash.name = this.name;\n    hash.plugin = this.constructor;\n    hash.instance = this;\n    return hash;\n  }\n\n  /**\n   * Triggers an event on the plugin object and overrides\n   * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.\n   *\n   * @param   {string|Object} event\n   *          An event type or an object with a type property.\n   *\n   * @param   {Object} [hash={}]\n   *          Additional data hash to merge with a\n   *          {@link PluginEventHash|PluginEventHash}.\n   *\n   * @return {boolean}\n   *          Whether or not default was prevented.\n   */\n  trigger(event, hash = {}) {\n    return trigger(this.eventBusEl_, event, this.getEventHash(hash));\n  }\n\n  /**\n   * Handles \"statechanged\" events on the plugin. No-op by default, override by\n   * subclassing.\n   *\n   * @abstract\n   * @param    {Event} e\n   *           An event object provided by a \"statechanged\" event.\n   *\n   * @param    {Object} e.changes\n   *           An object describing changes that occurred with the \"statechanged\"\n   *           event.\n   */\n  handleStateChanged(e) {}\n\n  /**\n   * Disposes a plugin.\n   *\n   * Subclasses can override this if they want, but for the sake of safety,\n   * it's probably best to subscribe the \"dispose\" event.\n   *\n   * @fires Plugin#dispose\n   */\n  dispose() {\n    const {\n      name,\n      player\n    } = this;\n\n    /**\n     * Signals that a advanced plugin is about to be disposed.\n     *\n     * @event Plugin#dispose\n     * @type  {Event}\n     */\n    this.trigger('dispose');\n    this.off();\n    player.off('dispose', this.dispose);\n\n    // Eliminate any possible sources of leaking memory by clearing up\n    // references between the player and the plugin instance and nulling out\n    // the plugin's state and replacing methods with a function that throws.\n    player[PLUGIN_CACHE_KEY][name] = false;\n    this.player = this.state = null;\n\n    // Finally, replace the plugin name on the player with a new factory\n    // function, so that the plugin is ready to be set up again.\n    player[name] = createPluginFactory(name, pluginStorage[name]);\n  }\n\n  /**\n   * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).\n   *\n   * @param   {string|Function} plugin\n   *          If a string, matches the name of a plugin. If a function, will be\n   *          tested directly.\n   *\n   * @return {boolean}\n   *          Whether or not a plugin is a basic plugin.\n   */\n  static isBasic(plugin) {\n    const p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;\n    return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);\n  }\n\n  /**\n   * Register a Video.js plugin.\n   *\n   * @param   {string} name\n   *          The name of the plugin to be registered. Must be a string and\n   *          must not match an existing plugin or a method on the `Player`\n   *          prototype.\n   *\n   * @param   {typeof Plugin|Function} plugin\n   *          A sub-class of `Plugin` or a function for basic plugins.\n   *\n   * @return {typeof Plugin|Function}\n   *          For advanced plugins, a factory function for that plugin. For\n   *          basic plugins, a wrapper function that initializes the plugin.\n   */\n  static registerPlugin(name, plugin) {\n    if (typeof name !== 'string') {\n      throw new Error(`Illegal plugin name, \"${name}\", must be a string, was ${typeof name}.`);\n    }\n    if (pluginExists(name)) {\n      log$1.warn(`A plugin named \"${name}\" already exists. You may want to avoid re-registering plugins!`);\n    } else if (Player.prototype.hasOwnProperty(name)) {\n      throw new Error(`Illegal plugin name, \"${name}\", cannot share a name with an existing player method!`);\n    }\n    if (typeof plugin !== 'function') {\n      throw new Error(`Illegal plugin for \"${name}\", must be a function, was ${typeof plugin}.`);\n    }\n    pluginStorage[name] = plugin;\n\n    // Add a player prototype method for all sub-classed plugins (but not for\n    // the base Plugin class).\n    if (name !== BASE_PLUGIN_NAME) {\n      if (Plugin.isBasic(plugin)) {\n        Player.prototype[name] = createBasicPlugin(name, plugin);\n      } else {\n        Player.prototype[name] = createPluginFactory(name, plugin);\n      }\n    }\n    return plugin;\n  }\n\n  /**\n   * De-register a Video.js plugin.\n   *\n   * @param  {string} name\n   *         The name of the plugin to be de-registered. Must be a string that\n   *         matches an existing plugin.\n   *\n   * @throws {Error}\n   *         If an attempt is made to de-register the base plugin.\n   */\n  static deregisterPlugin(name) {\n    if (name === BASE_PLUGIN_NAME) {\n      throw new Error('Cannot de-register base plugin.');\n    }\n    if (pluginExists(name)) {\n      delete pluginStorage[name];\n      delete Player.prototype[name];\n    }\n  }\n\n  /**\n   * Gets an object containing multiple Video.js plugins.\n   *\n   * @param   {Array} [names]\n   *          If provided, should be an array of plugin names. Defaults to _all_\n   *          plugin names.\n   *\n   * @return {Object|undefined}\n   *          An object containing plugin(s) associated with their name(s) or\n   *          `undefined` if no matching plugins exist).\n   */\n  static getPlugins(names = Object.keys(pluginStorage)) {\n    let result;\n    names.forEach(name => {\n      const plugin = getPlugin(name);\n      if (plugin) {\n        result = result || {};\n        result[name] = plugin;\n      }\n    });\n    return result;\n  }\n\n  /**\n   * Gets a plugin's version, if available\n   *\n   * @param   {string} name\n   *          The name of a plugin.\n   *\n   * @return {string}\n   *          The plugin's version or an empty string.\n   */\n  static getPluginVersion(name) {\n    const plugin = getPlugin(name);\n    return plugin && plugin.VERSION || '';\n  }\n}\n\n/**\n * Gets a plugin by name if it exists.\n *\n * @static\n * @method   getPlugin\n * @memberOf Plugin\n * @param    {string} name\n *           The name of a plugin.\n *\n * @returns  {typeof Plugin|Function|undefined}\n *           The plugin (or `undefined`).\n */\nPlugin.getPlugin = getPlugin;\n\n/**\n * The name of the base plugin class as it is registered.\n *\n * @type {string}\n */\nPlugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;\nPlugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);\n\n/**\n * Documented in player.js\n *\n * @ignore\n */\nPlayer.prototype.usingPlugin = function (name) {\n  return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;\n};\n\n/**\n * Documented in player.js\n *\n * @ignore\n */\nPlayer.prototype.hasPlugin = function (name) {\n  return !!pluginExists(name);\n};\n\n/**\n * Signals that a plugin is about to be set up on a player.\n *\n * @event    Player#beforepluginsetup\n * @type     {PluginEventHash}\n */\n\n/**\n * Signals that a plugin is about to be set up on a player - by name. The name\n * is the name of the plugin.\n *\n * @event    Player#beforepluginsetup:$name\n * @type     {PluginEventHash}\n */\n\n/**\n * Signals that a plugin has just been set up on a player.\n *\n * @event    Player#pluginsetup\n * @type     {PluginEventHash}\n */\n\n/**\n * Signals that a plugin has just been set up on a player - by name. The name\n * is the name of the plugin.\n *\n * @event    Player#pluginsetup:$name\n * @type     {PluginEventHash}\n */\n\n/**\n * @typedef  {Object} PluginEventHash\n *\n * @property {string} instance\n *           For basic plugins, the return value of the plugin function. For\n *           advanced plugins, the plugin instance on which the event is fired.\n *\n * @property {string} name\n *           The name of the plugin.\n *\n * @property {string} plugin\n *           For basic plugins, the plugin function. For advanced plugins, the\n *           plugin class/constructor.\n */\n\n/**\n * @file deprecate.js\n * @module deprecate\n */\n\n/**\n * Decorate a function with a deprecation message the first time it is called.\n *\n * @param  {string}   message\n *         A deprecation message to log the first time the returned function\n *         is called.\n *\n * @param  {Function} fn\n *         The function to be deprecated.\n *\n * @return {Function}\n *         A wrapper function that will log a deprecation warning the first\n *         time it is called. The return value will be the return value of\n *         the wrapped function.\n */\nfunction deprecate(message, fn) {\n  let warned = false;\n  return function (...args) {\n    if (!warned) {\n      log$1.warn(message);\n    }\n    warned = true;\n    return fn.apply(this, args);\n  };\n}\n\n/**\n * Internal function used to mark a function as deprecated in the next major\n * version with consistent messaging.\n *\n * @param  {number}   major   The major version where it will be removed\n * @param  {string}   oldName The old function name\n * @param  {string}   newName The new function name\n * @param  {Function} fn      The function to deprecate\n * @return {Function}         The decorated function\n */\nfunction deprecateForMajor(major, oldName, newName, fn) {\n  return deprecate(`${oldName} is deprecated and will be removed in ${major}.0; please use ${newName} instead.`, fn);\n}\n\nvar VjsErrors = {\n  NetworkBadStatus: 'networkbadstatus',\n  NetworkRequestFailed: 'networkrequestfailed',\n  NetworkRequestAborted: 'networkrequestaborted',\n  NetworkRequestTimeout: 'networkrequesttimeout',\n  NetworkBodyParserFailed: 'networkbodyparserfailed',\n  StreamingHlsPlaylistParserError: 'streaminghlsplaylistparsererror',\n  StreamingDashManifestParserError: 'streamingdashmanifestparsererror',\n  StreamingContentSteeringParserError: 'streamingcontentsteeringparsererror',\n  StreamingVttParserError: 'streamingvttparsererror',\n  StreamingFailedToSelectNextSegment: 'streamingfailedtoselectnextsegment',\n  StreamingFailedToDecryptSegment: 'streamingfailedtodecryptsegment',\n  StreamingFailedToTransmuxSegment: 'streamingfailedtotransmuxsegment',\n  StreamingFailedToAppendSegment: 'streamingfailedtoappendsegment',\n  StreamingCodecsChangeError: 'streamingcodecschangeerror'\n};\n\n/**\n * @file video.js\n * @module videojs\n */\n\n/** @import { PlayerReadyCallback } from './player' */\n\n/**\n * Normalize an `id` value by trimming off a leading `#`\n *\n * @private\n * @param   {string} id\n *          A string, maybe with a leading `#`.\n *\n * @return {string}\n *          The string, without any leading `#`.\n */\nconst normalizeId = id => id.indexOf('#') === 0 ? id.slice(1) : id;\n\n/**\n * The `videojs()` function doubles as the main function for users to create a\n * {@link Player} instance as well as the main library namespace.\n *\n * It can also be used as a getter for a pre-existing {@link Player} instance.\n * However, we _strongly_ recommend using `videojs.getPlayer()` for this\n * purpose because it avoids any potential for unintended initialization.\n *\n * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)\n * of our JSDoc template, we cannot properly document this as both a function\n * and a namespace, so its function signature is documented here.\n *\n * #### Arguments\n * ##### id\n * string|Element, **required**\n *\n * Video element or video element ID.\n *\n * ##### options\n * Object, optional\n *\n * Options object for providing settings.\n * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).\n *\n * ##### ready\n * {@link Component~ReadyCallback}, optional\n *\n * A function to be called when the {@link Player} and {@link Tech} are ready.\n *\n * #### Return Value\n *\n * The `videojs()` function returns a {@link Player} instance.\n *\n * @namespace\n *\n * @borrows AudioTrack as AudioTrack\n * @borrows Component.getComponent as getComponent\n * @borrows module:events.on as on\n * @borrows module:events.one as one\n * @borrows module:events.off as off\n * @borrows module:events.trigger as trigger\n * @borrows EventTarget as EventTarget\n * @borrows module:middleware.use as use\n * @borrows Player.players as players\n * @borrows Plugin.registerPlugin as registerPlugin\n * @borrows Plugin.deregisterPlugin as deregisterPlugin\n * @borrows Plugin.getPlugins as getPlugins\n * @borrows Plugin.getPlugin as getPlugin\n * @borrows Plugin.getPluginVersion as getPluginVersion\n * @borrows Tech.getTech as getTech\n * @borrows Tech.registerTech as registerTech\n * @borrows TextTrack as TextTrack\n * @borrows VideoTrack as VideoTrack\n *\n * @param  {string|Element} id\n *         Video element or video element ID.\n *\n * @param  {Object} [options]\n *         Options object for providing settings.\n *         See: [Options Guide](https://docs.videojs.com/tutorial-options.html).\n *\n * @param  {PlayerReadyCallback} [ready]\n *         A function to be called when the {@link Player} and {@link Tech} are\n *         ready.\n *\n * @return {Player}\n *         The `videojs()` function returns a {@link Player|Player} instance.\n */\nfunction videojs(id, options, ready) {\n  let player = videojs.getPlayer(id);\n  if (player) {\n    if (options) {\n      log$1.warn(`Player \"${id}\" is already initialised. Options will not be applied.`);\n    }\n    if (ready) {\n      player.ready(ready);\n    }\n    return player;\n  }\n  const el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;\n  if (!isEl(el)) {\n    throw new TypeError('The element or ID supplied is not valid. (videojs)');\n  }\n\n  // document.body.contains(el) will only check if el is contained within that one document.\n  // This causes problems for elements in iframes.\n  // Instead, use the element's ownerDocument instead of the global document.\n  // This will make sure that the element is indeed in the dom of that document.\n  // Additionally, check that the document in question has a default view.\n  // If the document is no longer attached to the dom, the defaultView of the document will be null.\n  // If element is inside Shadow DOM (e.g. is part of a Custom element), ownerDocument.body\n  // always returns false. Instead, use the Shadow DOM root.\n  const inShadowDom = 'getRootNode' in el ? el.getRootNode() instanceof window$1.ShadowRoot : false;\n  const rootNode = inShadowDom ? el.getRootNode() : el.ownerDocument.body;\n  if (!el.ownerDocument.defaultView || !rootNode.contains(el)) {\n    log$1.warn('The element supplied is not included in the DOM');\n  }\n  options = options || {};\n\n  // Store a copy of the el before modification, if it is to be restored in destroy()\n  // If div ingest, store the parent div\n  if (options.restoreEl === true) {\n    options.restoreEl = (el.parentNode && el.parentNode.hasAttribute && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);\n  }\n  hooks('beforesetup').forEach(hookFunction => {\n    const opts = hookFunction(el, merge$1(options));\n    if (!isObject(opts) || Array.isArray(opts)) {\n      log$1.error('please return an object in beforesetup hooks');\n      return;\n    }\n    options = merge$1(options, opts);\n  });\n\n  // We get the current \"Player\" component here in case an integration has\n  // replaced it with a custom player.\n  const PlayerComponent = Component$1.getComponent('Player');\n  player = new PlayerComponent(el, options, ready);\n  hooks('setup').forEach(hookFunction => hookFunction(player));\n  return player;\n}\nvideojs.hooks_ = hooks_;\nvideojs.hooks = hooks;\nvideojs.hook = hook;\nvideojs.hookOnce = hookOnce;\nvideojs.removeHook = removeHook;\n\n// Add default styles\nif (window$1.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {\n  let style = $('.vjs-styles-defaults');\n  if (!style) {\n    style = createStyleElement('vjs-styles-defaults');\n    const head = $('head');\n    if (head) {\n      head.insertBefore(style, head.firstChild);\n    }\n    setTextContent(style, `\n      .video-js {\n        width: 300px;\n        height: 150px;\n      }\n\n      .vjs-fluid:not(.vjs-audio-only-mode) {\n        padding-top: 56.25%\n      }\n    `);\n  }\n}\n\n// Run Auto-load players\n// You have to wait at least once in case this script is loaded after your\n// video in the DOM (weird behavior only with minified version)\nautoSetupTimeout(1, videojs);\n\n/**\n * Current Video.js version. Follows [semantic versioning](https://semver.org/).\n *\n * @type {string}\n */\nvideojs.VERSION = version$6;\n\n/**\n * The global options object. These are the settings that take effect\n * if no overrides are specified when the player is created.\n *\n * @type {Object}\n */\nvideojs.options = Player.prototype.options_;\n\n/**\n * Get an object with the currently created players, keyed by player ID\n *\n * @return {Object}\n *         The created players\n */\nvideojs.getPlayers = () => Player.players;\n\n/**\n * Get a single player based on an ID or DOM element.\n *\n * This is useful if you want to check if an element or ID has an associated\n * Video.js player, but not create one if it doesn't.\n *\n * @param   {string|Element} id\n *          An HTML element - `<video>`, `<audio>`, or `<video-js>` -\n *          or a string matching the `id` of such an element.\n *\n * @return {Player|undefined}\n *          A player instance or `undefined` if there is no player instance\n *          matching the argument.\n */\nvideojs.getPlayer = id => {\n  const players = Player.players;\n  let tag;\n  if (typeof id === 'string') {\n    const nId = normalizeId(id);\n    const player = players[nId];\n    if (player) {\n      return player;\n    }\n    tag = $('#' + nId);\n  } else {\n    tag = id;\n  }\n  if (isEl(tag)) {\n    const {\n      player,\n      playerId\n    } = tag;\n\n    // Element may have a `player` property referring to an already created\n    // player instance. If so, return that.\n    if (player || players[playerId]) {\n      return player || players[playerId];\n    }\n  }\n};\n\n/**\n * Returns an array of all current players.\n *\n * @return {Array}\n *         An array of all players. The array will be in the order that\n *         `Object.keys` provides, which could potentially vary between\n *         JavaScript engines.\n *\n */\nvideojs.getAllPlayers = () =>\n// Disposed players leave a key with a `null` value, so we need to make sure\n// we filter those out.\nObject.keys(Player.players).map(k => Player.players[k]).filter(Boolean);\nvideojs.players = Player.players;\nvideojs.getComponent = Component$1.getComponent;\n\n/**\n * Register a component so it can referred to by name. Used when adding to other\n * components, either through addChild `component.addChild('myComponent')` or through\n * default children options  `{ children: ['myComponent'] }`.\n *\n * > NOTE: You could also just initialize the component before adding.\n * `component.addChild(new MyComponent());`\n *\n * @param {string} name\n *        The class name of the component\n *\n * @param {typeof Component} comp\n *        The component class\n *\n * @return {typeof Component}\n *         The newly registered component\n */\nvideojs.registerComponent = (name, comp) => {\n  if (Tech.isTech(comp)) {\n    log$1.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);\n  }\n  return Component$1.registerComponent.call(Component$1, name, comp);\n};\nvideojs.getTech = Tech.getTech;\nvideojs.registerTech = Tech.registerTech;\nvideojs.use = use;\n\n/**\n * An object that can be returned by a middleware to signify\n * that the middleware is being terminated.\n *\n * @type {object}\n * @property {object} middleware.TERMINATOR\n */\nObject.defineProperty(videojs, 'middleware', {\n  value: {},\n  writeable: false,\n  enumerable: true\n});\nObject.defineProperty(videojs.middleware, 'TERMINATOR', {\n  value: TERMINATOR,\n  writeable: false,\n  enumerable: true\n});\n\n/**\n * A reference to the {@link module:browser|browser utility module} as an object.\n *\n * @type {Object}\n * @see  {@link module:browser|browser}\n */\nvideojs.browser = browser;\n\n/**\n * A reference to the {@link module:obj|obj utility module} as an object.\n *\n * @type {Object}\n * @see  {@link module:obj|obj}\n */\nvideojs.obj = Obj;\n\n/**\n * Deprecated reference to the {@link module:obj.merge|merge function}\n *\n * @type {Function}\n * @see {@link module:obj.merge|merge}\n * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.merge instead.\n */\nvideojs.mergeOptions = deprecateForMajor(9, 'videojs.mergeOptions', 'videojs.obj.merge', merge$1);\n\n/**\n * Deprecated reference to the {@link module:obj.defineLazyProperty|defineLazyProperty function}\n *\n * @type {Function}\n * @see {@link module:obj.defineLazyProperty|defineLazyProperty}\n * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.defineLazyProperty instead.\n */\nvideojs.defineLazyProperty = deprecateForMajor(9, 'videojs.defineLazyProperty', 'videojs.obj.defineLazyProperty', defineLazyProperty);\n\n/**\n * Deprecated reference to the {@link module:fn.bind_|fn.bind_ function}\n *\n * @type {Function}\n * @see {@link module:fn.bind_|fn.bind_}\n * @deprecated Deprecated and will be removed in 9.0. Please use native Function.prototype.bind instead.\n */\nvideojs.bind = deprecateForMajor(9, 'videojs.bind', 'native Function.prototype.bind', bind_);\nvideojs.registerPlugin = Plugin.registerPlugin;\nvideojs.deregisterPlugin = Plugin.deregisterPlugin;\n\n/**\n * Deprecated method to register a plugin with Video.js\n *\n * @deprecated Deprecated and will be removed in 9.0. Use videojs.registerPlugin() instead.\n *\n * @param {string} name\n *        The plugin name\n*\n * @param {typeof Plugin|Function} plugin\n *         The plugin sub-class or function\n *\n * @return {typeof Plugin|Function}\n */\nvideojs.plugin = (name, plugin) => {\n  log$1.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');\n  return Plugin.registerPlugin(name, plugin);\n};\nvideojs.getPlugins = Plugin.getPlugins;\nvideojs.getPlugin = Plugin.getPlugin;\nvideojs.getPluginVersion = Plugin.getPluginVersion;\n\n/**\n * Adding languages so that they're available to all players.\n * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`\n *\n * @param {string} code\n *        The language code or dictionary property\n *\n * @param {Object} data\n *        The data values to be translated\n *\n * @return {Object}\n *         The resulting language dictionary object\n */\nvideojs.addLanguage = function (code, data) {\n  code = ('' + code).toLowerCase();\n  videojs.options.languages = merge$1(videojs.options.languages, {\n    [code]: data\n  });\n  return videojs.options.languages[code];\n};\n\n/**\n * A reference to the {@link module:log|log utility module} as an object.\n *\n * @type {Function}\n * @see  {@link module:log|log}\n */\nvideojs.log = log$1;\nvideojs.createLogger = createLogger;\n\n/**\n * A reference to the {@link module:time|time utility module} as an object.\n *\n * @type {Object}\n * @see {@link module:time|time}\n */\nvideojs.time = Time;\n\n/**\n * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}\n *\n * @type {Function}\n * @see {@link module:time.createTimeRanges|createTimeRanges}\n * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.\n */\nvideojs.createTimeRange = deprecateForMajor(9, 'videojs.createTimeRange', 'videojs.time.createTimeRanges', createTimeRanges$1);\n\n/**\n * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}\n *\n * @type {Function}\n * @see {@link module:time.createTimeRanges|createTimeRanges}\n * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.\n */\nvideojs.createTimeRanges = deprecateForMajor(9, 'videojs.createTimeRanges', 'videojs.time.createTimeRanges', createTimeRanges$1);\n\n/**\n * Deprecated reference to the {@link module:time.formatTime|formatTime function}\n *\n * @type {Function}\n * @see {@link module:time.formatTime|formatTime}\n * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.format instead.\n */\nvideojs.formatTime = deprecateForMajor(9, 'videojs.formatTime', 'videojs.time.formatTime', formatTime);\n\n/**\n * Deprecated reference to the {@link module:time.setFormatTime|setFormatTime function}\n *\n * @type {Function}\n * @see {@link module:time.setFormatTime|setFormatTime}\n * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.setFormat instead.\n */\nvideojs.setFormatTime = deprecateForMajor(9, 'videojs.setFormatTime', 'videojs.time.setFormatTime', setFormatTime);\n\n/**\n * Deprecated reference to the {@link module:time.resetFormatTime|resetFormatTime function}\n *\n * @type {Function}\n * @see {@link module:time.resetFormatTime|resetFormatTime}\n * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.resetFormat instead.\n */\nvideojs.resetFormatTime = deprecateForMajor(9, 'videojs.resetFormatTime', 'videojs.time.resetFormatTime', resetFormatTime);\n\n/**\n * Deprecated reference to the {@link module:url.parseUrl|Url.parseUrl function}\n *\n * @type {Function}\n * @see {@link module:url.parseUrl|parseUrl}\n * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.parseUrl instead.\n */\nvideojs.parseUrl = deprecateForMajor(9, 'videojs.parseUrl', 'videojs.url.parseUrl', parseUrl);\n\n/**\n * Deprecated reference to the {@link module:url.isCrossOrigin|Url.isCrossOrigin function}\n *\n * @type {Function}\n * @see {@link module:url.isCrossOrigin|isCrossOrigin}\n * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.isCrossOrigin instead.\n */\nvideojs.isCrossOrigin = deprecateForMajor(9, 'videojs.isCrossOrigin', 'videojs.url.isCrossOrigin', isCrossOrigin);\nvideojs.EventTarget = EventTarget$2;\nvideojs.any = any;\nvideojs.on = on;\nvideojs.one = one;\nvideojs.off = off;\nvideojs.trigger = trigger;\n\n/**\n * A cross-browser XMLHttpRequest wrapper.\n *\n * @function\n * @param    {Object} options\n *           Settings for the request.\n *\n * @return   {XMLHttpRequest|XDomainRequest}\n *           The request object.\n *\n * @see      https://github.com/Raynos/xhr\n */\nvideojs.xhr = XHR;\nvideojs.TrackList = TrackList;\nvideojs.TextTrack = TextTrack;\nvideojs.TextTrackList = TextTrackList;\nvideojs.AudioTrack = AudioTrack;\nvideojs.AudioTrackList = AudioTrackList;\nvideojs.VideoTrack = VideoTrack;\nvideojs.VideoTrackList = VideoTrackList;\n['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(k => {\n  videojs[k] = function () {\n    log$1.warn(`videojs.${k}() is deprecated; use videojs.dom.${k}() instead`);\n    return Dom[k].apply(null, arguments);\n  };\n});\nvideojs.computedStyle = deprecateForMajor(9, 'videojs.computedStyle', 'videojs.dom.computedStyle', computedStyle);\n\n/**\n * A reference to the {@link module:dom|DOM utility module} as an object.\n *\n * @type {Object}\n * @see {@link module:dom|dom}\n */\nvideojs.dom = Dom;\n\n/**\n * A reference to the {@link module:fn|fn utility module} as an object.\n *\n * @type {Object}\n * @see {@link module:fn|fn}\n */\nvideojs.fn = Fn;\n\n/**\n * A reference to the {@link module:num|num utility module} as an object.\n *\n * @type {Object}\n * @see {@link module:num|num}\n */\nvideojs.num = Num;\n\n/**\n * A reference to the {@link module:str|str utility module} as an object.\n *\n * @type {Object}\n * @see {@link module:str|str}\n */\nvideojs.str = Str;\n\n/**\n * A reference to the {@link module:url|URL utility module} as an object.\n *\n * @type {Object}\n * @see {@link module:url|url}\n */\nvideojs.url = Url;\n\n// The list of possible error types to occur in video.js\nvideojs.Error = VjsErrors;\n\n/*! @name videojs-contrib-quality-levels @version 4.1.0 @license Apache-2.0 */\n\n/**\n * A single QualityLevel.\n *\n * interface QualityLevel {\n *   readonly attribute DOMString id;\n *            attribute DOMString label;\n *   readonly attribute long width;\n *   readonly attribute long height;\n *   readonly attribute long bitrate;\n *            attribute boolean enabled;\n * };\n *\n * @class QualityLevel\n */\nclass QualityLevel {\n  /**\n   * Creates a QualityLevel\n   *\n   * @param {Representation|Object} representation The representation of the quality level\n   * @param {string}   representation.id        Unique id of the QualityLevel\n   * @param {number=}  representation.width     Resolution width of the QualityLevel\n   * @param {number=}  representation.height    Resolution height of the QualityLevel\n   * @param {number}   representation.bandwidth Bitrate of the QualityLevel\n   * @param {number=}  representation.frameRate Frame-rate of the QualityLevel\n   * @param {Function} representation.enabled   Callback to enable/disable QualityLevel\n   */\n  constructor(representation) {\n    let level = this; // eslint-disable-line\n\n    level.id = representation.id;\n    level.label = level.id;\n    level.width = representation.width;\n    level.height = representation.height;\n    level.bitrate = representation.bandwidth;\n    level.frameRate = representation.frameRate;\n    level.enabled_ = representation.enabled;\n    Object.defineProperty(level, 'enabled', {\n      /**\n       * Get whether the QualityLevel is enabled.\n       *\n       * @return {boolean} True if the QualityLevel is enabled.\n       */\n      get() {\n        return level.enabled_();\n      },\n      /**\n       * Enable or disable the QualityLevel.\n       *\n       * @param {boolean} enable true to enable QualityLevel, false to disable.\n       */\n      set(enable) {\n        level.enabled_(enable);\n      }\n    });\n    return level;\n  }\n}\n\n/**\n * A list of QualityLevels.\n *\n * interface QualityLevelList : EventTarget {\n *   getter QualityLevel (unsigned long index);\n *   readonly attribute unsigned long length;\n *   readonly attribute long selectedIndex;\n *\n *   void addQualityLevel(QualityLevel qualityLevel)\n *   void removeQualityLevel(QualityLevel remove)\n *   QualityLevel? getQualityLevelById(DOMString id);\n *\n *   attribute EventHandler onchange;\n *   attribute EventHandler onaddqualitylevel;\n *   attribute EventHandler onremovequalitylevel;\n * };\n *\n * @extends videojs.EventTarget\n * @class QualityLevelList\n */\nclass QualityLevelList extends videojs.EventTarget {\n  /**\n   * Creates a QualityLevelList.\n   */\n  constructor() {\n    super();\n    let list = this; // eslint-disable-line\n\n    list.levels_ = [];\n    list.selectedIndex_ = -1;\n\n    /**\n     * Get the index of the currently selected QualityLevel.\n     *\n     * @returns {number} The index of the selected QualityLevel. -1 if none selected.\n     * @readonly\n     */\n    Object.defineProperty(list, 'selectedIndex', {\n      get() {\n        return list.selectedIndex_;\n      }\n    });\n\n    /**\n     * Get the length of the list of QualityLevels.\n     *\n     * @returns {number} The length of the list.\n     * @readonly\n     */\n    Object.defineProperty(list, 'length', {\n      get() {\n        return list.levels_.length;\n      }\n    });\n    list[Symbol.iterator] = () => list.levels_.values();\n    return list;\n  }\n\n  /**\n   * Adds a quality level to the list.\n   *\n   * @param {Representation|Object} representation The representation of the quality level\n   * @param {string}   representation.id        Unique id of the QualityLevel\n   * @param {number=}  representation.width     Resolution width of the QualityLevel\n   * @param {number=}  representation.height    Resolution height of the QualityLevel\n   * @param {number}   representation.bandwidth Bitrate of the QualityLevel\n   * @param {number=}  representation.frameRate Frame-rate of the QualityLevel\n   * @param {Function} representation.enabled   Callback to enable/disable QualityLevel\n   * @return {QualityLevel} the QualityLevel added to the list\n   * @method addQualityLevel\n   */\n  addQualityLevel(representation) {\n    let qualityLevel = this.getQualityLevelById(representation.id);\n\n    // Do not add duplicate quality levels\n    if (qualityLevel) {\n      return qualityLevel;\n    }\n    const index = this.levels_.length;\n    qualityLevel = new QualityLevel(representation);\n    if (!('' + index in this)) {\n      Object.defineProperty(this, index, {\n        get() {\n          return this.levels_[index];\n        }\n      });\n    }\n    this.levels_.push(qualityLevel);\n    this.trigger({\n      qualityLevel,\n      type: 'addqualitylevel'\n    });\n    return qualityLevel;\n  }\n\n  /**\n   * Removes a quality level from the list.\n   *\n   * @param {QualityLevel} qualityLevel The QualityLevel to remove from the list.\n   * @return {QualityLevel|null} the QualityLevel removed or null if nothing removed\n   * @method removeQualityLevel\n   */\n  removeQualityLevel(qualityLevel) {\n    let removed = null;\n    for (let i = 0, l = this.length; i < l; i++) {\n      if (this[i] === qualityLevel) {\n        removed = this.levels_.splice(i, 1)[0];\n        if (this.selectedIndex_ === i) {\n          this.selectedIndex_ = -1;\n        } else if (this.selectedIndex_ > i) {\n          this.selectedIndex_--;\n        }\n        break;\n      }\n    }\n    if (removed) {\n      this.trigger({\n        qualityLevel,\n        type: 'removequalitylevel'\n      });\n    }\n    return removed;\n  }\n\n  /**\n   * Searches for a QualityLevel with the given id.\n   *\n   * @param {string} id The id of the QualityLevel to find.\n   * @return {QualityLevel|null} The QualityLevel with id, or null if not found.\n   * @method getQualityLevelById\n   */\n  getQualityLevelById(id) {\n    for (let i = 0, l = this.length; i < l; i++) {\n      const level = this[i];\n      if (level.id === id) {\n        return level;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Resets the list of QualityLevels to empty\n   *\n   * @method dispose\n   */\n  dispose() {\n    this.selectedIndex_ = -1;\n    this.levels_.length = 0;\n  }\n}\n\n/**\n * change - The selected QualityLevel has changed.\n * addqualitylevel - A QualityLevel has been added to the QualityLevelList.\n * removequalitylevel - A QualityLevel has been removed from the QualityLevelList.\n */\nQualityLevelList.prototype.allowedEvents_ = {\n  change: 'change',\n  addqualitylevel: 'addqualitylevel',\n  removequalitylevel: 'removequalitylevel'\n};\n\n// emulate attribute EventHandler support to allow for feature detection\nfor (const event in QualityLevelList.prototype.allowedEvents_) {\n  QualityLevelList.prototype['on' + event] = null;\n}\nvar version$5 = \"4.1.0\";\n\n/**\n * Initialization function for the qualityLevels plugin. Sets up the QualityLevelList and\n * event handlers.\n *\n * @param {Player} player Player object.\n * @param {Object} options Plugin options object.\n * @return {QualityLevelList} a list of QualityLevels\n */\nconst initPlugin$1 = function (player, options) {\n  const originalPluginFn = player.qualityLevels;\n  const qualityLevelList = new QualityLevelList();\n  const disposeHandler = function () {\n    qualityLevelList.dispose();\n    player.qualityLevels = originalPluginFn;\n    player.off('dispose', disposeHandler);\n  };\n  player.on('dispose', disposeHandler);\n  player.qualityLevels = () => qualityLevelList;\n  player.qualityLevels.VERSION = version$5;\n  return qualityLevelList;\n};\n\n/**\n * A video.js plugin.\n *\n * In the plugin function, the value of `this` is a video.js `Player`\n * instance. You cannot rely on the player being in a \"ready\" state here,\n * depending on how the plugin is invoked. This may or may not be important\n * to you; if not, remove the wait for \"ready\"!\n *\n * @param {Object} options Plugin options object\n * @return {QualityLevelList} a list of QualityLevels\n */\nconst qualityLevels = function (options) {\n  return initPlugin$1(this, videojs.obj.merge({}, options));\n};\n\n// Register the plugin with video.js.\nvideojs.registerPlugin('qualityLevels', qualityLevels);\n\n// Include the version number.\nqualityLevels.VERSION = version$5;\n\n/*! @name @videojs/http-streaming @version 3.17.2 @license Apache-2.0 */\n\n/**\n * @file resolve-url.js - Handling how URLs are resolved and manipulated\n */\nconst resolveUrl = _resolveUrl;\n/**\n * If the xhr request was redirected, return the responseURL, otherwise,\n * return the original url.\n *\n * @api private\n *\n * @param  {string} url - an url being requested\n * @param  {XMLHttpRequest} req - xhr request result\n *\n * @return {string}\n */\n\nconst resolveManifestRedirect = (url, req) => {\n  // To understand how the responseURL below is set and generated:\n  // - https://fetch.spec.whatwg.org/#concept-response-url\n  // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling\n  if (req && req.responseURL && url !== req.responseURL) {\n    return req.responseURL;\n  }\n  return url;\n};\nconst logger = source => {\n  if (videojs.log.debug) {\n    return videojs.log.debug.bind(videojs, 'VHS:', `${source} >`);\n  }\n  return function () {};\n};\n\n/**\n * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.\n */\n/**\n * Delegates to videojs.obj.merge (Video.js 8) or\n * videojs.mergeOptions (Video.js 7).\n */\n\nfunction merge(...args) {\n  const context = videojs.obj || videojs;\n  const fn = context.merge || context.mergeOptions;\n  return fn.apply(context, args);\n}\n/**\n * Delegates to videojs.time.createTimeRanges (Video.js 8) or\n * videojs.createTimeRanges (Video.js 7).\n */\n\nfunction createTimeRanges(...args) {\n  const context = videojs.time || videojs;\n  const fn = context.createTimeRanges || context.createTimeRanges;\n  return fn.apply(context, args);\n}\n/**\n * Converts provided buffered ranges to a descriptive string\n *\n * @param {TimeRanges} buffered - received buffered time ranges\n *\n * @return {string} - descriptive string\n */\n\nfunction bufferedRangesToString(buffered) {\n  if (buffered.length === 0) {\n    return 'Buffered Ranges are empty';\n  }\n  let bufferedRangesStr = 'Buffered Ranges: \\n';\n  for (let i = 0; i < buffered.length; i++) {\n    const start = buffered.start(i);\n    const end = buffered.end(i);\n    bufferedRangesStr += `${start} --> ${end}. Duration (${end - start})\\n`;\n  }\n  return bufferedRangesStr;\n}\n\n/**\n * ranges\n *\n * Utilities for working with TimeRanges.\n *\n */\n\nconst TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range\n// can be misleading because of precision differences or when the current media has poorly\n// aligned audio and video, which can cause values to be slightly off from what you would\n// expect. This value is what we consider to be safe to use in such comparisons to account\n// for these scenarios.\n\nconst SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;\nconst filterRanges = function (timeRanges, predicate) {\n  const results = [];\n  let i;\n  if (timeRanges && timeRanges.length) {\n    // Search for ranges that match the predicate\n    for (i = 0; i < timeRanges.length; i++) {\n      if (predicate(timeRanges.start(i), timeRanges.end(i))) {\n        results.push([timeRanges.start(i), timeRanges.end(i)]);\n      }\n    }\n  }\n  return createTimeRanges(results);\n};\n/**\n * Attempts to find the buffered TimeRange that contains the specified\n * time.\n *\n * @param {TimeRanges} buffered - the TimeRanges object to query\n * @param {number} time  - the time to filter on.\n * @return {TimeRanges} a new TimeRanges object\n */\n\nconst findRange = function (buffered, time) {\n  return filterRanges(buffered, function (start, end) {\n    return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;\n  });\n};\n/**\n * Returns the TimeRanges that begin later than the specified time.\n *\n * @param {TimeRanges} timeRanges - the TimeRanges object to query\n * @param {number} time - the time to filter on.\n * @return {TimeRanges} a new TimeRanges object.\n */\n\nconst findNextRange = function (timeRanges, time) {\n  return filterRanges(timeRanges, function (start) {\n    return start - TIME_FUDGE_FACTOR >= time;\n  });\n};\n/**\n * Returns gaps within a list of TimeRanges\n *\n * @param {TimeRanges} buffered - the TimeRanges object\n * @return {TimeRanges} a TimeRanges object of gaps\n */\n\nconst findGaps = function (buffered) {\n  if (buffered.length < 2) {\n    return createTimeRanges();\n  }\n  const ranges = [];\n  for (let i = 1; i < buffered.length; i++) {\n    const start = buffered.end(i - 1);\n    const end = buffered.start(i);\n    ranges.push([start, end]);\n  }\n  return createTimeRanges(ranges);\n};\n/**\n * Calculate the intersection of two TimeRanges\n *\n * @param {TimeRanges} bufferA\n * @param {TimeRanges} bufferB\n * @return {TimeRanges} The interesection of `bufferA` with `bufferB`\n */\n\nconst bufferIntersection = function (bufferA, bufferB) {\n  let start = null;\n  let end = null;\n  let arity = 0;\n  const extents = [];\n  const ranges = [];\n  if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {\n    return createTimeRanges();\n  } // Handle the case where we have both buffers and create an\n  // intersection of the two\n\n  let count = bufferA.length; // A) Gather up all start and end times\n\n  while (count--) {\n    extents.push({\n      time: bufferA.start(count),\n      type: 'start'\n    });\n    extents.push({\n      time: bufferA.end(count),\n      type: 'end'\n    });\n  }\n  count = bufferB.length;\n  while (count--) {\n    extents.push({\n      time: bufferB.start(count),\n      type: 'start'\n    });\n    extents.push({\n      time: bufferB.end(count),\n      type: 'end'\n    });\n  } // B) Sort them by time\n\n  extents.sort(function (a, b) {\n    return a.time - b.time;\n  }); // C) Go along one by one incrementing arity for start and decrementing\n  //    arity for ends\n\n  for (count = 0; count < extents.length; count++) {\n    if (extents[count].type === 'start') {\n      arity++; // D) If arity is ever incremented to 2 we are entering an\n      //    overlapping range\n\n      if (arity === 2) {\n        start = extents[count].time;\n      }\n    } else if (extents[count].type === 'end') {\n      arity--; // E) If arity is ever decremented to 1 we leaving an\n      //    overlapping range\n\n      if (arity === 1) {\n        end = extents[count].time;\n      }\n    } // F) Record overlapping ranges\n\n    if (start !== null && end !== null) {\n      ranges.push([start, end]);\n      start = null;\n      end = null;\n    }\n  }\n  return createTimeRanges(ranges);\n};\n/**\n * Gets a human readable string for a TimeRange\n *\n * @param {TimeRange} range\n * @return {string} a human readable string\n */\n\nconst printableRange = range => {\n  const strArr = [];\n  if (!range || !range.length) {\n    return '';\n  }\n  for (let i = 0; i < range.length; i++) {\n    strArr.push(range.start(i) + ' => ' + range.end(i));\n  }\n  return strArr.join(', ');\n};\n/**\n * Calculates the amount of time left in seconds until the player hits the end of the\n * buffer and causes a rebuffer\n *\n * @param {TimeRange} buffered\n *        The state of the buffer\n * @param {Numnber} currentTime\n *        The current time of the player\n * @param {number} playbackRate\n *        The current playback rate of the player. Defaults to 1.\n * @return {number}\n *         Time until the player has to start rebuffering in seconds.\n * @function timeUntilRebuffer\n */\n\nconst timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {\n  const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;\n  return (bufferedEnd - currentTime) / playbackRate;\n};\n/**\n * Converts a TimeRanges object into an array representation\n *\n * @param {TimeRanges} timeRanges\n * @return {Array}\n */\n\nconst timeRangesToArray = timeRanges => {\n  const timeRangesList = [];\n  for (let i = 0; i < timeRanges.length; i++) {\n    timeRangesList.push({\n      start: timeRanges.start(i),\n      end: timeRanges.end(i)\n    });\n  }\n  return timeRangesList;\n};\n/**\n * Determines if two time range objects are different.\n *\n * @param {TimeRange} a\n *        the first time range object to check\n *\n * @param {TimeRange} b\n *        the second time range object to check\n *\n * @return {Boolean}\n *         Whether the time range objects differ\n */\n\nconst isRangeDifferent = function (a, b) {\n  // same object\n  if (a === b) {\n    return false;\n  } // one or the other is undefined\n\n  if (!a && b || !b && a) {\n    return true;\n  } // length is different\n\n  if (a.length !== b.length) {\n    return true;\n  } // see if any start/end pair is different\n\n  for (let i = 0; i < a.length; i++) {\n    if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {\n      return true;\n    }\n  } // if the length and every pair is the same\n  // this is the same time range\n\n  return false;\n};\nconst lastBufferedEnd = function (a) {\n  if (!a || !a.length || !a.end) {\n    return;\n  }\n  return a.end(a.length - 1);\n};\n/**\n * A utility function to add up the amount of time in a timeRange\n * after a specified startTime.\n * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0\n *     would return 40 as there are 40s seconds after 0 in the timeRange\n *\n * @param {TimeRange} range\n *        The range to check against\n * @param {number} startTime\n *        The time in the time range that you should start counting from\n *\n * @return {number}\n *          The number of seconds in the buffer passed the specified time.\n */\n\nconst timeAheadOf = function (range, startTime) {\n  let time = 0;\n  if (!range || !range.length) {\n    return time;\n  }\n  for (let i = 0; i < range.length; i++) {\n    const start = range.start(i);\n    const end = range.end(i); // startTime is after this range entirely\n\n    if (startTime > end) {\n      continue;\n    } // startTime is within this range\n\n    if (startTime > start && startTime <= end) {\n      time += end - startTime;\n      continue;\n    } // startTime is before this range.\n\n    time += end - start;\n  }\n  return time;\n};\n\n/**\n * @file playlist.js\n *\n * Playlist related utilities.\n */\n/**\n * Get the duration of a segment, with special cases for\n * llhls segments that do not have a duration yet.\n *\n * @param {Object} playlist\n *        the playlist that the segment belongs to.\n * @param {Object} segment\n *        the segment to get a duration for.\n *\n * @return {number}\n *          the segment duration\n */\n\nconst segmentDurationWithParts = (playlist, segment) => {\n  // if this isn't a preload segment\n  // then we will have a segment duration that is accurate.\n  if (!segment.preload) {\n    return segment.duration;\n  } // otherwise we have to add up parts and preload hints\n  // to get an up to date duration.\n\n  let result = 0;\n  (segment.parts || []).forEach(function (p) {\n    result += p.duration;\n  }); // for preload hints we have to use partTargetDuration\n  // as they won't even have a duration yet.\n\n  (segment.preloadHints || []).forEach(function (p) {\n    if (p.type === 'PART') {\n      result += playlist.partTargetDuration;\n    }\n  });\n  return result;\n};\n/**\n * A function to get a combined list of parts and segments with durations\n * and indexes.\n *\n * @param {Playlist} playlist the playlist to get the list for.\n *\n * @return {Array} The part/segment list.\n */\n\nconst getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {\n  if (segment.parts) {\n    segment.parts.forEach(function (part, pi) {\n      acc.push({\n        duration: part.duration,\n        segmentIndex: si,\n        partIndex: pi,\n        part,\n        segment\n      });\n    });\n  } else {\n    acc.push({\n      duration: segment.duration,\n      segmentIndex: si,\n      partIndex: null,\n      segment,\n      part: null\n    });\n  }\n  return acc;\n}, []);\nconst getLastParts = media => {\n  const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];\n  return lastSegment && lastSegment.parts || [];\n};\nconst getKnownPartCount = ({\n  preloadSegment\n}) => {\n  if (!preloadSegment) {\n    return;\n  }\n  const {\n    parts,\n    preloadHints\n  } = preloadSegment;\n  let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);\n  partCount += parts && parts.length ? parts.length : 0;\n  return partCount;\n};\n/**\n * Get the number of seconds to delay from the end of a\n * live playlist.\n *\n * @param {Playlist} main the main playlist\n * @param {Playlist} media the media playlist\n * @return {number} the hold back in seconds.\n */\n\nconst liveEdgeDelay = (main, media) => {\n  if (media.endList) {\n    return 0;\n  } // dash suggestedPresentationDelay trumps everything\n\n  if (main && main.suggestedPresentationDelay) {\n    return main.suggestedPresentationDelay;\n  }\n  const hasParts = getLastParts(media).length > 0; // look for \"part\" delays from ll-hls first\n\n  if (hasParts && media.serverControl && media.serverControl.partHoldBack) {\n    return media.serverControl.partHoldBack;\n  } else if (hasParts && media.partTargetDuration) {\n    return media.partTargetDuration * 3; // finally look for full segment delays\n  } else if (media.serverControl && media.serverControl.holdBack) {\n    return media.serverControl.holdBack;\n  } else if (media.targetDuration) {\n    return media.targetDuration * 3;\n  }\n  return 0;\n};\n/**\n * walk backward until we find a duration we can use\n * or return a failure\n *\n * @param {Playlist} playlist the playlist to walk through\n * @param {Number} endSequence the mediaSequence to stop walking on\n */\n\nconst backwardDuration = function (playlist, endSequence) {\n  let result = 0;\n  let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following\n  // the interval, use it\n\n  let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline\n  // information that is earlier than endSequence\n\n  if (segment) {\n    if (typeof segment.start !== 'undefined') {\n      return {\n        result: segment.start,\n        precise: true\n      };\n    }\n    if (typeof segment.end !== 'undefined') {\n      return {\n        result: segment.end - segment.duration,\n        precise: true\n      };\n    }\n  }\n  while (i--) {\n    segment = playlist.segments[i];\n    if (typeof segment.end !== 'undefined') {\n      return {\n        result: result + segment.end,\n        precise: true\n      };\n    }\n    result += segmentDurationWithParts(playlist, segment);\n    if (typeof segment.start !== 'undefined') {\n      return {\n        result: result + segment.start,\n        precise: true\n      };\n    }\n  }\n  return {\n    result,\n    precise: false\n  };\n};\n/**\n * walk forward until we find a duration we can use\n * or return a failure\n *\n * @param {Playlist} playlist the playlist to walk through\n * @param {number} endSequence the mediaSequence to stop walking on\n */\n\nconst forwardDuration = function (playlist, endSequence) {\n  let result = 0;\n  let segment;\n  let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline\n  // information\n\n  for (; i < playlist.segments.length; i++) {\n    segment = playlist.segments[i];\n    if (typeof segment.start !== 'undefined') {\n      return {\n        result: segment.start - result,\n        precise: true\n      };\n    }\n    result += segmentDurationWithParts(playlist, segment);\n    if (typeof segment.end !== 'undefined') {\n      return {\n        result: segment.end - result,\n        precise: true\n      };\n    }\n  } // indicate we didn't find a useful duration estimate\n\n  return {\n    result: -1,\n    precise: false\n  };\n};\n/**\n  * Calculate the media duration from the segments associated with a\n  * playlist. The duration of a subinterval of the available segments\n  * may be calculated by specifying an end index.\n  *\n  * @param {Object} playlist a media playlist object\n  * @param {number=} endSequence an exclusive upper boundary\n  * for the playlist.  Defaults to playlist length.\n  * @param {number} expired the amount of time that has dropped\n  * off the front of the playlist in a live scenario\n  * @return {number} the duration between the first available segment\n  * and end index.\n  */\n\nconst intervalDuration = function (playlist, endSequence, expired) {\n  if (typeof endSequence === 'undefined') {\n    endSequence = playlist.mediaSequence + playlist.segments.length;\n  }\n  if (endSequence < playlist.mediaSequence) {\n    return 0;\n  } // do a backward walk to estimate the duration\n\n  const backward = backwardDuration(playlist, endSequence);\n  if (backward.precise) {\n    // if we were able to base our duration estimate on timing\n    // information provided directly from the Media Source, return\n    // it\n    return backward.result;\n  } // walk forward to see if a precise duration estimate can be made\n  // that way\n\n  const forward = forwardDuration(playlist, endSequence);\n  if (forward.precise) {\n    // we found a segment that has been buffered and so it's\n    // position is known precisely\n    return forward.result;\n  } // return the less-precise, playlist-based duration estimate\n\n  return backward.result + expired;\n};\n/**\n  * Calculates the duration of a playlist. If a start and end index\n  * are specified, the duration will be for the subset of the media\n  * timeline between those two indices. The total duration for live\n  * playlists is always Infinity.\n  *\n  * @param {Object} playlist a media playlist object\n  * @param {number=} endSequence an exclusive upper\n  * boundary for the playlist. Defaults to the playlist media\n  * sequence number plus its length.\n  * @param {number=} expired the amount of time that has\n  * dropped off the front of the playlist in a live scenario\n  * @return {number} the duration between the start index and end\n  * index.\n  */\n\nconst duration = function (playlist, endSequence, expired) {\n  if (!playlist) {\n    return 0;\n  }\n  if (typeof expired !== 'number') {\n    expired = 0;\n  } // if a slice of the total duration is not requested, use\n  // playlist-level duration indicators when they're present\n\n  if (typeof endSequence === 'undefined') {\n    // if present, use the duration specified in the playlist\n    if (playlist.totalDuration) {\n      return playlist.totalDuration;\n    } // duration should be Infinity for live playlists\n\n    if (!playlist.endList) {\n      return window$1.Infinity;\n    }\n  } // calculate the total duration based on the segment durations\n\n  return intervalDuration(playlist, endSequence, expired);\n};\n/**\n  * Calculate the time between two indexes in the current playlist\n  * neight the start- nor the end-index need to be within the current\n  * playlist in which case, the targetDuration of the playlist is used\n  * to approximate the durations of the segments\n  *\n  * @param {Array} options.durationList list to iterate over for durations.\n  * @param {number} options.defaultDuration duration to use for elements before or after the durationList\n  * @param {number} options.startIndex partsAndSegments index to start\n  * @param {number} options.endIndex partsAndSegments index to end.\n  * @return {number} the number of seconds between startIndex and endIndex\n  */\n\nconst sumDurations = function ({\n  defaultDuration,\n  durationList,\n  startIndex,\n  endIndex\n}) {\n  let durations = 0;\n  if (startIndex > endIndex) {\n    [startIndex, endIndex] = [endIndex, startIndex];\n  }\n  if (startIndex < 0) {\n    for (let i = startIndex; i < Math.min(0, endIndex); i++) {\n      durations += defaultDuration;\n    }\n    startIndex = 0;\n  }\n  for (let i = startIndex; i < endIndex; i++) {\n    durations += durationList[i].duration;\n  }\n  return durations;\n};\n/**\n * Calculates the playlist end time\n *\n * @param {Object} playlist a media playlist object\n * @param {number=} expired the amount of time that has\n *                  dropped off the front of the playlist in a live scenario\n * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the\n *                        playlist end calculation should consider the safe live end\n *                        (truncate the playlist end by three segments). This is normally\n *                        used for calculating the end of the playlist's seekable range.\n *                        This takes into account the value of liveEdgePadding.\n *                        Setting liveEdgePadding to 0 is equivalent to setting this to false.\n * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.\n *                 If this is provided, it is used in the safe live end calculation.\n *                 Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.\n *                 Corresponds to suggestedPresentationDelay in DASH manifests.\n * @return {number} the end time of playlist\n * @function playlistEnd\n */\n\nconst playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {\n  if (!playlist || !playlist.segments) {\n    return null;\n  }\n  if (playlist.endList) {\n    return duration(playlist);\n  }\n  if (expired === null) {\n    return null;\n  }\n  expired = expired || 0;\n  let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);\n  if (useSafeLiveEnd) {\n    liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);\n    lastSegmentEndTime -= liveEdgePadding;\n  } // don't return a time less than zero\n\n  return Math.max(0, lastSegmentEndTime);\n};\n/**\n  * Calculates the interval of time that is currently seekable in a\n  * playlist. The returned time ranges are relative to the earliest\n  * moment in the specified playlist that is still available. A full\n  * seekable implementation for live streams would need to offset\n  * these values by the duration of content that has expired from the\n  * stream.\n  *\n  * @param {Object} playlist a media playlist object\n  * dropped off the front of the playlist in a live scenario\n  * @param {number=} expired the amount of time that has\n  * dropped off the front of the playlist in a live scenario\n  * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.\n  *        Corresponds to suggestedPresentationDelay in DASH manifests.\n  * @return {TimeRanges} the periods of time that are valid targets\n  * for seeking\n  */\n\nconst seekable = function (playlist, expired, liveEdgePadding) {\n  const useSafeLiveEnd = true;\n  const seekableStart = expired || 0;\n  let seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);\n  if (seekableEnd === null) {\n    return createTimeRanges();\n  } // Clamp seekable end since it can not be less than the seekable start\n\n  if (seekableEnd < seekableStart) {\n    seekableEnd = seekableStart;\n  }\n  return createTimeRanges(seekableStart, seekableEnd);\n};\n/**\n * Determine the index and estimated starting time of the segment that\n * contains a specified playback position in a media playlist.\n *\n * @param {Object} options.playlist the media playlist to query\n * @param {number} options.currentTime The number of seconds since the earliest\n * possible position to determine the containing segment for\n * @param {number} options.startTime the time when the segment/part starts\n * @param {number} options.startingSegmentIndex the segment index to start looking at.\n * @param {number?} [options.startingPartIndex] the part index to look at within the segment.\n *\n * @return {Object} an object with partIndex, segmentIndex, and startTime.\n */\n\nconst getMediaInfoForTime = function ({\n  playlist,\n  currentTime,\n  startingSegmentIndex,\n  startingPartIndex,\n  startTime,\n  exactManifestTimings\n}) {\n  let time = currentTime - startTime;\n  const partsAndSegments = getPartsAndSegments(playlist);\n  let startIndex = 0;\n  for (let i = 0; i < partsAndSegments.length; i++) {\n    const partAndSegment = partsAndSegments[i];\n    if (startingSegmentIndex !== partAndSegment.segmentIndex) {\n      continue;\n    } // skip this if part index does not match.\n\n    if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {\n      continue;\n    }\n    startIndex = i;\n    break;\n  }\n  if (time < 0) {\n    // Walk backward from startIndex in the playlist, adding durations\n    // until we find a segment that contains `time` and return it\n    if (startIndex > 0) {\n      for (let i = startIndex - 1; i >= 0; i--) {\n        const partAndSegment = partsAndSegments[i];\n        time += partAndSegment.duration;\n        if (exactManifestTimings) {\n          if (time < 0) {\n            continue;\n          }\n        } else if (time + TIME_FUDGE_FACTOR <= 0) {\n          continue;\n        }\n        return {\n          partIndex: partAndSegment.partIndex,\n          segmentIndex: partAndSegment.segmentIndex,\n          startTime: startTime - sumDurations({\n            defaultDuration: playlist.targetDuration,\n            durationList: partsAndSegments,\n            startIndex,\n            endIndex: i\n          })\n        };\n      }\n    } // We were unable to find a good segment within the playlist\n    // so select the first segment\n\n    return {\n      partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,\n      segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,\n      startTime: currentTime\n    };\n  } // When startIndex is negative, we first walk forward to first segment\n  // adding target durations. If we \"run out of time\" before getting to\n  // the first segment, return the first segment\n\n  if (startIndex < 0) {\n    for (let i = startIndex; i < 0; i++) {\n      time -= playlist.targetDuration;\n      if (time < 0) {\n        return {\n          partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,\n          segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,\n          startTime: currentTime\n        };\n      }\n    }\n    startIndex = 0;\n  } // Walk forward from startIndex in the playlist, subtracting durations\n  // until we find a segment that contains `time` and return it\n\n  for (let i = startIndex; i < partsAndSegments.length; i++) {\n    const partAndSegment = partsAndSegments[i];\n    time -= partAndSegment.duration;\n    const canUseFudgeFactor = partAndSegment.duration > TIME_FUDGE_FACTOR;\n    const isExactlyAtTheEnd = time === 0;\n    const isExtremelyCloseToTheEnd = canUseFudgeFactor && time + TIME_FUDGE_FACTOR >= 0;\n    if (isExactlyAtTheEnd || isExtremelyCloseToTheEnd) {\n      // 1) We are exactly at the end of the current segment.\n      // 2) We are extremely close to the end of the current segment (The difference is less than  1 / 30).\n      //    We may encounter this situation when\n      //    we don't have exact match between segment duration info in the manifest and the actual duration of the segment\n      //    For example:\n      //    We appended 3 segments 10 seconds each, meaning we should have 30 sec buffered,\n      //    but we the actual buffered is 29.99999\n      //\n      // In both cases:\n      // if we passed current time -> it means that we already played current segment\n      // if we passed buffered.end -> it means that this segment is already loaded and buffered\n      // we should select the next segment if we have one:\n      if (i !== partsAndSegments.length - 1) {\n        continue;\n      }\n    }\n    if (exactManifestTimings) {\n      if (time > 0) {\n        continue;\n      }\n    } else if (time - TIME_FUDGE_FACTOR >= 0) {\n      continue;\n    }\n    return {\n      partIndex: partAndSegment.partIndex,\n      segmentIndex: partAndSegment.segmentIndex,\n      startTime: startTime + sumDurations({\n        defaultDuration: playlist.targetDuration,\n        durationList: partsAndSegments,\n        startIndex,\n        endIndex: i\n      })\n    };\n  } // We are out of possible candidates so load the last one...\n\n  return {\n    segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,\n    partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,\n    startTime: currentTime\n  };\n};\n/**\n * Check whether the playlist is excluded or not.\n *\n * @param {Object} playlist the media playlist object\n * @return {boolean} whether the playlist is excluded or not\n * @function isExcluded\n */\n\nconst isExcluded = function (playlist) {\n  return playlist.excludeUntil && playlist.excludeUntil > Date.now();\n};\n/**\n * Check whether the playlist is compatible with current playback configuration or has\n * been excluded permanently for being incompatible.\n *\n * @param {Object} playlist the media playlist object\n * @return {boolean} whether the playlist is incompatible or not\n * @function isIncompatible\n */\n\nconst isIncompatible = function (playlist) {\n  return playlist.excludeUntil && playlist.excludeUntil === Infinity;\n};\n/**\n * Check whether the playlist is enabled or not.\n *\n * @param {Object} playlist the media playlist object\n * @return {boolean} whether the playlist is enabled or not\n * @function isEnabled\n */\n\nconst isEnabled = function (playlist) {\n  const excluded = isExcluded(playlist);\n  return !playlist.disabled && !excluded;\n};\n/**\n * Check whether the playlist has been manually disabled through the representations api.\n *\n * @param {Object} playlist the media playlist object\n * @return {boolean} whether the playlist is disabled manually or not\n * @function isDisabled\n */\n\nconst isDisabled = function (playlist) {\n  return playlist.disabled;\n};\n/**\n * Returns whether the current playlist is an AES encrypted HLS stream\n *\n * @return {boolean} true if it's an AES encrypted HLS stream\n */\n\nconst isAes = function (media) {\n  for (let i = 0; i < media.segments.length; i++) {\n    if (media.segments[i].key) {\n      return true;\n    }\n  }\n  return false;\n};\n/**\n * Checks if the playlist has a value for the specified attribute\n *\n * @param {string} attr\n *        Attribute to check for\n * @param {Object} playlist\n *        The media playlist object\n * @return {boolean}\n *         Whether the playlist contains a value for the attribute or not\n * @function hasAttribute\n */\n\nconst hasAttribute = function (attr, playlist) {\n  return playlist.attributes && playlist.attributes[attr];\n};\n/**\n * Estimates the time required to complete a segment download from the specified playlist\n *\n * @param {number} segmentDuration\n *        Duration of requested segment\n * @param {number} bandwidth\n *        Current measured bandwidth of the player\n * @param {Object} playlist\n *        The media playlist object\n * @param {number=} bytesReceived\n *        Number of bytes already received for the request. Defaults to 0\n * @return {number|NaN}\n *         The estimated time to request the segment. NaN if bandwidth information for\n *         the given playlist is unavailable\n * @function estimateSegmentRequestTime\n */\n\nconst estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {\n  if (!hasAttribute('BANDWIDTH', playlist)) {\n    return NaN;\n  }\n  const size = segmentDuration * playlist.attributes.BANDWIDTH;\n  return (size - bytesReceived * 8) / bandwidth;\n};\n/*\n * Returns whether the current playlist is the lowest rendition\n *\n * @return {Boolean} true if on lowest rendition\n */\n\nconst isLowestEnabledRendition = (main, media) => {\n  if (main.playlists.length === 1) {\n    return true;\n  }\n  const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;\n  return main.playlists.filter(playlist => {\n    if (!isEnabled(playlist)) {\n      return false;\n    }\n    return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;\n  }).length === 0;\n};\nconst playlistMatch = (a, b) => {\n  // both playlits are null\n  // or only one playlist is non-null\n  // no match\n  if (!a && !b || !a && b || a && !b) {\n    return false;\n  } // playlist objects are the same, match\n\n  if (a === b) {\n    return true;\n  } // first try to use id as it should be the most\n  // accurate\n\n  if (a.id && b.id && a.id === b.id) {\n    return true;\n  } // next try to use reslovedUri as it should be the\n  // second most accurate.\n\n  if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {\n    return true;\n  } // finally try to use uri as it should be accurate\n  // but might miss a few cases for relative uris\n\n  if (a.uri && b.uri && a.uri === b.uri) {\n    return true;\n  }\n  return false;\n};\nconst someAudioVariant = function (main, callback) {\n  const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};\n  let found = false;\n  for (const groupName in AUDIO) {\n    for (const label in AUDIO[groupName]) {\n      found = callback(AUDIO[groupName][label]);\n      if (found) {\n        break;\n      }\n    }\n    if (found) {\n      break;\n    }\n  }\n  return !!found;\n};\nconst isAudioOnly = main => {\n  // we are audio only if we have no main playlists but do\n  // have media group playlists.\n  if (!main || !main.playlists || !main.playlists.length) {\n    // without audio variants or playlists this\n    // is not an audio only main.\n    const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);\n    return found;\n  } // if every playlist has only an audio codec it is audio only\n\n  for (let i = 0; i < main.playlists.length; i++) {\n    const playlist = main.playlists[i];\n    const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.\n\n    if (CODECS && CODECS.split(',').every(c => isAudioCodec(c))) {\n      continue;\n    } // playlist is in an audio group it is audio only\n\n    const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));\n    if (found) {\n      continue;\n    } // if we make it here this playlist isn't audio and we\n    // are not audio only\n\n    return false;\n  } // if we make it past every playlist without returning, then\n  // this is an audio only playlist.\n\n  return true;\n}; // exports\n\nvar Playlist = {\n  liveEdgeDelay,\n  duration,\n  seekable,\n  getMediaInfoForTime,\n  isEnabled,\n  isDisabled,\n  isExcluded,\n  isIncompatible,\n  playlistEnd,\n  isAes,\n  hasAttribute,\n  estimateSegmentRequestTime,\n  isLowestEnabledRendition,\n  isAudioOnly,\n  playlistMatch,\n  segmentDurationWithParts\n};\nconst {\n  log\n} = videojs;\nconst createPlaylistID = (index, uri) => {\n  return `${index}-${uri}`;\n}; // default function for creating a group id\n\nconst groupID = (type, group, label) => {\n  return `placeholder-uri-${type}-${group}-${label}`;\n};\n/**\n * Parses a given m3u8 playlist\n *\n * @param {Function} [onwarn]\n *        a function to call when the parser triggers a warning event.\n * @param {Function} [oninfo]\n *        a function to call when the parser triggers an info event.\n * @param {string} manifestString\n *        The downloaded manifest string\n * @param {Object[]} [customTagParsers]\n *        An array of custom tag parsers for the m3u8-parser instance\n * @param {Object[]} [customTagMappers]\n *        An array of custom tag mappers for the m3u8-parser instance\n * @param {boolean} [llhls]\n *        Whether to keep ll-hls features in the manifest after parsing.\n * @return {Object}\n *         The manifest object\n */\n\nconst parseManifest = ({\n  onwarn,\n  oninfo,\n  manifestString,\n  customTagParsers = [],\n  customTagMappers = [],\n  llhls\n}) => {\n  const parser = new Parser();\n  if (onwarn) {\n    parser.on('warn', onwarn);\n  }\n  if (oninfo) {\n    parser.on('info', oninfo);\n  }\n  customTagParsers.forEach(customParser => parser.addParser(customParser));\n  customTagMappers.forEach(mapper => parser.addTagMapper(mapper));\n  parser.push(manifestString);\n  parser.end();\n  const manifest = parser.manifest; // remove llhls features from the parsed manifest\n  // if we don't want llhls support.\n\n  if (!llhls) {\n    ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {\n      if (manifest.hasOwnProperty(k)) {\n        delete manifest[k];\n      }\n    });\n    if (manifest.segments) {\n      manifest.segments.forEach(function (segment) {\n        ['parts', 'preloadHints'].forEach(function (k) {\n          if (segment.hasOwnProperty(k)) {\n            delete segment[k];\n          }\n        });\n      });\n    }\n  }\n  if (!manifest.targetDuration) {\n    let targetDuration = 10;\n    if (manifest.segments && manifest.segments.length) {\n      targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);\n    }\n    if (onwarn) {\n      onwarn({\n        message: `manifest has no targetDuration defaulting to ${targetDuration}`\n      });\n    }\n    manifest.targetDuration = targetDuration;\n  }\n  const parts = getLastParts(manifest);\n  if (parts.length && !manifest.partTargetDuration) {\n    const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);\n    if (onwarn) {\n      onwarn({\n        message: `manifest has no partTargetDuration defaulting to ${partTargetDuration}`\n      });\n      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.');\n    }\n    manifest.partTargetDuration = partTargetDuration;\n  }\n  return manifest;\n};\n/**\n * Loops through all supported media groups in main and calls the provided\n * callback for each group\n *\n * @param {Object} main\n *        The parsed main manifest object\n * @param {Function} callback\n *        Callback to call for each media group\n */\n\nconst forEachMediaGroup = (main, callback) => {\n  if (!main.mediaGroups) {\n    return;\n  }\n  ['AUDIO', 'SUBTITLES'].forEach(mediaType => {\n    if (!main.mediaGroups[mediaType]) {\n      return;\n    }\n    for (const groupKey in main.mediaGroups[mediaType]) {\n      for (const labelKey in main.mediaGroups[mediaType][groupKey]) {\n        const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];\n        callback(mediaProperties, mediaType, groupKey, labelKey);\n      }\n    }\n  });\n};\n/**\n * Adds properties and attributes to the playlist to keep consistent functionality for\n * playlists throughout VHS.\n *\n * @param {Object} config\n *        Arguments object\n * @param {Object} config.playlist\n *        The media playlist\n * @param {string} [config.uri]\n *        The uri to the media playlist (if media playlist is not from within a main\n *        playlist)\n * @param {string} id\n *        ID to use for the playlist\n */\n\nconst setupMediaPlaylist = ({\n  playlist,\n  uri,\n  id\n}) => {\n  playlist.id = id;\n  playlist.playlistErrors_ = 0;\n  if (uri) {\n    // For media playlists, m3u8-parser does not have access to a URI, as HLS media\n    // playlists do not contain their own source URI, but one is needed for consistency in\n    // VHS.\n    playlist.uri = uri;\n  } // For HLS main playlists, even though certain attributes MUST be defined, the\n  // stream may still be played without them.\n  // For HLS media playlists, m3u8-parser does not attach an attributes object to the\n  // manifest.\n  //\n  // To avoid undefined reference errors through the project, and make the code easier\n  // to write/read, add an empty attributes object for these cases.\n\n  playlist.attributes = playlist.attributes || {};\n};\n/**\n * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where\n * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to\n * playlist references to the playlists array.\n *\n * @param {Object} main\n *        The main playlist\n */\n\nconst setupMediaPlaylists = main => {\n  let i = main.playlists.length;\n  while (i--) {\n    const playlist = main.playlists[i];\n    setupMediaPlaylist({\n      playlist,\n      id: createPlaylistID(i, playlist.uri)\n    });\n    playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);\n    main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility\n\n    main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,\n    // the stream can be played without it. Although an attributes property may have been\n    // added to the playlist to prevent undefined references, issue a warning to fix the\n    // manifest.\n\n    if (!playlist.attributes.BANDWIDTH) {\n      log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');\n    }\n  }\n};\n/**\n * Adds resolvedUri properties to each media group.\n *\n * @param {Object} main\n *        The main playlist\n */\n\nconst resolveMediaGroupUris = main => {\n  forEachMediaGroup(main, properties => {\n    if (properties.uri) {\n      properties.resolvedUri = resolveUrl(main.uri, properties.uri);\n    }\n  });\n};\n/**\n * Creates a main playlist wrapper to insert a sole media playlist into.\n *\n * @param {Object} media\n *        Media playlist\n * @param {string} uri\n *        The media URI\n *\n * @return {Object}\n *         main playlist\n */\n\nconst mainForMedia = (media, uri) => {\n  const id = createPlaylistID(0, uri);\n  const main = {\n    mediaGroups: {\n      'AUDIO': {},\n      'VIDEO': {},\n      'CLOSED-CAPTIONS': {},\n      'SUBTITLES': {}\n    },\n    uri: window$1.location.href,\n    resolvedUri: window$1.location.href,\n    playlists: [{\n      uri,\n      id,\n      resolvedUri: uri,\n      // m3u8-parser does not attach an attributes property to media playlists so make\n      // sure that the property is attached to avoid undefined reference errors\n      attributes: {}\n    }]\n  }; // set up ID reference\n\n  main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility\n\n  main.playlists[uri] = main.playlists[0];\n  return main;\n};\n/**\n * Does an in-place update of the main manifest to add updated playlist URI references\n * as well as other properties needed by VHS that aren't included by the parser.\n *\n * @param {Object} main\n *        main manifest object\n * @param {string} uri\n *        The source URI\n * @param {function} createGroupID\n *        A function to determine how to create the groupID for mediaGroups\n */\n\nconst addPropertiesToMain = (main, uri, createGroupID = groupID) => {\n  main.uri = uri;\n  for (let i = 0; i < main.playlists.length; i++) {\n    if (!main.playlists[i].uri) {\n      // Set up phony URIs for the playlists since playlists are referenced by their URIs\n      // throughout VHS, but some formats (e.g., DASH) don't have external URIs\n      // TODO: consider adding dummy URIs in mpd-parser\n      const phonyUri = `placeholder-uri-${i}`;\n      main.playlists[i].uri = phonyUri;\n    }\n  }\n  const audioOnlyMain = isAudioOnly(main);\n  forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {\n    // add a playlist array under properties\n    if (!properties.playlists || !properties.playlists.length) {\n      // If the manifest is audio only and this media group does not have a uri, check\n      // if the media group is located in the main list of playlists. If it is, don't add\n      // placeholder properties as it shouldn't be considered an alternate audio track.\n      if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {\n        for (let i = 0; i < main.playlists.length; i++) {\n          const p = main.playlists[i];\n          if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {\n            return;\n          }\n        }\n      }\n      properties.playlists = [_extends({}, properties)];\n    }\n    properties.playlists.forEach(function (p, i) {\n      const groupId = createGroupID(mediaType, groupKey, labelKey, p);\n      const id = createPlaylistID(i, groupId);\n      if (p.uri) {\n        p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);\n      } else {\n        // DEPRECATED, this has been added to prevent a breaking change.\n        // previously we only ever had a single media group playlist, so\n        // we mark the first playlist uri without prepending the index as we used to\n        // ideally we would do all of the playlists the same way.\n        p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use\n        // the placeholder again\n\n        p.resolvedUri = p.uri;\n      }\n      p.id = p.id || id; // add an empty attributes object, all playlists are\n      // expected to have this.\n\n      p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)\n\n      main.playlists[p.id] = p;\n      main.playlists[p.uri] = p;\n    });\n  });\n  setupMediaPlaylists(main);\n  resolveMediaGroupUris(main);\n};\nclass DateRangesStorage {\n  constructor() {\n    this.offset_ = null;\n    this.pendingDateRanges_ = new Map();\n    this.processedDateRanges_ = new Map();\n  }\n  setOffset(segments = []) {\n    // already set\n    if (this.offset_ !== null) {\n      return;\n    } // no segment to process\n\n    if (!segments.length) {\n      return;\n    }\n    const [firstSegment] = segments; // no program date time\n\n    if (firstSegment.programDateTime === undefined) {\n      return;\n    } // Set offset as ProgramDateTime for the very first segment of the very first playlist load:\n\n    this.offset_ = firstSegment.programDateTime / 1000;\n  }\n  setPendingDateRanges(dateRanges = []) {\n    if (!dateRanges.length) {\n      return;\n    }\n    const [dateRange] = dateRanges;\n    const startTime = dateRange.startDate.getTime();\n    this.trimProcessedDateRanges_(startTime);\n    this.pendingDateRanges_ = dateRanges.reduce((map, pendingDateRange) => {\n      map.set(pendingDateRange.id, pendingDateRange);\n      return map;\n    }, new Map());\n  }\n  processDateRange(dateRange) {\n    this.pendingDateRanges_.delete(dateRange.id);\n    this.processedDateRanges_.set(dateRange.id, dateRange);\n  }\n  getDateRangesToProcess() {\n    if (this.offset_ === null) {\n      return [];\n    }\n    const dateRangeClasses = {};\n    const dateRangesToProcess = [];\n    this.pendingDateRanges_.forEach((dateRange, id) => {\n      if (this.processedDateRanges_.has(id)) {\n        return;\n      }\n      dateRange.startTime = dateRange.startDate.getTime() / 1000 - this.offset_;\n      dateRange.processDateRange = () => this.processDateRange(dateRange);\n      dateRangesToProcess.push(dateRange);\n      if (!dateRange.class) {\n        return;\n      }\n      if (dateRangeClasses[dateRange.class]) {\n        const length = dateRangeClasses[dateRange.class].push(dateRange);\n        dateRange.classListIndex = length - 1;\n      } else {\n        dateRangeClasses[dateRange.class] = [dateRange];\n        dateRange.classListIndex = 0;\n      }\n    });\n    for (const dateRange of dateRangesToProcess) {\n      const classList = dateRangeClasses[dateRange.class] || [];\n      if (dateRange.endDate) {\n        dateRange.endTime = dateRange.endDate.getTime() / 1000 - this.offset_;\n      } else if (dateRange.endOnNext && classList[dateRange.classListIndex + 1]) {\n        dateRange.endTime = classList[dateRange.classListIndex + 1].startTime;\n      } else if (dateRange.duration) {\n        dateRange.endTime = dateRange.startTime + dateRange.duration;\n      } else if (dateRange.plannedDuration) {\n        dateRange.endTime = dateRange.startTime + dateRange.plannedDuration;\n      } else {\n        dateRange.endTime = dateRange.startTime;\n      }\n    }\n    return dateRangesToProcess;\n  }\n  trimProcessedDateRanges_(startTime) {\n    const copy = new Map(this.processedDateRanges_);\n    copy.forEach((dateRange, id) => {\n      if (dateRange.startDate.getTime() < startTime) {\n        this.processedDateRanges_.delete(id);\n      }\n    });\n  }\n}\nconst QUOTA_EXCEEDED_ERR = 22;\nconst getStreamingNetworkErrorMetadata = ({\n  requestType,\n  request,\n  error,\n  parseFailure\n}) => {\n  const isBadStatus = request.status < 200 || request.status > 299;\n  const isFailure = request.status >= 400 && request.status <= 499;\n  const errorMetadata = {\n    uri: request.uri,\n    requestType\n  };\n  const isBadStatusOrParseFailure = isBadStatus && !isFailure || parseFailure;\n  if (error && isFailure) {\n    // copy original error and add to the metadata.\n    errorMetadata.error = _extends({}, error);\n    errorMetadata.errorType = videojs.Error.NetworkRequestFailed;\n  } else if (request.aborted) {\n    errorMetadata.errorType = videojs.Error.NetworkRequestAborted;\n  } else if (request.timedout) {\n    errorMetadata.errorType = videojs.Error.NetworkRequestTimeout;\n  } else if (isBadStatusOrParseFailure) {\n    const errorType = parseFailure ? videojs.Error.NetworkBodyParserFailed : videojs.Error.NetworkBadStatus;\n    errorMetadata.errorType = errorType;\n    errorMetadata.status = request.status;\n    errorMetadata.headers = request.headers;\n  }\n  return errorMetadata;\n};\n\n/**\n * @file - codecs.js - Handles tasks regarding codec strings such as translating them to\n * codec strings, or translating codec strings into objects that can be examined.\n */\nconst logFn$1 = logger('CodecUtils');\n/**\n * Returns a set of codec strings parsed from the playlist or the default\n * codec strings if no codecs were specified in the playlist\n *\n * @param {Playlist} media the current media playlist\n * @return {Object} an object with the video and audio codecs\n */\n\nconst getCodecs = function (media) {\n  // if the codecs were explicitly specified, use them instead of the\n  // defaults\n  const mediaAttributes = media.attributes || {};\n  if (mediaAttributes.CODECS) {\n    return parseCodecs(mediaAttributes.CODECS);\n  }\n};\nconst isMaat = (main, media) => {\n  const mediaAttributes = media.attributes || {};\n  return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];\n};\nconst isMuxed = (main, media) => {\n  if (!isMaat(main, media)) {\n    return true;\n  }\n  const mediaAttributes = media.attributes || {};\n  const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];\n  for (const groupId in audioGroup) {\n    // If an audio group has a URI (the case for HLS, as HLS will use external playlists),\n    // or there are listed playlists (the case for DASH, as the manifest will have already\n    // provided all of the details necessary to generate the audio playlist, as opposed to\n    // HLS' externally requested playlists), then the content is demuxed.\n    if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {\n      return true;\n    }\n  }\n  return false;\n};\nconst unwrapCodecList = function (codecList) {\n  const codecs = {};\n  codecList.forEach(({\n    mediaType,\n    type,\n    details\n  }) => {\n    codecs[mediaType] = codecs[mediaType] || [];\n    codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));\n  });\n  Object.keys(codecs).forEach(function (mediaType) {\n    if (codecs[mediaType].length > 1) {\n      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.`);\n      codecs[mediaType] = null;\n      return;\n    }\n    codecs[mediaType] = codecs[mediaType][0];\n  });\n  return codecs;\n};\nconst codecCount = function (codecObj) {\n  let count = 0;\n  if (codecObj.audio) {\n    count++;\n  }\n  if (codecObj.video) {\n    count++;\n  }\n  return count;\n};\n/**\n * Calculates the codec strings for a working configuration of\n * SourceBuffers to play variant streams in a main playlist. If\n * there is no possible working configuration, an empty object will be\n * returned.\n *\n * @param main {Object} the m3u8 object for the main playlist\n * @param media {Object} the m3u8 object for the variant playlist\n * @return {Object} the codec strings.\n *\n * @private\n */\n\nconst codecsForPlaylist = function (main, media) {\n  const mediaAttributes = media.attributes || {};\n  const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.\n  // Put another way, there is no way to have a video-only multiple-audio HLS!\n\n  if (isMaat(main, media) && !codecInfo.audio) {\n    if (!isMuxed(main, media)) {\n      // It is possible for codecs to be specified on the audio media group playlist but\n      // not on the rendition playlist. This is mostly the case for DASH, where audio and\n      // video are always separate (and separately specified).\n      const defaultCodecs = unwrapCodecList(codecsFromDefault(main, mediaAttributes.AUDIO) || []);\n      if (defaultCodecs.audio) {\n        codecInfo.audio = defaultCodecs.audio;\n      }\n    }\n  }\n  return codecInfo;\n};\nconst {\n  EventTarget: EventTarget$1\n} = videojs;\nconst addLLHLSQueryDirectives = (uri, media) => {\n  if (media.endList || !media.serverControl) {\n    return uri;\n  }\n  const parameters = {};\n  if (media.serverControl.canBlockReload) {\n    const {\n      preloadSegment\n    } = media; // next msn is a zero based value, length is not.\n\n    let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely\n    // that we are going to request a part of that preload segment.\n    // the logic below is used to determine that.\n\n    if (preloadSegment) {\n      const parts = preloadSegment.parts || []; // _HLS_part is a zero based index\n\n      const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the\n      // length of parts, then we know we had part preload hints\n      // and we need to add the _HLS_part= query\n\n      if (nextPart > -1 && nextPart !== parts.length - 1) {\n        // add existing parts to our preload hints\n        // eslint-disable-next-line\n        parameters._HLS_part = nextPart;\n      } // this if statement makes sure that we request the msn\n      // of the preload segment if:\n      // 1. the preload segment had parts (and was not yet a full segment)\n      //    but was added to our segments array\n      // 2. the preload segment had preload hints for parts that are not in\n      //    the manifest yet.\n      // in all other cases we want the segment after the preload segment\n      // which will be given by using media.segments.length because it is 1 based\n      // rather than 0 based.\n\n      if (nextPart > -1 || parts.length) {\n        nextMSN--;\n      }\n    } // add _HLS_msn= in front of any _HLS_part query\n    // eslint-disable-next-line\n\n    parameters._HLS_msn = nextMSN;\n  }\n  if (media.serverControl && media.serverControl.canSkipUntil) {\n    // add _HLS_skip= infront of all other queries.\n    // eslint-disable-next-line\n    parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';\n  }\n  if (Object.keys(parameters).length) {\n    const parsedUri = new window$1.URL(uri);\n    ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {\n      if (!parameters.hasOwnProperty(name)) {\n        return;\n      }\n      parsedUri.searchParams.set(name, parameters[name]);\n    });\n    uri = parsedUri.toString();\n  }\n  return uri;\n};\n/**\n * Returns a new segment object with properties and\n * the parts array merged.\n *\n * @param {Object} a the old segment\n * @param {Object} b the new segment\n *\n * @return {Object} the merged segment\n */\n\nconst updateSegment = (a, b) => {\n  if (!a) {\n    return b;\n  }\n  const result = merge(a, b); // if only the old segment has preload hints\n  // and the new one does not, remove preload hints.\n\n  if (a.preloadHints && !b.preloadHints) {\n    delete result.preloadHints;\n  } // if only the old segment has parts\n  // then the parts are no longer valid\n\n  if (a.parts && !b.parts) {\n    delete result.parts; // if both segments have parts\n    // copy part propeties from the old segment\n    // to the new one.\n  } else if (a.parts && b.parts) {\n    for (let i = 0; i < b.parts.length; i++) {\n      if (a.parts && a.parts[i]) {\n        result.parts[i] = merge(a.parts[i], b.parts[i]);\n      }\n    }\n  } // set skipped to false for segments that have\n  // have had information merged from the old segment.\n\n  if (!a.skipped && b.skipped) {\n    result.skipped = false;\n  } // set preload to false for segments that have\n  // had information added in the new segment.\n\n  if (a.preload && !b.preload) {\n    result.preload = false;\n  }\n  return result;\n};\n/**\n * Returns a new array of segments that is the result of merging\n * properties from an older list of segments onto an updated\n * list. No properties on the updated playlist will be ovewritten.\n *\n * @param {Array} original the outdated list of segments\n * @param {Array} update the updated list of segments\n * @param {number=} offset the index of the first update\n * segment in the original segment list. For non-live playlists,\n * this should always be zero and does not need to be\n * specified. For live playlists, it should be the difference\n * between the media sequence numbers in the original and updated\n * playlists.\n * @return {Array} a list of merged segment objects\n */\n\nconst updateSegments = (original, update, offset) => {\n  const oldSegments = original.slice();\n  const newSegments = update.slice();\n  offset = offset || 0;\n  const result = [];\n  let currentMap;\n  for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {\n    const oldSegment = oldSegments[newIndex + offset];\n    const newSegment = newSegments[newIndex];\n    if (oldSegment) {\n      currentMap = oldSegment.map || currentMap;\n      result.push(updateSegment(oldSegment, newSegment));\n    } else {\n      // carry over map to new segment if it is missing\n      if (currentMap && !newSegment.map) {\n        newSegment.map = currentMap;\n      }\n      result.push(newSegment);\n    }\n  }\n  return result;\n};\nconst resolveSegmentUris = (segment, baseUri) => {\n  // preloadSegment will not have a uri at all\n  // as the segment isn't actually in the manifest yet, only parts\n  if (!segment.resolvedUri && segment.uri) {\n    segment.resolvedUri = resolveUrl(baseUri, segment.uri);\n  }\n  if (segment.key && !segment.key.resolvedUri) {\n    segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);\n  }\n  if (segment.map && !segment.map.resolvedUri) {\n    segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);\n  }\n  if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {\n    segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);\n  }\n  if (segment.parts && segment.parts.length) {\n    segment.parts.forEach(p => {\n      if (p.resolvedUri) {\n        return;\n      }\n      p.resolvedUri = resolveUrl(baseUri, p.uri);\n    });\n  }\n  if (segment.preloadHints && segment.preloadHints.length) {\n    segment.preloadHints.forEach(p => {\n      if (p.resolvedUri) {\n        return;\n      }\n      p.resolvedUri = resolveUrl(baseUri, p.uri);\n    });\n  }\n};\nconst getAllSegments = function (media) {\n  const segments = media.segments || [];\n  const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently\n  // a usable segment, only include a preloadSegment that has\n  // parts.\n\n  if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {\n    // if preloadHints has a MAP that means that the\n    // init segment is going to change. We cannot use any of the parts\n    // from this preload segment.\n    if (preloadSegment.preloadHints) {\n      for (let i = 0; i < preloadSegment.preloadHints.length; i++) {\n        if (preloadSegment.preloadHints[i].type === 'MAP') {\n          return segments;\n        }\n      }\n    } // set the duration for our preload segment to target duration.\n\n    preloadSegment.duration = media.targetDuration;\n    preloadSegment.preload = true;\n    segments.push(preloadSegment);\n  }\n  return segments;\n}; // consider the playlist unchanged if the playlist object is the same or\n// the number of segments is equal, the media sequence number is unchanged,\n// and this playlist hasn't become the end of the playlist\n\nconst isPlaylistUnchanged = (a, b) => a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence && a.preloadSegment === b.preloadSegment;\n/**\n  * Returns a new main playlist that is the result of merging an\n  * updated media playlist into the original version. If the\n  * updated media playlist does not match any of the playlist\n  * entries in the original main playlist, null is returned.\n  *\n  * @param {Object} main a parsed main M3U8 object\n  * @param {Object} media a parsed media M3U8 object\n  * @return {Object} a new object that represents the original\n  * main playlist with the updated media playlist merged in, or\n  * null if the merge produced no change.\n  */\n\nconst updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {\n  const result = merge(main, {});\n  const oldMedia = result.playlists[newMedia.id];\n  if (!oldMedia) {\n    return null;\n  }\n  if (unchangedCheck(oldMedia, newMedia)) {\n    return null;\n  }\n  newMedia.segments = getAllSegments(newMedia);\n  const mergedPlaylist = merge(oldMedia, newMedia); // always use the new media's preload segment\n\n  if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {\n    delete mergedPlaylist.preloadSegment;\n  } // if the update could overlap existing segment information, merge the two segment lists\n\n  if (oldMedia.segments) {\n    if (newMedia.skip) {\n      newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge\n      // old properties into the new segments\n\n      for (let i = 0; i < newMedia.skip.skippedSegments; i++) {\n        newMedia.segments.unshift({\n          skipped: true\n        });\n      }\n    }\n    mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);\n  } // resolve any segment URIs to prevent us from having to do it later\n\n  mergedPlaylist.segments.forEach(segment => {\n    resolveSegmentUris(segment, mergedPlaylist.resolvedUri);\n  }); // TODO Right now in the playlists array there are two references to each playlist, one\n  // that is referenced by index, and one by URI. The index reference may no longer be\n  // necessary.\n\n  for (let i = 0; i < result.playlists.length; i++) {\n    if (result.playlists[i].id === newMedia.id) {\n      result.playlists[i] = mergedPlaylist;\n    }\n  }\n  result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility\n\n  result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.\n\n  forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {\n    if (!properties.playlists) {\n      return;\n    }\n    for (let i = 0; i < properties.playlists.length; i++) {\n      if (newMedia.id === properties.playlists[i].id) {\n        properties.playlists[i] = mergedPlaylist;\n      }\n    }\n  });\n  return result;\n};\n/**\n * Calculates the time to wait before refreshing a live playlist\n *\n * @param {Object} media\n *        The current media\n * @param {boolean} update\n *        True if there were any updates from the last refresh, false otherwise\n * @return {number}\n *         The time in ms to wait before refreshing the live playlist\n */\n\nconst refreshDelay = (media, update) => {\n  const segments = media.segments || [];\n  const lastSegment = segments[segments.length - 1];\n  const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];\n  const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;\n  if (update && lastDuration) {\n    return lastDuration * 1000;\n  } // if the playlist is unchanged since the last reload or last segment duration\n  // cannot be determined, try again after half the target duration\n\n  return (media.partTargetDuration || media.targetDuration || 10) * 500;\n};\nconst playlistMetadataPayload = (playlists, type, isLive) => {\n  if (!playlists) {\n    return;\n  }\n  const renditions = [];\n  playlists.forEach(playlist => {\n    // we need attributes to populate rendition data.\n    if (!playlist.attributes) {\n      return;\n    }\n    const {\n      BANDWIDTH,\n      RESOLUTION,\n      CODECS\n    } = playlist.attributes;\n    renditions.push({\n      id: playlist.id,\n      bandwidth: BANDWIDTH,\n      resolution: RESOLUTION,\n      codecs: CODECS\n    });\n  });\n  return {\n    type,\n    isLive,\n    renditions\n  };\n};\n/**\n * Load a playlist from a remote location\n *\n * @class PlaylistLoader\n * @extends Stream\n * @param {string|Object} src url or object of manifest\n * @param {boolean} withCredentials the withCredentials xhr option\n * @class\n */\n\nclass PlaylistLoader extends EventTarget$1 {\n  constructor(src, vhs, options = {}) {\n    super();\n    if (!src) {\n      throw new Error('A non-empty playlist URL or object is required');\n    }\n    this.logger_ = logger('PlaylistLoader');\n    const {\n      withCredentials = false\n    } = options;\n    this.src = src;\n    this.vhs_ = vhs;\n    this.withCredentials = withCredentials;\n    this.addDateRangesToTextTrack_ = options.addDateRangesToTextTrack;\n    const vhsOptions = vhs.options_;\n    this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];\n    this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];\n    this.llhls = vhsOptions && vhsOptions.llhls;\n    this.dateRangesStorage_ = new DateRangesStorage(); // initialize the loader state\n\n    this.state = 'HAVE_NOTHING'; // live playlist staleness timeout\n\n    this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);\n    this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);\n    this.on('loadedplaylist', this.handleLoadedPlaylist_.bind(this));\n  }\n  handleLoadedPlaylist_() {\n    const mediaPlaylist = this.media();\n    if (!mediaPlaylist) {\n      return;\n    }\n    this.dateRangesStorage_.setOffset(mediaPlaylist.segments);\n    this.dateRangesStorage_.setPendingDateRanges(mediaPlaylist.dateRanges);\n    const availableDateRanges = this.dateRangesStorage_.getDateRangesToProcess();\n    if (!availableDateRanges.length || !this.addDateRangesToTextTrack_) {\n      return;\n    }\n    this.addDateRangesToTextTrack_(availableDateRanges);\n  }\n  handleMediaupdatetimeout_() {\n    if (this.state !== 'HAVE_METADATA') {\n      // only refresh the media playlist if no other activity is going on\n      return;\n    }\n    const media = this.media();\n    let uri = resolveUrl(this.main.uri, media.uri);\n    if (this.llhls) {\n      uri = addLLHLSQueryDirectives(uri, media);\n    }\n    this.state = 'HAVE_CURRENT_METADATA';\n    this.request = this.vhs_.xhr({\n      uri,\n      withCredentials: this.withCredentials,\n      requestType: 'hls-playlist'\n    }, (error, req) => {\n      // disposed\n      if (!this.request) {\n        return;\n      }\n      if (error) {\n        return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');\n      }\n      this.haveMetadata({\n        playlistString: this.request.responseText,\n        url: this.media().uri,\n        id: this.media().id\n      });\n    });\n  }\n  playlistRequestError(xhr, playlist, startingState) {\n    const {\n      uri,\n      id\n    } = playlist; // any in-flight request is now finished\n\n    this.request = null;\n    if (startingState) {\n      this.state = startingState;\n    }\n    this.error = {\n      playlist: this.main.playlists[id],\n      status: xhr.status,\n      message: `HLS playlist request error at URL: ${uri}.`,\n      responseText: xhr.responseText,\n      code: xhr.status >= 500 ? 4 : 2,\n      metadata: getStreamingNetworkErrorMetadata({\n        requestType: xhr.requestType,\n        request: xhr,\n        error: xhr.error\n      })\n    };\n    this.trigger('error');\n  }\n  parseManifest_({\n    url,\n    manifestString\n  }) {\n    try {\n      const parsed = parseManifest({\n        onwarn: ({\n          message\n        }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),\n        oninfo: ({\n          message\n        }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),\n        manifestString,\n        customTagParsers: this.customTagParsers,\n        customTagMappers: this.customTagMappers,\n        llhls: this.llhls\n      });\n      /**\n       * VHS does not support switching between variants with and without audio and video\n       * so we want to filter out audio-only variants when variants with video and(or) audio are also detected.\n       */\n\n      if (!parsed.playlists || !parsed.playlists.length) {\n        return parsed;\n      }\n      this.excludeAudioOnlyVariants(parsed.playlists);\n      return parsed;\n    } catch (error) {\n      this.error = error;\n      this.error.metadata = {\n        errorType: videojs.Error.StreamingHlsPlaylistParserError,\n        error\n      };\n    }\n  }\n  excludeAudioOnlyVariants(playlists) {\n    // helper function\n    const hasVideo = playlist => {\n      const attributes = playlist.attributes || {};\n      const {\n        width,\n        height\n      } = attributes.RESOLUTION || {};\n      if (width && height) {\n        return true;\n      } // parse codecs string from playlist attributes\n\n      const codecsList = getCodecs(playlist) || []; // unwrap list\n\n      const codecsInfo = unwrapCodecList(codecsList);\n      return Boolean(codecsInfo.video);\n    };\n    if (playlists.some(hasVideo)) {\n      playlists.forEach(playlist => {\n        if (!hasVideo(playlist)) {\n          playlist.excludeUntil = Infinity;\n        }\n      });\n    }\n  }\n  /**\n   * Update the playlist loader's state in response to a new or updated playlist.\n   *\n   * @param {string} [playlistString]\n   *        Playlist string (if playlistObject is not provided)\n   * @param {Object} [playlistObject]\n   *        Playlist object (if playlistString is not provided)\n   * @param {string} url\n   *        URL of playlist\n   * @param {string} id\n   *        ID to use for playlist\n   */\n\n  haveMetadata({\n    playlistString,\n    playlistObject,\n    url,\n    id\n  }) {\n    // any in-flight request is now finished\n    this.request = null;\n    this.state = 'HAVE_METADATA';\n    const metadata = {\n      playlistInfo: {\n        type: 'media',\n        uri: url\n      }\n    };\n    this.trigger({\n      type: 'playlistparsestart',\n      metadata\n    });\n    const playlist = playlistObject || this.parseManifest_({\n      url,\n      manifestString: playlistString\n    });\n    playlist.lastRequest = Date.now();\n    setupMediaPlaylist({\n      playlist,\n      uri: url,\n      id\n    }); // merge this playlist into the main manifest\n\n    const update = updateMain$1(this.main, playlist);\n    this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;\n    this.pendingMedia_ = null;\n    if (update) {\n      this.main = update;\n      this.media_ = this.main.playlists[id];\n    } else {\n      this.trigger('playlistunchanged');\n    }\n    this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));\n    metadata.parsedPlaylist = playlistMetadataPayload(this.main.playlists, metadata.playlistInfo.type, !this.media_.endList);\n    this.trigger({\n      type: 'playlistparsecomplete',\n      metadata\n    });\n    this.trigger('loadedplaylist');\n  }\n  /**\n    * Abort any outstanding work and clean up.\n    */\n\n  dispose() {\n    this.trigger('dispose');\n    this.stopRequest();\n    window$1.clearTimeout(this.mediaUpdateTimeout);\n    window$1.clearTimeout(this.finalRenditionTimeout);\n    this.dateRangesStorage_ = new DateRangesStorage();\n    this.off();\n  }\n  stopRequest() {\n    if (this.request) {\n      const oldRequest = this.request;\n      this.request = null;\n      oldRequest.onreadystatechange = null;\n      oldRequest.abort();\n    }\n  }\n  /**\n    * When called without any arguments, returns the currently\n    * active media playlist. When called with a single argument,\n    * triggers the playlist loader to asynchronously switch to the\n    * specified media playlist. Calling this method while the\n    * loader is in the HAVE_NOTHING causes an error to be emitted\n    * but otherwise has no effect.\n    *\n    * @param {Object=} playlist the parsed media playlist\n    * object to switch to\n    * @param {boolean=} shouldDelay whether we should delay the request by half target duration\n    *\n    * @return {Playlist} the current loaded media\n    */\n\n  media(playlist, shouldDelay) {\n    // getter\n    if (!playlist) {\n      return this.media_;\n    } // setter\n\n    if (this.state === 'HAVE_NOTHING') {\n      throw new Error('Cannot switch media playlist from ' + this.state);\n    } // find the playlist object if the target playlist has been\n    // specified by URI\n\n    if (typeof playlist === 'string') {\n      if (!this.main.playlists[playlist]) {\n        throw new Error('Unknown playlist URI: ' + playlist);\n      }\n      playlist = this.main.playlists[playlist];\n    }\n    window$1.clearTimeout(this.finalRenditionTimeout);\n    if (shouldDelay) {\n      const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;\n      this.finalRenditionTimeout = window$1.setTimeout(this.media.bind(this, playlist, false), delay);\n      return;\n    }\n    const startingState = this.state;\n    const mediaChange = !this.media_ || playlist.id !== this.media_.id;\n    const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately\n\n    if (mainPlaylistRef && mainPlaylistRef.endList ||\n    // handle the case of a playlist object (e.g., if using vhs-json with a resolved\n    // media playlist or, for the case of demuxed audio, a resolved audio media group)\n    playlist.endList && playlist.segments.length) {\n      // abort outstanding playlist requests\n      if (this.request) {\n        this.request.onreadystatechange = null;\n        this.request.abort();\n        this.request = null;\n      }\n      this.state = 'HAVE_METADATA';\n      this.media_ = playlist; // trigger media change if the active media has been updated\n\n      if (mediaChange) {\n        this.trigger('mediachanging');\n        if (startingState === 'HAVE_MAIN_MANIFEST') {\n          // The initial playlist was a main manifest, and the first media selected was\n          // also provided (in the form of a resolved playlist object) as part of the\n          // source object (rather than just a URL). Therefore, since the media playlist\n          // doesn't need to be requested, loadedmetadata won't trigger as part of the\n          // normal flow, and needs an explicit trigger here.\n          this.trigger('loadedmetadata');\n        } else {\n          this.trigger('mediachange');\n        }\n      }\n      return;\n    } // We update/set the timeout here so that live playlists\n    // that are not a media change will \"start\" the loader as expected.\n    // We expect that this function will start the media update timeout\n    // cycle again. This also prevents a playlist switch failure from\n    // causing us to stall during live.\n\n    this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op\n\n    if (!mediaChange) {\n      return;\n    }\n    this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request\n\n    if (this.request) {\n      if (playlist.resolvedUri === this.request.url) {\n        // requesting to switch to the same playlist multiple times\n        // has no effect after the first\n        return;\n      }\n      this.request.onreadystatechange = null;\n      this.request.abort();\n      this.request = null;\n    } // request the new playlist\n\n    if (this.media_) {\n      this.trigger('mediachanging');\n    }\n    this.pendingMedia_ = playlist;\n    const metadata = {\n      playlistInfo: {\n        type: 'media',\n        uri: playlist.uri\n      }\n    };\n    this.trigger({\n      type: 'playlistrequeststart',\n      metadata\n    });\n    this.request = this.vhs_.xhr({\n      uri: playlist.resolvedUri,\n      withCredentials: this.withCredentials,\n      requestType: 'hls-playlist'\n    }, (error, req) => {\n      // disposed\n      if (!this.request) {\n        return;\n      }\n      playlist.lastRequest = Date.now();\n      playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);\n      if (error) {\n        return this.playlistRequestError(this.request, playlist, startingState);\n      }\n      this.trigger({\n        type: 'playlistrequestcomplete',\n        metadata\n      });\n      this.haveMetadata({\n        playlistString: req.responseText,\n        url: playlist.uri,\n        id: playlist.id\n      }); // fire loadedmetadata the first time a media playlist is loaded\n\n      if (startingState === 'HAVE_MAIN_MANIFEST') {\n        this.trigger('loadedmetadata');\n      } else {\n        this.trigger('mediachange');\n      }\n    });\n  }\n  /**\n   * pause loading of the playlist\n   */\n\n  pause() {\n    if (this.mediaUpdateTimeout) {\n      window$1.clearTimeout(this.mediaUpdateTimeout);\n      this.mediaUpdateTimeout = null;\n    }\n    this.stopRequest();\n    if (this.state === 'HAVE_NOTHING') {\n      // If we pause the loader before any data has been retrieved, its as if we never\n      // started, so reset to an unstarted state.\n      this.started = false;\n    } // Need to restore state now that no activity is happening\n\n    if (this.state === 'SWITCHING_MEDIA') {\n      // if the loader was in the process of switching media, it should either return to\n      // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media\n      // playlist yet. This is determined by the existence of loader.media_\n      if (this.media_) {\n        this.state = 'HAVE_METADATA';\n      } else {\n        this.state = 'HAVE_MAIN_MANIFEST';\n      }\n    } else if (this.state === 'HAVE_CURRENT_METADATA') {\n      this.state = 'HAVE_METADATA';\n    }\n  }\n  /**\n   * start loading of the playlist\n   */\n\n  load(shouldDelay) {\n    if (this.mediaUpdateTimeout) {\n      window$1.clearTimeout(this.mediaUpdateTimeout);\n      this.mediaUpdateTimeout = null;\n    }\n    const media = this.media();\n    if (shouldDelay) {\n      const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;\n      this.mediaUpdateTimeout = window$1.setTimeout(() => {\n        this.mediaUpdateTimeout = null;\n        this.load();\n      }, delay);\n      return;\n    }\n    if (!this.started) {\n      this.start();\n      return;\n    }\n    if (media && !media.endList) {\n      this.trigger('mediaupdatetimeout');\n    } else {\n      this.trigger('loadedplaylist');\n    }\n  }\n  updateMediaUpdateTimeout_(delay) {\n    if (this.mediaUpdateTimeout) {\n      window$1.clearTimeout(this.mediaUpdateTimeout);\n      this.mediaUpdateTimeout = null;\n    } // we only have use mediaupdatetimeout for live playlists.\n\n    if (!this.media() || this.media().endList) {\n      return;\n    }\n    this.mediaUpdateTimeout = window$1.setTimeout(() => {\n      this.mediaUpdateTimeout = null;\n      this.trigger('mediaupdatetimeout');\n      this.updateMediaUpdateTimeout_(delay);\n    }, delay);\n  }\n  /**\n   * start loading of the playlist\n   */\n\n  start() {\n    this.started = true;\n    if (typeof this.src === 'object') {\n      // in the case of an entirely constructed manifest object (meaning there's no actual\n      // manifest on a server), default the uri to the page's href\n      if (!this.src.uri) {\n        this.src.uri = window$1.location.href;\n      } // resolvedUri is added on internally after the initial request. Since there's no\n      // request for pre-resolved manifests, add on resolvedUri here.\n\n      this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first\n      // request can be skipped (since the top level of the manifest, at a minimum, is\n      // already available as a parsed manifest object). However, if the manifest object\n      // represents a main playlist, some media playlists may need to be resolved before\n      // the starting segment list is available. Therefore, go directly to setup of the\n      // initial playlist, and let the normal flow continue from there.\n      //\n      // Note that the call to setup is asynchronous, as other sections of VHS may assume\n      // that the first request is asynchronous.\n\n      setTimeout(() => {\n        this.setupInitialPlaylist(this.src);\n      }, 0);\n      return;\n    }\n    const metadata = {\n      playlistInfo: {\n        type: 'multivariant',\n        uri: this.src\n      }\n    };\n    this.trigger({\n      type: 'playlistrequeststart',\n      metadata\n    }); // request the specified URL\n\n    this.request = this.vhs_.xhr({\n      uri: this.src,\n      withCredentials: this.withCredentials,\n      requestType: 'hls-playlist'\n    }, (error, req) => {\n      // disposed\n      if (!this.request) {\n        return;\n      } // clear the loader's request reference\n\n      this.request = null;\n      if (error) {\n        this.error = {\n          status: req.status,\n          message: `HLS playlist request error at URL: ${this.src}.`,\n          responseText: req.responseText,\n          // MEDIA_ERR_NETWORK\n          code: 2,\n          metadata: getStreamingNetworkErrorMetadata({\n            requestType: req.requestType,\n            request: req,\n            error\n          })\n        };\n        if (this.state === 'HAVE_NOTHING') {\n          this.started = false;\n        }\n        return this.trigger('error');\n      }\n      this.trigger({\n        type: 'playlistrequestcomplete',\n        metadata\n      });\n      this.src = resolveManifestRedirect(this.src, req);\n      this.trigger({\n        type: 'playlistparsestart',\n        metadata\n      });\n      const manifest = this.parseManifest_({\n        manifestString: req.responseText,\n        url: this.src\n      }); // we haven't loaded any variant playlists here so we default to false for isLive.\n\n      metadata.parsedPlaylist = playlistMetadataPayload(manifest.playlists, metadata.playlistInfo.type, false);\n      this.trigger({\n        type: 'playlistparsecomplete',\n        metadata\n      });\n      this.setupInitialPlaylist(manifest);\n    });\n  }\n  srcUri() {\n    return typeof this.src === 'string' ? this.src : this.src.uri;\n  }\n  /**\n   * Given a manifest object that's either a main or media playlist, trigger the proper\n   * events and set the state of the playlist loader.\n   *\n   * If the manifest object represents a main playlist, `loadedplaylist` will be\n   * triggered to allow listeners to select a playlist. If none is selected, the loader\n   * will default to the first one in the playlists array.\n   *\n   * If the manifest object represents a media playlist, `loadedplaylist` will be\n   * triggered followed by `loadedmetadata`, as the only available playlist is loaded.\n   *\n   * In the case of a media playlist, a main playlist object wrapper with one playlist\n   * will be created so that all logic can handle playlists in the same fashion (as an\n   * assumed manifest object schema).\n   *\n   * @param {Object} manifest\n   *        The parsed manifest object\n   */\n\n  setupInitialPlaylist(manifest) {\n    this.state = 'HAVE_MAIN_MANIFEST';\n    if (manifest.playlists) {\n      this.main = manifest;\n      addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,\n      // then resolve URIs in advance, as they are usually done after a playlist request,\n      // which may not happen if the playlist is resolved.\n\n      manifest.playlists.forEach(playlist => {\n        playlist.segments = getAllSegments(playlist);\n        playlist.segments.forEach(segment => {\n          resolveSegmentUris(segment, playlist.resolvedUri);\n        });\n      });\n      this.trigger('loadedplaylist');\n      if (!this.request) {\n        // no media playlist was specifically selected so start\n        // from the first listed one\n        this.media(this.main.playlists[0]);\n      }\n      return;\n    } // In order to support media playlists passed in as vhs-json, the case where the uri\n    // is not provided as part of the manifest should be considered, and an appropriate\n    // default used.\n\n    const uri = this.srcUri() || window$1.location.href;\n    this.main = mainForMedia(manifest, uri);\n    this.haveMetadata({\n      playlistObject: manifest,\n      url: uri,\n      id: this.main.playlists[0].id\n    });\n    this.trigger('loadedmetadata');\n  }\n  /**\n   * Updates or deletes a preexisting pathway clone.\n   * Ensures that all playlists related to the old pathway clone are\n   * either updated or deleted.\n   *\n   * @param {Object} clone On update, the pathway clone object for the newly updated pathway clone.\n   *        On delete, the old pathway clone object to be deleted.\n   * @param {boolean} isUpdate True if the pathway is to be updated,\n   *        false if it is meant to be deleted.\n   */\n\n  updateOrDeleteClone(clone, isUpdate) {\n    const main = this.main;\n    const pathway = clone.ID;\n    let i = main.playlists.length; // Iterate backwards through the playlist so we can remove playlists if necessary.\n\n    while (i--) {\n      const p = main.playlists[i];\n      if (p.attributes['PATHWAY-ID'] === pathway) {\n        const oldPlaylistUri = p.resolvedUri;\n        const oldPlaylistId = p.id; // update the indexed playlist and add new playlists by ID and URI\n\n        if (isUpdate) {\n          const newPlaylistUri = this.createCloneURI_(p.resolvedUri, clone);\n          const newPlaylistId = createPlaylistID(pathway, newPlaylistUri);\n          const attributes = this.createCloneAttributes_(pathway, p.attributes);\n          const updatedPlaylist = this.createClonePlaylist_(p, newPlaylistId, clone, attributes);\n          main.playlists[i] = updatedPlaylist;\n          main.playlists[newPlaylistId] = updatedPlaylist;\n          main.playlists[newPlaylistUri] = updatedPlaylist;\n        } else {\n          // Remove the indexed playlist.\n          main.playlists.splice(i, 1);\n        } // Remove playlists by the old ID and URI.\n\n        delete main.playlists[oldPlaylistId];\n        delete main.playlists[oldPlaylistUri];\n      }\n    }\n    this.updateOrDeleteCloneMedia(clone, isUpdate);\n  }\n  /**\n   * Updates or deletes media data based on the pathway clone object.\n   * Due to the complexity of the media groups and playlists, in all cases\n   * we remove all of the old media groups and playlists.\n   * On updates, we then create new media groups and playlists based on the\n   * new pathway clone object.\n   *\n   * @param {Object} clone The pathway clone object for the newly updated pathway clone.\n   * @param {boolean} isUpdate True if the pathway is to be updated,\n   *        false if it is meant to be deleted.\n   */\n\n  updateOrDeleteCloneMedia(clone, isUpdate) {\n    const main = this.main;\n    const id = clone.ID;\n    ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(mediaType => {\n      if (!main.mediaGroups[mediaType] || !main.mediaGroups[mediaType][id]) {\n        return;\n      }\n      for (const groupKey in main.mediaGroups[mediaType]) {\n        // Remove all media playlists for the media group for this pathway clone.\n        if (groupKey === id) {\n          for (const labelKey in main.mediaGroups[mediaType][groupKey]) {\n            const oldMedia = main.mediaGroups[mediaType][groupKey][labelKey];\n            oldMedia.playlists.forEach((p, i) => {\n              const oldMediaPlaylist = main.playlists[p.id];\n              const oldPlaylistId = oldMediaPlaylist.id;\n              const oldPlaylistUri = oldMediaPlaylist.resolvedUri;\n              delete main.playlists[oldPlaylistId];\n              delete main.playlists[oldPlaylistUri];\n            });\n          } // Delete the old media group.\n\n          delete main.mediaGroups[mediaType][groupKey];\n        }\n      }\n    }); // Create the new media groups and playlists if there is an update.\n\n    if (isUpdate) {\n      this.createClonedMediaGroups_(clone);\n    }\n  }\n  /**\n   * Given a pathway clone object, clones all necessary playlists.\n   *\n   * @param {Object} clone The pathway clone object.\n   * @param {Object} basePlaylist The original playlist to clone from.\n   */\n\n  addClonePathway(clone, basePlaylist = {}) {\n    const main = this.main;\n    const index = main.playlists.length;\n    const uri = this.createCloneURI_(basePlaylist.resolvedUri, clone);\n    const playlistId = createPlaylistID(clone.ID, uri);\n    const attributes = this.createCloneAttributes_(clone.ID, basePlaylist.attributes);\n    const playlist = this.createClonePlaylist_(basePlaylist, playlistId, clone, attributes);\n    main.playlists[index] = playlist; // add playlist by ID and URI\n\n    main.playlists[playlistId] = playlist;\n    main.playlists[uri] = playlist;\n    this.createClonedMediaGroups_(clone);\n  }\n  /**\n   * Given a pathway clone object we create clones of all media.\n   * In this function, all necessary information and updated playlists\n   * are added to the `mediaGroup` object.\n   * Playlists are also added to the `playlists` array so the media groups\n   * will be properly linked.\n   *\n   * @param {Object} clone The pathway clone object.\n   */\n\n  createClonedMediaGroups_(clone) {\n    const id = clone.ID;\n    const baseID = clone['BASE-ID'];\n    const main = this.main;\n    ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(mediaType => {\n      // If the media type doesn't exist, or there is already a clone, skip\n      // to the next media type.\n      if (!main.mediaGroups[mediaType] || main.mediaGroups[mediaType][id]) {\n        return;\n      }\n      for (const groupKey in main.mediaGroups[mediaType]) {\n        if (groupKey === baseID) {\n          // Create the group.\n          main.mediaGroups[mediaType][id] = {};\n        } else {\n          // There is no need to iterate over label keys in this case.\n          continue;\n        }\n        for (const labelKey in main.mediaGroups[mediaType][groupKey]) {\n          const oldMedia = main.mediaGroups[mediaType][groupKey][labelKey];\n          main.mediaGroups[mediaType][id][labelKey] = _extends({}, oldMedia);\n          const newMedia = main.mediaGroups[mediaType][id][labelKey]; // update URIs on the media\n\n          const newUri = this.createCloneURI_(oldMedia.resolvedUri, clone);\n          newMedia.resolvedUri = newUri;\n          newMedia.uri = newUri; // Reset playlists in the new media group.\n\n          newMedia.playlists = []; // Create new playlists in the newly cloned media group.\n\n          oldMedia.playlists.forEach((p, i) => {\n            const oldMediaPlaylist = main.playlists[p.id];\n            const group = groupID(mediaType, id, labelKey);\n            const newPlaylistID = createPlaylistID(id, group); // Check to see if it already exists\n\n            if (oldMediaPlaylist && !main.playlists[newPlaylistID]) {\n              const newMediaPlaylist = this.createClonePlaylist_(oldMediaPlaylist, newPlaylistID, clone);\n              const newPlaylistUri = newMediaPlaylist.resolvedUri;\n              main.playlists[newPlaylistID] = newMediaPlaylist;\n              main.playlists[newPlaylistUri] = newMediaPlaylist;\n            }\n            newMedia.playlists[i] = this.createClonePlaylist_(p, newPlaylistID, clone);\n          });\n        }\n      }\n    });\n  }\n  /**\n   * Using the original playlist to be cloned, and the pathway clone object\n   * information, we create a new playlist.\n   *\n   * @param {Object} basePlaylist  The original playlist to be cloned from.\n   * @param {string} id The desired id of the newly cloned playlist.\n   * @param {Object} clone The pathway clone object.\n   * @param {Object} attributes An optional object to populate the `attributes` property in the playlist.\n   *\n   * @return {Object} The combined cloned playlist.\n   */\n\n  createClonePlaylist_(basePlaylist, id, clone, attributes) {\n    const uri = this.createCloneURI_(basePlaylist.resolvedUri, clone);\n    const newProps = {\n      resolvedUri: uri,\n      uri,\n      id\n    }; // Remove all segments from previous playlist in the clone.\n\n    if (basePlaylist.segments) {\n      newProps.segments = [];\n    }\n    if (attributes) {\n      newProps.attributes = attributes;\n    }\n    return merge(basePlaylist, newProps);\n  }\n  /**\n   * Generates an updated URI for a cloned pathway based on the original\n   * pathway's URI and the paramaters from the pathway clone object in the\n   * content steering server response.\n   *\n   * @param {string} baseUri URI to be updated in the cloned pathway.\n   * @param {Object} clone The pathway clone object.\n   *\n   * @return {string} The updated URI for the cloned pathway.\n   */\n\n  createCloneURI_(baseURI, clone) {\n    const uri = new URL(baseURI);\n    uri.hostname = clone['URI-REPLACEMENT'].HOST;\n    const params = clone['URI-REPLACEMENT'].PARAMS; // Add params to the cloned URL.\n\n    for (const key of Object.keys(params)) {\n      uri.searchParams.set(key, params[key]);\n    }\n    return uri.href;\n  }\n  /**\n   * Helper function to create the attributes needed for the new clone.\n   * This mainly adds the necessary media attributes.\n   *\n   * @param {string} id The pathway clone object ID.\n   * @param {Object} oldAttributes The old attributes to compare to.\n   * @return {Object} The new attributes to add to the playlist.\n   */\n\n  createCloneAttributes_(id, oldAttributes) {\n    const attributes = {\n      ['PATHWAY-ID']: id\n    };\n    ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(mediaType => {\n      if (oldAttributes[mediaType]) {\n        attributes[mediaType] = id;\n      }\n    });\n    return attributes;\n  }\n  /**\n   * Returns the key ID set from a playlist\n   *\n   * @param {playlist} playlist to fetch the key ID set from.\n   * @return a Set of 32 digit hex strings that represent the unique keyIds for that playlist.\n   */\n\n  getKeyIdSet(playlist) {\n    const keyIds = new Set();\n    if (!playlist || !playlist.contentProtection) {\n      return keyIds;\n    }\n    for (const keysystem in playlist.contentProtection) {\n      if (playlist.contentProtection[keysystem] && playlist.contentProtection[keysystem].attributes && playlist.contentProtection[keysystem].attributes.keyId) {\n        const keyId = playlist.contentProtection[keysystem].attributes.keyId;\n        keyIds.add(keyId.toLowerCase());\n      }\n    }\n    return keyIds;\n  }\n}\n\n/**\n * @file xhr.js\n */\n\nconst callbackWrapper = function (request, error, response, callback) {\n  const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;\n  if (!error && reqResponse) {\n    request.responseTime = Date.now();\n    request.roundTripTime = request.responseTime - request.requestTime;\n    request.bytesReceived = reqResponse.byteLength || reqResponse.length;\n    if (!request.bandwidth) {\n      request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);\n    }\n  }\n  if (response.headers) {\n    request.responseHeaders = response.headers;\n  } // videojs.xhr now uses a specific code on the error\n  // object to signal that a request has timed out instead\n  // of setting a boolean on the request object\n\n  if (error && error.code === 'ETIMEDOUT') {\n    request.timedout = true;\n  } // videojs.xhr no longer considers status codes outside of 200 and 0\n  // (for file uris) to be errors, but the old XHR did, so emulate that\n  // behavior. Status 206 may be used in response to byterange requests.\n\n  if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {\n    error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));\n  }\n  callback(error, request);\n};\n/**\n * Iterates over the request hooks Set and calls them in order\n *\n * @param {Set} hooks the hook Set to iterate over\n * @param {Object} options the request options to pass to the xhr wrapper\n * @return the callback hook function return value, the modified or new options Object.\n */\n\nconst callAllRequestHooks = (requestSet, options) => {\n  if (!requestSet || !requestSet.size) {\n    return;\n  }\n  let newOptions = options;\n  requestSet.forEach(requestCallback => {\n    newOptions = requestCallback(newOptions);\n  });\n  return newOptions;\n};\n/**\n * Iterates over the response hooks Set and calls them in order.\n *\n * @param {Set} hooks the hook Set to iterate over\n * @param {Object} request the xhr request object\n * @param {Object} error the xhr error object\n * @param {Object} response the xhr response object\n */\n\nconst callAllResponseHooks = (responseSet, request, error, response) => {\n  if (!responseSet || !responseSet.size) {\n    return;\n  }\n  responseSet.forEach(responseCallback => {\n    responseCallback(request, error, response);\n  });\n};\nconst xhrFactory = function () {\n  const xhr = function XhrFunction(options, callback) {\n    // Add a default timeout\n    options = merge({\n      timeout: 45e3\n    }, options); // Allow an optional user-specified function to modify the option\n    // object before we construct the xhr request\n    // TODO: Remove beforeRequest in the next major release.\n\n    const beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest; // onRequest and onResponse hooks as a Set, at either the player or global level.\n    // TODO: new Set added here for beforeRequest alias. Remove this when beforeRequest is removed.\n\n    const _requestCallbackSet = XhrFunction._requestCallbackSet || videojs.Vhs.xhr._requestCallbackSet || new Set();\n    const _responseCallbackSet = XhrFunction._responseCallbackSet || videojs.Vhs.xhr._responseCallbackSet;\n    if (beforeRequest && typeof beforeRequest === 'function') {\n      videojs.log.warn('beforeRequest is deprecated, use onRequest instead.');\n      _requestCallbackSet.add(beforeRequest);\n    } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden\n    // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11\n\n    const xhrMethod = videojs.Vhs.xhr.original === true ? videojs.xhr : videojs.Vhs.xhr; // call all registered onRequest hooks, assign new options.\n\n    const beforeRequestOptions = callAllRequestHooks(_requestCallbackSet, options); // Remove the beforeRequest function from the hooks set so stale beforeRequest functions are not called.\n\n    _requestCallbackSet.delete(beforeRequest); // xhrMethod will call XMLHttpRequest.open and XMLHttpRequest.send\n\n    const request = xhrMethod(beforeRequestOptions || options, function (error, response) {\n      // call all registered onResponse hooks\n      callAllResponseHooks(_responseCallbackSet, request, error, response);\n      return callbackWrapper(request, error, response, callback);\n    });\n    const originalAbort = request.abort;\n    request.abort = function () {\n      request.aborted = true;\n      return originalAbort.apply(request, arguments);\n    };\n    request.uri = options.uri;\n    request.requestType = options.requestType;\n    request.requestTime = Date.now();\n    return request;\n  };\n  xhr.original = true;\n  return xhr;\n};\n/**\n * Turns segment byterange into a string suitable for use in\n * HTTP Range requests\n *\n * @param {Object} byterange - an object with two values defining the start and end\n *                             of a byte-range\n */\n\nconst byterangeStr = function (byterange) {\n  // `byterangeEnd` is one less than `offset + length` because the HTTP range\n  // header uses inclusive ranges\n  let byterangeEnd;\n  const byterangeStart = byterange.offset;\n  if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {\n    byterangeEnd = window$1.BigInt(byterange.offset) + window$1.BigInt(byterange.length) - window$1.BigInt(1);\n  } else {\n    byterangeEnd = byterange.offset + byterange.length - 1;\n  }\n  return 'bytes=' + byterangeStart + '-' + byterangeEnd;\n};\n/**\n * Defines headers for use in the xhr request for a particular segment.\n *\n * @param {Object} segment - a simplified copy of the segmentInfo object\n *                           from SegmentLoader\n */\n\nconst segmentXhrHeaders = function (segment) {\n  const headers = {};\n  if (segment.byterange) {\n    headers.Range = byterangeStr(segment.byterange);\n  }\n  return headers;\n};\n\n/**\n * @file bin-utils.js\n */\n\n/**\n * convert a TimeRange to text\n *\n * @param {TimeRange} range the timerange to use for conversion\n * @param {number} i the iterator on the range to convert\n * @return {string} the range in string format\n */\n\nconst textRange = function (range, i) {\n  return range.start(i) + '-' + range.end(i);\n};\n/**\n * format a number as hex string\n *\n * @param {number} e The number\n * @param {number} i the iterator\n * @return {string} the hex formatted number as a string\n */\n\nconst formatHexString = function (e, i) {\n  const value = e.toString(16);\n  return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');\n};\nconst formatAsciiString = function (e) {\n  if (e >= 0x20 && e < 0x7e) {\n    return String.fromCharCode(e);\n  }\n  return '.';\n};\n/**\n * Creates an object for sending to a web worker modifying properties that are TypedArrays\n * into a new object with seperated properties for the buffer, byteOffset, and byteLength.\n *\n * @param {Object} message\n *        Object of properties and values to send to the web worker\n * @return {Object}\n *         Modified message with TypedArray values expanded\n * @function createTransferableMessage\n */\n\nconst createTransferableMessage = function (message) {\n  const transferable = {};\n  Object.keys(message).forEach(key => {\n    const value = message[key];\n    if (isArrayBufferView(value)) {\n      transferable[key] = {\n        bytes: value.buffer,\n        byteOffset: value.byteOffset,\n        byteLength: value.byteLength\n      };\n    } else {\n      transferable[key] = value;\n    }\n  });\n  return transferable;\n};\n/**\n * Returns a unique string identifier for a media initialization\n * segment.\n *\n * @param {Object} initSegment\n *        the init segment object.\n *\n * @return {string} the generated init segment id\n */\n\nconst initSegmentId = function (initSegment) {\n  const byterange = initSegment.byterange || {\n    length: Infinity,\n    offset: 0\n  };\n  return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');\n};\n/**\n * Returns a unique string identifier for a media segment key.\n *\n * @param {Object} key the encryption key\n * @return {string} the unique id for the media segment key.\n */\n\nconst segmentKeyId = function (key) {\n  return key.resolvedUri;\n};\n/**\n * utils to help dump binary data to the console\n *\n * @param {Array|TypedArray} data\n *        data to dump to a string\n *\n * @return {string} the data as a hex string.\n */\n\nconst hexDump = data => {\n  const bytes = Array.prototype.slice.call(data);\n  const step = 16;\n  let result = '';\n  let hex;\n  let ascii;\n  for (let j = 0; j < bytes.length / step; j++) {\n    hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');\n    ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');\n    result += hex + ' ' + ascii + '\\n';\n  }\n  return result;\n};\nconst tagDump = ({\n  bytes\n}) => hexDump(bytes);\nconst textRanges = ranges => {\n  let result = '';\n  let i;\n  for (i = 0; i < ranges.length; i++) {\n    result += textRange(ranges, i) + ' ';\n  }\n  return result;\n};\nvar utils = /*#__PURE__*/Object.freeze({\n  __proto__: null,\n  createTransferableMessage: createTransferableMessage,\n  initSegmentId: initSegmentId,\n  segmentKeyId: segmentKeyId,\n  hexDump: hexDump,\n  tagDump: tagDump,\n  textRanges: textRanges\n});\n\n// TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux\n// 25% was arbitrarily chosen, and may need to be refined over time.\n\nconst SEGMENT_END_FUDGE_PERCENT = 0.25;\n/**\n * Converts a player time (any time that can be gotten/set from player.currentTime(),\n * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a\n * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).\n *\n * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an \"anchor\n * point\" (a point where we have a mapping from program time to player time, with player\n * time being the post transmux start of the segment).\n *\n * For more details, see [this doc](../../docs/program-time-from-player-time.md).\n *\n * @param {number} playerTime the player time\n * @param {Object} segment the segment which contains the player time\n * @return {Date} program time\n */\n\nconst playerTimeToProgramTime = (playerTime, segment) => {\n  if (!segment.dateTimeObject) {\n    // Can't convert without an \"anchor point\" for the program time (i.e., a time that can\n    // be used to map the start of a segment with a real world time).\n    return null;\n  }\n  const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;\n  const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended\n\n  const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;\n  const offsetFromSegmentStart = playerTime - startOfSegment;\n  return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);\n};\nconst originalSegmentVideoDuration = videoTimingInfo => {\n  return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;\n};\n/**\n * Finds a segment that contains the time requested given as an ISO-8601 string. The\n * returned segment might be an estimate or an accurate match.\n *\n * @param {string} programTime The ISO-8601 programTime to find a match for\n * @param {Object} playlist A playlist object to search within\n */\n\nconst findSegmentForProgramTime = (programTime, playlist) => {\n  // Assumptions:\n  //  - verifyProgramDateTimeTags has already been run\n  //  - live streams have been started\n  let dateTimeObject;\n  try {\n    dateTimeObject = new Date(programTime);\n  } catch (e) {\n    return null;\n  }\n  if (!playlist || !playlist.segments || playlist.segments.length === 0) {\n    return null;\n  }\n  let segment = playlist.segments[0];\n  if (dateTimeObject < new Date(segment.dateTimeObject)) {\n    // Requested time is before stream start.\n    return null;\n  }\n  for (let i = 0; i < playlist.segments.length - 1; i++) {\n    segment = playlist.segments[i];\n    const nextSegmentStart = new Date(playlist.segments[i + 1].dateTimeObject);\n    if (dateTimeObject < nextSegmentStart) {\n      break;\n    }\n  }\n  const lastSegment = playlist.segments[playlist.segments.length - 1];\n  const lastSegmentStart = lastSegment.dateTimeObject;\n  const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;\n  const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);\n  if (dateTimeObject > lastSegmentEnd) {\n    // Beyond the end of the stream, or our best guess of the end of the stream.\n    return null;\n  }\n  if (dateTimeObject > new Date(lastSegmentStart)) {\n    segment = lastSegment;\n  }\n  return {\n    segment,\n    estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),\n    // Although, given that all segments have accurate date time objects, the segment\n    // selected should be accurate, unless the video has been transmuxed at some point\n    // (determined by the presence of the videoTimingInfo object), the segment's \"player\n    // time\" (the start time in the player) can't be considered accurate.\n    type: segment.videoTimingInfo ? 'accurate' : 'estimate'\n  };\n};\n/**\n * Finds a segment that contains the given player time(in seconds).\n *\n * @param {number} time The player time to find a match for\n * @param {Object} playlist A playlist object to search within\n */\n\nconst findSegmentForPlayerTime = (time, playlist) => {\n  // Assumptions:\n  // - there will always be a segment.duration\n  // - we can start from zero\n  // - segments are in time order\n  if (!playlist || !playlist.segments || playlist.segments.length === 0) {\n    return null;\n  }\n  let segmentEnd = 0;\n  let segment;\n  for (let i = 0; i < playlist.segments.length; i++) {\n    segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and\n    // should contain the most accurate values we have for the segment's player times.\n    //\n    // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall\n    // back to an estimate based on the manifest derived (inaccurate) segment.duration, to\n    // calculate an end value.\n\n    segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;\n    if (time <= segmentEnd) {\n      break;\n    }\n  }\n  const lastSegment = playlist.segments[playlist.segments.length - 1];\n  if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {\n    // The time requested is beyond the stream end.\n    return null;\n  }\n  if (time > segmentEnd) {\n    // The time is within or beyond the last segment.\n    //\n    // Check to see if the time is beyond a reasonable guess of the end of the stream.\n    if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {\n      // Technically, because the duration value is only an estimate, the time may still\n      // exist in the last segment, however, there isn't enough information to make even\n      // a reasonable estimate.\n      return null;\n    }\n    segment = lastSegment;\n  }\n  return {\n    segment,\n    estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,\n    // Because videoTimingInfo is only set after transmux, it is the only way to get\n    // accurate timing values.\n    type: segment.videoTimingInfo ? 'accurate' : 'estimate'\n  };\n};\n/**\n * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.\n * If the offset returned is positive, the programTime occurs after the\n * comparisonTimestamp.\n * If the offset is negative, the programTime occurs before the comparisonTimestamp.\n *\n * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against\n * @param {string} programTime The programTime as an ISO-8601 string\n * @return {number} offset\n */\n\nconst getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {\n  let segmentDateTime;\n  let programDateTime;\n  try {\n    segmentDateTime = new Date(comparisonTimeStamp);\n    programDateTime = new Date(programTime);\n  } catch (e) {// TODO handle error\n  }\n  const segmentTimeEpoch = segmentDateTime.getTime();\n  const programTimeEpoch = programDateTime.getTime();\n  return (programTimeEpoch - segmentTimeEpoch) / 1000;\n};\n/**\n * Checks that all segments in this playlist have programDateTime tags.\n *\n * @param {Object} playlist A playlist object\n */\n\nconst verifyProgramDateTimeTags = playlist => {\n  if (!playlist.segments || playlist.segments.length === 0) {\n    return false;\n  }\n  for (let i = 0; i < playlist.segments.length; i++) {\n    const segment = playlist.segments[i];\n    if (!segment.dateTimeObject) {\n      return false;\n    }\n  }\n  return true;\n};\n/**\n * Returns the programTime of the media given a playlist and a playerTime.\n * The playlist must have programDateTime tags for a programDateTime tag to be returned.\n * If the segments containing the time requested have not been buffered yet, an estimate\n * may be returned to the callback.\n *\n * @param {Object} args\n * @param {Object} args.playlist A playlist object to search within\n * @param {number} time A playerTime in seconds\n * @param {Function} callback(err, programTime)\n * @return {string} err.message A detailed error message\n * @return {Object} programTime\n * @return {number} programTime.mediaSeconds The streamTime in seconds\n * @return {string} programTime.programDateTime The programTime as an ISO-8601 String\n */\n\nconst getProgramTime = ({\n  playlist,\n  time = undefined,\n  callback\n}) => {\n  if (!callback) {\n    throw new Error('getProgramTime: callback must be provided');\n  }\n  if (!playlist || time === undefined) {\n    return callback({\n      message: 'getProgramTime: playlist and time must be provided'\n    });\n  }\n  const matchedSegment = findSegmentForPlayerTime(time, playlist);\n  if (!matchedSegment) {\n    return callback({\n      message: 'valid programTime was not found'\n    });\n  }\n  if (matchedSegment.type === 'estimate') {\n    return callback({\n      message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',\n      seekTime: matchedSegment.estimatedStart\n    });\n  }\n  const programTimeObject = {\n    mediaSeconds: time\n  };\n  const programTime = playerTimeToProgramTime(time, matchedSegment.segment);\n  if (programTime) {\n    programTimeObject.programDateTime = programTime.toISOString();\n  }\n  return callback(null, programTimeObject);\n};\n/**\n * Seeks in the player to a time that matches the given programTime ISO-8601 string.\n *\n * @param {Object} args\n * @param {string} args.programTime A programTime to seek to as an ISO-8601 String\n * @param {Object} args.playlist A playlist to look within\n * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.\n * @param {Function} args.seekTo A method to perform a seek\n * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.\n * @param {Object} args.tech The tech to seek on\n * @param {Function} args.callback(err, newTime) A callback to return the new time to\n * @return {string} err.message A detailed error message\n * @return {number} newTime The exact time that was seeked to in seconds\n */\n\nconst seekToProgramTime = ({\n  programTime,\n  playlist,\n  retryCount = 2,\n  seekTo,\n  pauseAfterSeek = true,\n  tech,\n  callback\n}) => {\n  if (!callback) {\n    throw new Error('seekToProgramTime: callback must be provided');\n  }\n  if (typeof programTime === 'undefined' || !playlist || !seekTo) {\n    return callback({\n      message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'\n    });\n  }\n  if (!playlist.endList && !tech.hasStarted_) {\n    return callback({\n      message: 'player must be playing a live stream to start buffering'\n    });\n  }\n  if (!verifyProgramDateTimeTags(playlist)) {\n    return callback({\n      message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri\n    });\n  }\n  const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match\n\n  if (!matchedSegment) {\n    return callback({\n      message: `${programTime} was not found in the stream`\n    });\n  }\n  const segment = matchedSegment.segment;\n  const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);\n  if (matchedSegment.type === 'estimate') {\n    // we've run out of retries\n    if (retryCount === 0) {\n      return callback({\n        message: `${programTime} is not buffered yet. Try again`\n      });\n    }\n    seekTo(matchedSegment.estimatedStart + mediaOffset);\n    tech.one('seeked', () => {\n      seekToProgramTime({\n        programTime,\n        playlist,\n        retryCount: retryCount - 1,\n        seekTo,\n        pauseAfterSeek,\n        tech,\n        callback\n      });\n    });\n    return;\n  } // Since the segment.start value is determined from the buffered end or ending time\n  // of the prior segment, the seekToTime doesn't need to account for any transmuxer\n  // modifications.\n\n  const seekToTime = segment.start + mediaOffset;\n  const seekedCallback = () => {\n    return callback(null, tech.currentTime());\n  }; // listen for seeked event\n\n  tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state\n\n  if (pauseAfterSeek) {\n    tech.pause();\n  }\n  seekTo(seekToTime);\n};\n\n// which will only happen if the request is complete.\n\nconst callbackOnCompleted = (request, cb) => {\n  if (request.readyState === 4) {\n    return cb();\n  }\n  return;\n};\nconst containerRequest = (uri, xhr, cb, requestType) => {\n  let bytes = [];\n  let id3Offset;\n  let finished = false;\n  const endRequestAndCallback = function (err, req, type, _bytes) {\n    req.abort();\n    finished = true;\n    return cb(err, req, type, _bytes);\n  };\n  const progressListener = function (error, request) {\n    if (finished) {\n      return;\n    }\n    if (error) {\n      error.metadata = getStreamingNetworkErrorMetadata({\n        requestType,\n        request,\n        error\n      });\n      return endRequestAndCallback(error, request, '', bytes);\n    } // grap the new part of content that was just downloaded\n\n    const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes\n\n    bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));\n    id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type\n    // or we need at least two bytes after an id3Offset\n\n    if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {\n      return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));\n    }\n    const type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data\n    // to see the second sync byte, wait until we have enough data\n    // before declaring it ts\n\n    if (type === 'ts' && bytes.length < 188) {\n      return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));\n    } // this may be an unsynced ts segment\n    // wait for 376 bytes before detecting no container\n\n    if (!type && bytes.length < 376) {\n      return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));\n    }\n    return endRequestAndCallback(null, request, type, bytes);\n  };\n  const options = {\n    uri,\n    beforeSend(request) {\n      // this forces the browser to pass the bytes to us unprocessed\n      request.overrideMimeType('text/plain; charset=x-user-defined');\n      request.addEventListener('progress', function ({\n        total,\n        loaded\n      }) {\n        return callbackWrapper(request, null, {\n          statusCode: request.status\n        }, progressListener);\n      });\n    }\n  };\n  const request = xhr(options, function (error, response) {\n    return callbackWrapper(request, error, response, progressListener);\n  });\n  return request;\n};\nconst {\n  EventTarget\n} = videojs;\nconst dashPlaylistUnchanged = function (a, b) {\n  if (!isPlaylistUnchanged(a, b)) {\n    return false;\n  } // for dash the above check will often return true in scenarios where\n  // the playlist actually has changed because mediaSequence isn't a\n  // dash thing, and we often set it to 1. So if the playlists have the same amount\n  // of segments we return true.\n  // So for dash we need to make sure that the underlying segments are different.\n  // if sidx changed then the playlists are different.\n\n  if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {\n    return false;\n  } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {\n    return false;\n  } // one or the other does not have segments\n  // there was a change.\n\n  if (a.segments && !b.segments || !a.segments && b.segments) {\n    return false;\n  } // neither has segments nothing changed\n\n  if (!a.segments && !b.segments) {\n    return true;\n  } // check segments themselves\n\n  for (let i = 0; i < a.segments.length; i++) {\n    const aSegment = a.segments[i];\n    const bSegment = b.segments[i]; // if uris are different between segments there was a change\n\n    if (aSegment.uri !== bSegment.uri) {\n      return false;\n    } // neither segment has a byterange, there will be no byterange change.\n\n    if (!aSegment.byterange && !bSegment.byterange) {\n      continue;\n    }\n    const aByterange = aSegment.byterange;\n    const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.\n\n    if (aByterange && !bByterange || !aByterange && bByterange) {\n      return false;\n    } // if both segments have byterange with different offsets, there was a change.\n\n    if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {\n      return false;\n    }\n  } // if everything was the same with segments, this is the same playlist.\n\n  return true;\n};\n/**\n * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation\n * ID in the parser. This allows for continuous playout across periods with the same representation IDs\n * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support\n * periods without continuous playback this function may need modification as well as the parser.\n */\n\nconst dashGroupId = (type, group, label, playlist) => {\n  // If the manifest somehow does not have an ID (non-dash compliant), use the label.\n  const playlistId = playlist.attributes.NAME || label;\n  return `placeholder-uri-${type}-${group}-${playlistId}`;\n};\n/**\n * Parses the main XML string and updates playlist URI references.\n *\n * @param {Object} config\n *        Object of arguments\n * @param {string} config.mainXml\n *        The mpd XML\n * @param {string} config.srcUrl\n *        The mpd URL\n * @param {Date} config.clientOffset\n *         A time difference between server and client\n * @param {Object} config.sidxMapping\n *        SIDX mappings for moof/mdat URIs and byte ranges\n * @return {Object}\n *         The parsed mpd manifest object\n */\n\nconst parseMainXml = ({\n  mainXml,\n  srcUrl,\n  clientOffset,\n  sidxMapping,\n  previousManifest\n}) => {\n  const manifest = parse(mainXml, {\n    manifestUri: srcUrl,\n    clientOffset,\n    sidxMapping,\n    previousManifest\n  });\n  addPropertiesToMain(manifest, srcUrl, dashGroupId);\n  return manifest;\n};\n/**\n * Removes any mediaGroup labels that no longer exist in the newMain\n *\n * @param {Object} update\n *         The previous mpd object being updated\n * @param {Object} newMain\n *         The new mpd object\n */\n\nconst removeOldMediaGroupLabels = (update, newMain) => {\n  forEachMediaGroup(update, (properties, type, group, label) => {\n    if (!newMain.mediaGroups[type][group] || !(label in newMain.mediaGroups[type][group])) {\n      delete update.mediaGroups[type][group][label];\n    }\n  });\n};\n/**\n * Returns a new main manifest that is the result of merging an updated main manifest\n * into the original version.\n *\n * @param {Object} oldMain\n *        The old parsed mpd object\n * @param {Object} newMain\n *        The updated parsed mpd object\n * @return {Object}\n *         A new object representing the original main manifest with the updated media\n *         playlists merged in\n */\n\nconst updateMain = (oldMain, newMain, sidxMapping) => {\n  let noChanges = true;\n  let update = merge(oldMain, {\n    // These are top level properties that can be updated\n    duration: newMain.duration,\n    minimumUpdatePeriod: newMain.minimumUpdatePeriod,\n    timelineStarts: newMain.timelineStarts\n  }); // First update the playlists in playlist list\n\n  for (let i = 0; i < newMain.playlists.length; i++) {\n    const playlist = newMain.playlists[i];\n    if (playlist.sidx) {\n      const sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already\n\n      if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {\n        addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);\n      }\n    }\n    const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);\n    if (playlistUpdate) {\n      update = playlistUpdate;\n      noChanges = false;\n    }\n  } // Then update media group playlists\n\n  forEachMediaGroup(newMain, (properties, type, group, label) => {\n    if (properties.playlists && properties.playlists.length) {\n      const id = properties.playlists[0].id;\n      const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);\n      if (playlistUpdate) {\n        update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.\n\n        if (!(label in update.mediaGroups[type][group])) {\n          update.mediaGroups[type][group][label] = properties;\n        } // update the playlist reference within media groups\n\n        update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];\n        noChanges = false;\n      }\n    }\n  }); // remove mediaGroup labels and references that no longer exist in the newMain\n\n  removeOldMediaGroupLabels(update, newMain);\n  if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {\n    noChanges = false;\n  }\n  if (noChanges) {\n    return null;\n  }\n  return update;\n}; // SIDX should be equivalent if the URI and byteranges of the SIDX match.\n// If the SIDXs have maps, the two maps should match,\n// both `a` and `b` missing SIDXs is considered matching.\n// If `a` or `b` but not both have a map, they aren't matching.\n\nconst equivalentSidx = (a, b) => {\n  const neitherMap = Boolean(!a.map && !b.map);\n  const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);\n  return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;\n}; // exported for testing\n\nconst compareSidxEntry = (playlists, oldSidxMapping) => {\n  const newSidxMapping = {};\n  for (const id in playlists) {\n    const playlist = playlists[id];\n    const currentSidxInfo = playlist.sidx;\n    if (currentSidxInfo) {\n      const key = generateSidxKey(currentSidxInfo);\n      if (!oldSidxMapping[key]) {\n        break;\n      }\n      const savedSidxInfo = oldSidxMapping[key].sidxInfo;\n      if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {\n        newSidxMapping[key] = oldSidxMapping[key];\n      }\n    }\n  }\n  return newSidxMapping;\n};\n/**\n *  A function that filters out changed items as they need to be requested separately.\n *\n *  The method is exported for testing\n *\n *  @param {Object} main the parsed mpd XML returned via mpd-parser\n *  @param {Object} oldSidxMapping the SIDX to compare against\n */\n\nconst filterChangedSidxMappings = (main, oldSidxMapping) => {\n  const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);\n  let mediaGroupSidx = videoSidx;\n  forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {\n    if (properties.playlists && properties.playlists.length) {\n      const playlists = properties.playlists;\n      mediaGroupSidx = merge(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));\n    }\n  });\n  return mediaGroupSidx;\n};\nclass DashPlaylistLoader extends EventTarget {\n  // DashPlaylistLoader must accept either a src url or a playlist because subsequent\n  // playlist loader setups from media groups will expect to be able to pass a playlist\n  // (since there aren't external URLs to media playlists with DASH)\n  constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {\n    super();\n    this.isPaused_ = true;\n    this.mainPlaylistLoader_ = mainPlaylistLoader || this;\n    if (!mainPlaylistLoader) {\n      this.isMain_ = true;\n    }\n    const {\n      withCredentials = false\n    } = options;\n    this.vhs_ = vhs;\n    this.withCredentials = withCredentials;\n    this.addMetadataToTextTrack = options.addMetadataToTextTrack;\n    if (!srcUrlOrPlaylist) {\n      throw new Error('A non-empty playlist URL or object is required');\n    } // event naming?\n\n    this.on('minimumUpdatePeriod', () => {\n      this.refreshXml_();\n    }); // live playlist staleness timeout\n\n    this.on('mediaupdatetimeout', () => {\n      this.refreshMedia_(this.media().id);\n    });\n    this.state = 'HAVE_NOTHING';\n    this.loadedPlaylists_ = {};\n    this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state\n    // The mainPlaylistLoader will be created with a string\n\n    if (this.isMain_) {\n      this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes\n      // once multi-period is refactored\n\n      this.mainPlaylistLoader_.sidxMapping_ = {};\n    } else {\n      this.childPlaylist_ = srcUrlOrPlaylist;\n    }\n  }\n  get isPaused() {\n    return this.isPaused_;\n  }\n  requestErrored_(err, request, startingState) {\n    // disposed\n    if (!this.request) {\n      return true;\n    } // pending request is cleared\n\n    this.request = null;\n    if (err) {\n      // use the provided error object or create one\n      // based on the request/response\n      this.error = typeof err === 'object' && !(err instanceof Error) ? err : {\n        status: request.status,\n        message: 'DASH request error at URL: ' + request.uri,\n        response: request.response,\n        // MEDIA_ERR_NETWORK\n        code: 2,\n        metadata: err.metadata\n      };\n      if (startingState) {\n        this.state = startingState;\n      }\n      this.trigger('error');\n      return true;\n    }\n  }\n  /**\n   * Verify that the container of the sidx segment can be parsed\n   * and if it can, get and parse that segment.\n   */\n\n  addSidxSegments_(playlist, startingState, cb) {\n    const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.\n\n    if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {\n      // keep this function async\n      window$1.clearTimeout(this.mediaRequest_);\n      this.mediaRequest_ = window$1.setTimeout(() => cb(false), 0);\n      return;\n    } // resolve the segment URL relative to the playlist\n\n    const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);\n    const fin = (err, request) => {\n      if (this.requestErrored_(err, request, startingState)) {\n        return;\n      }\n      const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;\n      const {\n        requestType\n      } = request;\n      let sidx;\n      try {\n        sidx = parseSidx(toUint8(request.response).subarray(8));\n      } catch (e) {\n        e.metadata = getStreamingNetworkErrorMetadata({\n          requestType,\n          request,\n          parseFailure: true\n        }); // sidx parsing failed.\n\n        this.requestErrored_(e, request, startingState);\n        return;\n      }\n      sidxMapping[sidxKey] = {\n        sidxInfo: playlist.sidx,\n        sidx\n      };\n      addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);\n      return cb(true);\n    };\n    const REQUEST_TYPE = 'dash-sidx';\n    this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {\n      if (err) {\n        return fin(err, request);\n      }\n      if (!container || container !== 'mp4') {\n        const sidxContainer = container || 'unknown';\n        return fin({\n          status: request.status,\n          message: `Unsupported ${sidxContainer} container type for sidx segment at URL: ${uri}`,\n          // response is just bytes in this case\n          // but we really don't want to return that.\n          response: '',\n          playlist,\n          internal: true,\n          playlistExclusionDuration: Infinity,\n          // MEDIA_ERR_NETWORK\n          code: 2\n        }, request);\n      } // if we already downloaded the sidx bytes in the container request, use them\n\n      const {\n        offset,\n        length\n      } = playlist.sidx.byterange;\n      if (bytes.length >= length + offset) {\n        return fin(err, {\n          response: bytes.subarray(offset, offset + length),\n          status: request.status,\n          uri: request.uri\n        });\n      } // otherwise request sidx bytes\n\n      this.request = this.vhs_.xhr({\n        uri,\n        responseType: 'arraybuffer',\n        requestType: 'dash-sidx',\n        headers: segmentXhrHeaders({\n          byterange: playlist.sidx.byterange\n        })\n      }, fin);\n    }, REQUEST_TYPE);\n  }\n  dispose() {\n    this.isPaused_ = true;\n    this.trigger('dispose');\n    this.stopRequest();\n    this.loadedPlaylists_ = {};\n    window$1.clearTimeout(this.minimumUpdatePeriodTimeout_);\n    window$1.clearTimeout(this.mediaRequest_);\n    window$1.clearTimeout(this.mediaUpdateTimeout);\n    this.mediaUpdateTimeout = null;\n    this.mediaRequest_ = null;\n    this.minimumUpdatePeriodTimeout_ = null;\n    if (this.mainPlaylistLoader_.createMupOnMedia_) {\n      this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);\n      this.mainPlaylistLoader_.createMupOnMedia_ = null;\n    }\n    this.off();\n  }\n  hasPendingRequest() {\n    return this.request || this.mediaRequest_;\n  }\n  stopRequest() {\n    if (this.request) {\n      const oldRequest = this.request;\n      this.request = null;\n      oldRequest.onreadystatechange = null;\n      oldRequest.abort();\n    }\n  }\n  media(playlist) {\n    // getter\n    if (!playlist) {\n      return this.media_;\n    } // setter\n\n    if (this.state === 'HAVE_NOTHING') {\n      throw new Error('Cannot switch media playlist from ' + this.state);\n    }\n    const startingState = this.state; // find the playlist object if the target playlist has been specified by URI\n\n    if (typeof playlist === 'string') {\n      if (!this.mainPlaylistLoader_.main.playlists[playlist]) {\n        throw new Error('Unknown playlist URI: ' + playlist);\n      }\n      playlist = this.mainPlaylistLoader_.main.playlists[playlist];\n    }\n    const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately\n\n    if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {\n      this.state = 'HAVE_METADATA';\n      this.media_ = playlist; // trigger media change if the active media has been updated\n\n      if (mediaChange) {\n        this.trigger('mediachanging');\n        this.trigger('mediachange');\n      }\n      return;\n    } // switching to the active playlist is a no-op\n\n    if (!mediaChange) {\n      return;\n    } // switching from an already loaded playlist\n\n    if (this.media_) {\n      this.trigger('mediachanging');\n    }\n    this.addSidxSegments_(playlist, startingState, sidxChanged => {\n      // everything is ready just continue to haveMetadata\n      this.haveMetadata({\n        startingState,\n        playlist\n      });\n    });\n  }\n  haveMetadata({\n    startingState,\n    playlist\n  }) {\n    this.state = 'HAVE_METADATA';\n    this.loadedPlaylists_[playlist.id] = playlist;\n    window$1.clearTimeout(this.mediaRequest_);\n    this.mediaRequest_ = null; // This will trigger loadedplaylist\n\n    this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded\n    // to resolve setup of media groups\n\n    if (startingState === 'HAVE_MAIN_MANIFEST') {\n      this.trigger('loadedmetadata');\n    } else {\n      // trigger media change if the active media has been updated\n      this.trigger('mediachange');\n    }\n  }\n  pause() {\n    this.isPaused_ = true;\n    if (this.mainPlaylistLoader_.createMupOnMedia_) {\n      this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);\n      this.mainPlaylistLoader_.createMupOnMedia_ = null;\n    }\n    this.stopRequest();\n    window$1.clearTimeout(this.mediaUpdateTimeout);\n    this.mediaUpdateTimeout = null;\n    if (this.isMain_) {\n      window$1.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);\n      this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;\n    }\n    if (this.state === 'HAVE_NOTHING') {\n      // If we pause the loader before any data has been retrieved, its as if we never\n      // started, so reset to an unstarted state.\n      this.started = false;\n    }\n  }\n  load(isFinalRendition) {\n    this.isPaused_ = false;\n    window$1.clearTimeout(this.mediaUpdateTimeout);\n    this.mediaUpdateTimeout = null;\n    const media = this.media();\n    if (isFinalRendition) {\n      const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;\n      this.mediaUpdateTimeout = window$1.setTimeout(() => this.load(), delay);\n      return;\n    } // because the playlists are internal to the manifest, load should either load the\n    // main manifest, or do nothing but trigger an event\n\n    if (!this.started) {\n      this.start();\n      return;\n    }\n    if (media && !media.endList) {\n      // Check to see if this is the main loader and the MUP was cleared (this happens\n      // when the loader was paused). `media` should be set at this point since one is always\n      // set during `start()`.\n      if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {\n        // Trigger minimumUpdatePeriod to refresh the main manifest\n        this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated\n\n        this.updateMinimumUpdatePeriodTimeout_();\n      }\n      this.trigger('mediaupdatetimeout');\n    } else {\n      this.trigger('loadedplaylist');\n    }\n  }\n  start() {\n    this.started = true; // We don't need to request the main manifest again\n    // Call this asynchronously to match the xhr request behavior below\n\n    if (!this.isMain_) {\n      window$1.clearTimeout(this.mediaRequest_);\n      this.mediaRequest_ = window$1.setTimeout(() => this.haveMain_(), 0);\n      return;\n    }\n    this.requestMain_((req, mainChanged) => {\n      this.haveMain_();\n      if (!this.hasPendingRequest() && !this.media_) {\n        this.media(this.mainPlaylistLoader_.main.playlists[0]);\n      }\n    });\n  }\n  requestMain_(cb) {\n    const metadata = {\n      manifestInfo: {\n        uri: this.mainPlaylistLoader_.srcUrl\n      }\n    };\n    this.trigger({\n      type: 'manifestrequeststart',\n      metadata\n    });\n    this.request = this.vhs_.xhr({\n      uri: this.mainPlaylistLoader_.srcUrl,\n      withCredentials: this.withCredentials,\n      requestType: 'dash-manifest'\n    }, (error, req) => {\n      if (error) {\n        const {\n          requestType\n        } = req;\n        error.metadata = getStreamingNetworkErrorMetadata({\n          requestType,\n          request: req,\n          error\n        });\n      }\n      if (this.requestErrored_(error, req)) {\n        if (this.state === 'HAVE_NOTHING') {\n          this.started = false;\n        }\n        return;\n      }\n      this.trigger({\n        type: 'manifestrequestcomplete',\n        metadata\n      });\n      const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;\n      this.mainPlaylistLoader_.mainXml_ = req.responseText;\n      if (req.responseHeaders && req.responseHeaders.date) {\n        this.mainLoaded_ = Date.parse(req.responseHeaders.date);\n      } else {\n        this.mainLoaded_ = Date.now();\n      }\n      this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);\n      if (mainChanged) {\n        this.handleMain_();\n        this.syncClientServerClock_(() => {\n          return cb(req, mainChanged);\n        });\n        return;\n      }\n      return cb(req, mainChanged);\n    });\n  }\n  /**\n   * Parses the main xml for UTCTiming node to sync the client clock to the server\n   * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.\n   *\n   * @param {Function} done\n   *        Function to call when clock sync has completed\n   */\n\n  syncClientServerClock_(done) {\n    const utcTiming = parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the\n    // server clock\n\n    if (utcTiming === null) {\n      this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();\n      return done();\n    }\n    if (utcTiming.method === 'DIRECT') {\n      this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();\n      return done();\n    }\n    this.request = this.vhs_.xhr({\n      uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),\n      method: utcTiming.method,\n      withCredentials: this.withCredentials,\n      requestType: 'dash-clock-sync'\n    }, (error, req) => {\n      // disposed\n      if (!this.request) {\n        return;\n      }\n      if (error) {\n        const {\n          requestType\n        } = req;\n        this.error.metadata = getStreamingNetworkErrorMetadata({\n          requestType,\n          request: req,\n          error\n        }); // sync request failed, fall back to using date header from mpd\n        // TODO: log warning\n\n        this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();\n        return done();\n      }\n      let serverTime;\n      if (utcTiming.method === 'HEAD') {\n        if (!req.responseHeaders || !req.responseHeaders.date) {\n          // expected date header not preset, fall back to using date header from mpd\n          // TODO: log warning\n          serverTime = this.mainLoaded_;\n        } else {\n          serverTime = Date.parse(req.responseHeaders.date);\n        }\n      } else {\n        serverTime = Date.parse(req.responseText);\n      }\n      this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();\n      done();\n    });\n  }\n  haveMain_() {\n    this.state = 'HAVE_MAIN_MANIFEST';\n    if (this.isMain_) {\n      // We have the main playlist at this point, so\n      // trigger this to allow PlaylistController\n      // to make an initial playlist selection\n      this.trigger('loadedplaylist');\n    } else if (!this.media_) {\n      // no media playlist was specifically selected so select\n      // the one the child playlist loader was created with\n      this.media(this.childPlaylist_);\n    }\n  }\n  handleMain_() {\n    // clear media request\n    window$1.clearTimeout(this.mediaRequest_);\n    this.mediaRequest_ = null;\n    const oldMain = this.mainPlaylistLoader_.main;\n    const metadata = {\n      manifestInfo: {\n        uri: this.mainPlaylistLoader_.srcUrl\n      }\n    };\n    this.trigger({\n      type: 'manifestparsestart',\n      metadata\n    });\n    let newMain;\n    try {\n      newMain = parseMainXml({\n        mainXml: this.mainPlaylistLoader_.mainXml_,\n        srcUrl: this.mainPlaylistLoader_.srcUrl,\n        clientOffset: this.mainPlaylistLoader_.clientOffset_,\n        sidxMapping: this.mainPlaylistLoader_.sidxMapping_,\n        previousManifest: oldMain\n      });\n    } catch (error) {\n      this.error = error;\n      this.error.metadata = {\n        errorType: videojs.Error.StreamingDashManifestParserError,\n        error\n      };\n      this.trigger('error');\n    } // if we have an old main to compare the new main against\n\n    if (oldMain) {\n      newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);\n    } // only update main if we have a new main\n\n    this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;\n    const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];\n    if (location && location !== this.mainPlaylistLoader_.srcUrl) {\n      this.mainPlaylistLoader_.srcUrl = location;\n    }\n    if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {\n      this.updateMinimumUpdatePeriodTimeout_();\n    }\n    this.addEventStreamToMetadataTrack_(newMain);\n    if (newMain) {\n      const {\n        duration,\n        endList\n      } = newMain;\n      const renditions = [];\n      newMain.playlists.forEach(playlist => {\n        renditions.push({\n          id: playlist.id,\n          bandwidth: playlist.attributes.BANDWIDTH,\n          resolution: playlist.attributes.RESOLUTION,\n          codecs: playlist.attributes.CODECS\n        });\n      });\n      const parsedManifest = {\n        duration,\n        isLive: !endList,\n        renditions\n      };\n      metadata.parsedManifest = parsedManifest;\n      this.trigger({\n        type: 'manifestparsecomplete',\n        metadata\n      });\n    }\n    return Boolean(newMain);\n  }\n  updateMinimumUpdatePeriodTimeout_() {\n    const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media\n    // a new one will be added if needed.\n\n    if (mpl.createMupOnMedia_) {\n      mpl.off('loadedmetadata', mpl.createMupOnMedia_);\n      mpl.createMupOnMedia_ = null;\n    } // clear any pending timeouts\n\n    if (mpl.minimumUpdatePeriodTimeout_) {\n      window$1.clearTimeout(mpl.minimumUpdatePeriodTimeout_);\n      mpl.minimumUpdatePeriodTimeout_ = null;\n    }\n    let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current\n    // MPD has no future validity, so a new one will need to be acquired when new\n    // media segments are to be made available. Thus, we use the target duration\n    // in this case\n\n    if (mup === 0) {\n      if (mpl.media()) {\n        mup = mpl.media().targetDuration * 1000;\n      } else {\n        mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;\n        mpl.one('loadedmetadata', mpl.createMupOnMedia_);\n      }\n    } // if minimumUpdatePeriod is invalid or <= zero, which\n    // can happen when a live video becomes VOD. skip timeout\n    // creation.\n\n    if (typeof mup !== 'number' || mup <= 0) {\n      if (mup < 0) {\n        this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);\n      }\n      return;\n    }\n    this.createMUPTimeout_(mup);\n  }\n  createMUPTimeout_(mup) {\n    const mpl = this.mainPlaylistLoader_;\n    mpl.minimumUpdatePeriodTimeout_ = window$1.setTimeout(() => {\n      mpl.minimumUpdatePeriodTimeout_ = null;\n      mpl.trigger('minimumUpdatePeriod');\n      mpl.createMUPTimeout_(mup);\n    }, mup);\n  }\n  /**\n   * Sends request to refresh the main xml and updates the parsed main manifest\n   */\n\n  refreshXml_() {\n    this.requestMain_((req, mainChanged) => {\n      if (!mainChanged) {\n        return;\n      }\n      if (this.media_) {\n        this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];\n      } // This will filter out updated sidx info from the mapping\n\n      this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);\n      this.addSidxSegments_(this.media(), this.state, sidxChanged => {\n        // TODO: do we need to reload the current playlist?\n        this.refreshMedia_(this.media().id);\n      });\n    });\n  }\n  /**\n   * Refreshes the media playlist by re-parsing the main xml and updating playlist\n   * references. If this is an alternate loader, the updated parsed manifest is retrieved\n   * from the main loader.\n   */\n\n  refreshMedia_(mediaID) {\n    if (!mediaID) {\n      throw new Error('refreshMedia_ must take a media id');\n    } // for main we have to reparse the main xml\n    // to re-create segments based on current timing values\n    // which may change media. We only skip updating the main manifest\n    // if this is the first time this.media_ is being set.\n    // as main was just parsed in that case.\n\n    if (this.media_ && this.isMain_) {\n      this.handleMain_();\n    }\n    const playlists = this.mainPlaylistLoader_.main.playlists;\n    const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];\n    if (mediaChanged) {\n      this.media_ = playlists[mediaID];\n    } else {\n      this.trigger('playlistunchanged');\n    }\n    if (!this.mediaUpdateTimeout) {\n      const createMediaUpdateTimeout = () => {\n        if (this.media().endList) {\n          return;\n        }\n        this.mediaUpdateTimeout = window$1.setTimeout(() => {\n          this.trigger('mediaupdatetimeout');\n          createMediaUpdateTimeout();\n        }, refreshDelay(this.media(), Boolean(mediaChanged)));\n      };\n      createMediaUpdateTimeout();\n    }\n    this.trigger('loadedplaylist');\n  }\n  /**\n   * Takes eventstream data from a parsed DASH manifest and adds it to the metadata text track.\n   *\n   * @param {manifest} newMain the newly parsed manifest\n   */\n\n  addEventStreamToMetadataTrack_(newMain) {\n    // Only add new event stream metadata if we have a new manifest.\n    if (newMain && this.mainPlaylistLoader_.main.eventStream) {\n      // convert EventStream to ID3-like data.\n      const metadataArray = this.mainPlaylistLoader_.main.eventStream.map(eventStreamNode => {\n        return {\n          cueTime: eventStreamNode.start,\n          frames: [{\n            data: eventStreamNode.messageData\n          }]\n        };\n      });\n      this.addMetadataToTextTrack('EventStream', metadataArray, this.mainPlaylistLoader_.main.duration);\n    }\n  }\n  /**\n   * Returns the key ID set from a playlist\n   *\n   * @param {playlist} playlist to fetch the key ID set from.\n   * @return a Set of 32 digit hex strings that represent the unique keyIds for that playlist.\n   */\n\n  getKeyIdSet(playlist) {\n    if (playlist.contentProtection) {\n      const keyIds = new Set();\n      for (const keysystem in playlist.contentProtection) {\n        const defaultKID = playlist.contentProtection[keysystem].attributes['cenc:default_KID'];\n        if (defaultKID) {\n          // DASH keyIds are separated by dashes.\n          keyIds.add(defaultKID.replace(/-/g, '').toLowerCase());\n        }\n      }\n      return keyIds;\n    }\n  }\n}\nvar Config = {\n  GOAL_BUFFER_LENGTH: 30,\n  MAX_GOAL_BUFFER_LENGTH: 60,\n  BACK_BUFFER_LENGTH: 30,\n  GOAL_BUFFER_LENGTH_RATE: 1,\n  // 0.5 MB/s\n  INITIAL_BANDWIDTH: 4194304,\n  // A fudge factor to apply to advertised playlist bitrates to account for\n  // temporary flucations in client bandwidth\n  BANDWIDTH_VARIANCE: 1.2,\n  // How much of the buffer must be filled before we consider upswitching\n  BUFFER_LOW_WATER_LINE: 0,\n  MAX_BUFFER_LOW_WATER_LINE: 30,\n  // TODO: Remove this when experimentalBufferBasedABR is removed\n  EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,\n  BUFFER_LOW_WATER_LINE_RATE: 1,\n  // If the buffer is greater than the high water line, we won't switch down\n  BUFFER_HIGH_WATER_LINE: 30\n};\nconst stringToArrayBuffer = string => {\n  const view = new Uint8Array(new ArrayBuffer(string.length));\n  for (let i = 0; i < string.length; i++) {\n    view[i] = string.charCodeAt(i);\n  }\n  return view.buffer;\n};\n\n/* global Blob, BlobBuilder, Worker */\n// unify worker interface\nconst browserWorkerPolyFill = function (workerObj) {\n  // node only supports on/off\n  workerObj.on = workerObj.addEventListener;\n  workerObj.off = workerObj.removeEventListener;\n  return workerObj;\n};\nconst createObjectURL = function (str) {\n  try {\n    return URL.createObjectURL(new Blob([str], {\n      type: 'application/javascript'\n    }));\n  } catch (e) {\n    const blob = new BlobBuilder();\n    blob.append(str);\n    return URL.createObjectURL(blob.getBlob());\n  }\n};\nconst factory = function (code) {\n  return function () {\n    const objectUrl = createObjectURL(code);\n    const worker = browserWorkerPolyFill(new Worker(objectUrl));\n    worker.objURL = objectUrl;\n    const terminate = worker.terminate;\n    worker.on = worker.addEventListener;\n    worker.off = worker.removeEventListener;\n    worker.terminate = function () {\n      URL.revokeObjectURL(objectUrl);\n      return terminate.call(this);\n    };\n    return worker;\n  };\n};\nconst transform = function (code) {\n  return `var browserWorkerPolyFill = ${browserWorkerPolyFill.toString()};\\n` + 'browserWorkerPolyFill(self);\\n' + code;\n};\nconst getWorkerString = function (fn) {\n  return fn.toString().replace(/^function.+?{/, '').slice(0, -1);\n};\n\n/* rollup-plugin-worker-factory start for worker!/home/runner/work/http-streaming/http-streaming/src/transmuxer-worker.js */\nconst workerCode$1 = transform(getWorkerString(function () {\n  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * A lightweight readable stream implemention that handles event dispatching.\n   * Objects that inherit from streams should call init in their constructors.\n   */\n\n  var Stream$8 = function () {\n    this.init = function () {\n      var listeners = {};\n      /**\n       * Add a listener for a specified event type.\n       * @param type {string} the event name\n       * @param listener {function} the callback to be invoked when an event of\n       * the specified type occurs\n       */\n\n      this.on = function (type, listener) {\n        if (!listeners[type]) {\n          listeners[type] = [];\n        }\n        listeners[type] = listeners[type].concat(listener);\n      };\n      /**\n       * Remove a listener for a specified event type.\n       * @param type {string} the event name\n       * @param listener {function} a function previously registered for this\n       * type of event through `on`\n       */\n\n      this.off = function (type, listener) {\n        var index;\n        if (!listeners[type]) {\n          return false;\n        }\n        index = listeners[type].indexOf(listener);\n        listeners[type] = listeners[type].slice();\n        listeners[type].splice(index, 1);\n        return index > -1;\n      };\n      /**\n       * Trigger an event of the specified type on this stream. Any additional\n       * arguments to this function are passed as parameters to event listeners.\n       * @param type {string} the event name\n       */\n\n      this.trigger = function (type) {\n        var callbacks, i, length, args;\n        callbacks = listeners[type];\n        if (!callbacks) {\n          return;\n        } // Slicing the arguments on every invocation of this method\n        // can add a significant amount of overhead. Avoid the\n        // intermediate object creation for the common case of a\n        // single callback argument\n\n        if (arguments.length === 2) {\n          length = callbacks.length;\n          for (i = 0; i < length; ++i) {\n            callbacks[i].call(this, arguments[1]);\n          }\n        } else {\n          args = [];\n          i = arguments.length;\n          for (i = 1; i < arguments.length; ++i) {\n            args.push(arguments[i]);\n          }\n          length = callbacks.length;\n          for (i = 0; i < length; ++i) {\n            callbacks[i].apply(this, args);\n          }\n        }\n      };\n      /**\n       * Destroys the stream and cleans up.\n       */\n\n      this.dispose = function () {\n        listeners = {};\n      };\n    };\n  };\n  /**\n   * Forwards all `data` events on this stream to the destination stream. The\n   * destination stream should provide a method `push` to receive the data\n   * events as they arrive.\n   * @param destination {stream} the stream that will receive all `data` events\n   * @param autoFlush {boolean} if false, we will not call `flush` on the destination\n   *                            when the current stream emits a 'done' event\n   * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options\n   */\n\n  Stream$8.prototype.pipe = function (destination) {\n    this.on('data', function (data) {\n      destination.push(data);\n    });\n    this.on('done', function (flushSource) {\n      destination.flush(flushSource);\n    });\n    this.on('partialdone', function (flushSource) {\n      destination.partialFlush(flushSource);\n    });\n    this.on('endedtimeline', function (flushSource) {\n      destination.endTimeline(flushSource);\n    });\n    this.on('reset', function (flushSource) {\n      destination.reset(flushSource);\n    });\n    return destination;\n  }; // Default stream functions that are expected to be overridden to perform\n  // actual work. These are provided by the prototype as a sort of no-op\n  // implementation so that we don't have to check for their existence in the\n  // `pipe` function above.\n\n  Stream$8.prototype.push = function (data) {\n    this.trigger('data', data);\n  };\n  Stream$8.prototype.flush = function (flushSource) {\n    this.trigger('done', flushSource);\n  };\n  Stream$8.prototype.partialFlush = function (flushSource) {\n    this.trigger('partialdone', flushSource);\n  };\n  Stream$8.prototype.endTimeline = function (flushSource) {\n    this.trigger('endedtimeline', flushSource);\n  };\n  Stream$8.prototype.reset = function (flushSource) {\n    this.trigger('reset', flushSource);\n  };\n  var stream = Stream$8;\n  var MAX_UINT32$1 = Math.pow(2, 32);\n  var getUint64$5 = function (uint8) {\n    var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);\n    var value;\n    if (dv.getBigUint64) {\n      value = dv.getBigUint64(0);\n      if (value < Number.MAX_SAFE_INTEGER) {\n        return Number(value);\n      }\n      return value;\n    }\n    return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);\n  };\n  var numbers = {\n    getUint64: getUint64$5,\n    MAX_UINT32: MAX_UINT32$1\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Functions that generate fragmented MP4s suitable for use with Media\n   * Source Extensions.\n   */\n\n  var MAX_UINT32 = numbers.MAX_UINT32;\n  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\n\n  (function () {\n    var i;\n    types = {\n      avc1: [],\n      // codingname\n      avcC: [],\n      btrt: [],\n      dinf: [],\n      dref: [],\n      esds: [],\n      ftyp: [],\n      hdlr: [],\n      mdat: [],\n      mdhd: [],\n      mdia: [],\n      mfhd: [],\n      minf: [],\n      moof: [],\n      moov: [],\n      mp4a: [],\n      // codingname\n      mvex: [],\n      mvhd: [],\n      pasp: [],\n      sdtp: [],\n      smhd: [],\n      stbl: [],\n      stco: [],\n      stsc: [],\n      stsd: [],\n      stsz: [],\n      stts: [],\n      styp: [],\n      tfdt: [],\n      tfhd: [],\n      traf: [],\n      trak: [],\n      trun: [],\n      trex: [],\n      tkhd: [],\n      vmhd: []\n    }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we\n    // don't throw an error\n\n    if (typeof Uint8Array === 'undefined') {\n      return;\n    }\n    for (i in types) {\n      if (types.hasOwnProperty(i)) {\n        types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];\n      }\n    }\n    MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);\n    AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);\n    MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);\n    VIDEO_HDLR = new Uint8Array([0x00,\n    // version 0\n    0x00, 0x00, 0x00,\n    // flags\n    0x00, 0x00, 0x00, 0x00,\n    // pre_defined\n    0x76, 0x69, 0x64, 0x65,\n    // handler_type: 'vide'\n    0x00, 0x00, 0x00, 0x00,\n    // reserved\n    0x00, 0x00, 0x00, 0x00,\n    // reserved\n    0x00, 0x00, 0x00, 0x00,\n    // reserved\n    0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'\n    ]);\n    AUDIO_HDLR = new Uint8Array([0x00,\n    // version 0\n    0x00, 0x00, 0x00,\n    // flags\n    0x00, 0x00, 0x00, 0x00,\n    // pre_defined\n    0x73, 0x6f, 0x75, 0x6e,\n    // handler_type: 'soun'\n    0x00, 0x00, 0x00, 0x00,\n    // reserved\n    0x00, 0x00, 0x00, 0x00,\n    // reserved\n    0x00, 0x00, 0x00, 0x00,\n    // reserved\n    0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'\n    ]);\n    HDLR_TYPES = {\n      video: VIDEO_HDLR,\n      audio: AUDIO_HDLR\n    };\n    DREF = new Uint8Array([0x00,\n    // version 0\n    0x00, 0x00, 0x00,\n    // flags\n    0x00, 0x00, 0x00, 0x01,\n    // entry_count\n    0x00, 0x00, 0x00, 0x0c,\n    // entry_size\n    0x75, 0x72, 0x6c, 0x20,\n    // 'url' type\n    0x00,\n    // version 0\n    0x00, 0x00, 0x01 // entry_flags\n    ]);\n    SMHD = new Uint8Array([0x00,\n    // version\n    0x00, 0x00, 0x00,\n    // flags\n    0x00, 0x00,\n    // balance, 0 means centered\n    0x00, 0x00 // reserved\n    ]);\n    STCO = new Uint8Array([0x00,\n    // version\n    0x00, 0x00, 0x00,\n    // flags\n    0x00, 0x00, 0x00, 0x00 // entry_count\n    ]);\n    STSC = STCO;\n    STSZ = new Uint8Array([0x00,\n    // version\n    0x00, 0x00, 0x00,\n    // flags\n    0x00, 0x00, 0x00, 0x00,\n    // sample_size\n    0x00, 0x00, 0x00, 0x00 // sample_count\n    ]);\n    STTS = STCO;\n    VMHD = new Uint8Array([0x00,\n    // version\n    0x00, 0x00, 0x01,\n    // flags\n    0x00, 0x00,\n    // graphicsmode\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor\n    ]);\n  })();\n  box = function (type) {\n    var payload = [],\n      size = 0,\n      i,\n      result,\n      view;\n    for (i = 1; i < arguments.length; i++) {\n      payload.push(arguments[i]);\n    }\n    i = payload.length; // calculate the total size we need to allocate\n\n    while (i--) {\n      size += payload[i].byteLength;\n    }\n    result = new Uint8Array(size + 8);\n    view = new DataView(result.buffer, result.byteOffset, result.byteLength);\n    view.setUint32(0, result.byteLength);\n    result.set(type, 4); // copy the payload into the result\n\n    for (i = 0, size = 8; i < payload.length; i++) {\n      result.set(payload[i], size);\n      size += payload[i].byteLength;\n    }\n    return result;\n  };\n  dinf = function () {\n    return box(types.dinf, box(types.dref, DREF));\n  };\n  esds = function (track) {\n    return box(types.esds, new Uint8Array([0x00,\n    // version\n    0x00, 0x00, 0x00,\n    // flags\n    // ES_Descriptor\n    0x03,\n    // tag, ES_DescrTag\n    0x19,\n    // length\n    0x00, 0x00,\n    // ES_ID\n    0x00,\n    // streamDependenceFlag, URL_flag, reserved, streamPriority\n    // DecoderConfigDescriptor\n    0x04,\n    // tag, DecoderConfigDescrTag\n    0x11,\n    // length\n    0x40,\n    // object type\n    0x15,\n    // streamType\n    0x00, 0x06, 0x00,\n    // bufferSizeDB\n    0x00, 0x00, 0xda, 0xc0,\n    // maxBitrate\n    0x00, 0x00, 0xda, 0xc0,\n    // avgBitrate\n    // DecoderSpecificInfo\n    0x05,\n    // tag, DecoderSpecificInfoTag\n    0x02,\n    // length\n    // ISO/IEC 14496-3, AudioSpecificConfig\n    // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35\n    track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig\n    ]));\n  };\n  ftyp = function () {\n    return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);\n  };\n  hdlr = function (type) {\n    return box(types.hdlr, HDLR_TYPES[type]);\n  };\n  mdat = function (data) {\n    return box(types.mdat, data);\n  };\n  mdhd = function (track) {\n    var result = new Uint8Array([0x00,\n    // version 0\n    0x00, 0x00, 0x00,\n    // flags\n    0x00, 0x00, 0x00, 0x02,\n    // creation_time\n    0x00, 0x00, 0x00, 0x03,\n    // modification_time\n    0x00, 0x01, 0x5f, 0x90,\n    // timescale, 90,000 \"ticks\" per second\n    track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF,\n    // duration\n    0x55, 0xc4,\n    // 'und' language (undetermined)\n    0x00, 0x00]); // Use the sample rate from the track metadata, when it is\n    // defined. The sample rate can be parsed out of an ADTS header, for\n    // instance.\n\n    if (track.samplerate) {\n      result[12] = track.samplerate >>> 24 & 0xFF;\n      result[13] = track.samplerate >>> 16 & 0xFF;\n      result[14] = track.samplerate >>> 8 & 0xFF;\n      result[15] = track.samplerate & 0xFF;\n    }\n    return box(types.mdhd, result);\n  };\n  mdia = function (track) {\n    return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));\n  };\n  mfhd = function (sequenceNumber) {\n    return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,\n    // flags\n    (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number\n    ]));\n  };\n  minf = function (track) {\n    return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));\n  };\n  moof = function (sequenceNumber, tracks) {\n    var trackFragments = [],\n      i = tracks.length; // build traf boxes for each track fragment\n\n    while (i--) {\n      trackFragments[i] = traf(tracks[i]);\n    }\n    return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));\n  };\n  /**\n   * Returns a movie box.\n   * @param tracks {array} the tracks associated with this movie\n   * @see ISO/IEC 14496-12:2012(E), section 8.2.1\n   */\n\n  moov = function (tracks) {\n    var i = tracks.length,\n      boxes = [];\n    while (i--) {\n      boxes[i] = trak(tracks[i]);\n    }\n    return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));\n  };\n  mvex = function (tracks) {\n    var i = tracks.length,\n      boxes = [];\n    while (i--) {\n      boxes[i] = trex(tracks[i]);\n    }\n    return box.apply(null, [types.mvex].concat(boxes));\n  };\n  mvhd = function (duration) {\n    var bytes = new Uint8Array([0x00,\n    // version 0\n    0x00, 0x00, 0x00,\n    // flags\n    0x00, 0x00, 0x00, 0x01,\n    // creation_time\n    0x00, 0x00, 0x00, 0x02,\n    // modification_time\n    0x00, 0x01, 0x5f, 0x90,\n    // timescale, 90,000 \"ticks\" per second\n    (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF,\n    // duration\n    0x00, 0x01, 0x00, 0x00,\n    // 1.0 rate\n    0x01, 0x00,\n    // 1.0 volume\n    0x00, 0x00,\n    // reserved\n    0x00, 0x00, 0x00, 0x00,\n    // reserved\n    0x00, 0x00, 0x00, 0x00,\n    // reserved\n    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,\n    // transformation: unity matrix\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    // pre_defined\n    0xff, 0xff, 0xff, 0xff // next_track_ID\n    ]);\n    return box(types.mvhd, bytes);\n  };\n  sdtp = function (track) {\n    var samples = track.samples || [],\n      bytes = new Uint8Array(4 + samples.length),\n      flags,\n      i; // leave the full box header (4 bytes) all zero\n    // write the sample table\n\n    for (i = 0; i < samples.length; i++) {\n      flags = samples[i].flags;\n      bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;\n    }\n    return box(types.sdtp, bytes);\n  };\n  stbl = function (track) {\n    return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));\n  };\n  (function () {\n    var videoSample, audioSample;\n    stsd = function (track) {\n      return box(types.stsd, new Uint8Array([0x00,\n      // version 0\n      0x00, 0x00, 0x00,\n      // flags\n      0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));\n    };\n    videoSample = function (track) {\n      var sps = track.sps || [],\n        pps = track.pps || [],\n        sequenceParameterSets = [],\n        pictureParameterSets = [],\n        i,\n        avc1Box; // assemble the SPSs\n\n      for (i = 0; i < sps.length; i++) {\n        sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);\n        sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength\n\n        sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS\n      } // assemble the PPSs\n\n      for (i = 0; i < pps.length; i++) {\n        pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);\n        pictureParameterSets.push(pps[i].byteLength & 0xFF);\n        pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));\n      }\n      avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      // reserved\n      0x00, 0x01,\n      // data_reference_index\n      0x00, 0x00,\n      // pre_defined\n      0x00, 0x00,\n      // reserved\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      // pre_defined\n      (track.width & 0xff00) >> 8, track.width & 0xff,\n      // width\n      (track.height & 0xff00) >> 8, track.height & 0xff,\n      // height\n      0x00, 0x48, 0x00, 0x00,\n      // horizresolution\n      0x00, 0x48, 0x00, 0x00,\n      // vertresolution\n      0x00, 0x00, 0x00, 0x00,\n      // reserved\n      0x00, 0x01,\n      // frame_count\n      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,\n      // compressorname\n      0x00, 0x18,\n      // depth = 24\n      0x11, 0x11 // pre_defined = -1\n      ]), box(types.avcC, new Uint8Array([0x01,\n      // configurationVersion\n      track.profileIdc,\n      // AVCProfileIndication\n      track.profileCompatibility,\n      // profile_compatibility\n      track.levelIdc,\n      // AVCLevelIndication\n      0xff // lengthSizeMinusOne, hard-coded to 4 bytes\n      ].concat([sps.length],\n      // numOfSequenceParameterSets\n      sequenceParameterSets,\n      // \"SPS\"\n      [pps.length],\n      // numOfPictureParameterSets\n      pictureParameterSets // \"PPS\"\n      ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,\n      // bufferSizeDB\n      0x00, 0x2d, 0xc6, 0xc0,\n      // maxBitrate\n      0x00, 0x2d, 0xc6, 0xc0 // avgBitrate\n      ]))];\n      if (track.sarRatio) {\n        var hSpacing = track.sarRatio[0],\n          vSpacing = track.sarRatio[1];\n        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])));\n      }\n      return box.apply(null, avc1Box);\n    };\n    audioSample = function (track) {\n      return box(types.mp4a, new Uint8Array([\n      // SampleEntry, ISO/IEC 14496-12\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      // reserved\n      0x00, 0x01,\n      // data_reference_index\n      // AudioSampleEntry, ISO/IEC 14496-12\n      0x00, 0x00, 0x00, 0x00,\n      // reserved\n      0x00, 0x00, 0x00, 0x00,\n      // reserved\n      (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff,\n      // channelcount\n      (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff,\n      // samplesize\n      0x00, 0x00,\n      // pre_defined\n      0x00, 0x00,\n      // reserved\n      (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16\n      // MP4AudioSampleEntry, ISO/IEC 14496-14\n      ]), esds(track));\n    };\n  })();\n  tkhd = function (track) {\n    var result = new Uint8Array([0x00,\n    // version 0\n    0x00, 0x00, 0x07,\n    // flags\n    0x00, 0x00, 0x00, 0x00,\n    // creation_time\n    0x00, 0x00, 0x00, 0x00,\n    // modification_time\n    (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,\n    // track_ID\n    0x00, 0x00, 0x00, 0x00,\n    // reserved\n    (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF,\n    // duration\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    // reserved\n    0x00, 0x00,\n    // layer\n    0x00, 0x00,\n    // alternate_group\n    0x01, 0x00,\n    // non-audio track volume\n    0x00, 0x00,\n    // reserved\n    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,\n    // transformation: unity matrix\n    (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00,\n    // width\n    (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height\n    ]);\n    return box(types.tkhd, result);\n  };\n  /**\n   * Generate a track fragment (traf) box. A traf box collects metadata\n   * about tracks in a movie fragment (moof) box.\n   */\n\n  traf = function (track) {\n    var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;\n    trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00,\n    // version 0\n    0x00, 0x00, 0x3a,\n    // flags\n    (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,\n    // track_ID\n    0x00, 0x00, 0x00, 0x01,\n    // sample_description_index\n    0x00, 0x00, 0x00, 0x00,\n    // default_sample_duration\n    0x00, 0x00, 0x00, 0x00,\n    // default_sample_size\n    0x00, 0x00, 0x00, 0x00 // default_sample_flags\n    ]));\n    upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);\n    lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);\n    trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01,\n    // version 1\n    0x00, 0x00, 0x00,\n    // flags\n    // baseMediaDecodeTime\n    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\n    // the containing moof to the first payload byte of the associated\n    // mdat\n\n    dataOffset = 32 +\n    // tfhd\n    20 +\n    // tfdt\n    8 +\n    // traf header\n    16 +\n    // mfhd\n    8 +\n    // moof header\n    8; // mdat header\n    // audio tracks require less metadata\n\n    if (track.type === 'audio') {\n      trackFragmentRun = trun$1(track, dataOffset);\n      return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);\n    } // video tracks should contain an independent and disposable samples\n    // box (sdtp)\n    // generate one and adjust offsets to match\n\n    sampleDependencyTable = sdtp(track);\n    trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);\n    return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);\n  };\n  /**\n   * Generate a track box.\n   * @param track {object} a track definition\n   * @return {Uint8Array} the track box\n   */\n\n  trak = function (track) {\n    track.duration = track.duration || 0xffffffff;\n    return box(types.trak, tkhd(track), mdia(track));\n  };\n  trex = function (track) {\n    var result = new Uint8Array([0x00,\n    // version 0\n    0x00, 0x00, 0x00,\n    // flags\n    (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,\n    // track_ID\n    0x00, 0x00, 0x00, 0x01,\n    // default_sample_description_index\n    0x00, 0x00, 0x00, 0x00,\n    // default_sample_duration\n    0x00, 0x00, 0x00, 0x00,\n    // default_sample_size\n    0x00, 0x01, 0x00, 0x01 // default_sample_flags\n    ]); // the last two bytes of default_sample_flags is the sample\n    // degradation priority, a hint about the importance of this sample\n    // relative to others. Lower the degradation priority for all sample\n    // types other than video.\n\n    if (track.type !== 'video') {\n      result[result.length - 1] = 0x00;\n    }\n    return box(types.trex, result);\n  };\n  (function () {\n    var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a\n    // duration is present for the first sample, it will be present for\n    // all subsequent samples.\n    // see ISO/IEC 14496-12:2012, Section 8.8.8.1\n\n    trunHeader = function (samples, offset) {\n      var durationPresent = 0,\n        sizePresent = 0,\n        flagsPresent = 0,\n        compositionTimeOffset = 0; // trun flag constants\n\n      if (samples.length) {\n        if (samples[0].duration !== undefined) {\n          durationPresent = 0x1;\n        }\n        if (samples[0].size !== undefined) {\n          sizePresent = 0x2;\n        }\n        if (samples[0].flags !== undefined) {\n          flagsPresent = 0x4;\n        }\n        if (samples[0].compositionTimeOffset !== undefined) {\n          compositionTimeOffset = 0x8;\n        }\n      }\n      return [0x00,\n      // version 0\n      0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01,\n      // flags\n      (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF,\n      // sample_count\n      (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset\n      ];\n    };\n    videoTrun = function (track, offset) {\n      var bytesOffest, bytes, header, samples, sample, i;\n      samples = track.samples || [];\n      offset += 8 + 12 + 16 * samples.length;\n      header = trunHeader(samples, offset);\n      bytes = new Uint8Array(header.length + samples.length * 16);\n      bytes.set(header);\n      bytesOffest = header.length;\n      for (i = 0; i < samples.length; i++) {\n        sample = samples[i];\n        bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;\n        bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;\n        bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;\n        bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration\n\n        bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;\n        bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;\n        bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;\n        bytes[bytesOffest++] = sample.size & 0xFF; // sample_size\n\n        bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;\n        bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;\n        bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;\n        bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags\n\n        bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;\n        bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;\n        bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;\n        bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset\n      }\n      return box(types.trun, bytes);\n    };\n    audioTrun = function (track, offset) {\n      var bytes, bytesOffest, header, samples, sample, i;\n      samples = track.samples || [];\n      offset += 8 + 12 + 8 * samples.length;\n      header = trunHeader(samples, offset);\n      bytes = new Uint8Array(header.length + samples.length * 8);\n      bytes.set(header);\n      bytesOffest = header.length;\n      for (i = 0; i < samples.length; i++) {\n        sample = samples[i];\n        bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;\n        bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;\n        bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;\n        bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration\n\n        bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;\n        bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;\n        bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;\n        bytes[bytesOffest++] = sample.size & 0xFF; // sample_size\n      }\n      return box(types.trun, bytes);\n    };\n    trun$1 = function (track, offset) {\n      if (track.type === 'audio') {\n        return audioTrun(track, offset);\n      }\n      return videoTrun(track, offset);\n    };\n  })();\n  var mp4Generator = {\n    ftyp: ftyp,\n    mdat: mdat,\n    moof: moof,\n    moov: moov,\n    initSegment: function (tracks) {\n      var fileType = ftyp(),\n        movie = moov(tracks),\n        result;\n      result = new Uint8Array(fileType.byteLength + movie.byteLength);\n      result.set(fileType);\n      result.set(movie, fileType.byteLength);\n      return result;\n    }\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n  // composed of the nal units that make up that frame\n  // Also keep track of cummulative data about the frame from the nal units such\n  // as the frame duration, starting pts, etc.\n\n  var groupNalsIntoFrames = function (nalUnits) {\n    var i,\n      currentNal,\n      currentFrame = [],\n      frames = []; // TODO added for LHLS, make sure this is OK\n\n    frames.byteLength = 0;\n    frames.nalCount = 0;\n    frames.duration = 0;\n    currentFrame.byteLength = 0;\n    for (i = 0; i < nalUnits.length; i++) {\n      currentNal = nalUnits[i]; // Split on 'aud'-type nal units\n\n      if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {\n        // Since the very first nal unit is expected to be an AUD\n        // only push to the frames array when currentFrame is not empty\n        if (currentFrame.length) {\n          currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK\n\n          frames.byteLength += currentFrame.byteLength;\n          frames.nalCount += currentFrame.length;\n          frames.duration += currentFrame.duration;\n          frames.push(currentFrame);\n        }\n        currentFrame = [currentNal];\n        currentFrame.byteLength = currentNal.data.byteLength;\n        currentFrame.pts = currentNal.pts;\n        currentFrame.dts = currentNal.dts;\n      } else {\n        // Specifically flag key frames for ease of use later\n        if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {\n          currentFrame.keyFrame = true;\n        }\n        currentFrame.duration = currentNal.dts - currentFrame.dts;\n        currentFrame.byteLength += currentNal.data.byteLength;\n        currentFrame.push(currentNal);\n      }\n    } // For the last frame, use the duration of the previous frame if we\n    // have nothing better to go on\n\n    if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {\n      currentFrame.duration = frames[frames.length - 1].duration;\n    } // Push the final frame\n    // TODO added for LHLS, make sure this is OK\n\n    frames.byteLength += currentFrame.byteLength;\n    frames.nalCount += currentFrame.length;\n    frames.duration += currentFrame.duration;\n    frames.push(currentFrame);\n    return frames;\n  }; // Convert an array of frames into an array of Gop with each Gop being composed\n  // of the frames that make up that Gop\n  // Also keep track of cummulative data about the Gop from the frames such as the\n  // Gop duration, starting pts, etc.\n\n  var groupFramesIntoGops = function (frames) {\n    var i,\n      currentFrame,\n      currentGop = [],\n      gops = []; // We must pre-set some of the values on the Gop since we\n    // keep running totals of these values\n\n    currentGop.byteLength = 0;\n    currentGop.nalCount = 0;\n    currentGop.duration = 0;\n    currentGop.pts = frames[0].pts;\n    currentGop.dts = frames[0].dts; // store some metadata about all the Gops\n\n    gops.byteLength = 0;\n    gops.nalCount = 0;\n    gops.duration = 0;\n    gops.pts = frames[0].pts;\n    gops.dts = frames[0].dts;\n    for (i = 0; i < frames.length; i++) {\n      currentFrame = frames[i];\n      if (currentFrame.keyFrame) {\n        // Since the very first frame is expected to be an keyframe\n        // only push to the gops array when currentGop is not empty\n        if (currentGop.length) {\n          gops.push(currentGop);\n          gops.byteLength += currentGop.byteLength;\n          gops.nalCount += currentGop.nalCount;\n          gops.duration += currentGop.duration;\n        }\n        currentGop = [currentFrame];\n        currentGop.nalCount = currentFrame.length;\n        currentGop.byteLength = currentFrame.byteLength;\n        currentGop.pts = currentFrame.pts;\n        currentGop.dts = currentFrame.dts;\n        currentGop.duration = currentFrame.duration;\n      } else {\n        currentGop.duration += currentFrame.duration;\n        currentGop.nalCount += currentFrame.length;\n        currentGop.byteLength += currentFrame.byteLength;\n        currentGop.push(currentFrame);\n      }\n    }\n    if (gops.length && currentGop.duration <= 0) {\n      currentGop.duration = gops[gops.length - 1].duration;\n    }\n    gops.byteLength += currentGop.byteLength;\n    gops.nalCount += currentGop.nalCount;\n    gops.duration += currentGop.duration; // push the final Gop\n\n    gops.push(currentGop);\n    return gops;\n  };\n  /*\n   * Search for the first keyframe in the GOPs and throw away all frames\n   * until that keyframe. Then extend the duration of the pulled keyframe\n   * and pull the PTS and DTS of the keyframe so that it covers the time\n   * range of the frames that were disposed.\n   *\n   * @param {Array} gops video GOPs\n   * @returns {Array} modified video GOPs\n   */\n\n  var extendFirstKeyFrame = function (gops) {\n    var currentGop;\n    if (!gops[0][0].keyFrame && gops.length > 1) {\n      // Remove the first GOP\n      currentGop = gops.shift();\n      gops.byteLength -= currentGop.byteLength;\n      gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the\n      // first gop to cover the time period of the\n      // frames we just removed\n\n      gops[0][0].dts = currentGop.dts;\n      gops[0][0].pts = currentGop.pts;\n      gops[0][0].duration += currentGop.duration;\n    }\n    return gops;\n  };\n  /**\n   * Default sample object\n   * see ISO/IEC 14496-12:2012, section 8.6.4.3\n   */\n\n  var createDefaultSample = function () {\n    return {\n      size: 0,\n      flags: {\n        isLeading: 0,\n        dependsOn: 1,\n        isDependedOn: 0,\n        hasRedundancy: 0,\n        degradationPriority: 0,\n        isNonSyncSample: 1\n      }\n    };\n  };\n  /*\n   * Collates information from a video frame into an object for eventual\n   * entry into an MP4 sample table.\n   *\n   * @param {Object} frame the video frame\n   * @param {Number} dataOffset the byte offset to position the sample\n   * @return {Object} object containing sample table info for a frame\n   */\n\n  var sampleForFrame = function (frame, dataOffset) {\n    var sample = createDefaultSample();\n    sample.dataOffset = dataOffset;\n    sample.compositionTimeOffset = frame.pts - frame.dts;\n    sample.duration = frame.duration;\n    sample.size = 4 * frame.length; // Space for nal unit size\n\n    sample.size += frame.byteLength;\n    if (frame.keyFrame) {\n      sample.flags.dependsOn = 2;\n      sample.flags.isNonSyncSample = 0;\n    }\n    return sample;\n  }; // generate the track's sample table from an array of gops\n\n  var generateSampleTable$1 = function (gops, baseDataOffset) {\n    var h,\n      i,\n      sample,\n      currentGop,\n      currentFrame,\n      dataOffset = baseDataOffset || 0,\n      samples = [];\n    for (h = 0; h < gops.length; h++) {\n      currentGop = gops[h];\n      for (i = 0; i < currentGop.length; i++) {\n        currentFrame = currentGop[i];\n        sample = sampleForFrame(currentFrame, dataOffset);\n        dataOffset += sample.size;\n        samples.push(sample);\n      }\n    }\n    return samples;\n  }; // generate the track's raw mdat data from an array of gops\n\n  var concatenateNalData = function (gops) {\n    var h,\n      i,\n      j,\n      currentGop,\n      currentFrame,\n      currentNal,\n      dataOffset = 0,\n      nalsByteLength = gops.byteLength,\n      numberOfNals = gops.nalCount,\n      totalByteLength = nalsByteLength + 4 * numberOfNals,\n      data = new Uint8Array(totalByteLength),\n      view = new DataView(data.buffer); // For each Gop..\n\n    for (h = 0; h < gops.length; h++) {\n      currentGop = gops[h]; // For each Frame..\n\n      for (i = 0; i < currentGop.length; i++) {\n        currentFrame = currentGop[i]; // For each NAL..\n\n        for (j = 0; j < currentFrame.length; j++) {\n          currentNal = currentFrame[j];\n          view.setUint32(dataOffset, currentNal.data.byteLength);\n          dataOffset += 4;\n          data.set(currentNal.data, dataOffset);\n          dataOffset += currentNal.data.byteLength;\n        }\n      }\n    }\n    return data;\n  }; // generate the track's sample table from a frame\n\n  var generateSampleTableForFrame = function (frame, baseDataOffset) {\n    var sample,\n      dataOffset = baseDataOffset || 0,\n      samples = [];\n    sample = sampleForFrame(frame, dataOffset);\n    samples.push(sample);\n    return samples;\n  }; // generate the track's raw mdat data from a frame\n\n  var concatenateNalDataForFrame = function (frame) {\n    var i,\n      currentNal,\n      dataOffset = 0,\n      nalsByteLength = frame.byteLength,\n      numberOfNals = frame.length,\n      totalByteLength = nalsByteLength + 4 * numberOfNals,\n      data = new Uint8Array(totalByteLength),\n      view = new DataView(data.buffer); // For each NAL..\n\n    for (i = 0; i < frame.length; i++) {\n      currentNal = frame[i];\n      view.setUint32(dataOffset, currentNal.data.byteLength);\n      dataOffset += 4;\n      data.set(currentNal.data, dataOffset);\n      dataOffset += currentNal.data.byteLength;\n    }\n    return data;\n  };\n  var frameUtils$1 = {\n    groupNalsIntoFrames: groupNalsIntoFrames,\n    groupFramesIntoGops: groupFramesIntoGops,\n    extendFirstKeyFrame: extendFirstKeyFrame,\n    generateSampleTable: generateSampleTable$1,\n    concatenateNalData: concatenateNalData,\n    generateSampleTableForFrame: generateSampleTableForFrame,\n    concatenateNalDataForFrame: concatenateNalDataForFrame\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n\n  var highPrefix = [33, 16, 5, 32, 164, 27];\n  var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];\n  var zeroFill = function (count) {\n    var a = [];\n    while (count--) {\n      a.push(0);\n    }\n    return a;\n  };\n  var makeTable = function (metaTable) {\n    return Object.keys(metaTable).reduce(function (obj, key) {\n      obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {\n        return arr.concat(part);\n      }, []));\n      return obj;\n    }, {});\n  };\n  var silence;\n  var silence_1 = function () {\n    if (!silence) {\n      // Frames-of-silence to use for filling in missing AAC frames\n      var coneOfSilence = {\n        96000: [highPrefix, [227, 64], zeroFill(154), [56]],\n        88200: [highPrefix, [231], zeroFill(170), [56]],\n        64000: [highPrefix, [248, 192], zeroFill(240), [56]],\n        48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],\n        44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],\n        32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],\n        24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],\n        16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],\n        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]],\n        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]],\n        8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]\n      };\n      silence = makeTable(coneOfSilence);\n    }\n    return silence;\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n\n  var ONE_SECOND_IN_TS$4 = 90000,\n    // 90kHz clock\n    secondsToVideoTs,\n    secondsToAudioTs,\n    videoTsToSeconds,\n    audioTsToSeconds,\n    audioTsToVideoTs,\n    videoTsToAudioTs,\n    metadataTsToSeconds;\n  secondsToVideoTs = function (seconds) {\n    return seconds * ONE_SECOND_IN_TS$4;\n  };\n  secondsToAudioTs = function (seconds, sampleRate) {\n    return seconds * sampleRate;\n  };\n  videoTsToSeconds = function (timestamp) {\n    return timestamp / ONE_SECOND_IN_TS$4;\n  };\n  audioTsToSeconds = function (timestamp, sampleRate) {\n    return timestamp / sampleRate;\n  };\n  audioTsToVideoTs = function (timestamp, sampleRate) {\n    return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));\n  };\n  videoTsToAudioTs = function (timestamp, sampleRate) {\n    return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);\n  };\n  /**\n   * Adjust ID3 tag or caption timing information by the timeline pts values\n   * (if keepOriginalTimestamps is false) and convert to seconds\n   */\n\n  metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {\n    return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);\n  };\n  var clock$2 = {\n    ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,\n    secondsToVideoTs: secondsToVideoTs,\n    secondsToAudioTs: secondsToAudioTs,\n    videoTsToSeconds: videoTsToSeconds,\n    audioTsToSeconds: audioTsToSeconds,\n    audioTsToVideoTs: audioTsToVideoTs,\n    videoTsToAudioTs: videoTsToAudioTs,\n    metadataTsToSeconds: metadataTsToSeconds\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n\n  var coneOfSilence = silence_1;\n  var clock$1 = clock$2;\n  /**\n   * Sum the `byteLength` properties of the data in each AAC frame\n   */\n\n  var sumFrameByteLengths = function (array) {\n    var i,\n      currentObj,\n      sum = 0; // sum the byteLength's all each nal unit in the frame\n\n    for (i = 0; i < array.length; i++) {\n      currentObj = array[i];\n      sum += currentObj.data.byteLength;\n    }\n    return sum;\n  }; // Possibly pad (prefix) the audio track with silence if appending this track\n  // would lead to the introduction of a gap in the audio buffer\n\n  var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {\n    var baseMediaDecodeTimeTs,\n      frameDuration = 0,\n      audioGapDuration = 0,\n      audioFillFrameCount = 0,\n      audioFillDuration = 0,\n      silentFrame,\n      i,\n      firstFrame;\n    if (!frames.length) {\n      return;\n    }\n    baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills\n\n    frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));\n    if (audioAppendStartTs && videoBaseMediaDecodeTime) {\n      // insert the shortest possible amount (audio gap or audio to video gap)\n      audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap\n\n      audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);\n      audioFillDuration = audioFillFrameCount * frameDuration;\n    } // don't attempt to fill gaps smaller than a single frame or larger\n    // than a half second\n\n    if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {\n      return;\n    }\n    silentFrame = coneOfSilence()[track.samplerate];\n    if (!silentFrame) {\n      // we don't have a silent frame pregenerated for the sample rate, so use a frame\n      // from the content instead\n      silentFrame = frames[0].data;\n    }\n    for (i = 0; i < audioFillFrameCount; i++) {\n      firstFrame = frames[0];\n      frames.splice(0, 0, {\n        data: silentFrame,\n        dts: firstFrame.dts - frameDuration,\n        pts: firstFrame.pts - frameDuration\n      });\n    }\n    track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));\n    return audioFillDuration;\n  }; // If the audio segment extends before the earliest allowed dts\n  // value, remove AAC frames until starts at or after the earliest\n  // allowed DTS so that we don't end up with a negative baseMedia-\n  // DecodeTime for the audio track\n\n  var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {\n    if (track.minSegmentDts >= earliestAllowedDts) {\n      return adtsFrames;\n    } // We will need to recalculate the earliest segment Dts\n\n    track.minSegmentDts = Infinity;\n    return adtsFrames.filter(function (currentFrame) {\n      // If this is an allowed frame, keep it and record it's Dts\n      if (currentFrame.dts >= earliestAllowedDts) {\n        track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);\n        track.minSegmentPts = track.minSegmentDts;\n        return true;\n      } // Otherwise, discard it\n\n      return false;\n    });\n  }; // generate the track's raw mdat data from an array of frames\n\n  var generateSampleTable = function (frames) {\n    var i,\n      currentFrame,\n      samples = [];\n    for (i = 0; i < frames.length; i++) {\n      currentFrame = frames[i];\n      samples.push({\n        size: currentFrame.data.byteLength,\n        duration: 1024 // For AAC audio, all samples contain 1024 samples\n      });\n    }\n    return samples;\n  }; // generate the track's sample table from an array of frames\n\n  var concatenateFrameData = function (frames) {\n    var i,\n      currentFrame,\n      dataOffset = 0,\n      data = new Uint8Array(sumFrameByteLengths(frames));\n    for (i = 0; i < frames.length; i++) {\n      currentFrame = frames[i];\n      data.set(currentFrame.data, dataOffset);\n      dataOffset += currentFrame.data.byteLength;\n    }\n    return data;\n  };\n  var audioFrameUtils$1 = {\n    prefixWithSilence: prefixWithSilence,\n    trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,\n    generateSampleTable: generateSampleTable,\n    concatenateFrameData: concatenateFrameData\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n\n  var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;\n  /**\n   * Store information about the start and end of the track and the\n   * duration for each frame/sample we process in order to calculate\n   * the baseMediaDecodeTime\n   */\n\n  var collectDtsInfo = function (track, data) {\n    if (typeof data.pts === 'number') {\n      if (track.timelineStartInfo.pts === undefined) {\n        track.timelineStartInfo.pts = data.pts;\n      }\n      if (track.minSegmentPts === undefined) {\n        track.minSegmentPts = data.pts;\n      } else {\n        track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);\n      }\n      if (track.maxSegmentPts === undefined) {\n        track.maxSegmentPts = data.pts;\n      } else {\n        track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);\n      }\n    }\n    if (typeof data.dts === 'number') {\n      if (track.timelineStartInfo.dts === undefined) {\n        track.timelineStartInfo.dts = data.dts;\n      }\n      if (track.minSegmentDts === undefined) {\n        track.minSegmentDts = data.dts;\n      } else {\n        track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);\n      }\n      if (track.maxSegmentDts === undefined) {\n        track.maxSegmentDts = data.dts;\n      } else {\n        track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);\n      }\n    }\n  };\n  /**\n   * Clear values used to calculate the baseMediaDecodeTime between\n   * tracks\n   */\n\n  var clearDtsInfo = function (track) {\n    delete track.minSegmentDts;\n    delete track.maxSegmentDts;\n    delete track.minSegmentPts;\n    delete track.maxSegmentPts;\n  };\n  /**\n   * Calculate the track's baseMediaDecodeTime based on the earliest\n   * DTS the transmuxer has ever seen and the minimum DTS for the\n   * current track\n   * @param track {object} track metadata configuration\n   * @param keepOriginalTimestamps {boolean} If true, keep the timestamps\n   *        in the source; false to adjust the first segment to start at 0.\n   */\n\n  var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {\n    var baseMediaDecodeTime,\n      scale,\n      minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.\n\n    if (!keepOriginalTimestamps) {\n      minSegmentDts -= track.timelineStartInfo.dts;\n    } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where\n    // we want the start of the first segment to be placed\n\n    baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first\n\n    baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative\n\n    baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);\n    if (track.type === 'audio') {\n      // Audio has a different clock equal to the sampling_rate so we need to\n      // scale the PTS values into the clock rate of the track\n      scale = track.samplerate / ONE_SECOND_IN_TS$3;\n      baseMediaDecodeTime *= scale;\n      baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);\n    }\n    return baseMediaDecodeTime;\n  };\n  var trackDecodeInfo$1 = {\n    clearDtsInfo: clearDtsInfo,\n    calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,\n    collectDtsInfo: collectDtsInfo\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Reads in-band caption information from a video elementary\n   * stream. Captions must follow the CEA-708 standard for injection\n   * into an MPEG-2 transport streams.\n   * @see https://en.wikipedia.org/wiki/CEA-708\n   * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf\n   */\n  // payload type field to indicate how they are to be\n  // interpreted. CEAS-708 caption content is always transmitted with\n  // payload type 0x04.\n\n  var USER_DATA_REGISTERED_ITU_T_T35 = 4,\n    RBSP_TRAILING_BITS = 128;\n  /**\n    * Parse a supplemental enhancement information (SEI) NAL unit.\n    * Stops parsing once a message of type ITU T T35 has been found.\n    *\n    * @param bytes {Uint8Array} the bytes of a SEI NAL unit\n    * @return {object} the parsed SEI payload\n    * @see Rec. ITU-T H.264, 7.3.2.3.1\n    */\n\n  var parseSei = function (bytes) {\n    var i = 0,\n      result = {\n        payloadType: -1,\n        payloadSize: 0\n      },\n      payloadType = 0,\n      payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message\n\n    while (i < bytes.byteLength) {\n      // stop once we have hit the end of the sei_rbsp\n      if (bytes[i] === RBSP_TRAILING_BITS) {\n        break;\n      } // Parse payload type\n\n      while (bytes[i] === 0xFF) {\n        payloadType += 255;\n        i++;\n      }\n      payloadType += bytes[i++]; // Parse payload size\n\n      while (bytes[i] === 0xFF) {\n        payloadSize += 255;\n        i++;\n      }\n      payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break\n      // there can only ever be one caption message in a frame's sei\n\n      if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {\n        var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);\n        if (userIdentifier === 'GA94') {\n          result.payloadType = payloadType;\n          result.payloadSize = payloadSize;\n          result.payload = bytes.subarray(i, i + payloadSize);\n          break;\n        } else {\n          result.payload = void 0;\n        }\n      } // skip the payload and parse the next message\n\n      i += payloadSize;\n      payloadType = 0;\n      payloadSize = 0;\n    }\n    return result;\n  }; // see ANSI/SCTE 128-1 (2013), section 8.1\n\n  var parseUserData = function (sei) {\n    // itu_t_t35_contry_code must be 181 (United States) for\n    // captions\n    if (sei.payload[0] !== 181) {\n      return null;\n    } // itu_t_t35_provider_code should be 49 (ATSC) for captions\n\n    if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {\n      return null;\n    } // the user_identifier should be \"GA94\" to indicate ATSC1 data\n\n    if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {\n      return null;\n    } // finally, user_data_type_code should be 0x03 for caption data\n\n    if (sei.payload[7] !== 0x03) {\n      return null;\n    } // return the user_data_type_structure and strip the trailing\n    // marker bits\n\n    return sei.payload.subarray(8, sei.payload.length - 1);\n  }; // see CEA-708-D, section 4.4\n\n  var parseCaptionPackets = function (pts, userData) {\n    var results = [],\n      i,\n      count,\n      offset,\n      data; // if this is just filler, return immediately\n\n    if (!(userData[0] & 0x40)) {\n      return results;\n    } // parse out the cc_data_1 and cc_data_2 fields\n\n    count = userData[0] & 0x1f;\n    for (i = 0; i < count; i++) {\n      offset = i * 3;\n      data = {\n        type: userData[offset + 2] & 0x03,\n        pts: pts\n      }; // capture cc data when cc_valid is 1\n\n      if (userData[offset + 2] & 0x04) {\n        data.ccData = userData[offset + 3] << 8 | userData[offset + 4];\n        results.push(data);\n      }\n    }\n    return results;\n  };\n  var discardEmulationPreventionBytes$1 = function (data) {\n    var length = data.byteLength,\n      emulationPreventionBytesPositions = [],\n      i = 1,\n      newLength,\n      newData; // Find all `Emulation Prevention Bytes`\n\n    while (i < length - 2) {\n      if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {\n        emulationPreventionBytesPositions.push(i + 2);\n        i += 2;\n      } else {\n        i++;\n      }\n    } // If no Emulation Prevention Bytes were found just return the original\n    // array\n\n    if (emulationPreventionBytesPositions.length === 0) {\n      return data;\n    } // Create a new array to hold the NAL unit data\n\n    newLength = length - emulationPreventionBytesPositions.length;\n    newData = new Uint8Array(newLength);\n    var sourceIndex = 0;\n    for (i = 0; i < newLength; sourceIndex++, i++) {\n      if (sourceIndex === emulationPreventionBytesPositions[0]) {\n        // Skip this byte\n        sourceIndex++; // Remove this position index\n\n        emulationPreventionBytesPositions.shift();\n      }\n      newData[i] = data[sourceIndex];\n    }\n    return newData;\n  }; // exports\n\n  var captionPacketParser = {\n    parseSei: parseSei,\n    parseUserData: parseUserData,\n    parseCaptionPackets: parseCaptionPackets,\n    discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,\n    USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Reads in-band caption information from a video elementary\n   * stream. Captions must follow the CEA-708 standard for injection\n   * into an MPEG-2 transport streams.\n   * @see https://en.wikipedia.org/wiki/CEA-708\n   * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf\n   */\n  // Link To Transport\n  // -----------------\n\n  var Stream$7 = stream;\n  var cea708Parser = captionPacketParser;\n  var CaptionStream$2 = function (options) {\n    options = options || {};\n    CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true\n\n    this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;\n    this.captionPackets_ = [];\n    this.ccStreams_ = [new Cea608Stream(0, 0),\n    // eslint-disable-line no-use-before-define\n    new Cea608Stream(0, 1),\n    // eslint-disable-line no-use-before-define\n    new Cea608Stream(1, 0),\n    // eslint-disable-line no-use-before-define\n    new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define\n    ];\n    if (this.parse708captions_) {\n      this.cc708Stream_ = new Cea708Stream({\n        captionServices: options.captionServices\n      }); // eslint-disable-line no-use-before-define\n    }\n    this.reset(); // forward data and done events from CCs to this CaptionStream\n\n    this.ccStreams_.forEach(function (cc) {\n      cc.on('data', this.trigger.bind(this, 'data'));\n      cc.on('partialdone', this.trigger.bind(this, 'partialdone'));\n      cc.on('done', this.trigger.bind(this, 'done'));\n    }, this);\n    if (this.parse708captions_) {\n      this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));\n      this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));\n      this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));\n    }\n  };\n  CaptionStream$2.prototype = new Stream$7();\n  CaptionStream$2.prototype.push = function (event) {\n    var sei, userData, newCaptionPackets; // only examine SEI NALs\n\n    if (event.nalUnitType !== 'sei_rbsp') {\n      return;\n    } // parse the sei\n\n    sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip\n\n    if (!sei.payload) {\n      return;\n    } // ignore everything but user_data_registered_itu_t_t35\n\n    if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {\n      return;\n    } // parse out the user data payload\n\n    userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData\n\n    if (!userData) {\n      return;\n    } // Sometimes, the same segment # will be downloaded twice. To stop the\n    // caption data from being processed twice, we track the latest dts we've\n    // received and ignore everything with a dts before that. However, since\n    // data for a specific dts can be split across packets on either side of\n    // a segment boundary, we need to make sure we *don't* ignore the packets\n    // from the *next* segment that have dts === this.latestDts_. By constantly\n    // tracking the number of packets received with dts === this.latestDts_, we\n    // know how many should be ignored once we start receiving duplicates.\n\n    if (event.dts < this.latestDts_) {\n      // We've started getting older data, so set the flag.\n      this.ignoreNextEqualDts_ = true;\n      return;\n    } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {\n      this.numSameDts_--;\n      if (!this.numSameDts_) {\n        // We've received the last duplicate packet, time to start processing again\n        this.ignoreNextEqualDts_ = false;\n      }\n      return;\n    } // parse out CC data packets and save them for later\n\n    newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);\n    this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);\n    if (this.latestDts_ !== event.dts) {\n      this.numSameDts_ = 0;\n    }\n    this.numSameDts_++;\n    this.latestDts_ = event.dts;\n  };\n  CaptionStream$2.prototype.flushCCStreams = function (flushType) {\n    this.ccStreams_.forEach(function (cc) {\n      return flushType === 'flush' ? cc.flush() : cc.partialFlush();\n    }, this);\n  };\n  CaptionStream$2.prototype.flushStream = function (flushType) {\n    // make sure we actually parsed captions before proceeding\n    if (!this.captionPackets_.length) {\n      this.flushCCStreams(flushType);\n      return;\n    } // In Chrome, the Array#sort function is not stable so add a\n    // presortIndex that we can use to ensure we get a stable-sort\n\n    this.captionPackets_.forEach(function (elem, idx) {\n      elem.presortIndex = idx;\n    }); // sort caption byte-pairs based on their PTS values\n\n    this.captionPackets_.sort(function (a, b) {\n      if (a.pts === b.pts) {\n        return a.presortIndex - b.presortIndex;\n      }\n      return a.pts - b.pts;\n    });\n    this.captionPackets_.forEach(function (packet) {\n      if (packet.type < 2) {\n        // Dispatch packet to the right Cea608Stream\n        this.dispatchCea608Packet(packet);\n      } else {\n        // Dispatch packet to the Cea708Stream\n        this.dispatchCea708Packet(packet);\n      }\n    }, this);\n    this.captionPackets_.length = 0;\n    this.flushCCStreams(flushType);\n  };\n  CaptionStream$2.prototype.flush = function () {\n    return this.flushStream('flush');\n  }; // Only called if handling partial data\n\n  CaptionStream$2.prototype.partialFlush = function () {\n    return this.flushStream('partialFlush');\n  };\n  CaptionStream$2.prototype.reset = function () {\n    this.latestDts_ = null;\n    this.ignoreNextEqualDts_ = false;\n    this.numSameDts_ = 0;\n    this.activeCea608Channel_ = [null, null];\n    this.ccStreams_.forEach(function (ccStream) {\n      ccStream.reset();\n    });\n  }; // From the CEA-608 spec:\n\n  /*\n   * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed\n   * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is\n   * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair\n   * and subsequent data should then be processed according to the FCC rules. It may be necessary for the\n   * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)\n   * to switch to captioning or Text.\n  */\n  // With that in mind, we ignore any data between an XDS control code and a\n  // subsequent closed-captioning control code.\n\n  CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {\n    // NOTE: packet.type is the CEA608 field\n    if (this.setsTextOrXDSActive(packet)) {\n      this.activeCea608Channel_[packet.type] = null;\n    } else if (this.setsChannel1Active(packet)) {\n      this.activeCea608Channel_[packet.type] = 0;\n    } else if (this.setsChannel2Active(packet)) {\n      this.activeCea608Channel_[packet.type] = 1;\n    }\n    if (this.activeCea608Channel_[packet.type] === null) {\n      // If we haven't received anything to set the active channel, or the\n      // packets are Text/XDS data, discard the data; we don't want jumbled\n      // captions\n      return;\n    }\n    this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);\n  };\n  CaptionStream$2.prototype.setsChannel1Active = function (packet) {\n    return (packet.ccData & 0x7800) === 0x1000;\n  };\n  CaptionStream$2.prototype.setsChannel2Active = function (packet) {\n    return (packet.ccData & 0x7800) === 0x1800;\n  };\n  CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {\n    return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;\n  };\n  CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {\n    if (this.parse708captions_) {\n      this.cc708Stream_.push(packet);\n    }\n  }; // ----------------------\n  // Session to Application\n  // ----------------------\n  // This hash maps special and extended character codes to their\n  // proper Unicode equivalent. The first one-byte key is just a\n  // non-standard character code. The two-byte keys that follow are\n  // the extended CEA708 character codes, along with the preceding\n  // 0x10 extended character byte to distinguish these codes from\n  // non-extended character codes. Every CEA708 character code that\n  // is not in this object maps directly to a standard unicode\n  // character code.\n  // The transparent space and non-breaking transparent space are\n  // technically not fully supported since there is no code to\n  // make them transparent, so they have normal non-transparent\n  // stand-ins.\n  // The special closed caption (CC) character isn't a standard\n  // unicode character, so a fairly similar unicode character was\n  // chosen in it's place.\n\n  var CHARACTER_TRANSLATION_708 = {\n    0x7f: 0x266a,\n    // ♪\n    0x1020: 0x20,\n    // Transparent Space\n    0x1021: 0xa0,\n    // Nob-breaking Transparent Space\n    0x1025: 0x2026,\n    // …\n    0x102a: 0x0160,\n    // Š\n    0x102c: 0x0152,\n    // Œ\n    0x1030: 0x2588,\n    // █\n    0x1031: 0x2018,\n    // ‘\n    0x1032: 0x2019,\n    // ’\n    0x1033: 0x201c,\n    // “\n    0x1034: 0x201d,\n    // ”\n    0x1035: 0x2022,\n    // •\n    0x1039: 0x2122,\n    // ™\n    0x103a: 0x0161,\n    // š\n    0x103c: 0x0153,\n    // œ\n    0x103d: 0x2120,\n    // ℠\n    0x103f: 0x0178,\n    // Ÿ\n    0x1076: 0x215b,\n    // ⅛\n    0x1077: 0x215c,\n    // ⅜\n    0x1078: 0x215d,\n    // ⅝\n    0x1079: 0x215e,\n    // ⅞\n    0x107a: 0x23d0,\n    // ⏐\n    0x107b: 0x23a4,\n    // ⎤\n    0x107c: 0x23a3,\n    // ⎣\n    0x107d: 0x23af,\n    // ⎯\n    0x107e: 0x23a6,\n    // ⎦\n    0x107f: 0x23a1,\n    // ⎡\n    0x10a0: 0x3138 // ㄸ (CC char)\n  };\n  var get708CharFromCode = function (code) {\n    var newCode = CHARACTER_TRANSLATION_708[code] || code;\n    if (code & 0x1000 && code === newCode) {\n      // Invalid extended code\n      return '';\n    }\n    return String.fromCharCode(newCode);\n  };\n  var within708TextBlock = function (b) {\n    return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;\n  };\n  var Cea708Window = function (windowNum) {\n    this.windowNum = windowNum;\n    this.reset();\n  };\n  Cea708Window.prototype.reset = function () {\n    this.clearText();\n    this.pendingNewLine = false;\n    this.winAttr = {};\n    this.penAttr = {};\n    this.penLoc = {};\n    this.penColor = {}; // These default values are arbitrary,\n    // defineWindow will usually override them\n\n    this.visible = 0;\n    this.rowLock = 0;\n    this.columnLock = 0;\n    this.priority = 0;\n    this.relativePositioning = 0;\n    this.anchorVertical = 0;\n    this.anchorHorizontal = 0;\n    this.anchorPoint = 0;\n    this.rowCount = 1;\n    this.virtualRowCount = this.rowCount + 1;\n    this.columnCount = 41;\n    this.windowStyle = 0;\n    this.penStyle = 0;\n  };\n  Cea708Window.prototype.getText = function () {\n    return this.rows.join('\\n');\n  };\n  Cea708Window.prototype.clearText = function () {\n    this.rows = [''];\n    this.rowIdx = 0;\n  };\n  Cea708Window.prototype.newLine = function (pts) {\n    if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {\n      this.beforeRowOverflow(pts);\n    }\n    if (this.rows.length > 0) {\n      this.rows.push('');\n      this.rowIdx++;\n    } // Show all virtual rows since there's no visible scrolling\n\n    while (this.rows.length > this.virtualRowCount) {\n      this.rows.shift();\n      this.rowIdx--;\n    }\n  };\n  Cea708Window.prototype.isEmpty = function () {\n    if (this.rows.length === 0) {\n      return true;\n    } else if (this.rows.length === 1) {\n      return this.rows[0] === '';\n    }\n    return false;\n  };\n  Cea708Window.prototype.addText = function (text) {\n    this.rows[this.rowIdx] += text;\n  };\n  Cea708Window.prototype.backspace = function () {\n    if (!this.isEmpty()) {\n      var row = this.rows[this.rowIdx];\n      this.rows[this.rowIdx] = row.substr(0, row.length - 1);\n    }\n  };\n  var Cea708Service = function (serviceNum, encoding, stream) {\n    this.serviceNum = serviceNum;\n    this.text = '';\n    this.currentWindow = new Cea708Window(-1);\n    this.windows = [];\n    this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided\n\n    if (typeof encoding === 'string') {\n      this.createTextDecoder(encoding);\n    }\n  };\n  /**\n   * Initialize service windows\n   * Must be run before service use\n   *\n   * @param  {Integer}  pts               PTS value\n   * @param  {Function} beforeRowOverflow Function to execute before row overflow of a window\n   */\n\n  Cea708Service.prototype.init = function (pts, beforeRowOverflow) {\n    this.startPts = pts;\n    for (var win = 0; win < 8; win++) {\n      this.windows[win] = new Cea708Window(win);\n      if (typeof beforeRowOverflow === 'function') {\n        this.windows[win].beforeRowOverflow = beforeRowOverflow;\n      }\n    }\n  };\n  /**\n   * Set current window of service to be affected by commands\n   *\n   * @param  {Integer} windowNum Window number\n   */\n\n  Cea708Service.prototype.setCurrentWindow = function (windowNum) {\n    this.currentWindow = this.windows[windowNum];\n  };\n  /**\n   * Try to create a TextDecoder if it is natively supported\n   */\n\n  Cea708Service.prototype.createTextDecoder = function (encoding) {\n    if (typeof TextDecoder === 'undefined') {\n      this.stream.trigger('log', {\n        level: 'warn',\n        message: 'The `encoding` option is unsupported without TextDecoder support'\n      });\n    } else {\n      try {\n        this.textDecoder_ = new TextDecoder(encoding);\n      } catch (error) {\n        this.stream.trigger('log', {\n          level: 'warn',\n          message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error\n        });\n      }\n    }\n  };\n  var Cea708Stream = function (options) {\n    options = options || {};\n    Cea708Stream.prototype.init.call(this);\n    var self = this;\n    var captionServices = options.captionServices || {};\n    var captionServiceEncodings = {};\n    var serviceProps; // Get service encodings from captionServices option block\n\n    Object.keys(captionServices).forEach(serviceName => {\n      serviceProps = captionServices[serviceName];\n      if (/^SERVICE/.test(serviceName)) {\n        captionServiceEncodings[serviceName] = serviceProps.encoding;\n      }\n    });\n    this.serviceEncodings = captionServiceEncodings;\n    this.current708Packet = null;\n    this.services = {};\n    this.push = function (packet) {\n      if (packet.type === 3) {\n        // 708 packet start\n        self.new708Packet();\n        self.add708Bytes(packet);\n      } else {\n        if (self.current708Packet === null) {\n          // This should only happen at the start of a file if there's no packet start.\n          self.new708Packet();\n        }\n        self.add708Bytes(packet);\n      }\n    };\n  };\n  Cea708Stream.prototype = new Stream$7();\n  /**\n   * Push current 708 packet, create new 708 packet.\n   */\n\n  Cea708Stream.prototype.new708Packet = function () {\n    if (this.current708Packet !== null) {\n      this.push708Packet();\n    }\n    this.current708Packet = {\n      data: [],\n      ptsVals: []\n    };\n  };\n  /**\n   * Add pts and both bytes from packet into current 708 packet.\n   */\n\n  Cea708Stream.prototype.add708Bytes = function (packet) {\n    var data = packet.ccData;\n    var byte0 = data >>> 8;\n    var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec\n    // that service blocks will always line up with byte pairs.\n\n    this.current708Packet.ptsVals.push(packet.pts);\n    this.current708Packet.data.push(byte0);\n    this.current708Packet.data.push(byte1);\n  };\n  /**\n   * Parse completed 708 packet into service blocks and push each service block.\n   */\n\n  Cea708Stream.prototype.push708Packet = function () {\n    var packet708 = this.current708Packet;\n    var packetData = packet708.data;\n    var serviceNum = null;\n    var blockSize = null;\n    var i = 0;\n    var b = packetData[i++];\n    packet708.seq = b >> 6;\n    packet708.sizeCode = b & 0x3f; // 0b00111111;\n\n    for (; i < packetData.length; i++) {\n      b = packetData[i++];\n      serviceNum = b >> 5;\n      blockSize = b & 0x1f; // 0b00011111\n\n      if (serviceNum === 7 && blockSize > 0) {\n        // Extended service num\n        b = packetData[i++];\n        serviceNum = b;\n      }\n      this.pushServiceBlock(serviceNum, i, blockSize);\n      if (blockSize > 0) {\n        i += blockSize - 1;\n      }\n    }\n  };\n  /**\n   * Parse service block, execute commands, read text.\n   *\n   * Note: While many of these commands serve important purposes,\n   * many others just parse out the parameters or attributes, but\n   * nothing is done with them because this is not a full and complete\n   * implementation of the entire 708 spec.\n   *\n   * @param  {Integer} serviceNum Service number\n   * @param  {Integer} start      Start index of the 708 packet data\n   * @param  {Integer} size       Block size\n   */\n\n  Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {\n    var b;\n    var i = start;\n    var packetData = this.current708Packet.data;\n    var service = this.services[serviceNum];\n    if (!service) {\n      service = this.initService(serviceNum, i);\n    }\n    for (; i < start + size && i < packetData.length; i++) {\n      b = packetData[i];\n      if (within708TextBlock(b)) {\n        i = this.handleText(i, service);\n      } else if (b === 0x18) {\n        i = this.multiByteCharacter(i, service);\n      } else if (b === 0x10) {\n        i = this.extendedCommands(i, service);\n      } else if (0x80 <= b && b <= 0x87) {\n        i = this.setCurrentWindow(i, service);\n      } else if (0x98 <= b && b <= 0x9f) {\n        i = this.defineWindow(i, service);\n      } else if (b === 0x88) {\n        i = this.clearWindows(i, service);\n      } else if (b === 0x8c) {\n        i = this.deleteWindows(i, service);\n      } else if (b === 0x89) {\n        i = this.displayWindows(i, service);\n      } else if (b === 0x8a) {\n        i = this.hideWindows(i, service);\n      } else if (b === 0x8b) {\n        i = this.toggleWindows(i, service);\n      } else if (b === 0x97) {\n        i = this.setWindowAttributes(i, service);\n      } else if (b === 0x90) {\n        i = this.setPenAttributes(i, service);\n      } else if (b === 0x91) {\n        i = this.setPenColor(i, service);\n      } else if (b === 0x92) {\n        i = this.setPenLocation(i, service);\n      } else if (b === 0x8f) {\n        service = this.reset(i, service);\n      } else if (b === 0x08) {\n        // BS: Backspace\n        service.currentWindow.backspace();\n      } else if (b === 0x0c) {\n        // FF: Form feed\n        service.currentWindow.clearText();\n      } else if (b === 0x0d) {\n        // CR: Carriage return\n        service.currentWindow.pendingNewLine = true;\n      } else if (b === 0x0e) {\n        // HCR: Horizontal carriage return\n        service.currentWindow.clearText();\n      } else if (b === 0x8d) {\n        // DLY: Delay, nothing to do\n        i++;\n      } else ;\n    }\n  };\n  /**\n   * Execute an extended command\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.extendedCommands = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[++i];\n    if (within708TextBlock(b)) {\n      i = this.handleText(i, service, {\n        isExtended: true\n      });\n    }\n    return i;\n  };\n  /**\n   * Get PTS value of a given byte index\n   *\n   * @param  {Integer} byteIndex  Index of the byte\n   * @return {Integer}            PTS\n   */\n\n  Cea708Stream.prototype.getPts = function (byteIndex) {\n    // There's 1 pts value per 2 bytes\n    return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];\n  };\n  /**\n   * Initializes a service\n   *\n   * @param  {Integer} serviceNum Service number\n   * @return {Service}            Initialized service object\n   */\n\n  Cea708Stream.prototype.initService = function (serviceNum, i) {\n    var serviceName = 'SERVICE' + serviceNum;\n    var self = this;\n    var serviceName;\n    var encoding;\n    if (serviceName in this.serviceEncodings) {\n      encoding = this.serviceEncodings[serviceName];\n    }\n    this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);\n    this.services[serviceNum].init(this.getPts(i), function (pts) {\n      self.flushDisplayed(pts, self.services[serviceNum]);\n    });\n    return this.services[serviceNum];\n  };\n  /**\n   * Execute text writing to current window\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.handleText = function (i, service, options) {\n    var isExtended = options && options.isExtended;\n    var isMultiByte = options && options.isMultiByte;\n    var packetData = this.current708Packet.data;\n    var extended = isExtended ? 0x1000 : 0x0000;\n    var currentByte = packetData[i];\n    var nextByte = packetData[i + 1];\n    var win = service.currentWindow;\n    var char;\n    var charCodeArray; // Converts an array of bytes to a unicode hex string.\n\n    function toHexString(byteArray) {\n      return byteArray.map(byte => {\n        return ('0' + (byte & 0xFF).toString(16)).slice(-2);\n      }).join('');\n    }\n    if (isMultiByte) {\n      charCodeArray = [currentByte, nextByte];\n      i++;\n    } else {\n      charCodeArray = [currentByte];\n    } // Use the TextDecoder if one was created for this service\n\n    if (service.textDecoder_ && !isExtended) {\n      char = service.textDecoder_.decode(new Uint8Array(charCodeArray));\n    } else {\n      // We assume any multi-byte char without a decoder is unicode.\n      if (isMultiByte) {\n        const unicode = toHexString(charCodeArray); // Takes a unicode hex string and creates a single character.\n\n        char = String.fromCharCode(parseInt(unicode, 16));\n      } else {\n        char = get708CharFromCode(extended | currentByte);\n      }\n    }\n    if (win.pendingNewLine && !win.isEmpty()) {\n      win.newLine(this.getPts(i));\n    }\n    win.pendingNewLine = false;\n    win.addText(char);\n    return i;\n  };\n  /**\n   * Handle decoding of multibyte character\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.multiByteCharacter = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var firstByte = packetData[i + 1];\n    var secondByte = packetData[i + 2];\n    if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {\n      i = this.handleText(++i, service, {\n        isMultiByte: true\n      });\n    }\n    return i;\n  };\n  /**\n   * Parse and execute the CW# command.\n   *\n   * Set the current window.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.setCurrentWindow = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[i];\n    var windowNum = b & 0x07;\n    service.setCurrentWindow(windowNum);\n    return i;\n  };\n  /**\n   * Parse and execute the DF# command.\n   *\n   * Define a window and set it as the current window.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.defineWindow = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[i];\n    var windowNum = b & 0x07;\n    service.setCurrentWindow(windowNum);\n    var win = service.currentWindow;\n    b = packetData[++i];\n    win.visible = (b & 0x20) >> 5; // v\n\n    win.rowLock = (b & 0x10) >> 4; // rl\n\n    win.columnLock = (b & 0x08) >> 3; // cl\n\n    win.priority = b & 0x07; // p\n\n    b = packetData[++i];\n    win.relativePositioning = (b & 0x80) >> 7; // rp\n\n    win.anchorVertical = b & 0x7f; // av\n\n    b = packetData[++i];\n    win.anchorHorizontal = b; // ah\n\n    b = packetData[++i];\n    win.anchorPoint = (b & 0xf0) >> 4; // ap\n\n    win.rowCount = b & 0x0f; // rc\n\n    b = packetData[++i];\n    win.columnCount = b & 0x3f; // cc\n\n    b = packetData[++i];\n    win.windowStyle = (b & 0x38) >> 3; // ws\n\n    win.penStyle = b & 0x07; // ps\n    // The spec says there are (rowCount+1) \"virtual rows\"\n\n    win.virtualRowCount = win.rowCount + 1;\n    return i;\n  };\n  /**\n   * Parse and execute the SWA command.\n   *\n   * Set attributes of the current window.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.setWindowAttributes = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[i];\n    var winAttr = service.currentWindow.winAttr;\n    b = packetData[++i];\n    winAttr.fillOpacity = (b & 0xc0) >> 6; // fo\n\n    winAttr.fillRed = (b & 0x30) >> 4; // fr\n\n    winAttr.fillGreen = (b & 0x0c) >> 2; // fg\n\n    winAttr.fillBlue = b & 0x03; // fb\n\n    b = packetData[++i];\n    winAttr.borderType = (b & 0xc0) >> 6; // bt\n\n    winAttr.borderRed = (b & 0x30) >> 4; // br\n\n    winAttr.borderGreen = (b & 0x0c) >> 2; // bg\n\n    winAttr.borderBlue = b & 0x03; // bb\n\n    b = packetData[++i];\n    winAttr.borderType += (b & 0x80) >> 5; // bt\n\n    winAttr.wordWrap = (b & 0x40) >> 6; // ww\n\n    winAttr.printDirection = (b & 0x30) >> 4; // pd\n\n    winAttr.scrollDirection = (b & 0x0c) >> 2; // sd\n\n    winAttr.justify = b & 0x03; // j\n\n    b = packetData[++i];\n    winAttr.effectSpeed = (b & 0xf0) >> 4; // es\n\n    winAttr.effectDirection = (b & 0x0c) >> 2; // ed\n\n    winAttr.displayEffect = b & 0x03; // de\n\n    return i;\n  };\n  /**\n   * Gather text from all displayed windows and push a caption to output.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   */\n\n  Cea708Stream.prototype.flushDisplayed = function (pts, service) {\n    var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily\n    // display text in the correct order, but sample files so far have not shown any issue.\n\n    for (var winId = 0; winId < 8; winId++) {\n      if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {\n        displayedText.push(service.windows[winId].getText());\n      }\n    }\n    service.endPts = pts;\n    service.text = displayedText.join('\\n\\n');\n    this.pushCaption(service);\n    service.startPts = pts;\n  };\n  /**\n   * Push a caption to output if the caption contains text.\n   *\n   * @param  {Service} service  The service object to be affected\n   */\n\n  Cea708Stream.prototype.pushCaption = function (service) {\n    if (service.text !== '') {\n      this.trigger('data', {\n        startPts: service.startPts,\n        endPts: service.endPts,\n        text: service.text,\n        stream: 'cc708_' + service.serviceNum\n      });\n      service.text = '';\n      service.startPts = service.endPts;\n    }\n  };\n  /**\n   * Parse and execute the DSW command.\n   *\n   * Set visible property of windows based on the parsed bitmask.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.displayWindows = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[++i];\n    var pts = this.getPts(i);\n    this.flushDisplayed(pts, service);\n    for (var winId = 0; winId < 8; winId++) {\n      if (b & 0x01 << winId) {\n        service.windows[winId].visible = 1;\n      }\n    }\n    return i;\n  };\n  /**\n   * Parse and execute the HDW command.\n   *\n   * Set visible property of windows based on the parsed bitmask.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.hideWindows = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[++i];\n    var pts = this.getPts(i);\n    this.flushDisplayed(pts, service);\n    for (var winId = 0; winId < 8; winId++) {\n      if (b & 0x01 << winId) {\n        service.windows[winId].visible = 0;\n      }\n    }\n    return i;\n  };\n  /**\n   * Parse and execute the TGW command.\n   *\n   * Set visible property of windows based on the parsed bitmask.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.toggleWindows = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[++i];\n    var pts = this.getPts(i);\n    this.flushDisplayed(pts, service);\n    for (var winId = 0; winId < 8; winId++) {\n      if (b & 0x01 << winId) {\n        service.windows[winId].visible ^= 1;\n      }\n    }\n    return i;\n  };\n  /**\n   * Parse and execute the CLW command.\n   *\n   * Clear text of windows based on the parsed bitmask.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.clearWindows = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[++i];\n    var pts = this.getPts(i);\n    this.flushDisplayed(pts, service);\n    for (var winId = 0; winId < 8; winId++) {\n      if (b & 0x01 << winId) {\n        service.windows[winId].clearText();\n      }\n    }\n    return i;\n  };\n  /**\n   * Parse and execute the DLW command.\n   *\n   * Re-initialize windows based on the parsed bitmask.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.deleteWindows = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[++i];\n    var pts = this.getPts(i);\n    this.flushDisplayed(pts, service);\n    for (var winId = 0; winId < 8; winId++) {\n      if (b & 0x01 << winId) {\n        service.windows[winId].reset();\n      }\n    }\n    return i;\n  };\n  /**\n   * Parse and execute the SPA command.\n   *\n   * Set pen attributes of the current window.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.setPenAttributes = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[i];\n    var penAttr = service.currentWindow.penAttr;\n    b = packetData[++i];\n    penAttr.textTag = (b & 0xf0) >> 4; // tt\n\n    penAttr.offset = (b & 0x0c) >> 2; // o\n\n    penAttr.penSize = b & 0x03; // s\n\n    b = packetData[++i];\n    penAttr.italics = (b & 0x80) >> 7; // i\n\n    penAttr.underline = (b & 0x40) >> 6; // u\n\n    penAttr.edgeType = (b & 0x38) >> 3; // et\n\n    penAttr.fontStyle = b & 0x07; // fs\n\n    return i;\n  };\n  /**\n   * Parse and execute the SPC command.\n   *\n   * Set pen color of the current window.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.setPenColor = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[i];\n    var penColor = service.currentWindow.penColor;\n    b = packetData[++i];\n    penColor.fgOpacity = (b & 0xc0) >> 6; // fo\n\n    penColor.fgRed = (b & 0x30) >> 4; // fr\n\n    penColor.fgGreen = (b & 0x0c) >> 2; // fg\n\n    penColor.fgBlue = b & 0x03; // fb\n\n    b = packetData[++i];\n    penColor.bgOpacity = (b & 0xc0) >> 6; // bo\n\n    penColor.bgRed = (b & 0x30) >> 4; // br\n\n    penColor.bgGreen = (b & 0x0c) >> 2; // bg\n\n    penColor.bgBlue = b & 0x03; // bb\n\n    b = packetData[++i];\n    penColor.edgeRed = (b & 0x30) >> 4; // er\n\n    penColor.edgeGreen = (b & 0x0c) >> 2; // eg\n\n    penColor.edgeBlue = b & 0x03; // eb\n\n    return i;\n  };\n  /**\n   * Parse and execute the SPL command.\n   *\n   * Set pen location of the current window.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Integer}          New index after parsing\n   */\n\n  Cea708Stream.prototype.setPenLocation = function (i, service) {\n    var packetData = this.current708Packet.data;\n    var b = packetData[i];\n    var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak\n\n    service.currentWindow.pendingNewLine = true;\n    b = packetData[++i];\n    penLoc.row = b & 0x0f; // r\n\n    b = packetData[++i];\n    penLoc.column = b & 0x3f; // c\n\n    return i;\n  };\n  /**\n   * Execute the RST command.\n   *\n   * Reset service to a clean slate. Re-initialize.\n   *\n   * @param  {Integer} i        Current index in the 708 packet\n   * @param  {Service} service  The service object to be affected\n   * @return {Service}          Re-initialized service\n   */\n\n  Cea708Stream.prototype.reset = function (i, service) {\n    var pts = this.getPts(i);\n    this.flushDisplayed(pts, service);\n    return this.initService(service.serviceNum, i);\n  }; // This hash maps non-ASCII, special, and extended character codes to their\n  // proper Unicode equivalent. The first keys that are only a single byte\n  // are the non-standard ASCII characters, which simply map the CEA608 byte\n  // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608\n  // character codes, but have their MSB bitmasked with 0x03 so that a lookup\n  // can be performed regardless of the field and data channel on which the\n  // character code was received.\n\n  var CHARACTER_TRANSLATION = {\n    0x2a: 0xe1,\n    // á\n    0x5c: 0xe9,\n    // é\n    0x5e: 0xed,\n    // í\n    0x5f: 0xf3,\n    // ó\n    0x60: 0xfa,\n    // ú\n    0x7b: 0xe7,\n    // ç\n    0x7c: 0xf7,\n    // ÷\n    0x7d: 0xd1,\n    // Ñ\n    0x7e: 0xf1,\n    // ñ\n    0x7f: 0x2588,\n    // █\n    0x0130: 0xae,\n    // ®\n    0x0131: 0xb0,\n    // °\n    0x0132: 0xbd,\n    // ½\n    0x0133: 0xbf,\n    // ¿\n    0x0134: 0x2122,\n    // ™\n    0x0135: 0xa2,\n    // ¢\n    0x0136: 0xa3,\n    // £\n    0x0137: 0x266a,\n    // ♪\n    0x0138: 0xe0,\n    // à\n    0x0139: 0xa0,\n    //\n    0x013a: 0xe8,\n    // è\n    0x013b: 0xe2,\n    // â\n    0x013c: 0xea,\n    // ê\n    0x013d: 0xee,\n    // î\n    0x013e: 0xf4,\n    // ô\n    0x013f: 0xfb,\n    // û\n    0x0220: 0xc1,\n    // Á\n    0x0221: 0xc9,\n    // É\n    0x0222: 0xd3,\n    // Ó\n    0x0223: 0xda,\n    // Ú\n    0x0224: 0xdc,\n    // Ü\n    0x0225: 0xfc,\n    // ü\n    0x0226: 0x2018,\n    // ‘\n    0x0227: 0xa1,\n    // ¡\n    0x0228: 0x2a,\n    // *\n    0x0229: 0x27,\n    // '\n    0x022a: 0x2014,\n    // —\n    0x022b: 0xa9,\n    // ©\n    0x022c: 0x2120,\n    // ℠\n    0x022d: 0x2022,\n    // •\n    0x022e: 0x201c,\n    // “\n    0x022f: 0x201d,\n    // ”\n    0x0230: 0xc0,\n    // À\n    0x0231: 0xc2,\n    // Â\n    0x0232: 0xc7,\n    // Ç\n    0x0233: 0xc8,\n    // È\n    0x0234: 0xca,\n    // Ê\n    0x0235: 0xcb,\n    // Ë\n    0x0236: 0xeb,\n    // ë\n    0x0237: 0xce,\n    // Î\n    0x0238: 0xcf,\n    // Ï\n    0x0239: 0xef,\n    // ï\n    0x023a: 0xd4,\n    // Ô\n    0x023b: 0xd9,\n    // Ù\n    0x023c: 0xf9,\n    // ù\n    0x023d: 0xdb,\n    // Û\n    0x023e: 0xab,\n    // «\n    0x023f: 0xbb,\n    // »\n    0x0320: 0xc3,\n    // Ã\n    0x0321: 0xe3,\n    // ã\n    0x0322: 0xcd,\n    // Í\n    0x0323: 0xcc,\n    // Ì\n    0x0324: 0xec,\n    // ì\n    0x0325: 0xd2,\n    // Ò\n    0x0326: 0xf2,\n    // ò\n    0x0327: 0xd5,\n    // Õ\n    0x0328: 0xf5,\n    // õ\n    0x0329: 0x7b,\n    // {\n    0x032a: 0x7d,\n    // }\n    0x032b: 0x5c,\n    // \\\n    0x032c: 0x5e,\n    // ^\n    0x032d: 0x5f,\n    // _\n    0x032e: 0x7c,\n    // |\n    0x032f: 0x7e,\n    // ~\n    0x0330: 0xc4,\n    // Ä\n    0x0331: 0xe4,\n    // ä\n    0x0332: 0xd6,\n    // Ö\n    0x0333: 0xf6,\n    // ö\n    0x0334: 0xdf,\n    // ß\n    0x0335: 0xa5,\n    // ¥\n    0x0336: 0xa4,\n    // ¤\n    0x0337: 0x2502,\n    // │\n    0x0338: 0xc5,\n    // Å\n    0x0339: 0xe5,\n    // å\n    0x033a: 0xd8,\n    // Ø\n    0x033b: 0xf8,\n    // ø\n    0x033c: 0x250c,\n    // ┌\n    0x033d: 0x2510,\n    // ┐\n    0x033e: 0x2514,\n    // └\n    0x033f: 0x2518 // ┘\n  };\n  var getCharFromCode = function (code) {\n    if (code === null) {\n      return '';\n    }\n    code = CHARACTER_TRANSLATION[code] || code;\n    return String.fromCharCode(code);\n  }; // the index of the last row in a CEA-608 display buffer\n\n  var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of\n  // getting it through bit logic.\n\n  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\n  // cells. The \"bottom\" row is the last element in the outer array.\n  // We keep track of positioning information as we go by storing the\n  // number of indentations and the tab offset in this buffer.\n\n  var createDisplayBuffer = function () {\n    var result = [],\n      i = BOTTOM_ROW + 1;\n    while (i--) {\n      result.push({\n        text: '',\n        indent: 0,\n        offset: 0\n      });\n    }\n    return result;\n  };\n  var Cea608Stream = function (field, dataChannel) {\n    Cea608Stream.prototype.init.call(this);\n    this.field_ = field || 0;\n    this.dataChannel_ = dataChannel || 0;\n    this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);\n    this.setConstants();\n    this.reset();\n    this.push = function (packet) {\n      var data, swap, char0, char1, text; // remove the parity bits\n\n      data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice\n\n      if (data === this.lastControlCode_) {\n        this.lastControlCode_ = null;\n        return;\n      } // Store control codes\n\n      if ((data & 0xf000) === 0x1000) {\n        this.lastControlCode_ = data;\n      } else if (data !== this.PADDING_) {\n        this.lastControlCode_ = null;\n      }\n      char0 = data >>> 8;\n      char1 = data & 0xff;\n      if (data === this.PADDING_) {\n        return;\n      } else if (data === this.RESUME_CAPTION_LOADING_) {\n        this.mode_ = 'popOn';\n      } else if (data === this.END_OF_CAPTION_) {\n        // If an EOC is received while in paint-on mode, the displayed caption\n        // text should be swapped to non-displayed memory as if it was a pop-on\n        // caption. Because of that, we should explicitly switch back to pop-on\n        // mode\n        this.mode_ = 'popOn';\n        this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now\n\n        this.flushDisplayed(packet.pts); // flip memory\n\n        swap = this.displayed_;\n        this.displayed_ = this.nonDisplayed_;\n        this.nonDisplayed_ = swap; // start measuring the time to display the caption\n\n        this.startPts_ = packet.pts;\n      } else if (data === this.ROLL_UP_2_ROWS_) {\n        this.rollUpRows_ = 2;\n        this.setRollUp(packet.pts);\n      } else if (data === this.ROLL_UP_3_ROWS_) {\n        this.rollUpRows_ = 3;\n        this.setRollUp(packet.pts);\n      } else if (data === this.ROLL_UP_4_ROWS_) {\n        this.rollUpRows_ = 4;\n        this.setRollUp(packet.pts);\n      } else if (data === this.CARRIAGE_RETURN_) {\n        this.clearFormatting(packet.pts);\n        this.flushDisplayed(packet.pts);\n        this.shiftRowsUp_();\n        this.startPts_ = packet.pts;\n      } else if (data === this.BACKSPACE_) {\n        if (this.mode_ === 'popOn') {\n          this.nonDisplayed_[this.row_].text = this.nonDisplayed_[this.row_].text.slice(0, -1);\n        } else {\n          this.displayed_[this.row_].text = this.displayed_[this.row_].text.slice(0, -1);\n        }\n      } else if (data === this.ERASE_DISPLAYED_MEMORY_) {\n        this.flushDisplayed(packet.pts);\n        this.displayed_ = createDisplayBuffer();\n      } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {\n        this.nonDisplayed_ = createDisplayBuffer();\n      } else if (data === this.RESUME_DIRECT_CAPTIONING_) {\n        if (this.mode_ !== 'paintOn') {\n          // NOTE: This should be removed when proper caption positioning is\n          // implemented\n          this.flushDisplayed(packet.pts);\n          this.displayed_ = createDisplayBuffer();\n        }\n        this.mode_ = 'paintOn';\n        this.startPts_ = packet.pts; // Append special characters to caption text\n      } else if (this.isSpecialCharacter(char0, char1)) {\n        // Bitmask char0 so that we can apply character transformations\n        // regardless of field and data channel.\n        // Then byte-shift to the left and OR with char1 so we can pass the\n        // entire character code to `getCharFromCode`.\n        char0 = (char0 & 0x03) << 8;\n        text = getCharFromCode(char0 | char1);\n        this[this.mode_](packet.pts, text);\n        this.column_++; // Append extended characters to caption text\n      } else if (this.isExtCharacter(char0, char1)) {\n        // Extended characters always follow their \"non-extended\" equivalents.\n        // IE if a \"è\" is desired, you'll always receive \"eè\"; non-compliant\n        // decoders are supposed to drop the \"è\", while compliant decoders\n        // backspace the \"e\" and insert \"è\".\n        // Delete the previous character\n        if (this.mode_ === 'popOn') {\n          this.nonDisplayed_[this.row_].text = this.nonDisplayed_[this.row_].text.slice(0, -1);\n        } else {\n          this.displayed_[this.row_].text = this.displayed_[this.row_].text.slice(0, -1);\n        } // Bitmask char0 so that we can apply character transformations\n        // regardless of field and data channel.\n        // Then byte-shift to the left and OR with char1 so we can pass the\n        // entire character code to `getCharFromCode`.\n\n        char0 = (char0 & 0x03) << 8;\n        text = getCharFromCode(char0 | char1);\n        this[this.mode_](packet.pts, text);\n        this.column_++; // Process mid-row codes\n      } else if (this.isMidRowCode(char0, char1)) {\n        // Attributes are not additive, so clear all formatting\n        this.clearFormatting(packet.pts); // According to the standard, mid-row codes\n        // should be replaced with spaces, so add one now\n\n        this[this.mode_](packet.pts, ' ');\n        this.column_++;\n        if ((char1 & 0xe) === 0xe) {\n          this.addFormatting(packet.pts, ['i']);\n        }\n        if ((char1 & 0x1) === 0x1) {\n          this.addFormatting(packet.pts, ['u']);\n        } // Detect offset control codes and adjust cursor\n      } else if (this.isOffsetControlCode(char0, char1)) {\n        // Cursor position is set by indent PAC (see below) in 4-column\n        // increments, with an additional offset code of 1-3 to reach any\n        // of the 32 columns specified by CEA-608. So all we need to do\n        // here is increment the column cursor by the given offset.\n        const offset = char1 & 0x03; // For an offest value 1-3, set the offset for that caption\n        // in the non-displayed array.\n\n        this.nonDisplayed_[this.row_].offset = offset;\n        this.column_ += offset; // Detect PACs (Preamble Address Codes)\n      } else if (this.isPAC(char0, char1)) {\n        // There's no logic for PAC -> row mapping, so we have to just\n        // find the row code in an array and use its index :(\n        var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode\n\n        if (this.mode_ === 'rollUp') {\n          // This implies that the base row is incorrectly set.\n          // As per the recommendation in CEA-608(Base Row Implementation), defer to the number\n          // of roll-up rows set.\n          if (row - this.rollUpRows_ + 1 < 0) {\n            row = this.rollUpRows_ - 1;\n          }\n          this.setRollUp(packet.pts, row);\n        } // Ensure the row is between 0 and 14, otherwise use the most\n        // recent or default row.\n\n        if (row !== this.row_ && row >= 0 && row <= 14) {\n          // formatting is only persistent for current row\n          this.clearFormatting(packet.pts);\n          this.row_ = row;\n        } // All PACs can apply underline, so detect and apply\n        // (All odd-numbered second bytes set underline)\n\n        if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {\n          this.addFormatting(packet.pts, ['u']);\n        }\n        if ((data & 0x10) === 0x10) {\n          // We've got an indent level code. Each successive even number\n          // increments the column cursor by 4, so we can get the desired\n          // column position by bit-shifting to the right (to get n/2)\n          // and multiplying by 4.\n          const indentations = (data & 0xe) >> 1;\n          this.column_ = indentations * 4; // add to the number of indentations for positioning\n\n          this.nonDisplayed_[this.row_].indent += indentations;\n        }\n        if (this.isColorPAC(char1)) {\n          // it's a color code, though we only support white, which\n          // can be either normal or italicized. white italics can be\n          // either 0x4e or 0x6e depending on the row, so we just\n          // bitwise-and with 0xe to see if italics should be turned on\n          if ((char1 & 0xe) === 0xe) {\n            this.addFormatting(packet.pts, ['i']);\n          }\n        } // We have a normal character in char0, and possibly one in char1\n      } else if (this.isNormalChar(char0)) {\n        if (char1 === 0x00) {\n          char1 = null;\n        }\n        text = getCharFromCode(char0);\n        text += getCharFromCode(char1);\n        this[this.mode_](packet.pts, text);\n        this.column_ += text.length;\n      } // finish data processing\n    };\n  };\n  Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the\n  // display buffer\n\n  Cea608Stream.prototype.flushDisplayed = function (pts) {\n    const logWarning = index => {\n      this.trigger('log', {\n        level: 'warn',\n        message: 'Skipping a malformed 608 caption at index ' + index + '.'\n      });\n    };\n    const content = [];\n    this.displayed_.forEach((row, i) => {\n      if (row && row.text && row.text.length) {\n        try {\n          // remove spaces from the start and end of the string\n          row.text = row.text.trim();\n        } catch (e) {\n          // Ordinarily, this shouldn't happen. However, caption\n          // parsing errors should not throw exceptions and\n          // break playback.\n          logWarning(i);\n        } // See the below link for more details on the following fields:\n        // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608\n\n        if (row.text.length) {\n          content.push({\n            // The text to be displayed in the caption from this specific row, with whitespace removed.\n            text: row.text,\n            // Value between 1 and 15 representing the PAC row used to calculate line height.\n            line: i + 1,\n            // A number representing the indent position by percentage (CEA-608 PAC indent code).\n            // The value will be a number between 10 and 80. Offset is used to add an aditional\n            // value to the position if necessary.\n            position: 10 + Math.min(70, row.indent * 10) + row.offset * 2.5\n          });\n        }\n      } else if (row === undefined || row === null) {\n        logWarning(i);\n      }\n    });\n    if (content.length) {\n      this.trigger('data', {\n        startPts: this.startPts_,\n        endPts: pts,\n        content,\n        stream: this.name_\n      });\n    }\n  };\n  /**\n   * Zero out the data, used for startup and on seek\n   */\n\n  Cea608Stream.prototype.reset = function () {\n    this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will\n    // actually display captions. If a caption is shifted to a row\n    // with a lower index than this, it is cleared from the display\n    // buffer\n\n    this.topRow_ = 0;\n    this.startPts_ = 0;\n    this.displayed_ = createDisplayBuffer();\n    this.nonDisplayed_ = createDisplayBuffer();\n    this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing\n\n    this.column_ = 0;\n    this.row_ = BOTTOM_ROW;\n    this.rollUpRows_ = 2; // This variable holds currently-applied formatting\n\n    this.formatting_ = [];\n  };\n  /**\n   * Sets up control code and related constants for this instance\n   */\n\n  Cea608Stream.prototype.setConstants = function () {\n    // The following attributes have these uses:\n    // ext_ :    char0 for mid-row codes, and the base for extended\n    //           chars (ext_+0, ext_+1, and ext_+2 are char0s for\n    //           extended codes)\n    // control_: char0 for control codes, except byte-shifted to the\n    //           left so that we can do this.control_ | CONTROL_CODE\n    // offset_:  char0 for tab offset codes\n    //\n    // It's also worth noting that control codes, and _only_ control codes,\n    // differ between field 1 and field2. Field 2 control codes are always\n    // their field 1 value plus 1. That's why there's the \"| field\" on the\n    // control value.\n    if (this.dataChannel_ === 0) {\n      this.BASE_ = 0x10;\n      this.EXT_ = 0x11;\n      this.CONTROL_ = (0x14 | this.field_) << 8;\n      this.OFFSET_ = 0x17;\n    } else if (this.dataChannel_ === 1) {\n      this.BASE_ = 0x18;\n      this.EXT_ = 0x19;\n      this.CONTROL_ = (0x1c | this.field_) << 8;\n      this.OFFSET_ = 0x1f;\n    } // Constants for the LSByte command codes recognized by Cea608Stream. This\n    // list is not exhaustive. For a more comprehensive listing and semantics see\n    // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf\n    // Padding\n\n    this.PADDING_ = 0x0000; // Pop-on Mode\n\n    this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;\n    this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode\n\n    this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;\n    this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;\n    this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;\n    this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode\n\n    this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure\n\n    this.BACKSPACE_ = this.CONTROL_ | 0x21;\n    this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;\n    this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;\n  };\n  /**\n   * Detects if the 2-byte packet data is a special character\n   *\n   * Special characters have a second byte in the range 0x30 to 0x3f,\n   * with the first byte being 0x11 (for data channel 1) or 0x19 (for\n   * data channel 2).\n   *\n   * @param  {Integer} char0 The first byte\n   * @param  {Integer} char1 The second byte\n   * @return {Boolean}       Whether the 2 bytes are an special character\n   */\n\n  Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {\n    return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;\n  };\n  /**\n   * Detects if the 2-byte packet data is an extended character\n   *\n   * Extended characters have a second byte in the range 0x20 to 0x3f,\n   * with the first byte being 0x12 or 0x13 (for data channel 1) or\n   * 0x1a or 0x1b (for data channel 2).\n   *\n   * @param  {Integer} char0 The first byte\n   * @param  {Integer} char1 The second byte\n   * @return {Boolean}       Whether the 2 bytes are an extended character\n   */\n\n  Cea608Stream.prototype.isExtCharacter = function (char0, char1) {\n    return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;\n  };\n  /**\n   * Detects if the 2-byte packet is a mid-row code\n   *\n   * Mid-row codes have a second byte in the range 0x20 to 0x2f, with\n   * the first byte being 0x11 (for data channel 1) or 0x19 (for data\n   * channel 2).\n   *\n   * @param  {Integer} char0 The first byte\n   * @param  {Integer} char1 The second byte\n   * @return {Boolean}       Whether the 2 bytes are a mid-row code\n   */\n\n  Cea608Stream.prototype.isMidRowCode = function (char0, char1) {\n    return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;\n  };\n  /**\n   * Detects if the 2-byte packet is an offset control code\n   *\n   * Offset control codes have a second byte in the range 0x21 to 0x23,\n   * with the first byte being 0x17 (for data channel 1) or 0x1f (for\n   * data channel 2).\n   *\n   * @param  {Integer} char0 The first byte\n   * @param  {Integer} char1 The second byte\n   * @return {Boolean}       Whether the 2 bytes are an offset control code\n   */\n\n  Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {\n    return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;\n  };\n  /**\n   * Detects if the 2-byte packet is a Preamble Address Code\n   *\n   * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)\n   * or 0x18 to 0x1f (for data channel 2), with the second byte in the\n   * range 0x40 to 0x7f.\n   *\n   * @param  {Integer} char0 The first byte\n   * @param  {Integer} char1 The second byte\n   * @return {Boolean}       Whether the 2 bytes are a PAC\n   */\n\n  Cea608Stream.prototype.isPAC = function (char0, char1) {\n    return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;\n  };\n  /**\n   * Detects if a packet's second byte is in the range of a PAC color code\n   *\n   * PAC color codes have the second byte be in the range 0x40 to 0x4f, or\n   * 0x60 to 0x6f.\n   *\n   * @param  {Integer} char1 The second byte\n   * @return {Boolean}       Whether the byte is a color PAC\n   */\n\n  Cea608Stream.prototype.isColorPAC = function (char1) {\n    return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;\n  };\n  /**\n   * Detects if a single byte is in the range of a normal character\n   *\n   * Normal text bytes are in the range 0x20 to 0x7f.\n   *\n   * @param  {Integer} char  The byte\n   * @return {Boolean}       Whether the byte is a normal character\n   */\n\n  Cea608Stream.prototype.isNormalChar = function (char) {\n    return char >= 0x20 && char <= 0x7f;\n  };\n  /**\n   * Configures roll-up\n   *\n   * @param  {Integer} pts         Current PTS\n   * @param  {Integer} newBaseRow  Used by PACs to slide the current window to\n   *                               a new position\n   */\n\n  Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {\n    // Reset the base row to the bottom row when switching modes\n    if (this.mode_ !== 'rollUp') {\n      this.row_ = BOTTOM_ROW;\n      this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up\n\n      this.flushDisplayed(pts);\n      this.nonDisplayed_ = createDisplayBuffer();\n      this.displayed_ = createDisplayBuffer();\n    }\n    if (newBaseRow !== undefined && newBaseRow !== this.row_) {\n      // move currently displayed captions (up or down) to the new base row\n      for (var i = 0; i < this.rollUpRows_; i++) {\n        this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];\n        this.displayed_[this.row_ - i] = {\n          text: '',\n          indent: 0,\n          offset: 0\n        };\n      }\n    }\n    if (newBaseRow === undefined) {\n      newBaseRow = this.row_;\n    }\n    this.topRow_ = newBaseRow - this.rollUpRows_ + 1;\n  }; // Adds the opening HTML tag for the passed character to the caption text,\n  // and keeps track of it for later closing\n\n  Cea608Stream.prototype.addFormatting = function (pts, format) {\n    this.formatting_ = this.formatting_.concat(format);\n    var text = format.reduce(function (text, format) {\n      return text + '<' + format + '>';\n    }, '');\n    this[this.mode_](pts, text);\n  }; // Adds HTML closing tags for current formatting to caption text and\n  // clears remembered formatting\n\n  Cea608Stream.prototype.clearFormatting = function (pts) {\n    if (!this.formatting_.length) {\n      return;\n    }\n    var text = this.formatting_.reverse().reduce(function (text, format) {\n      return text + '</' + format + '>';\n    }, '');\n    this.formatting_ = [];\n    this[this.mode_](pts, text);\n  }; // Mode Implementations\n\n  Cea608Stream.prototype.popOn = function (pts, text) {\n    var baseRow = this.nonDisplayed_[this.row_].text; // buffer characters\n\n    baseRow += text;\n    this.nonDisplayed_[this.row_].text = baseRow;\n  };\n  Cea608Stream.prototype.rollUp = function (pts, text) {\n    var baseRow = this.displayed_[this.row_].text;\n    baseRow += text;\n    this.displayed_[this.row_].text = baseRow;\n  };\n  Cea608Stream.prototype.shiftRowsUp_ = function () {\n    var i; // clear out inactive rows\n\n    for (i = 0; i < this.topRow_; i++) {\n      this.displayed_[i] = {\n        text: '',\n        indent: 0,\n        offset: 0\n      };\n    }\n    for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {\n      this.displayed_[i] = {\n        text: '',\n        indent: 0,\n        offset: 0\n      };\n    } // shift displayed rows up\n\n    for (i = this.topRow_; i < this.row_; i++) {\n      this.displayed_[i] = this.displayed_[i + 1];\n    } // clear out the bottom row\n\n    this.displayed_[this.row_] = {\n      text: '',\n      indent: 0,\n      offset: 0\n    };\n  };\n  Cea608Stream.prototype.paintOn = function (pts, text) {\n    var baseRow = this.displayed_[this.row_].text;\n    baseRow += text;\n    this.displayed_[this.row_].text = baseRow;\n  }; // exports\n\n  var captionStream = {\n    CaptionStream: CaptionStream$2,\n    Cea608Stream: Cea608Stream,\n    Cea708Stream: Cea708Stream\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n\n  var streamTypes = {\n    H264_STREAM_TYPE: 0x1B,\n    ADTS_STREAM_TYPE: 0x0F,\n    METADATA_STREAM_TYPE: 0x15\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Accepts program elementary stream (PES) data events and corrects\n   * decode and presentation time stamps to account for a rollover\n   * of the 33 bit value.\n   */\n\n  var Stream$6 = stream;\n  var MAX_TS = 8589934592;\n  var RO_THRESH = 4294967296;\n  var TYPE_SHARED = 'shared';\n  var handleRollover$1 = function (value, reference) {\n    var direction = 1;\n    if (value > reference) {\n      // If the current timestamp value is greater than our reference timestamp and we detect a\n      // timestamp rollover, this means the roll over is happening in the opposite direction.\n      // Example scenario: Enter a long stream/video just after a rollover occurred. The reference\n      // point will be set to a small number, e.g. 1. The user then seeks backwards over the\n      // rollover point. In loading this segment, the timestamp values will be very large,\n      // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust\n      // the time stamp to be `value - 2^33`.\n      direction = -1;\n    } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will\n    // cause an incorrect adjustment.\n\n    while (Math.abs(reference - value) > RO_THRESH) {\n      value += direction * MAX_TS;\n    }\n    return value;\n  };\n  var TimestampRolloverStream$1 = function (type) {\n    var lastDTS, referenceDTS;\n    TimestampRolloverStream$1.prototype.init.call(this); // The \"shared\" type is used in cases where a stream will contain muxed\n    // video and audio. We could use `undefined` here, but having a string\n    // makes debugging a little clearer.\n\n    this.type_ = type || TYPE_SHARED;\n    this.push = function (data) {\n      /**\n       * Rollover stream expects data from elementary stream.\n       * Elementary stream can push forward 2 types of data\n       * - Parsed Video/Audio/Timed-metadata PES (packetized elementary stream) packets\n       * - Tracks metadata from PMT (Program Map Table)\n       * Rollover stream expects pts/dts info to be available, since it stores lastDTS\n       * We should ignore non-PES packets since they may override lastDTS to undefined.\n       * lastDTS is important to signal the next segments\n       * about rollover from the previous segments.\n       */\n      if (data.type === 'metadata') {\n        this.trigger('data', data);\n        return;\n      } // Any \"shared\" rollover streams will accept _all_ data. Otherwise,\n      // streams will only accept data that matches their type.\n\n      if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {\n        return;\n      }\n      if (referenceDTS === undefined) {\n        referenceDTS = data.dts;\n      }\n      data.dts = handleRollover$1(data.dts, referenceDTS);\n      data.pts = handleRollover$1(data.pts, referenceDTS);\n      lastDTS = data.dts;\n      this.trigger('data', data);\n    };\n    this.flush = function () {\n      referenceDTS = lastDTS;\n      this.trigger('done');\n    };\n    this.endTimeline = function () {\n      this.flush();\n      this.trigger('endedtimeline');\n    };\n    this.discontinuity = function () {\n      referenceDTS = void 0;\n      lastDTS = void 0;\n    };\n    this.reset = function () {\n      this.discontinuity();\n      this.trigger('reset');\n    };\n  };\n  TimestampRolloverStream$1.prototype = new Stream$6();\n  var timestampRolloverStream = {\n    TimestampRolloverStream: TimestampRolloverStream$1,\n    handleRollover: handleRollover$1\n  }; // Once IE11 support is dropped, this function should be removed.\n\n  var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {\n    if (!typedArray) {\n      return -1;\n    }\n    var currentIndex = fromIndex;\n    for (; currentIndex < typedArray.length; currentIndex++) {\n      if (typedArray[currentIndex] === element) {\n        return currentIndex;\n      }\n    }\n    return -1;\n  };\n  var typedArray = {\n    typedArrayIndexOf: typedArrayIndexOf$1\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Tools for parsing ID3 frame data\n   * @see http://id3.org/id3v2.3.0\n   */\n\n  var typedArrayIndexOf = typedArray.typedArrayIndexOf,\n    // Frames that allow different types of text encoding contain a text\n    // encoding description byte [ID3v2.4.0 section 4.]\n    textEncodingDescriptionByte = {\n      Iso88591: 0x00,\n      // ISO-8859-1, terminated with \\0.\n      Utf16: 0x01,\n      // UTF-16 encoded Unicode BOM, terminated with \\0\\0\n      Utf16be: 0x02,\n      // UTF-16BE encoded Unicode, without BOM, terminated with \\0\\0\n      Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \\0\n    },\n    // return a percent-encoded representation of the specified byte range\n    // @see http://en.wikipedia.org/wiki/Percent-encoding \n    percentEncode$1 = function (bytes, start, end) {\n      var i,\n        result = '';\n      for (i = start; i < end; i++) {\n        result += '%' + ('00' + bytes[i].toString(16)).slice(-2);\n      }\n      return result;\n    },\n    // return the string representation of the specified byte range,\n    // interpreted as UTf-8.\n    parseUtf8 = function (bytes, start, end) {\n      return decodeURIComponent(percentEncode$1(bytes, start, end));\n    },\n    // return the string representation of the specified byte range,\n    // interpreted as ISO-8859-1.\n    parseIso88591$1 = function (bytes, start, end) {\n      return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line\n    },\n    parseSyncSafeInteger$1 = function (data) {\n      return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];\n    },\n    frameParsers = {\n      'APIC': function (frame) {\n        var i = 1,\n          mimeTypeEndIndex,\n          descriptionEndIndex,\n          LINK_MIME_TYPE = '-->';\n        if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {\n          // ignore frames with unrecognized character encodings\n          return;\n        } // parsing fields [ID3v2.4.0 section 4.14.]\n\n        mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);\n        if (mimeTypeEndIndex < 0) {\n          // malformed frame\n          return;\n        } // parsing Mime type field (terminated with \\0)\n\n        frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);\n        i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field\n\n        frame.pictureType = frame.data[i];\n        i++;\n        descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);\n        if (descriptionEndIndex < 0) {\n          // malformed frame\n          return;\n        } // parsing Description field (terminated with \\0)\n\n        frame.description = parseUtf8(frame.data, i, descriptionEndIndex);\n        i = descriptionEndIndex + 1;\n        if (frame.mimeType === LINK_MIME_TYPE) {\n          // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])\n          frame.url = parseIso88591$1(frame.data, i, frame.data.length);\n        } else {\n          // parsing Picture Data field as binary data\n          frame.pictureData = frame.data.subarray(i, frame.data.length);\n        }\n      },\n      'T*': function (frame) {\n        if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {\n          // ignore frames with unrecognized character encodings\n          return;\n        } // parse text field, do not include null terminator in the frame value\n        // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]\n\n        frame.value = parseUtf8(frame.data, 1, frame.data.length).replace(/\\0*$/, ''); // text information frames supports multiple strings, stored as a terminator separated list [ID3v2.4.0 section 4.2.]\n\n        frame.values = frame.value.split('\\0');\n      },\n      'TXXX': function (frame) {\n        var descriptionEndIndex;\n        if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {\n          // ignore frames with unrecognized character encodings\n          return;\n        }\n        descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);\n        if (descriptionEndIndex === -1) {\n          return;\n        } // parse the text fields\n\n        frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value\n        // frames that allow different types of encoding contain terminated text\n        // [ID3v2.4.0 section 4.]\n\n        frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\\0*$/, '');\n        frame.data = frame.value;\n      },\n      'W*': function (frame) {\n        // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]\n        // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]\n        frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\\0.*$/, '');\n      },\n      'WXXX': function (frame) {\n        var descriptionEndIndex;\n        if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {\n          // ignore frames with unrecognized character encodings\n          return;\n        }\n        descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);\n        if (descriptionEndIndex === -1) {\n          return;\n        } // parse the description and URL fields\n\n        frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]\n        // if the value is followed by a string termination all the following information\n        // should be ignored [ID3v2.4.0 section 4.3]\n\n        frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\\0.*$/, '');\n      },\n      'PRIV': function (frame) {\n        var i;\n        for (i = 0; i < frame.data.length; i++) {\n          if (frame.data[i] === 0) {\n            // parse the description and URL fields\n            frame.owner = parseIso88591$1(frame.data, 0, i);\n            break;\n          }\n        }\n        frame.privateData = frame.data.subarray(i + 1);\n        frame.data = frame.privateData;\n      }\n    };\n  var parseId3Frames$1 = function (data) {\n    var frameSize,\n      frameHeader,\n      frameStart = 10,\n      tagSize = 0,\n      frames = []; // If we don't have enough data for a header, 10 bytes, \n    // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.\n\n    if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {\n      return;\n    } // the frame size is transmitted as a 28-bit integer in the\n    // last four bytes of the ID3 header.\n    // The most significant bit of each byte is dropped and the\n    // results concatenated to recover the actual value.\n\n    tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more\n    // convenient for our comparisons to include it\n\n    tagSize += 10; // check bit 6 of byte 5 for the extended header flag.\n\n    var hasExtendedHeader = data[5] & 0x40;\n    if (hasExtendedHeader) {\n      // advance the frame start past the extended header\n      frameStart += 4; // header size field\n\n      frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));\n      tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end\n    } // parse one or more ID3 frames\n    // http://id3.org/id3v2.3.0#ID3v2_frame_overview\n\n    do {\n      // determine the number of bytes in this frame\n      frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));\n      if (frameSize < 1) {\n        break;\n      }\n      frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);\n      var frame = {\n        id: frameHeader,\n        data: data.subarray(frameStart + 10, frameStart + frameSize + 10)\n      };\n      frame.key = frame.id; // parse frame values\n\n      if (frameParsers[frame.id]) {\n        // use frame specific parser\n        frameParsers[frame.id](frame);\n      } else if (frame.id[0] === 'T') {\n        // use text frame generic parser\n        frameParsers['T*'](frame);\n      } else if (frame.id[0] === 'W') {\n        // use URL link frame generic parser\n        frameParsers['W*'](frame);\n      }\n      frames.push(frame);\n      frameStart += 10; // advance past the frame header\n\n      frameStart += frameSize; // advance past the frame body\n    } while (frameStart < tagSize);\n    return frames;\n  };\n  var parseId3 = {\n    parseId3Frames: parseId3Frames$1,\n    parseSyncSafeInteger: parseSyncSafeInteger$1,\n    frameParsers: frameParsers\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Accepts program elementary stream (PES) data events and parses out\n   * ID3 metadata from them, if present.\n   * @see http://id3.org/id3v2.3.0\n   */\n\n  var Stream$5 = stream,\n    StreamTypes$3 = streamTypes,\n    id3 = parseId3,\n    MetadataStream;\n  MetadataStream = function (options) {\n    var settings = {\n        // the bytes of the program-level descriptor field in MP2T\n        // see ISO/IEC 13818-1:2013 (E), section 2.6 \"Program and\n        // program element descriptors\"\n        descriptor: options && options.descriptor\n      },\n      // the total size in bytes of the ID3 tag being parsed\n      tagSize = 0,\n      // tag data that is not complete enough to be parsed\n      buffer = [],\n      // the total number of bytes currently in the buffer\n      bufferSize = 0,\n      i;\n    MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type\n    // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track\n\n    this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);\n    if (settings.descriptor) {\n      for (i = 0; i < settings.descriptor.length; i++) {\n        this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);\n      }\n    }\n    this.push = function (chunk) {\n      var tag, frameStart, frameSize, frame, i, frameHeader;\n      if (chunk.type !== 'timed-metadata') {\n        return;\n      } // if data_alignment_indicator is set in the PES header,\n      // we must have the start of a new ID3 tag. Assume anything\n      // remaining in the buffer was malformed and throw it out\n\n      if (chunk.dataAlignmentIndicator) {\n        bufferSize = 0;\n        buffer.length = 0;\n      } // ignore events that don't look like ID3 data\n\n      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))) {\n        this.trigger('log', {\n          level: 'warn',\n          message: 'Skipping unrecognized metadata packet'\n        });\n        return;\n      } // add this chunk to the data we've collected so far\n\n      buffer.push(chunk);\n      bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header\n\n      if (buffer.length === 1) {\n        // the frame size is transmitted as a 28-bit integer in the\n        // last four bytes of the ID3 header.\n        // The most significant bit of each byte is dropped and the\n        // results concatenated to recover the actual value.\n        tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more\n        // convenient for our comparisons to include it\n\n        tagSize += 10;\n      } // if the entire frame has not arrived, wait for more data\n\n      if (bufferSize < tagSize) {\n        return;\n      } // collect the entire frame so it can be parsed\n\n      tag = {\n        data: new Uint8Array(tagSize),\n        frames: [],\n        pts: buffer[0].pts,\n        dts: buffer[0].dts\n      };\n      for (i = 0; i < tagSize;) {\n        tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);\n        i += buffer[0].data.byteLength;\n        bufferSize -= buffer[0].data.byteLength;\n        buffer.shift();\n      } // find the start of the first frame and the end of the tag\n\n      frameStart = 10;\n      if (tag.data[5] & 0x40) {\n        // advance the frame start past the extended header\n        frameStart += 4; // header size field\n\n        frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end\n\n        tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));\n      } // parse one or more ID3 frames\n      // http://id3.org/id3v2.3.0#ID3v2_frame_overview\n\n      do {\n        // determine the number of bytes in this frame\n        frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));\n        if (frameSize < 1) {\n          this.trigger('log', {\n            level: 'warn',\n            message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'\n          }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames\n          // to be sent along.\n\n          break;\n        }\n        frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);\n        frame = {\n          id: frameHeader,\n          data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)\n        };\n        frame.key = frame.id; // parse frame values\n\n        if (id3.frameParsers[frame.id]) {\n          // use frame specific parser\n          id3.frameParsers[frame.id](frame);\n        } else if (frame.id[0] === 'T') {\n          // use text frame generic parser\n          id3.frameParsers['T*'](frame);\n        } else if (frame.id[0] === 'W') {\n          // use URL link frame generic parser\n          id3.frameParsers['W*'](frame);\n        } // handle the special PRIV frame used to indicate the start\n        // time for raw AAC data\n\n        if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {\n          var d = frame.data,\n            size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;\n          size *= 4;\n          size += d[7] & 0x03;\n          frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based\n          // on the value of this frame\n          // we couldn't have known the appropriate pts and dts before\n          // parsing this ID3 tag so set those values now\n\n          if (tag.pts === undefined && tag.dts === undefined) {\n            tag.pts = frame.timeStamp;\n            tag.dts = frame.timeStamp;\n          }\n          this.trigger('timestamp', frame);\n        }\n        tag.frames.push(frame);\n        frameStart += 10; // advance past the frame header\n\n        frameStart += frameSize; // advance past the frame body\n      } while (frameStart < tagSize);\n      this.trigger('data', tag);\n    };\n  };\n  MetadataStream.prototype = new Stream$5();\n  var metadataStream = MetadataStream;\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * A stream-based mp2t to mp4 converter. This utility can be used to\n   * deliver mp4s to a SourceBuffer on platforms that support native\n   * Media Source Extensions.\n   */\n\n  var Stream$4 = stream,\n    CaptionStream$1 = captionStream,\n    StreamTypes$2 = streamTypes,\n    TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types\n\n  var TransportPacketStream, TransportParseStream, ElementaryStream; // constants\n\n  var MP2T_PACKET_LENGTH$1 = 188,\n    // bytes\n    SYNC_BYTE$1 = 0x47;\n  /**\n   * Splits an incoming stream of binary data into MPEG-2 Transport\n   * Stream packets.\n   */\n\n  TransportPacketStream = function () {\n    var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),\n      bytesInBuffer = 0;\n    TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.\n\n    /**\n     * Split a stream of data into M2TS packets\n    **/\n\n    this.push = function (bytes) {\n      var startIndex = 0,\n        endIndex = MP2T_PACKET_LENGTH$1,\n        everything; // If there are bytes remaining from the last segment, prepend them to the\n      // bytes that were pushed in\n\n      if (bytesInBuffer) {\n        everything = new Uint8Array(bytes.byteLength + bytesInBuffer);\n        everything.set(buffer.subarray(0, bytesInBuffer));\n        everything.set(bytes, bytesInBuffer);\n        bytesInBuffer = 0;\n      } else {\n        everything = bytes;\n      } // While we have enough data for a packet\n\n      while (endIndex < everything.byteLength) {\n        // Look for a pair of start and end sync bytes in the data..\n        if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {\n          // We found a packet so emit it and jump one whole packet forward in\n          // the stream\n          this.trigger('data', everything.subarray(startIndex, endIndex));\n          startIndex += MP2T_PACKET_LENGTH$1;\n          endIndex += MP2T_PACKET_LENGTH$1;\n          continue;\n        } // If we get here, we have somehow become de-synchronized and we need to step\n        // forward one byte at a time until we find a pair of sync bytes that denote\n        // a packet\n\n        startIndex++;\n        endIndex++;\n      } // If there was some data left over at the end of the segment that couldn't\n      // possibly be a whole packet, keep it because it might be the start of a packet\n      // that continues in the next segment\n\n      if (startIndex < everything.byteLength) {\n        buffer.set(everything.subarray(startIndex), 0);\n        bytesInBuffer = everything.byteLength - startIndex;\n      }\n    };\n    /**\n     * Passes identified M2TS packets to the TransportParseStream to be parsed\n    **/\n\n    this.flush = function () {\n      // If the buffer contains a whole packet when we are being flushed, emit it\n      // and empty the buffer. Otherwise hold onto the data because it may be\n      // important for decoding the next segment\n      if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {\n        this.trigger('data', buffer);\n        bytesInBuffer = 0;\n      }\n      this.trigger('done');\n    };\n    this.endTimeline = function () {\n      this.flush();\n      this.trigger('endedtimeline');\n    };\n    this.reset = function () {\n      bytesInBuffer = 0;\n      this.trigger('reset');\n    };\n  };\n  TransportPacketStream.prototype = new Stream$4();\n  /**\n   * Accepts an MP2T TransportPacketStream and emits data events with parsed\n   * forms of the individual transport stream packets.\n   */\n\n  TransportParseStream = function () {\n    var parsePsi, parsePat, parsePmt, self;\n    TransportParseStream.prototype.init.call(this);\n    self = this;\n    this.packetsWaitingForPmt = [];\n    this.programMapTable = undefined;\n    parsePsi = function (payload, psi) {\n      var offset = 0; // PSI packets may be split into multiple sections and those\n      // sections may be split into multiple packets. If a PSI\n      // section starts in this packet, the payload_unit_start_indicator\n      // will be true and the first byte of the payload will indicate\n      // the offset from the current position to the start of the\n      // section.\n\n      if (psi.payloadUnitStartIndicator) {\n        offset += payload[offset] + 1;\n      }\n      if (psi.type === 'pat') {\n        parsePat(payload.subarray(offset), psi);\n      } else {\n        parsePmt(payload.subarray(offset), psi);\n      }\n    };\n    parsePat = function (payload, pat) {\n      pat.section_number = payload[7]; // eslint-disable-line camelcase\n\n      pat.last_section_number = payload[8]; // eslint-disable-line camelcase\n      // skip the PSI header and parse the first PMT entry\n\n      self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];\n      pat.pmtPid = self.pmtPid;\n    };\n    /**\n     * Parse out the relevant fields of a Program Map Table (PMT).\n     * @param payload {Uint8Array} the PMT-specific portion of an MP2T\n     * packet. The first byte in this array should be the table_id\n     * field.\n     * @param pmt {object} the object that should be decorated with\n     * fields parsed from the PMT.\n     */\n\n    parsePmt = function (payload, pmt) {\n      var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually\n      // take effect. We don't believe this should ever be the case\n      // for HLS but we'll ignore \"forward\" PMT declarations if we see\n      // them. Future PMT declarations have the current_next_indicator\n      // set to zero.\n\n      if (!(payload[5] & 0x01)) {\n        return;\n      } // overwrite any existing program map table\n\n      self.programMapTable = {\n        video: null,\n        audio: null,\n        'timed-metadata': {}\n      }; // the mapping table ends at the end of the current section\n\n      sectionLength = (payload[1] & 0x0f) << 8 | payload[2];\n      tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how\n      // long the program info descriptors are\n\n      programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table\n\n      offset = 12 + programInfoLength;\n      while (offset < tableEnd) {\n        var streamType = payload[offset];\n        var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types\n        // TODO: should this be done for metadata too? for now maintain behavior of\n        //       multiple metadata streams\n\n        if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {\n          self.programMapTable.video = pid;\n        } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {\n          self.programMapTable.audio = pid;\n        } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {\n          // map pid to stream type for metadata streams\n          self.programMapTable['timed-metadata'][pid] = streamType;\n        } // move to the next table entry\n        // skip past the elementary stream descriptors, if present\n\n        offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;\n      } // record the map on the packet as well\n\n      pmt.programMapTable = self.programMapTable;\n    };\n    /**\n     * Deliver a new MP2T packet to the next stream in the pipeline.\n     */\n\n    this.push = function (packet) {\n      var result = {},\n        offset = 4;\n      result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]\n\n      result.pid = packet[1] & 0x1f;\n      result.pid <<= 8;\n      result.pid |= packet[2]; // if an adaption field is present, its length is specified by the\n      // fifth byte of the TS packet header. The adaptation field is\n      // used to add stuffing to PES packets that don't fill a complete\n      // TS packet, and to specify some forms of timing and control data\n      // that we do not currently use.\n\n      if ((packet[3] & 0x30) >>> 4 > 0x01) {\n        offset += packet[offset] + 1;\n      } // parse the rest of the packet based on the type\n\n      if (result.pid === 0) {\n        result.type = 'pat';\n        parsePsi(packet.subarray(offset), result);\n        this.trigger('data', result);\n      } else if (result.pid === this.pmtPid) {\n        result.type = 'pmt';\n        parsePsi(packet.subarray(offset), result);\n        this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now\n\n        while (this.packetsWaitingForPmt.length) {\n          this.processPes_.apply(this, this.packetsWaitingForPmt.shift());\n        }\n      } else if (this.programMapTable === undefined) {\n        // When we have not seen a PMT yet, defer further processing of\n        // PES packets until one has been parsed\n        this.packetsWaitingForPmt.push([packet, offset, result]);\n      } else {\n        this.processPes_(packet, offset, result);\n      }\n    };\n    this.processPes_ = function (packet, offset, result) {\n      // set the appropriate stream type\n      if (result.pid === this.programMapTable.video) {\n        result.streamType = StreamTypes$2.H264_STREAM_TYPE;\n      } else if (result.pid === this.programMapTable.audio) {\n        result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;\n      } else {\n        // if not video or audio, it is timed-metadata or unknown\n        // if unknown, streamType will be undefined\n        result.streamType = this.programMapTable['timed-metadata'][result.pid];\n      }\n      result.type = 'pes';\n      result.data = packet.subarray(offset);\n      this.trigger('data', result);\n    };\n  };\n  TransportParseStream.prototype = new Stream$4();\n  TransportParseStream.STREAM_TYPES = {\n    h264: 0x1b,\n    adts: 0x0f\n  };\n  /**\n   * Reconsistutes program elementary stream (PES) packets from parsed\n   * transport stream packets. That is, if you pipe an\n   * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output\n   * events will be events which capture the bytes for individual PES\n   * packets plus relevant metadata that has been extracted from the\n   * container.\n   */\n\n  ElementaryStream = function () {\n    var self = this,\n      segmentHadPmt = false,\n      // PES packet fragments\n      video = {\n        data: [],\n        size: 0\n      },\n      audio = {\n        data: [],\n        size: 0\n      },\n      timedMetadata = {\n        data: [],\n        size: 0\n      },\n      programMapTable,\n      parsePes = function (payload, pes) {\n        var ptsDtsFlags;\n        const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array\n\n        pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets\n        // that are frame data that is continuing from the previous fragment. This\n        // is to check that the pes data is the start of a new pes payload\n\n        if (startPrefix !== 1) {\n          return;\n        } // get the packet length, this will be 0 for video\n\n        pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe\n\n        pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value\n        // and a DTS value. Determine what combination of values is\n        // available to work with.\n\n        ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number.  Javascript\n        // performs all bitwise operations on 32-bit integers but javascript\n        // supports a much greater range (52-bits) of integer using standard\n        // mathematical operations.\n        // We construct a 31-bit value using bitwise operators over the 31\n        // most significant bits and then multiply by 4 (equal to a left-shift\n        // of 2) before we add the final 2 least significant bits of the\n        // timestamp (equal to an OR.)\n\n        if (ptsDtsFlags & 0xC0) {\n          // the PTS and DTS are not written out directly. For information\n          // on how they are encoded, see\n          // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n          pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;\n          pes.pts *= 4; // Left shift by 2\n\n          pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs\n\n          pes.dts = pes.pts;\n          if (ptsDtsFlags & 0x40) {\n            pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;\n            pes.dts *= 4; // Left shift by 2\n\n            pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs\n          }\n        } // the data section starts immediately after the PES header.\n        // pes_header_data_length specifies the number of header bytes\n        // that follow the last byte of the field.\n\n        pes.data = payload.subarray(9 + payload[8]);\n      },\n      /**\n        * Pass completely parsed PES packets to the next stream in the pipeline\n       **/\n      flushStream = function (stream, type, forceFlush) {\n        var packetData = new Uint8Array(stream.size),\n          event = {\n            type: type\n          },\n          i = 0,\n          offset = 0,\n          packetFlushable = false,\n          fragment; // do nothing if there is not enough buffered data for a complete\n        // PES header\n\n        if (!stream.data.length || stream.size < 9) {\n          return;\n        }\n        event.trackId = stream.data[0].pid; // reassemble the packet\n\n        for (i = 0; i < stream.data.length; i++) {\n          fragment = stream.data[i];\n          packetData.set(fragment.data, offset);\n          offset += fragment.data.byteLength;\n        } // parse assembled packet's PES header\n\n        parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length\n        // check that there is enough stream data to fill the packet\n\n        packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right\n\n        if (forceFlush || packetFlushable) {\n          stream.size = 0;\n          stream.data.length = 0;\n        } // only emit packets that are complete. this is to avoid assembling\n        // incomplete PES packets due to poor segmentation\n\n        if (packetFlushable) {\n          self.trigger('data', event);\n        }\n      };\n    ElementaryStream.prototype.init.call(this);\n    /**\n     * Identifies M2TS packet types and parses PES packets using metadata\n     * parsed from the PMT\n     **/\n\n    this.push = function (data) {\n      ({\n        pat: function () {// we have to wait for the PMT to arrive as well before we\n          // have any meaningful metadata\n        },\n        pes: function () {\n          var stream, streamType;\n          switch (data.streamType) {\n            case StreamTypes$2.H264_STREAM_TYPE:\n              stream = video;\n              streamType = 'video';\n              break;\n            case StreamTypes$2.ADTS_STREAM_TYPE:\n              stream = audio;\n              streamType = 'audio';\n              break;\n            case StreamTypes$2.METADATA_STREAM_TYPE:\n              stream = timedMetadata;\n              streamType = 'timed-metadata';\n              break;\n            default:\n              // ignore unknown stream types\n              return;\n          } // if a new packet is starting, we can flush the completed\n          // packet\n\n          if (data.payloadUnitStartIndicator) {\n            flushStream(stream, streamType, true);\n          } // buffer this fragment until we are sure we've received the\n          // complete payload\n\n          stream.data.push(data);\n          stream.size += data.data.byteLength;\n        },\n        pmt: function () {\n          var event = {\n            type: 'metadata',\n            tracks: []\n          };\n          programMapTable = data.programMapTable; // translate audio and video streams to tracks\n\n          if (programMapTable.video !== null) {\n            event.tracks.push({\n              timelineStartInfo: {\n                baseMediaDecodeTime: 0\n              },\n              id: +programMapTable.video,\n              codec: 'avc',\n              type: 'video'\n            });\n          }\n          if (programMapTable.audio !== null) {\n            event.tracks.push({\n              timelineStartInfo: {\n                baseMediaDecodeTime: 0\n              },\n              id: +programMapTable.audio,\n              codec: 'adts',\n              type: 'audio'\n            });\n          }\n          segmentHadPmt = true;\n          self.trigger('data', event);\n        }\n      })[data.type]();\n    };\n    this.reset = function () {\n      video.size = 0;\n      video.data.length = 0;\n      audio.size = 0;\n      audio.data.length = 0;\n      this.trigger('reset');\n    };\n    /**\n     * Flush any remaining input. Video PES packets may be of variable\n     * length. Normally, the start of a new video packet can trigger the\n     * finalization of the previous packet. That is not possible if no\n     * more video is forthcoming, however. In that case, some other\n     * mechanism (like the end of the file) has to be employed. When it is\n     * clear that no additional data is forthcoming, calling this method\n     * will flush the buffered packets.\n     */\n\n    this.flushStreams_ = function () {\n      // !!THIS ORDER IS IMPORTANT!!\n      // video first then audio\n      flushStream(video, 'video');\n      flushStream(audio, 'audio');\n      flushStream(timedMetadata, 'timed-metadata');\n    };\n    this.flush = function () {\n      // if on flush we haven't had a pmt emitted\n      // and we have a pmt to emit. emit the pmt\n      // so that we trigger a trackinfo downstream.\n      if (!segmentHadPmt && programMapTable) {\n        var pmt = {\n          type: 'metadata',\n          tracks: []\n        }; // translate audio and video streams to tracks\n\n        if (programMapTable.video !== null) {\n          pmt.tracks.push({\n            timelineStartInfo: {\n              baseMediaDecodeTime: 0\n            },\n            id: +programMapTable.video,\n            codec: 'avc',\n            type: 'video'\n          });\n        }\n        if (programMapTable.audio !== null) {\n          pmt.tracks.push({\n            timelineStartInfo: {\n              baseMediaDecodeTime: 0\n            },\n            id: +programMapTable.audio,\n            codec: 'adts',\n            type: 'audio'\n          });\n        }\n        self.trigger('data', pmt);\n      }\n      segmentHadPmt = false;\n      this.flushStreams_();\n      this.trigger('done');\n    };\n  };\n  ElementaryStream.prototype = new Stream$4();\n  var m2ts$1 = {\n    PAT_PID: 0x0000,\n    MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,\n    TransportPacketStream: TransportPacketStream,\n    TransportParseStream: TransportParseStream,\n    ElementaryStream: ElementaryStream,\n    TimestampRolloverStream: TimestampRolloverStream,\n    CaptionStream: CaptionStream$1.CaptionStream,\n    Cea608Stream: CaptionStream$1.Cea608Stream,\n    Cea708Stream: CaptionStream$1.Cea708Stream,\n    MetadataStream: metadataStream\n  };\n  for (var type in StreamTypes$2) {\n    if (StreamTypes$2.hasOwnProperty(type)) {\n      m2ts$1[type] = StreamTypes$2[type];\n    }\n  }\n  var m2ts_1 = m2ts$1;\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n\n  var Stream$3 = stream;\n  var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;\n  var AdtsStream$1;\n  var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];\n  /*\n   * Accepts a ElementaryStream and emits data events with parsed\n   * AAC Audio Frames of the individual packets. Input audio in ADTS\n   * format is unpacked and re-emitted as AAC frames.\n   *\n   * @see http://wiki.multimedia.cx/index.php?title=ADTS\n   * @see http://wiki.multimedia.cx/?title=Understanding_AAC\n   */\n\n  AdtsStream$1 = function (handlePartialSegments) {\n    var buffer,\n      frameNum = 0;\n    AdtsStream$1.prototype.init.call(this);\n    this.skipWarn_ = function (start, end) {\n      this.trigger('log', {\n        level: 'warn',\n        message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`\n      });\n    };\n    this.push = function (packet) {\n      var i = 0,\n        frameLength,\n        protectionSkipBytes,\n        oldBuffer,\n        sampleCount,\n        adtsFrameDuration;\n      if (!handlePartialSegments) {\n        frameNum = 0;\n      }\n      if (packet.type !== 'audio') {\n        // ignore non-audio data\n        return;\n      } // Prepend any data in the buffer to the input data so that we can parse\n      // aac frames the cross a PES packet boundary\n\n      if (buffer && buffer.length) {\n        oldBuffer = buffer;\n        buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);\n        buffer.set(oldBuffer);\n        buffer.set(packet.data, oldBuffer.byteLength);\n      } else {\n        buffer = packet.data;\n      } // unpack any ADTS frames which have been fully received\n      // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS\n\n      var skip; // We use i + 7 here because we want to be able to parse the entire header.\n      // If we don't have enough bytes to do that, then we definitely won't have a full frame.\n\n      while (i + 7 < buffer.length) {\n        // Look for the start of an ADTS header..\n        if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {\n          if (typeof skip !== 'number') {\n            skip = i;\n          } // If a valid header was not found,  jump one forward and attempt to\n          // find a valid ADTS header starting at the next byte\n\n          i++;\n          continue;\n        }\n        if (typeof skip === 'number') {\n          this.skipWarn_(skip, i);\n          skip = null;\n        } // The protection skip bit tells us if we have 2 bytes of CRC data at the\n        // end of the ADTS header\n\n        protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the\n        // end of the sync sequence\n        // NOTE: frame length includes the size of the header\n\n        frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;\n        sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;\n        adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2]; // If we don't have enough data to actually finish this ADTS frame,\n        // then we have to wait for more data\n\n        if (buffer.byteLength - i < frameLength) {\n          break;\n        } // Otherwise, deliver the complete AAC frame\n\n        this.trigger('data', {\n          pts: packet.pts + frameNum * adtsFrameDuration,\n          dts: packet.dts + frameNum * adtsFrameDuration,\n          sampleCount: sampleCount,\n          audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,\n          channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,\n          samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],\n          samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,\n          // assume ISO/IEC 14496-12 AudioSampleEntry default of 16\n          samplesize: 16,\n          // data is the frame without it's header\n          data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)\n        });\n        frameNum++;\n        i += frameLength;\n      }\n      if (typeof skip === 'number') {\n        this.skipWarn_(skip, i);\n        skip = null;\n      } // remove processed bytes from the buffer.\n\n      buffer = buffer.subarray(i);\n    };\n    this.flush = function () {\n      frameNum = 0;\n      this.trigger('done');\n    };\n    this.reset = function () {\n      buffer = void 0;\n      this.trigger('reset');\n    };\n    this.endTimeline = function () {\n      buffer = void 0;\n      this.trigger('endedtimeline');\n    };\n  };\n  AdtsStream$1.prototype = new Stream$3();\n  var adts = AdtsStream$1;\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n\n  var ExpGolomb$1;\n  /**\n   * Parser for exponential Golomb codes, a variable-bitwidth number encoding\n   * scheme used by h264.\n   */\n\n  ExpGolomb$1 = function (workingData) {\n    var\n      // the number of bytes left to examine in workingData\n      workingBytesAvailable = workingData.byteLength,\n      // the current word being examined\n      workingWord = 0,\n      // :uint\n      // the number of bits left to examine in the current word\n      workingBitsAvailable = 0; // :uint;\n    // ():uint\n\n    this.length = function () {\n      return 8 * workingBytesAvailable;\n    }; // ():uint\n\n    this.bitsAvailable = function () {\n      return 8 * workingBytesAvailable + workingBitsAvailable;\n    }; // ():void\n\n    this.loadWord = function () {\n      var position = workingData.byteLength - workingBytesAvailable,\n        workingBytes = new Uint8Array(4),\n        availableBytes = Math.min(4, workingBytesAvailable);\n      if (availableBytes === 0) {\n        throw new Error('no bytes available');\n      }\n      workingBytes.set(workingData.subarray(position, position + availableBytes));\n      workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed\n\n      workingBitsAvailable = availableBytes * 8;\n      workingBytesAvailable -= availableBytes;\n    }; // (count:int):void\n\n    this.skipBits = function (count) {\n      var skipBytes; // :int\n\n      if (workingBitsAvailable > count) {\n        workingWord <<= count;\n        workingBitsAvailable -= count;\n      } else {\n        count -= workingBitsAvailable;\n        skipBytes = Math.floor(count / 8);\n        count -= skipBytes * 8;\n        workingBytesAvailable -= skipBytes;\n        this.loadWord();\n        workingWord <<= count;\n        workingBitsAvailable -= count;\n      }\n    }; // (size:int):uint\n\n    this.readBits = function (size) {\n      var bits = Math.min(workingBitsAvailable, size),\n        // :uint\n        valu = workingWord >>> 32 - bits; // :uint\n      // if size > 31, handle error\n\n      workingBitsAvailable -= bits;\n      if (workingBitsAvailable > 0) {\n        workingWord <<= bits;\n      } else if (workingBytesAvailable > 0) {\n        this.loadWord();\n      }\n      bits = size - bits;\n      if (bits > 0) {\n        return valu << bits | this.readBits(bits);\n      }\n      return valu;\n    }; // ():uint\n\n    this.skipLeadingZeros = function () {\n      var leadingZeroCount; // :uint\n\n      for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {\n        if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {\n          // the first bit of working word is 1\n          workingWord <<= leadingZeroCount;\n          workingBitsAvailable -= leadingZeroCount;\n          return leadingZeroCount;\n        }\n      } // we exhausted workingWord and still have not found a 1\n\n      this.loadWord();\n      return leadingZeroCount + this.skipLeadingZeros();\n    }; // ():void\n\n    this.skipUnsignedExpGolomb = function () {\n      this.skipBits(1 + this.skipLeadingZeros());\n    }; // ():void\n\n    this.skipExpGolomb = function () {\n      this.skipBits(1 + this.skipLeadingZeros());\n    }; // ():uint\n\n    this.readUnsignedExpGolomb = function () {\n      var clz = this.skipLeadingZeros(); // :uint\n\n      return this.readBits(clz + 1) - 1;\n    }; // ():int\n\n    this.readExpGolomb = function () {\n      var valu = this.readUnsignedExpGolomb(); // :int\n\n      if (0x01 & valu) {\n        // the number is odd if the low order bit is set\n        return 1 + valu >>> 1; // add 1 to make it even, and divide by 2\n      }\n      return -1 * (valu >>> 1); // divide by two then make it negative\n    }; // Some convenience functions\n    // :Boolean\n\n    this.readBoolean = function () {\n      return this.readBits(1) === 1;\n    }; // ():int\n\n    this.readUnsignedByte = function () {\n      return this.readBits(8);\n    };\n    this.loadWord();\n  };\n  var expGolomb = ExpGolomb$1;\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n\n  var Stream$2 = stream;\n  var ExpGolomb = expGolomb;\n  var H264Stream$1, NalByteStream;\n  var PROFILES_WITH_OPTIONAL_SPS_DATA;\n  /**\n   * Accepts a NAL unit byte stream and unpacks the embedded NAL units.\n   */\n\n  NalByteStream = function () {\n    var syncPoint = 0,\n      i,\n      buffer;\n    NalByteStream.prototype.init.call(this);\n    /*\n     * Scans a byte stream and triggers a data event with the NAL units found.\n     * @param {Object} data Event received from H264Stream\n     * @param {Uint8Array} data.data The h264 byte stream to be scanned\n     *\n     * @see H264Stream.push\n     */\n\n    this.push = function (data) {\n      var swapBuffer;\n      if (!buffer) {\n        buffer = data.data;\n      } else {\n        swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);\n        swapBuffer.set(buffer);\n        swapBuffer.set(data.data, buffer.byteLength);\n        buffer = swapBuffer;\n      }\n      var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B\n      // scan for NAL unit boundaries\n      // a match looks like this:\n      // 0 0 1 .. NAL .. 0 0 1\n      // ^ sync point        ^ i\n      // or this:\n      // 0 0 1 .. NAL .. 0 0 0\n      // ^ sync point        ^ i\n      // advance the sync point to a NAL start, if necessary\n\n      for (; syncPoint < len - 3; syncPoint++) {\n        if (buffer[syncPoint + 2] === 1) {\n          // the sync point is properly aligned\n          i = syncPoint + 5;\n          break;\n        }\n      }\n      while (i < len) {\n        // look at the current byte to determine if we've hit the end of\n        // a NAL unit boundary\n        switch (buffer[i]) {\n          case 0:\n            // skip past non-sync sequences\n            if (buffer[i - 1] !== 0) {\n              i += 2;\n              break;\n            } else if (buffer[i - 2] !== 0) {\n              i++;\n              break;\n            } // deliver the NAL unit if it isn't empty\n\n            if (syncPoint + 3 !== i - 2) {\n              this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));\n            } // drop trailing zeroes\n\n            do {\n              i++;\n            } while (buffer[i] !== 1 && i < len);\n            syncPoint = i - 2;\n            i += 3;\n            break;\n          case 1:\n            // skip past non-sync sequences\n            if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {\n              i += 3;\n              break;\n            } // deliver the NAL unit\n\n            this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));\n            syncPoint = i - 2;\n            i += 3;\n            break;\n          default:\n            // the current byte isn't a one or zero, so it cannot be part\n            // of a sync sequence\n            i += 3;\n            break;\n        }\n      } // filter out the NAL units that were delivered\n\n      buffer = buffer.subarray(syncPoint);\n      i -= syncPoint;\n      syncPoint = 0;\n    };\n    this.reset = function () {\n      buffer = null;\n      syncPoint = 0;\n      this.trigger('reset');\n    };\n    this.flush = function () {\n      // deliver the last buffered NAL unit\n      if (buffer && buffer.byteLength > 3) {\n        this.trigger('data', buffer.subarray(syncPoint + 3));\n      } // reset the stream state\n\n      buffer = null;\n      syncPoint = 0;\n      this.trigger('done');\n    };\n    this.endTimeline = function () {\n      this.flush();\n      this.trigger('endedtimeline');\n    };\n  };\n  NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS\n  // see Recommendation ITU-T H.264 (4/2013),\n  // 7.3.2.1.1 Sequence parameter set data syntax\n\n  PROFILES_WITH_OPTIONAL_SPS_DATA = {\n    100: true,\n    110: true,\n    122: true,\n    244: true,\n    44: true,\n    83: true,\n    86: true,\n    118: true,\n    128: true,\n    // TODO: the three profiles below don't\n    // appear to have sps data in the specificiation anymore?\n    138: true,\n    139: true,\n    134: true\n  };\n  /**\n   * Accepts input from a ElementaryStream and produces H.264 NAL unit data\n   * events.\n   */\n\n  H264Stream$1 = function () {\n    var nalByteStream = new NalByteStream(),\n      self,\n      trackId,\n      currentPts,\n      currentDts,\n      discardEmulationPreventionBytes,\n      readSequenceParameterSet,\n      skipScalingList;\n    H264Stream$1.prototype.init.call(this);\n    self = this;\n    /*\n     * Pushes a packet from a stream onto the NalByteStream\n     *\n     * @param {Object} packet - A packet received from a stream\n     * @param {Uint8Array} packet.data - The raw bytes of the packet\n     * @param {Number} packet.dts - Decode timestamp of the packet\n     * @param {Number} packet.pts - Presentation timestamp of the packet\n     * @param {Number} packet.trackId - The id of the h264 track this packet came from\n     * @param {('video'|'audio')} packet.type - The type of packet\n     *\n     */\n\n    this.push = function (packet) {\n      if (packet.type !== 'video') {\n        return;\n      }\n      trackId = packet.trackId;\n      currentPts = packet.pts;\n      currentDts = packet.dts;\n      nalByteStream.push(packet);\n    };\n    /*\n     * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps\n     * for the NALUs to the next stream component.\n     * Also, preprocess caption and sequence parameter NALUs.\n     *\n     * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`\n     * @see NalByteStream.push\n     */\n\n    nalByteStream.on('data', function (data) {\n      var event = {\n        trackId: trackId,\n        pts: currentPts,\n        dts: currentDts,\n        data: data,\n        nalUnitTypeCode: data[0] & 0x1f\n      };\n      switch (event.nalUnitTypeCode) {\n        case 0x05:\n          event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';\n          break;\n        case 0x06:\n          event.nalUnitType = 'sei_rbsp';\n          event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));\n          break;\n        case 0x07:\n          event.nalUnitType = 'seq_parameter_set_rbsp';\n          event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));\n          event.config = readSequenceParameterSet(event.escapedRBSP);\n          break;\n        case 0x08:\n          event.nalUnitType = 'pic_parameter_set_rbsp';\n          break;\n        case 0x09:\n          event.nalUnitType = 'access_unit_delimiter_rbsp';\n          break;\n      } // This triggers data on the H264Stream\n\n      self.trigger('data', event);\n    });\n    nalByteStream.on('done', function () {\n      self.trigger('done');\n    });\n    nalByteStream.on('partialdone', function () {\n      self.trigger('partialdone');\n    });\n    nalByteStream.on('reset', function () {\n      self.trigger('reset');\n    });\n    nalByteStream.on('endedtimeline', function () {\n      self.trigger('endedtimeline');\n    });\n    this.flush = function () {\n      nalByteStream.flush();\n    };\n    this.partialFlush = function () {\n      nalByteStream.partialFlush();\n    };\n    this.reset = function () {\n      nalByteStream.reset();\n    };\n    this.endTimeline = function () {\n      nalByteStream.endTimeline();\n    };\n    /**\n     * Advance the ExpGolomb decoder past a scaling list. The scaling\n     * list is optionally transmitted as part of a sequence parameter\n     * set and is not relevant to transmuxing.\n     * @param count {number} the number of entries in this scaling list\n     * @param expGolombDecoder {object} an ExpGolomb pointed to the\n     * start of a scaling list\n     * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n     */\n\n    skipScalingList = function (count, expGolombDecoder) {\n      var lastScale = 8,\n        nextScale = 8,\n        j,\n        deltaScale;\n      for (j = 0; j < count; j++) {\n        if (nextScale !== 0) {\n          deltaScale = expGolombDecoder.readExpGolomb();\n          nextScale = (lastScale + deltaScale + 256) % 256;\n        }\n        lastScale = nextScale === 0 ? lastScale : nextScale;\n      }\n    };\n    /**\n     * Expunge any \"Emulation Prevention\" bytes from a \"Raw Byte\n     * Sequence Payload\"\n     * @param data {Uint8Array} the bytes of a RBSP from a NAL\n     * unit\n     * @return {Uint8Array} the RBSP without any Emulation\n     * Prevention Bytes\n     */\n\n    discardEmulationPreventionBytes = function (data) {\n      var length = data.byteLength,\n        emulationPreventionBytesPositions = [],\n        i = 1,\n        newLength,\n        newData; // Find all `Emulation Prevention Bytes`\n\n      while (i < length - 2) {\n        if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {\n          emulationPreventionBytesPositions.push(i + 2);\n          i += 2;\n        } else {\n          i++;\n        }\n      } // If no Emulation Prevention Bytes were found just return the original\n      // array\n\n      if (emulationPreventionBytesPositions.length === 0) {\n        return data;\n      } // Create a new array to hold the NAL unit data\n\n      newLength = length - emulationPreventionBytesPositions.length;\n      newData = new Uint8Array(newLength);\n      var sourceIndex = 0;\n      for (i = 0; i < newLength; sourceIndex++, i++) {\n        if (sourceIndex === emulationPreventionBytesPositions[0]) {\n          // Skip this byte\n          sourceIndex++; // Remove this position index\n\n          emulationPreventionBytesPositions.shift();\n        }\n        newData[i] = data[sourceIndex];\n      }\n      return newData;\n    };\n    /**\n     * Read a sequence parameter set and return some interesting video\n     * properties. A sequence parameter set is the H264 metadata that\n     * describes the properties of upcoming video frames.\n     * @param data {Uint8Array} the bytes of a sequence parameter set\n     * @return {object} an object with configuration parsed from the\n     * sequence parameter set, including the dimensions of the\n     * associated video frames.\n     */\n\n    readSequenceParameterSet = function (data) {\n      var frameCropLeftOffset = 0,\n        frameCropRightOffset = 0,\n        frameCropTopOffset = 0,\n        frameCropBottomOffset = 0,\n        expGolombDecoder,\n        profileIdc,\n        levelIdc,\n        profileCompatibility,\n        chromaFormatIdc,\n        picOrderCntType,\n        numRefFramesInPicOrderCntCycle,\n        picWidthInMbsMinus1,\n        picHeightInMapUnitsMinus1,\n        frameMbsOnlyFlag,\n        scalingListCount,\n        sarRatio = [1, 1],\n        aspectRatioIdc,\n        i;\n      expGolombDecoder = new ExpGolomb(data);\n      profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc\n\n      profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag\n\n      levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)\n\n      expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id\n      // some profiles have more optional data we don't need\n\n      if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {\n        chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();\n        if (chromaFormatIdc === 3) {\n          expGolombDecoder.skipBits(1); // separate_colour_plane_flag\n        }\n        expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8\n\n        expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8\n\n        expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag\n\n        if (expGolombDecoder.readBoolean()) {\n          // seq_scaling_matrix_present_flag\n          scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;\n          for (i = 0; i < scalingListCount; i++) {\n            if (expGolombDecoder.readBoolean()) {\n              // seq_scaling_list_present_flag[ i ]\n              if (i < 6) {\n                skipScalingList(16, expGolombDecoder);\n              } else {\n                skipScalingList(64, expGolombDecoder);\n              }\n            }\n          }\n        }\n      }\n      expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4\n\n      picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();\n      if (picOrderCntType === 0) {\n        expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4\n      } else if (picOrderCntType === 1) {\n        expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag\n\n        expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic\n\n        expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field\n\n        numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();\n        for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n          expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]\n        }\n      }\n      expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames\n\n      expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag\n\n      picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();\n      picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();\n      frameMbsOnlyFlag = expGolombDecoder.readBits(1);\n      if (frameMbsOnlyFlag === 0) {\n        expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag\n      }\n      expGolombDecoder.skipBits(1); // direct_8x8_inference_flag\n\n      if (expGolombDecoder.readBoolean()) {\n        // frame_cropping_flag\n        frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();\n        frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();\n        frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();\n        frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();\n      }\n      if (expGolombDecoder.readBoolean()) {\n        // vui_parameters_present_flag\n        if (expGolombDecoder.readBoolean()) {\n          // aspect_ratio_info_present_flag\n          aspectRatioIdc = expGolombDecoder.readUnsignedByte();\n          switch (aspectRatioIdc) {\n            case 1:\n              sarRatio = [1, 1];\n              break;\n            case 2:\n              sarRatio = [12, 11];\n              break;\n            case 3:\n              sarRatio = [10, 11];\n              break;\n            case 4:\n              sarRatio = [16, 11];\n              break;\n            case 5:\n              sarRatio = [40, 33];\n              break;\n            case 6:\n              sarRatio = [24, 11];\n              break;\n            case 7:\n              sarRatio = [20, 11];\n              break;\n            case 8:\n              sarRatio = [32, 11];\n              break;\n            case 9:\n              sarRatio = [80, 33];\n              break;\n            case 10:\n              sarRatio = [18, 11];\n              break;\n            case 11:\n              sarRatio = [15, 11];\n              break;\n            case 12:\n              sarRatio = [64, 33];\n              break;\n            case 13:\n              sarRatio = [160, 99];\n              break;\n            case 14:\n              sarRatio = [4, 3];\n              break;\n            case 15:\n              sarRatio = [3, 2];\n              break;\n            case 16:\n              sarRatio = [2, 1];\n              break;\n            case 255:\n              {\n                sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];\n                break;\n              }\n          }\n          if (sarRatio) {\n            sarRatio[0] / sarRatio[1];\n          }\n        }\n      }\n      return {\n        profileIdc: profileIdc,\n        levelIdc: levelIdc,\n        profileCompatibility: profileCompatibility,\n        width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,\n        height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,\n        // sar is sample aspect ratio\n        sarRatio: sarRatio\n      };\n    };\n  };\n  H264Stream$1.prototype = new Stream$2();\n  var h264 = {\n    H264Stream: H264Stream$1,\n    NalByteStream: NalByteStream\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Utilities to detect basic properties and metadata about Aac data.\n   */\n\n  var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];\n  var parseId3TagSize = function (header, byteIndex) {\n    var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],\n      flags = header[byteIndex + 5],\n      footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0\n\n    returnSize = returnSize >= 0 ? returnSize : 0;\n    if (footerPresent) {\n      return returnSize + 20;\n    }\n    return returnSize + 10;\n  };\n  var getId3Offset = function (data, offset) {\n    if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {\n      return offset;\n    }\n    offset += parseId3TagSize(data, offset);\n    return getId3Offset(data, offset);\n  }; // TODO: use vhs-utils\n\n  var isLikelyAacData$1 = function (data) {\n    var offset = getId3Offset(data, 0);\n    return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 &&\n    // verify that the 2 layer bits are 0, aka this\n    // is not mp3 data but aac data.\n    (data[offset + 1] & 0x16) === 0x10;\n  };\n  var parseSyncSafeInteger = function (data) {\n    return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];\n  }; // return a percent-encoded representation of the specified byte range\n  // @see http://en.wikipedia.org/wiki/Percent-encoding\n\n  var percentEncode = function (bytes, start, end) {\n    var i,\n      result = '';\n    for (i = start; i < end; i++) {\n      result += '%' + ('00' + bytes[i].toString(16)).slice(-2);\n    }\n    return result;\n  }; // return the string representation of the specified byte range,\n  // interpreted as ISO-8859-1.\n\n  var parseIso88591 = function (bytes, start, end) {\n    return unescape(percentEncode(bytes, start, end)); // jshint ignore:line\n  };\n  var parseAdtsSize = function (header, byteIndex) {\n    var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,\n      middle = header[byteIndex + 4] << 3,\n      highTwo = header[byteIndex + 3] & 0x3 << 11;\n    return highTwo | middle | lowThree;\n  };\n  var parseType$5 = function (header, byteIndex) {\n    if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {\n      return 'timed-metadata';\n    } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {\n      return 'audio';\n    }\n    return null;\n  };\n  var parseSampleRate = function (packet) {\n    var i = 0;\n    while (i + 5 < packet.length) {\n      if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {\n        // If a valid header was not found,  jump one forward and attempt to\n        // find a valid ADTS header starting at the next byte\n        i++;\n        continue;\n      }\n      return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];\n    }\n    return null;\n  };\n  var parseAacTimestamp = function (packet) {\n    var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag\n\n    frameStart = 10;\n    if (packet[5] & 0x40) {\n      // advance the frame start past the extended header\n      frameStart += 4; // header size field\n\n      frameStart += parseSyncSafeInteger(packet.subarray(10, 14));\n    } // parse one or more ID3 frames\n    // http://id3.org/id3v2.3.0#ID3v2_frame_overview\n\n    do {\n      // determine the number of bytes in this frame\n      frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));\n      if (frameSize < 1) {\n        return null;\n      }\n      frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);\n      if (frameHeader === 'PRIV') {\n        frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);\n        for (var i = 0; i < frame.byteLength; i++) {\n          if (frame[i] === 0) {\n            var owner = parseIso88591(frame, 0, i);\n            if (owner === 'com.apple.streaming.transportStreamTimestamp') {\n              var d = frame.subarray(i + 1);\n              var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;\n              size *= 4;\n              size += d[7] & 0x03;\n              return size;\n            }\n            break;\n          }\n        }\n      }\n      frameStart += 10; // advance past the frame header\n\n      frameStart += frameSize; // advance past the frame body\n    } while (frameStart < packet.byteLength);\n    return null;\n  };\n  var utils = {\n    isLikelyAacData: isLikelyAacData$1,\n    parseId3TagSize: parseId3TagSize,\n    parseAdtsSize: parseAdtsSize,\n    parseType: parseType$5,\n    parseSampleRate: parseSampleRate,\n    parseAacTimestamp: parseAacTimestamp\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * A stream-based aac to mp4 converter. This utility can be used to\n   * deliver mp4s to a SourceBuffer on platforms that support native\n   * Media Source Extensions.\n   */\n\n  var Stream$1 = stream;\n  var aacUtils = utils; // Constants\n\n  var AacStream$1;\n  /**\n   * Splits an incoming stream of binary data into ADTS and ID3 Frames.\n   */\n\n  AacStream$1 = function () {\n    var everything = new Uint8Array(),\n      timeStamp = 0;\n    AacStream$1.prototype.init.call(this);\n    this.setTimestamp = function (timestamp) {\n      timeStamp = timestamp;\n    };\n    this.push = function (bytes) {\n      var frameSize = 0,\n        byteIndex = 0,\n        bytesLeft,\n        chunk,\n        packet,\n        tempLength; // If there are bytes remaining from the last segment, prepend them to the\n      // bytes that were pushed in\n\n      if (everything.length) {\n        tempLength = everything.length;\n        everything = new Uint8Array(bytes.byteLength + tempLength);\n        everything.set(everything.subarray(0, tempLength));\n        everything.set(bytes, tempLength);\n      } else {\n        everything = bytes;\n      }\n      while (everything.length - byteIndex >= 3) {\n        if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {\n          // Exit early because we don't have enough to parse\n          // the ID3 tag header\n          if (everything.length - byteIndex < 10) {\n            break;\n          } // check framesize\n\n          frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer\n          // to emit a full packet\n          // Add to byteIndex to support multiple ID3 tags in sequence\n\n          if (byteIndex + frameSize > everything.length) {\n            break;\n          }\n          chunk = {\n            type: 'timed-metadata',\n            data: everything.subarray(byteIndex, byteIndex + frameSize)\n          };\n          this.trigger('data', chunk);\n          byteIndex += frameSize;\n          continue;\n        } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {\n          // Exit early because we don't have enough to parse\n          // the ADTS frame header\n          if (everything.length - byteIndex < 7) {\n            break;\n          }\n          frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer\n          // to emit a full packet\n\n          if (byteIndex + frameSize > everything.length) {\n            break;\n          }\n          packet = {\n            type: 'audio',\n            data: everything.subarray(byteIndex, byteIndex + frameSize),\n            pts: timeStamp,\n            dts: timeStamp\n          };\n          this.trigger('data', packet);\n          byteIndex += frameSize;\n          continue;\n        }\n        byteIndex++;\n      }\n      bytesLeft = everything.length - byteIndex;\n      if (bytesLeft > 0) {\n        everything = everything.subarray(byteIndex);\n      } else {\n        everything = new Uint8Array();\n      }\n    };\n    this.reset = function () {\n      everything = new Uint8Array();\n      this.trigger('reset');\n    };\n    this.endTimeline = function () {\n      everything = new Uint8Array();\n      this.trigger('endedtimeline');\n    };\n  };\n  AacStream$1.prototype = new Stream$1();\n  var aac = AacStream$1;\n  var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];\n  var audioProperties = AUDIO_PROPERTIES$1;\n  var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];\n  var videoProperties = VIDEO_PROPERTIES$1;\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * A stream-based mp2t to mp4 converter. This utility can be used to\n   * deliver mp4s to a SourceBuffer on platforms that support native\n   * Media Source Extensions.\n   */\n\n  var Stream = stream;\n  var mp4 = mp4Generator;\n  var frameUtils = frameUtils$1;\n  var audioFrameUtils = audioFrameUtils$1;\n  var trackDecodeInfo = trackDecodeInfo$1;\n  var m2ts = m2ts_1;\n  var clock = clock$2;\n  var AdtsStream = adts;\n  var H264Stream = h264.H264Stream;\n  var AacStream = aac;\n  var isLikelyAacData = utils.isLikelyAacData;\n  var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;\n  var AUDIO_PROPERTIES = audioProperties;\n  var VIDEO_PROPERTIES = videoProperties; // object types\n\n  var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;\n  var retriggerForStream = function (key, event) {\n    event.stream = key;\n    this.trigger('log', event);\n  };\n  var addPipelineLogRetriggers = function (transmuxer, pipeline) {\n    var keys = Object.keys(pipeline);\n    for (var i = 0; i < keys.length; i++) {\n      var key = keys[i]; // skip non-stream keys and headOfPipeline\n      // which is just a duplicate\n\n      if (key === 'headOfPipeline' || !pipeline[key].on) {\n        continue;\n      }\n      pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));\n    }\n  };\n  /**\n   * Compare two arrays (even typed) for same-ness\n   */\n\n  var arrayEquals = function (a, b) {\n    var i;\n    if (a.length !== b.length) {\n      return false;\n    } // compare the value of each element in the array\n\n    for (i = 0; i < a.length; i++) {\n      if (a[i] !== b[i]) {\n        return false;\n      }\n    }\n    return true;\n  };\n  var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {\n    var ptsOffsetFromDts = startPts - startDts,\n      decodeDuration = endDts - startDts,\n      presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,\n    // however, the player time values will reflect a start from the baseMediaDecodeTime.\n    // In order to provide relevant values for the player times, base timing info on the\n    // baseMediaDecodeTime and the DTS and PTS durations of the segment.\n\n    return {\n      start: {\n        dts: baseMediaDecodeTime,\n        pts: baseMediaDecodeTime + ptsOffsetFromDts\n      },\n      end: {\n        dts: baseMediaDecodeTime + decodeDuration,\n        pts: baseMediaDecodeTime + presentationDuration\n      },\n      prependedContentDuration: prependedContentDuration,\n      baseMediaDecodeTime: baseMediaDecodeTime\n    };\n  };\n  /**\n   * Constructs a single-track, ISO BMFF media segment from AAC data\n   * events. The output of this stream can be fed to a SourceBuffer\n   * configured with a suitable initialization segment.\n   * @param track {object} track metadata configuration\n   * @param options {object} transmuxer options object\n   * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps\n   *        in the source; false to adjust the first segment to start at 0.\n   */\n\n  AudioSegmentStream = function (track, options) {\n    var adtsFrames = [],\n      sequenceNumber,\n      earliestAllowedDts = 0,\n      audioAppendStartTs = 0,\n      videoBaseMediaDecodeTime = Infinity;\n    options = options || {};\n    sequenceNumber = options.firstSequenceNumber || 0;\n    AudioSegmentStream.prototype.init.call(this);\n    this.push = function (data) {\n      trackDecodeInfo.collectDtsInfo(track, data);\n      if (track) {\n        AUDIO_PROPERTIES.forEach(function (prop) {\n          track[prop] = data[prop];\n        });\n      } // buffer audio data until end() is called\n\n      adtsFrames.push(data);\n    };\n    this.setEarliestDts = function (earliestDts) {\n      earliestAllowedDts = earliestDts;\n    };\n    this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {\n      videoBaseMediaDecodeTime = baseMediaDecodeTime;\n    };\n    this.setAudioAppendStart = function (timestamp) {\n      audioAppendStartTs = timestamp;\n    };\n    this.flush = function () {\n      var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed\n\n      if (adtsFrames.length === 0) {\n        this.trigger('done', 'AudioSegmentStream');\n        return;\n      }\n      frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);\n      track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock\n\n      videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to\n      // samples (that is, adts frames) in the audio data\n\n      track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat\n\n      mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));\n      adtsFrames = [];\n      moof = mp4.moof(sequenceNumber, [track]);\n      boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time\n\n      sequenceNumber++;\n      boxes.set(moof);\n      boxes.set(mdat, moof.byteLength);\n      trackDecodeInfo.clearDtsInfo(track);\n      frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with\n      // tests) on adding the timingInfo event. However, it seems unlikely that there's a\n      // valid use-case where an init segment/data should be triggered without associated\n      // frames. Leaving for now, but should be looked into.\n\n      if (frames.length) {\n        segmentDuration = frames.length * frameDuration;\n        this.trigger('segmentTimingInfo', generateSegmentTimingInfo(\n        // The audio track's baseMediaDecodeTime is in audio clock cycles, but the\n        // frame info is in video clock cycles. Convert to match expectation of\n        // listeners (that all timestamps will be based on video clock cycles).\n        clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate),\n        // frame times are already in video clock, as is segment duration\n        frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));\n        this.trigger('timingInfo', {\n          start: frames[0].pts,\n          end: frames[0].pts + segmentDuration\n        });\n      }\n      this.trigger('data', {\n        track: track,\n        boxes: boxes\n      });\n      this.trigger('done', 'AudioSegmentStream');\n    };\n    this.reset = function () {\n      trackDecodeInfo.clearDtsInfo(track);\n      adtsFrames = [];\n      this.trigger('reset');\n    };\n  };\n  AudioSegmentStream.prototype = new Stream();\n  /**\n   * Constructs a single-track, ISO BMFF media segment from H264 data\n   * events. The output of this stream can be fed to a SourceBuffer\n   * configured with a suitable initialization segment.\n   * @param track {object} track metadata configuration\n   * @param options {object} transmuxer options object\n   * @param options.alignGopsAtEnd {boolean} If true, start from the end of the\n   *        gopsToAlignWith list when attempting to align gop pts\n   * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps\n   *        in the source; false to adjust the first segment to start at 0.\n   */\n\n  VideoSegmentStream = function (track, options) {\n    var sequenceNumber,\n      nalUnits = [],\n      gopsToAlignWith = [],\n      config,\n      pps;\n    options = options || {};\n    sequenceNumber = options.firstSequenceNumber || 0;\n    VideoSegmentStream.prototype.init.call(this);\n    delete track.minPTS;\n    this.gopCache_ = [];\n    /**\n      * Constructs a ISO BMFF segment given H264 nalUnits\n      * @param {Object} nalUnit A data event representing a nalUnit\n      * @param {String} nalUnit.nalUnitType\n      * @param {Object} nalUnit.config Properties for a mp4 track\n      * @param {Uint8Array} nalUnit.data The nalUnit bytes\n      * @see lib/codecs/h264.js\n     **/\n\n    this.push = function (nalUnit) {\n      trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config\n\n      if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {\n        config = nalUnit.config;\n        track.sps = [nalUnit.data];\n        VIDEO_PROPERTIES.forEach(function (prop) {\n          track[prop] = config[prop];\n        }, this);\n      }\n      if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {\n        pps = nalUnit.data;\n        track.pps = [nalUnit.data];\n      } // buffer video until flush() is called\n\n      nalUnits.push(nalUnit);\n    };\n    /**\n      * Pass constructed ISO BMFF track and boxes on to the\n      * next stream in the pipeline\n     **/\n\n    this.flush = function () {\n      var frames,\n        gopForFusion,\n        gops,\n        moof,\n        mdat,\n        boxes,\n        prependedContentDuration = 0,\n        firstGop,\n        lastGop; // Throw away nalUnits at the start of the byte stream until\n      // we find the first AUD\n\n      while (nalUnits.length) {\n        if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {\n          break;\n        }\n        nalUnits.shift();\n      } // Return early if no video data has been observed\n\n      if (nalUnits.length === 0) {\n        this.resetStream_();\n        this.trigger('done', 'VideoSegmentStream');\n        return;\n      } // Organize the raw nal-units into arrays that represent\n      // higher-level constructs such as frames and gops\n      // (group-of-pictures)\n\n      frames = frameUtils.groupNalsIntoFrames(nalUnits);\n      gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have\n      // a problem since MSE (on Chrome) requires a leading keyframe.\n      //\n      // We have two approaches to repairing this situation:\n      // 1) GOP-FUSION:\n      //    This is where we keep track of the GOPS (group-of-pictures)\n      //    from previous fragments and attempt to find one that we can\n      //    prepend to the current fragment in order to create a valid\n      //    fragment.\n      // 2) KEYFRAME-PULLING:\n      //    Here we search for the first keyframe in the fragment and\n      //    throw away all the frames between the start of the fragment\n      //    and that keyframe. We then extend the duration and pull the\n      //    PTS of the keyframe forward so that it covers the time range\n      //    of the frames that were disposed of.\n      //\n      // #1 is far prefereable over #2 which can cause \"stuttering\" but\n      // requires more things to be just right.\n\n      if (!gops[0][0].keyFrame) {\n        // Search for a gop for fusion from our gopCache\n        gopForFusion = this.getGopForFusion_(nalUnits[0], track);\n        if (gopForFusion) {\n          // in order to provide more accurate timing information about the segment, save\n          // the number of seconds prepended to the original segment due to GOP fusion\n          prependedContentDuration = gopForFusion.duration;\n          gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the\n          // new gop at the beginning\n\n          gops.byteLength += gopForFusion.byteLength;\n          gops.nalCount += gopForFusion.nalCount;\n          gops.pts = gopForFusion.pts;\n          gops.dts = gopForFusion.dts;\n          gops.duration += gopForFusion.duration;\n        } else {\n          // If we didn't find a candidate gop fall back to keyframe-pulling\n          gops = frameUtils.extendFirstKeyFrame(gops);\n        }\n      } // Trim gops to align with gopsToAlignWith\n\n      if (gopsToAlignWith.length) {\n        var alignedGops;\n        if (options.alignGopsAtEnd) {\n          alignedGops = this.alignGopsAtEnd_(gops);\n        } else {\n          alignedGops = this.alignGopsAtStart_(gops);\n        }\n        if (!alignedGops) {\n          // save all the nals in the last GOP into the gop cache\n          this.gopCache_.unshift({\n            gop: gops.pop(),\n            pps: track.pps,\n            sps: track.sps\n          }); // Keep a maximum of 6 GOPs in the cache\n\n          this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits\n\n          nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith\n\n          this.resetStream_();\n          this.trigger('done', 'VideoSegmentStream');\n          return;\n        } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct\n        // when recalculated before sending off to CoalesceStream\n\n        trackDecodeInfo.clearDtsInfo(track);\n        gops = alignedGops;\n      }\n      trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to\n      // samples (that is, frames) in the video data\n\n      track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat\n\n      mdat = mp4.mdat(frameUtils.concatenateNalData(gops));\n      track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);\n      this.trigger('processedGopsInfo', gops.map(function (gop) {\n        return {\n          pts: gop.pts,\n          dts: gop.dts,\n          byteLength: gop.byteLength\n        };\n      }));\n      firstGop = gops[0];\n      lastGop = gops[gops.length - 1];\n      this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));\n      this.trigger('timingInfo', {\n        start: gops[0].pts,\n        end: gops[gops.length - 1].pts + gops[gops.length - 1].duration\n      }); // save all the nals in the last GOP into the gop cache\n\n      this.gopCache_.unshift({\n        gop: gops.pop(),\n        pps: track.pps,\n        sps: track.sps\n      }); // Keep a maximum of 6 GOPs in the cache\n\n      this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits\n\n      nalUnits = [];\n      this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);\n      this.trigger('timelineStartInfo', track.timelineStartInfo);\n      moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of\n      // throwing away hundreds of media segment fragments\n\n      boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time\n\n      sequenceNumber++;\n      boxes.set(moof);\n      boxes.set(mdat, moof.byteLength);\n      this.trigger('data', {\n        track: track,\n        boxes: boxes\n      });\n      this.resetStream_(); // Continue with the flush process now\n\n      this.trigger('done', 'VideoSegmentStream');\n    };\n    this.reset = function () {\n      this.resetStream_();\n      nalUnits = [];\n      this.gopCache_.length = 0;\n      gopsToAlignWith.length = 0;\n      this.trigger('reset');\n    };\n    this.resetStream_ = function () {\n      trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments\n      // for instance, when we are rendition switching\n\n      config = undefined;\n      pps = undefined;\n    }; // Search for a candidate Gop for gop-fusion from the gop cache and\n    // return it or return null if no good candidate was found\n\n    this.getGopForFusion_ = function (nalUnit) {\n      var halfSecond = 45000,\n        // Half-a-second in a 90khz clock\n        allowableOverlap = 10000,\n        // About 3 frames @ 30fps\n        nearestDistance = Infinity,\n        dtsDistance,\n        nearestGopObj,\n        currentGop,\n        currentGopObj,\n        i; // Search for the GOP nearest to the beginning of this nal unit\n\n      for (i = 0; i < this.gopCache_.length; i++) {\n        currentGopObj = this.gopCache_[i];\n        currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS\n\n        if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {\n          continue;\n        } // Reject Gops that would require a negative baseMediaDecodeTime\n\n        if (currentGop.dts < track.timelineStartInfo.dts) {\n          continue;\n        } // The distance between the end of the gop and the start of the nalUnit\n\n        dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within\n        // a half-second of the nal unit\n\n        if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {\n          // Always use the closest GOP we found if there is more than\n          // one candidate\n          if (!nearestGopObj || nearestDistance > dtsDistance) {\n            nearestGopObj = currentGopObj;\n            nearestDistance = dtsDistance;\n          }\n        }\n      }\n      if (nearestGopObj) {\n        return nearestGopObj.gop;\n      }\n      return null;\n    }; // trim gop list to the first gop found that has a matching pts with a gop in the list\n    // of gopsToAlignWith starting from the START of the list\n\n    this.alignGopsAtStart_ = function (gops) {\n      var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;\n      byteLength = gops.byteLength;\n      nalCount = gops.nalCount;\n      duration = gops.duration;\n      alignIndex = gopIndex = 0;\n      while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {\n        align = gopsToAlignWith[alignIndex];\n        gop = gops[gopIndex];\n        if (align.pts === gop.pts) {\n          break;\n        }\n        if (gop.pts > align.pts) {\n          // this current gop starts after the current gop we want to align on, so increment\n          // align index\n          alignIndex++;\n          continue;\n        } // current gop starts before the current gop we want to align on. so increment gop\n        // index\n\n        gopIndex++;\n        byteLength -= gop.byteLength;\n        nalCount -= gop.nalCount;\n        duration -= gop.duration;\n      }\n      if (gopIndex === 0) {\n        // no gops to trim\n        return gops;\n      }\n      if (gopIndex === gops.length) {\n        // all gops trimmed, skip appending all gops\n        return null;\n      }\n      alignedGops = gops.slice(gopIndex);\n      alignedGops.byteLength = byteLength;\n      alignedGops.duration = duration;\n      alignedGops.nalCount = nalCount;\n      alignedGops.pts = alignedGops[0].pts;\n      alignedGops.dts = alignedGops[0].dts;\n      return alignedGops;\n    }; // trim gop list to the first gop found that has a matching pts with a gop in the list\n    // of gopsToAlignWith starting from the END of the list\n\n    this.alignGopsAtEnd_ = function (gops) {\n      var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;\n      alignIndex = gopsToAlignWith.length - 1;\n      gopIndex = gops.length - 1;\n      alignEndIndex = null;\n      matchFound = false;\n      while (alignIndex >= 0 && gopIndex >= 0) {\n        align = gopsToAlignWith[alignIndex];\n        gop = gops[gopIndex];\n        if (align.pts === gop.pts) {\n          matchFound = true;\n          break;\n        }\n        if (align.pts > gop.pts) {\n          alignIndex--;\n          continue;\n        }\n        if (alignIndex === gopsToAlignWith.length - 1) {\n          // gop.pts is greater than the last alignment candidate. If no match is found\n          // by the end of this loop, we still want to append gops that come after this\n          // point\n          alignEndIndex = gopIndex;\n        }\n        gopIndex--;\n      }\n      if (!matchFound && alignEndIndex === null) {\n        return null;\n      }\n      var trimIndex;\n      if (matchFound) {\n        trimIndex = gopIndex;\n      } else {\n        trimIndex = alignEndIndex;\n      }\n      if (trimIndex === 0) {\n        return gops;\n      }\n      var alignedGops = gops.slice(trimIndex);\n      var metadata = alignedGops.reduce(function (total, gop) {\n        total.byteLength += gop.byteLength;\n        total.duration += gop.duration;\n        total.nalCount += gop.nalCount;\n        return total;\n      }, {\n        byteLength: 0,\n        duration: 0,\n        nalCount: 0\n      });\n      alignedGops.byteLength = metadata.byteLength;\n      alignedGops.duration = metadata.duration;\n      alignedGops.nalCount = metadata.nalCount;\n      alignedGops.pts = alignedGops[0].pts;\n      alignedGops.dts = alignedGops[0].dts;\n      return alignedGops;\n    };\n    this.alignGopsWith = function (newGopsToAlignWith) {\n      gopsToAlignWith = newGopsToAlignWith;\n    };\n  };\n  VideoSegmentStream.prototype = new Stream();\n  /**\n   * A Stream that can combine multiple streams (ie. audio & video)\n   * into a single output segment for MSE. Also supports audio-only\n   * and video-only streams.\n   * @param options {object} transmuxer options object\n   * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps\n   *        in the source; false to adjust the first segment to start at media timeline start.\n   */\n\n  CoalesceStream = function (options, metadataStream) {\n    // Number of Tracks per output segment\n    // If greater than 1, we combine multiple\n    // tracks into a single segment\n    this.numberOfTracks = 0;\n    this.metadataStream = metadataStream;\n    options = options || {};\n    if (typeof options.remux !== 'undefined') {\n      this.remuxTracks = !!options.remux;\n    } else {\n      this.remuxTracks = true;\n    }\n    if (typeof options.keepOriginalTimestamps === 'boolean') {\n      this.keepOriginalTimestamps = options.keepOriginalTimestamps;\n    } else {\n      this.keepOriginalTimestamps = false;\n    }\n    this.pendingTracks = [];\n    this.videoTrack = null;\n    this.pendingBoxes = [];\n    this.pendingCaptions = [];\n    this.pendingMetadata = [];\n    this.pendingBytes = 0;\n    this.emittedTracks = 0;\n    CoalesceStream.prototype.init.call(this); // Take output from multiple\n\n    this.push = function (output) {\n      // buffer incoming captions until the associated video segment\n      // finishes\n      if (output.content || output.text) {\n        return this.pendingCaptions.push(output);\n      } // buffer incoming id3 tags until the final flush\n\n      if (output.frames) {\n        return this.pendingMetadata.push(output);\n      } // Add this track to the list of pending tracks and store\n      // important information required for the construction of\n      // the final segment\n\n      this.pendingTracks.push(output.track);\n      this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?\n      // We unshift audio and push video because\n      // as of Chrome 75 when switching from\n      // one init segment to another if the video\n      // mdat does not appear after the audio mdat\n      // only audio will play for the duration of our transmux.\n\n      if (output.track.type === 'video') {\n        this.videoTrack = output.track;\n        this.pendingBoxes.push(output.boxes);\n      }\n      if (output.track.type === 'audio') {\n        this.audioTrack = output.track;\n        this.pendingBoxes.unshift(output.boxes);\n      }\n    };\n  };\n  CoalesceStream.prototype = new Stream();\n  CoalesceStream.prototype.flush = function (flushSource) {\n    var offset = 0,\n      event = {\n        captions: [],\n        captionStreams: {},\n        metadata: [],\n        info: {}\n      },\n      caption,\n      id3,\n      initSegment,\n      timelineStartPts = 0,\n      i;\n    if (this.pendingTracks.length < this.numberOfTracks) {\n      if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {\n        // Return because we haven't received a flush from a data-generating\n        // portion of the segment (meaning that we have only recieved meta-data\n        // or captions.)\n        return;\n      } else if (this.remuxTracks) {\n        // Return until we have enough tracks from the pipeline to remux (if we\n        // are remuxing audio and video into a single MP4)\n        return;\n      } else if (this.pendingTracks.length === 0) {\n        // In the case where we receive a flush without any data having been\n        // received we consider it an emitted track for the purposes of coalescing\n        // `done` events.\n        // We do this for the case where there is an audio and video track in the\n        // segment but no audio data. (seen in several playlists with alternate\n        // audio tracks and no audio present in the main TS segments.)\n        this.emittedTracks++;\n        if (this.emittedTracks >= this.numberOfTracks) {\n          this.trigger('done');\n          this.emittedTracks = 0;\n        }\n        return;\n      }\n    }\n    if (this.videoTrack) {\n      timelineStartPts = this.videoTrack.timelineStartInfo.pts;\n      VIDEO_PROPERTIES.forEach(function (prop) {\n        event.info[prop] = this.videoTrack[prop];\n      }, this);\n    } else if (this.audioTrack) {\n      timelineStartPts = this.audioTrack.timelineStartInfo.pts;\n      AUDIO_PROPERTIES.forEach(function (prop) {\n        event.info[prop] = this.audioTrack[prop];\n      }, this);\n    }\n    if (this.videoTrack || this.audioTrack) {\n      if (this.pendingTracks.length === 1) {\n        event.type = this.pendingTracks[0].type;\n      } else {\n        event.type = 'combined';\n      }\n      this.emittedTracks += this.pendingTracks.length;\n      initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment\n\n      event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov\n      // and track definitions\n\n      event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats\n\n      event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together\n\n      for (i = 0; i < this.pendingBoxes.length; i++) {\n        event.data.set(this.pendingBoxes[i], offset);\n        offset += this.pendingBoxes[i].byteLength;\n      } // Translate caption PTS times into second offsets to match the\n      // video timeline for the segment, and add track info\n\n      for (i = 0; i < this.pendingCaptions.length; i++) {\n        caption = this.pendingCaptions[i];\n        caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);\n        caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);\n        event.captionStreams[caption.stream] = true;\n        event.captions.push(caption);\n      } // Translate ID3 frame PTS times into second offsets to match the\n      // video timeline for the segment\n\n      for (i = 0; i < this.pendingMetadata.length; i++) {\n        id3 = this.pendingMetadata[i];\n        id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);\n        event.metadata.push(id3);\n      } // We add this to every single emitted segment even though we only need\n      // it for the first\n\n      event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state\n\n      this.pendingTracks.length = 0;\n      this.videoTrack = null;\n      this.pendingBoxes.length = 0;\n      this.pendingCaptions.length = 0;\n      this.pendingBytes = 0;\n      this.pendingMetadata.length = 0; // Emit the built segment\n      // We include captions and ID3 tags for backwards compatibility,\n      // ideally we should send only video and audio in the data event\n\n      this.trigger('data', event); // Emit each caption to the outside world\n      // Ideally, this would happen immediately on parsing captions,\n      // but we need to ensure that video data is sent back first\n      // so that caption timing can be adjusted to match video timing\n\n      for (i = 0; i < event.captions.length; i++) {\n        caption = event.captions[i];\n        this.trigger('caption', caption);\n      } // Emit each id3 tag to the outside world\n      // Ideally, this would happen immediately on parsing the tag,\n      // but we need to ensure that video data is sent back first\n      // so that ID3 frame timing can be adjusted to match video timing\n\n      for (i = 0; i < event.metadata.length; i++) {\n        id3 = event.metadata[i];\n        this.trigger('id3Frame', id3);\n      }\n    } // Only emit `done` if all tracks have been flushed and emitted\n\n    if (this.emittedTracks >= this.numberOfTracks) {\n      this.trigger('done');\n      this.emittedTracks = 0;\n    }\n  };\n  CoalesceStream.prototype.setRemux = function (val) {\n    this.remuxTracks = val;\n  };\n  /**\n   * A Stream that expects MP2T binary data as input and produces\n   * corresponding media segments, suitable for use with Media Source\n   * Extension (MSE) implementations that support the ISO BMFF byte\n   * stream format, like Chrome.\n   */\n\n  Transmuxer = function (options) {\n    var self = this,\n      hasFlushed = true,\n      videoTrack,\n      audioTrack;\n    Transmuxer.prototype.init.call(this);\n    options = options || {};\n    this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;\n    this.transmuxPipeline_ = {};\n    this.setupAacPipeline = function () {\n      var pipeline = {};\n      this.transmuxPipeline_ = pipeline;\n      pipeline.type = 'aac';\n      pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline\n\n      pipeline.aacStream = new AacStream();\n      pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');\n      pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');\n      pipeline.adtsStream = new AdtsStream();\n      pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);\n      pipeline.headOfPipeline = pipeline.aacStream;\n      pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);\n      pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);\n      pipeline.metadataStream.on('timestamp', function (frame) {\n        pipeline.aacStream.setTimestamp(frame.timeStamp);\n      });\n      pipeline.aacStream.on('data', function (data) {\n        if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {\n          return;\n        }\n        audioTrack = audioTrack || {\n          timelineStartInfo: {\n            baseMediaDecodeTime: self.baseMediaDecodeTime\n          },\n          codec: 'adts',\n          type: 'audio'\n        }; // hook up the audio segment stream to the first track with aac data\n\n        pipeline.coalesceStream.numberOfTracks++;\n        pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);\n        pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));\n        pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline\n\n        pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info\n\n        self.trigger('trackinfo', {\n          hasAudio: !!audioTrack,\n          hasVideo: !!videoTrack\n        });\n      }); // Re-emit any data coming from the coalesce stream to the outside world\n\n      pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline\n\n      pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));\n      addPipelineLogRetriggers(this, pipeline);\n    };\n    this.setupTsPipeline = function () {\n      var pipeline = {};\n      this.transmuxPipeline_ = pipeline;\n      pipeline.type = 'ts';\n      pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline\n\n      pipeline.packetStream = new m2ts.TransportPacketStream();\n      pipeline.parseStream = new m2ts.TransportParseStream();\n      pipeline.elementaryStream = new m2ts.ElementaryStream();\n      pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();\n      pipeline.adtsStream = new AdtsStream();\n      pipeline.h264Stream = new H264Stream();\n      pipeline.captionStream = new m2ts.CaptionStream(options);\n      pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);\n      pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams\n\n      pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!\n      // demux the streams\n\n      pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);\n      pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);\n      pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream\n\n      pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);\n      pipeline.elementaryStream.on('data', function (data) {\n        var i;\n        if (data.type === 'metadata') {\n          i = data.tracks.length; // scan the tracks listed in the metadata\n\n          while (i--) {\n            if (!videoTrack && data.tracks[i].type === 'video') {\n              videoTrack = data.tracks[i];\n              videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;\n            } else if (!audioTrack && data.tracks[i].type === 'audio') {\n              audioTrack = data.tracks[i];\n              audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;\n            }\n          } // hook up the video segment stream to the first track with h264 data\n\n          if (videoTrack && !pipeline.videoSegmentStream) {\n            pipeline.coalesceStream.numberOfTracks++;\n            pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);\n            pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));\n            pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {\n              // When video emits timelineStartInfo data after a flush, we forward that\n              // info to the AudioSegmentStream, if it exists, because video timeline\n              // data takes precedence.  Do not do this if keepOriginalTimestamps is set,\n              // because this is a particularly subtle form of timestamp alteration.\n              if (audioTrack && !options.keepOriginalTimestamps) {\n                audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the\n                // very earliest DTS we have seen in video because Chrome will\n                // interpret any video track with a baseMediaDecodeTime that is\n                // non-zero as a gap.\n\n                pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);\n              }\n            });\n            pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));\n            pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));\n            pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {\n              if (audioTrack) {\n                pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);\n              }\n            });\n            pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline\n\n            pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);\n          }\n          if (audioTrack && !pipeline.audioSegmentStream) {\n            // hook up the audio segment stream to the first track with aac data\n            pipeline.coalesceStream.numberOfTracks++;\n            pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);\n            pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));\n            pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));\n            pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline\n\n            pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);\n          } // emit pmt info\n\n          self.trigger('trackinfo', {\n            hasAudio: !!audioTrack,\n            hasVideo: !!videoTrack\n          });\n        }\n      }); // Re-emit any data coming from the coalesce stream to the outside world\n\n      pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));\n      pipeline.coalesceStream.on('id3Frame', function (id3Frame) {\n        id3Frame.dispatchType = pipeline.metadataStream.dispatchType;\n        self.trigger('id3Frame', id3Frame);\n      });\n      pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline\n\n      pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));\n      addPipelineLogRetriggers(this, pipeline);\n    }; // hook up the segment streams once track metadata is delivered\n\n    this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {\n      var pipeline = this.transmuxPipeline_;\n      if (!options.keepOriginalTimestamps) {\n        this.baseMediaDecodeTime = baseMediaDecodeTime;\n      }\n      if (audioTrack) {\n        audioTrack.timelineStartInfo.dts = undefined;\n        audioTrack.timelineStartInfo.pts = undefined;\n        trackDecodeInfo.clearDtsInfo(audioTrack);\n        if (pipeline.audioTimestampRolloverStream) {\n          pipeline.audioTimestampRolloverStream.discontinuity();\n        }\n      }\n      if (videoTrack) {\n        if (pipeline.videoSegmentStream) {\n          pipeline.videoSegmentStream.gopCache_ = [];\n        }\n        videoTrack.timelineStartInfo.dts = undefined;\n        videoTrack.timelineStartInfo.pts = undefined;\n        trackDecodeInfo.clearDtsInfo(videoTrack);\n        pipeline.captionStream.reset();\n      }\n      if (pipeline.timestampRolloverStream) {\n        pipeline.timestampRolloverStream.discontinuity();\n      }\n    };\n    this.setAudioAppendStart = function (timestamp) {\n      if (audioTrack) {\n        this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);\n      }\n    };\n    this.setRemux = function (val) {\n      var pipeline = this.transmuxPipeline_;\n      options.remux = val;\n      if (pipeline && pipeline.coalesceStream) {\n        pipeline.coalesceStream.setRemux(val);\n      }\n    };\n    this.alignGopsWith = function (gopsToAlignWith) {\n      if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {\n        this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);\n      }\n    };\n    this.getLogTrigger_ = function (key) {\n      var self = this;\n      return function (event) {\n        event.stream = key;\n        self.trigger('log', event);\n      };\n    }; // feed incoming data to the front of the parsing pipeline\n\n    this.push = function (data) {\n      if (hasFlushed) {\n        var isAac = isLikelyAacData(data);\n        if (isAac && this.transmuxPipeline_.type !== 'aac') {\n          this.setupAacPipeline();\n        } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {\n          this.setupTsPipeline();\n        }\n        hasFlushed = false;\n      }\n      this.transmuxPipeline_.headOfPipeline.push(data);\n    }; // flush any buffered data\n\n    this.flush = function () {\n      hasFlushed = true; // Start at the top of the pipeline and flush all pending work\n\n      this.transmuxPipeline_.headOfPipeline.flush();\n    };\n    this.endTimeline = function () {\n      this.transmuxPipeline_.headOfPipeline.endTimeline();\n    };\n    this.reset = function () {\n      if (this.transmuxPipeline_.headOfPipeline) {\n        this.transmuxPipeline_.headOfPipeline.reset();\n      }\n    }; // Caption data has to be reset when seeking outside buffered range\n\n    this.resetCaptions = function () {\n      if (this.transmuxPipeline_.captionStream) {\n        this.transmuxPipeline_.captionStream.reset();\n      }\n    };\n  };\n  Transmuxer.prototype = new Stream();\n  var transmuxer = {\n    Transmuxer: Transmuxer,\n    VideoSegmentStream: VideoSegmentStream,\n    AudioSegmentStream: AudioSegmentStream,\n    AUDIO_PROPERTIES: AUDIO_PROPERTIES,\n    VIDEO_PROPERTIES: VIDEO_PROPERTIES,\n    // exported for testing\n    generateSegmentTimingInfo: generateSegmentTimingInfo\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   */\n\n  var toUnsigned$3 = function (value) {\n    return value >>> 0;\n  };\n  var toHexString$1 = function (value) {\n    return ('00' + value.toString(16)).slice(-2);\n  };\n  var bin = {\n    toUnsigned: toUnsigned$3,\n    toHexString: toHexString$1\n  };\n  var parseType$4 = function (buffer) {\n    var result = '';\n    result += String.fromCharCode(buffer[0]);\n    result += String.fromCharCode(buffer[1]);\n    result += String.fromCharCode(buffer[2]);\n    result += String.fromCharCode(buffer[3]);\n    return result;\n  };\n  var parseType_1 = parseType$4;\n  var toUnsigned$2 = bin.toUnsigned;\n  var parseType$3 = parseType_1;\n  var findBox$5 = function (data, path) {\n    var results = [],\n      i,\n      size,\n      type,\n      end,\n      subresults;\n    if (!path.length) {\n      // short-circuit the search for empty paths\n      return null;\n    }\n    for (i = 0; i < data.byteLength;) {\n      size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);\n      type = parseType$3(data.subarray(i + 4, i + 8));\n      end = size > 1 ? i + size : data.byteLength;\n      if (type === path[0]) {\n        if (path.length === 1) {\n          // this is the end of the path and we've found the box we were\n          // looking for\n          results.push(data.subarray(i + 8, end));\n        } else {\n          // recursively search for the next box along the path\n          subresults = findBox$5(data.subarray(i + 8, end), path.slice(1));\n          if (subresults.length) {\n            results = results.concat(subresults);\n          }\n        }\n      }\n      i = end;\n    } // we've finished searching all of data\n\n    return results;\n  };\n  var findBox_1 = findBox$5;\n  var toUnsigned$1 = bin.toUnsigned;\n  var getUint64$4 = numbers.getUint64;\n  var tfdt = function (data) {\n    var result = {\n      version: data[0],\n      flags: new Uint8Array(data.subarray(1, 4))\n    };\n    if (result.version === 1) {\n      result.baseMediaDecodeTime = getUint64$4(data.subarray(4));\n    } else {\n      result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);\n    }\n    return result;\n  };\n  var parseTfdt$3 = tfdt;\n  var tfhd = function (data) {\n    var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n      result = {\n        version: data[0],\n        flags: new Uint8Array(data.subarray(1, 4)),\n        trackId: view.getUint32(4)\n      },\n      baseDataOffsetPresent = result.flags[2] & 0x01,\n      sampleDescriptionIndexPresent = result.flags[2] & 0x02,\n      defaultSampleDurationPresent = result.flags[2] & 0x08,\n      defaultSampleSizePresent = result.flags[2] & 0x10,\n      defaultSampleFlagsPresent = result.flags[2] & 0x20,\n      durationIsEmpty = result.flags[0] & 0x010000,\n      defaultBaseIsMoof = result.flags[0] & 0x020000,\n      i;\n    i = 8;\n    if (baseDataOffsetPresent) {\n      i += 4; // truncate top 4 bytes\n      // FIXME: should we read the full 64 bits?\n\n      result.baseDataOffset = view.getUint32(12);\n      i += 4;\n    }\n    if (sampleDescriptionIndexPresent) {\n      result.sampleDescriptionIndex = view.getUint32(i);\n      i += 4;\n    }\n    if (defaultSampleDurationPresent) {\n      result.defaultSampleDuration = view.getUint32(i);\n      i += 4;\n    }\n    if (defaultSampleSizePresent) {\n      result.defaultSampleSize = view.getUint32(i);\n      i += 4;\n    }\n    if (defaultSampleFlagsPresent) {\n      result.defaultSampleFlags = view.getUint32(i);\n    }\n    if (durationIsEmpty) {\n      result.durationIsEmpty = true;\n    }\n    if (!baseDataOffsetPresent && defaultBaseIsMoof) {\n      result.baseDataOffsetIsMoof = true;\n    }\n    return result;\n  };\n  var parseTfhd$2 = tfhd;\n  var getUint64$3 = numbers.getUint64;\n  var parseSidx = function (data) {\n    var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n      result = {\n        version: data[0],\n        flags: new Uint8Array(data.subarray(1, 4)),\n        references: [],\n        referenceId: view.getUint32(4),\n        timescale: view.getUint32(8)\n      },\n      i = 12;\n    if (result.version === 0) {\n      result.earliestPresentationTime = view.getUint32(i);\n      result.firstOffset = view.getUint32(i + 4);\n      i += 8;\n    } else {\n      // read 64 bits\n      result.earliestPresentationTime = getUint64$3(data.subarray(i));\n      result.firstOffset = getUint64$3(data.subarray(i + 8));\n      i += 16;\n    }\n    i += 2; // reserved\n\n    var referenceCount = view.getUint16(i);\n    i += 2; // start of references\n\n    for (; referenceCount > 0; i += 12, referenceCount--) {\n      result.references.push({\n        referenceType: (data[i] & 0x80) >>> 7,\n        referencedSize: view.getUint32(i) & 0x7FFFFFFF,\n        subsegmentDuration: view.getUint32(i + 4),\n        startsWithSap: !!(data[i + 8] & 0x80),\n        sapType: (data[i + 8] & 0x70) >>> 4,\n        sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF\n      });\n    }\n    return result;\n  };\n  var parseSidx_1 = parseSidx;\n  var parseSampleFlags$1 = function (flags) {\n    return {\n      isLeading: (flags[0] & 0x0c) >>> 2,\n      dependsOn: flags[0] & 0x03,\n      isDependedOn: (flags[1] & 0xc0) >>> 6,\n      hasRedundancy: (flags[1] & 0x30) >>> 4,\n      paddingValue: (flags[1] & 0x0e) >>> 1,\n      isNonSyncSample: flags[1] & 0x01,\n      degradationPriority: flags[2] << 8 | flags[3]\n    };\n  };\n  var parseSampleFlags_1 = parseSampleFlags$1;\n  var parseSampleFlags = parseSampleFlags_1;\n  var trun = function (data) {\n    var result = {\n        version: data[0],\n        flags: new Uint8Array(data.subarray(1, 4)),\n        samples: []\n      },\n      view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n      // Flag interpretation\n      dataOffsetPresent = result.flags[2] & 0x01,\n      // compare with 2nd byte of 0x1\n      firstSampleFlagsPresent = result.flags[2] & 0x04,\n      // compare with 2nd byte of 0x4\n      sampleDurationPresent = result.flags[1] & 0x01,\n      // compare with 2nd byte of 0x100\n      sampleSizePresent = result.flags[1] & 0x02,\n      // compare with 2nd byte of 0x200\n      sampleFlagsPresent = result.flags[1] & 0x04,\n      // compare with 2nd byte of 0x400\n      sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,\n      // compare with 2nd byte of 0x800\n      sampleCount = view.getUint32(4),\n      offset = 8,\n      sample;\n    if (dataOffsetPresent) {\n      // 32 bit signed integer\n      result.dataOffset = view.getInt32(offset);\n      offset += 4;\n    } // Overrides the flags for the first sample only. The order of\n    // optional values will be: duration, size, compositionTimeOffset\n\n    if (firstSampleFlagsPresent && sampleCount) {\n      sample = {\n        flags: parseSampleFlags(data.subarray(offset, offset + 4))\n      };\n      offset += 4;\n      if (sampleDurationPresent) {\n        sample.duration = view.getUint32(offset);\n        offset += 4;\n      }\n      if (sampleSizePresent) {\n        sample.size = view.getUint32(offset);\n        offset += 4;\n      }\n      if (sampleCompositionTimeOffsetPresent) {\n        if (result.version === 1) {\n          sample.compositionTimeOffset = view.getInt32(offset);\n        } else {\n          sample.compositionTimeOffset = view.getUint32(offset);\n        }\n        offset += 4;\n      }\n      result.samples.push(sample);\n      sampleCount--;\n    }\n    while (sampleCount--) {\n      sample = {};\n      if (sampleDurationPresent) {\n        sample.duration = view.getUint32(offset);\n        offset += 4;\n      }\n      if (sampleSizePresent) {\n        sample.size = view.getUint32(offset);\n        offset += 4;\n      }\n      if (sampleFlagsPresent) {\n        sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));\n        offset += 4;\n      }\n      if (sampleCompositionTimeOffsetPresent) {\n        if (result.version === 1) {\n          sample.compositionTimeOffset = view.getInt32(offset);\n        } else {\n          sample.compositionTimeOffset = view.getUint32(offset);\n        }\n        offset += 4;\n      }\n      result.samples.push(sample);\n    }\n    return result;\n  };\n  var parseTrun$2 = trun;\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Parse the internal MP4 structure into an equivalent javascript\n   * object.\n   */\n\n  var numberHelpers = numbers;\n  var getUint64$2 = numberHelpers.getUint64;\n  var inspectMp4,\n    textifyMp4,\n    parseMp4Date = function (seconds) {\n      return new Date(seconds * 1000 - 2082844800000);\n    },\n    parseType$2 = parseType_1,\n    findBox$4 = findBox_1,\n    nalParse = function (avcStream) {\n      var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),\n        result = [],\n        i,\n        length;\n      for (i = 0; i + 4 < avcStream.length; i += length) {\n        length = avcView.getUint32(i);\n        i += 4; // bail if this doesn't appear to be an H264 stream\n\n        if (length <= 0) {\n          result.push('<span style=\\'color:red;\\'>MALFORMED DATA</span>');\n          continue;\n        }\n        switch (avcStream[i] & 0x1F) {\n          case 0x01:\n            result.push('slice_layer_without_partitioning_rbsp');\n            break;\n          case 0x05:\n            result.push('slice_layer_without_partitioning_rbsp_idr');\n            break;\n          case 0x06:\n            result.push('sei_rbsp');\n            break;\n          case 0x07:\n            result.push('seq_parameter_set_rbsp');\n            break;\n          case 0x08:\n            result.push('pic_parameter_set_rbsp');\n            break;\n          case 0x09:\n            result.push('access_unit_delimiter_rbsp');\n            break;\n          default:\n            result.push('UNKNOWN NAL - ' + avcStream[i] & 0x1F);\n            break;\n        }\n      }\n      return result;\n    },\n    // registry of handlers for individual mp4 box types\n    parse = {\n      // codingname, not a first-class box type. stsd entries share the\n      // same format as real boxes so the parsing infrastructure can be\n      // shared\n      avc1: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n        return {\n          dataReferenceIndex: view.getUint16(6),\n          width: view.getUint16(24),\n          height: view.getUint16(26),\n          horizresolution: view.getUint16(28) + view.getUint16(30) / 16,\n          vertresolution: view.getUint16(32) + view.getUint16(34) / 16,\n          frameCount: view.getUint16(40),\n          depth: view.getUint16(74),\n          config: inspectMp4(data.subarray(78, data.byteLength))\n        };\n      },\n      avcC: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            configurationVersion: data[0],\n            avcProfileIndication: data[1],\n            profileCompatibility: data[2],\n            avcLevelIndication: data[3],\n            lengthSizeMinusOne: data[4] & 0x03,\n            sps: [],\n            pps: []\n          },\n          numOfSequenceParameterSets = data[5] & 0x1f,\n          numOfPictureParameterSets,\n          nalSize,\n          offset,\n          i; // iterate past any SPSs\n\n        offset = 6;\n        for (i = 0; i < numOfSequenceParameterSets; i++) {\n          nalSize = view.getUint16(offset);\n          offset += 2;\n          result.sps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));\n          offset += nalSize;\n        } // iterate past any PPSs\n\n        numOfPictureParameterSets = data[offset];\n        offset++;\n        for (i = 0; i < numOfPictureParameterSets; i++) {\n          nalSize = view.getUint16(offset);\n          offset += 2;\n          result.pps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));\n          offset += nalSize;\n        }\n        return result;\n      },\n      btrt: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n        return {\n          bufferSizeDB: view.getUint32(0),\n          maxBitrate: view.getUint32(4),\n          avgBitrate: view.getUint32(8)\n        };\n      },\n      edts: function edts(data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      elst: function elst(data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            version: view.getUint8(0),\n            flags: new Uint8Array(data.subarray(1, 4)),\n            edits: []\n          },\n          entryCount = view.getUint32(4),\n          i;\n        for (i = 8; entryCount; entryCount--) {\n          if (result.version === 0) {\n            result.edits.push({\n              segmentDuration: view.getUint32(i),\n              mediaTime: view.getInt32(i + 4),\n              mediaRate: view.getUint16(i + 8) + view.getUint16(i + 10) / (256 * 256)\n            });\n            i += 12;\n          } else {\n            result.edits.push({\n              segmentDuration: getUint64$2(data.subarray(i)),\n              mediaTime: getUint64$2(data.subarray(i + 8)),\n              mediaRate: view.getUint16(i + 16) + view.getUint16(i + 18) / (256 * 256)\n            });\n            i += 20;\n          }\n        }\n        return result;\n      },\n      esds: function (data) {\n        return {\n          version: data[0],\n          flags: new Uint8Array(data.subarray(1, 4)),\n          esId: data[6] << 8 | data[7],\n          streamPriority: data[8] & 0x1f,\n          decoderConfig: {\n            objectProfileIndication: data[11],\n            streamType: data[12] >>> 2 & 0x3f,\n            bufferSize: data[13] << 16 | data[14] << 8 | data[15],\n            maxBitrate: data[16] << 24 | data[17] << 16 | data[18] << 8 | data[19],\n            avgBitrate: data[20] << 24 | data[21] << 16 | data[22] << 8 | data[23],\n            decoderConfigDescriptor: {\n              tag: data[24],\n              length: data[25],\n              audioObjectType: data[26] >>> 3 & 0x1f,\n              samplingFrequencyIndex: (data[26] & 0x07) << 1 | data[27] >>> 7 & 0x01,\n              channelConfiguration: data[27] >>> 3 & 0x0f\n            }\n          }\n        };\n      },\n      ftyp: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            majorBrand: parseType$2(data.subarray(0, 4)),\n            minorVersion: view.getUint32(4),\n            compatibleBrands: []\n          },\n          i = 8;\n        while (i < data.byteLength) {\n          result.compatibleBrands.push(parseType$2(data.subarray(i, i + 4)));\n          i += 4;\n        }\n        return result;\n      },\n      dinf: function (data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      dref: function (data) {\n        return {\n          version: data[0],\n          flags: new Uint8Array(data.subarray(1, 4)),\n          dataReferences: inspectMp4(data.subarray(8))\n        };\n      },\n      hdlr: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            version: view.getUint8(0),\n            flags: new Uint8Array(data.subarray(1, 4)),\n            handlerType: parseType$2(data.subarray(8, 12)),\n            name: ''\n          },\n          i = 8; // parse out the name field\n\n        for (i = 24; i < data.byteLength; i++) {\n          if (data[i] === 0x00) {\n            // the name field is null-terminated\n            i++;\n            break;\n          }\n          result.name += String.fromCharCode(data[i]);\n        } // decode UTF-8 to javascript's internal representation\n        // see http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html\n\n        result.name = decodeURIComponent(escape(result.name));\n        return result;\n      },\n      mdat: function (data) {\n        return {\n          byteLength: data.byteLength,\n          nals: nalParse(data)\n        };\n      },\n      mdhd: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          i = 4,\n          language,\n          result = {\n            version: view.getUint8(0),\n            flags: new Uint8Array(data.subarray(1, 4)),\n            language: ''\n          };\n        if (result.version === 1) {\n          i += 4;\n          result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes\n\n          i += 8;\n          result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes\n\n          i += 4;\n          result.timescale = view.getUint32(i);\n          i += 8;\n          result.duration = view.getUint32(i); // truncating top 4 bytes\n        } else {\n          result.creationTime = parseMp4Date(view.getUint32(i));\n          i += 4;\n          result.modificationTime = parseMp4Date(view.getUint32(i));\n          i += 4;\n          result.timescale = view.getUint32(i);\n          i += 4;\n          result.duration = view.getUint32(i);\n        }\n        i += 4; // language is stored as an ISO-639-2/T code in an array of three 5-bit fields\n        // each field is the packed difference between its ASCII value and 0x60\n\n        language = view.getUint16(i);\n        result.language += String.fromCharCode((language >> 10) + 0x60);\n        result.language += String.fromCharCode(((language & 0x03e0) >> 5) + 0x60);\n        result.language += String.fromCharCode((language & 0x1f) + 0x60);\n        return result;\n      },\n      mdia: function (data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      mfhd: function (data) {\n        return {\n          version: data[0],\n          flags: new Uint8Array(data.subarray(1, 4)),\n          sequenceNumber: data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]\n        };\n      },\n      minf: function (data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      // codingname, not a first-class box type. stsd entries share the\n      // same format as real boxes so the parsing infrastructure can be\n      // shared\n      mp4a: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            // 6 bytes reserved\n            dataReferenceIndex: view.getUint16(6),\n            // 4 + 4 bytes reserved\n            channelcount: view.getUint16(16),\n            samplesize: view.getUint16(18),\n            // 2 bytes pre_defined\n            // 2 bytes reserved\n            samplerate: view.getUint16(24) + view.getUint16(26) / 65536\n          }; // if there are more bytes to process, assume this is an ISO/IEC\n        // 14496-14 MP4AudioSampleEntry and parse the ESDBox\n\n        if (data.byteLength > 28) {\n          result.streamDescriptor = inspectMp4(data.subarray(28))[0];\n        }\n        return result;\n      },\n      moof: function (data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      moov: function (data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      mvex: function (data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      mvhd: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          i = 4,\n          result = {\n            version: view.getUint8(0),\n            flags: new Uint8Array(data.subarray(1, 4))\n          };\n        if (result.version === 1) {\n          i += 4;\n          result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes\n\n          i += 8;\n          result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes\n\n          i += 4;\n          result.timescale = view.getUint32(i);\n          i += 8;\n          result.duration = view.getUint32(i); // truncating top 4 bytes\n        } else {\n          result.creationTime = parseMp4Date(view.getUint32(i));\n          i += 4;\n          result.modificationTime = parseMp4Date(view.getUint32(i));\n          i += 4;\n          result.timescale = view.getUint32(i);\n          i += 4;\n          result.duration = view.getUint32(i);\n        }\n        i += 4; // convert fixed-point, base 16 back to a number\n\n        result.rate = view.getUint16(i) + view.getUint16(i + 2) / 16;\n        i += 4;\n        result.volume = view.getUint8(i) + view.getUint8(i + 1) / 8;\n        i += 2;\n        i += 2;\n        i += 2 * 4;\n        result.matrix = new Uint32Array(data.subarray(i, i + 9 * 4));\n        i += 9 * 4;\n        i += 6 * 4;\n        result.nextTrackId = view.getUint32(i);\n        return result;\n      },\n      pdin: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n        return {\n          version: view.getUint8(0),\n          flags: new Uint8Array(data.subarray(1, 4)),\n          rate: view.getUint32(4),\n          initialDelay: view.getUint32(8)\n        };\n      },\n      sdtp: function (data) {\n        var result = {\n            version: data[0],\n            flags: new Uint8Array(data.subarray(1, 4)),\n            samples: []\n          },\n          i;\n        for (i = 4; i < data.byteLength; i++) {\n          result.samples.push({\n            dependsOn: (data[i] & 0x30) >> 4,\n            isDependedOn: (data[i] & 0x0c) >> 2,\n            hasRedundancy: data[i] & 0x03\n          });\n        }\n        return result;\n      },\n      sidx: parseSidx_1,\n      smhd: function (data) {\n        return {\n          version: data[0],\n          flags: new Uint8Array(data.subarray(1, 4)),\n          balance: data[4] + data[5] / 256\n        };\n      },\n      stbl: function (data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      ctts: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            version: view.getUint8(0),\n            flags: new Uint8Array(data.subarray(1, 4)),\n            compositionOffsets: []\n          },\n          entryCount = view.getUint32(4),\n          i;\n        for (i = 8; entryCount; i += 8, entryCount--) {\n          result.compositionOffsets.push({\n            sampleCount: view.getUint32(i),\n            sampleOffset: view[result.version === 0 ? 'getUint32' : 'getInt32'](i + 4)\n          });\n        }\n        return result;\n      },\n      stss: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            version: view.getUint8(0),\n            flags: new Uint8Array(data.subarray(1, 4)),\n            syncSamples: []\n          },\n          entryCount = view.getUint32(4),\n          i;\n        for (i = 8; entryCount; i += 4, entryCount--) {\n          result.syncSamples.push(view.getUint32(i));\n        }\n        return result;\n      },\n      stco: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            version: data[0],\n            flags: new Uint8Array(data.subarray(1, 4)),\n            chunkOffsets: []\n          },\n          entryCount = view.getUint32(4),\n          i;\n        for (i = 8; entryCount; i += 4, entryCount--) {\n          result.chunkOffsets.push(view.getUint32(i));\n        }\n        return result;\n      },\n      stsc: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          entryCount = view.getUint32(4),\n          result = {\n            version: data[0],\n            flags: new Uint8Array(data.subarray(1, 4)),\n            sampleToChunks: []\n          },\n          i;\n        for (i = 8; entryCount; i += 12, entryCount--) {\n          result.sampleToChunks.push({\n            firstChunk: view.getUint32(i),\n            samplesPerChunk: view.getUint32(i + 4),\n            sampleDescriptionIndex: view.getUint32(i + 8)\n          });\n        }\n        return result;\n      },\n      stsd: function (data) {\n        return {\n          version: data[0],\n          flags: new Uint8Array(data.subarray(1, 4)),\n          sampleDescriptions: inspectMp4(data.subarray(8))\n        };\n      },\n      stsz: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            version: data[0],\n            flags: new Uint8Array(data.subarray(1, 4)),\n            sampleSize: view.getUint32(4),\n            entries: []\n          },\n          i;\n        for (i = 12; i < data.byteLength; i += 4) {\n          result.entries.push(view.getUint32(i));\n        }\n        return result;\n      },\n      stts: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          result = {\n            version: data[0],\n            flags: new Uint8Array(data.subarray(1, 4)),\n            timeToSamples: []\n          },\n          entryCount = view.getUint32(4),\n          i;\n        for (i = 8; entryCount; i += 8, entryCount--) {\n          result.timeToSamples.push({\n            sampleCount: view.getUint32(i),\n            sampleDelta: view.getUint32(i + 4)\n          });\n        }\n        return result;\n      },\n      styp: function (data) {\n        return parse.ftyp(data);\n      },\n      tfdt: parseTfdt$3,\n      tfhd: parseTfhd$2,\n      tkhd: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength),\n          i = 4,\n          result = {\n            version: view.getUint8(0),\n            flags: new Uint8Array(data.subarray(1, 4))\n          };\n        if (result.version === 1) {\n          i += 4;\n          result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes\n\n          i += 8;\n          result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes\n\n          i += 4;\n          result.trackId = view.getUint32(i);\n          i += 4;\n          i += 8;\n          result.duration = view.getUint32(i); // truncating top 4 bytes\n        } else {\n          result.creationTime = parseMp4Date(view.getUint32(i));\n          i += 4;\n          result.modificationTime = parseMp4Date(view.getUint32(i));\n          i += 4;\n          result.trackId = view.getUint32(i);\n          i += 4;\n          i += 4;\n          result.duration = view.getUint32(i);\n        }\n        i += 4;\n        i += 2 * 4;\n        result.layer = view.getUint16(i);\n        i += 2;\n        result.alternateGroup = view.getUint16(i);\n        i += 2; // convert fixed-point, base 16 back to a number\n\n        result.volume = view.getUint8(i) + view.getUint8(i + 1) / 8;\n        i += 2;\n        i += 2;\n        result.matrix = new Uint32Array(data.subarray(i, i + 9 * 4));\n        i += 9 * 4;\n        result.width = view.getUint16(i) + view.getUint16(i + 2) / 65536;\n        i += 4;\n        result.height = view.getUint16(i) + view.getUint16(i + 2) / 65536;\n        return result;\n      },\n      traf: function (data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      trak: function (data) {\n        return {\n          boxes: inspectMp4(data)\n        };\n      },\n      trex: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n        return {\n          version: data[0],\n          flags: new Uint8Array(data.subarray(1, 4)),\n          trackId: view.getUint32(4),\n          defaultSampleDescriptionIndex: view.getUint32(8),\n          defaultSampleDuration: view.getUint32(12),\n          defaultSampleSize: view.getUint32(16),\n          sampleDependsOn: data[20] & 0x03,\n          sampleIsDependedOn: (data[21] & 0xc0) >> 6,\n          sampleHasRedundancy: (data[21] & 0x30) >> 4,\n          samplePaddingValue: (data[21] & 0x0e) >> 1,\n          sampleIsDifferenceSample: !!(data[21] & 0x01),\n          sampleDegradationPriority: view.getUint16(22)\n        };\n      },\n      trun: parseTrun$2,\n      'url ': function (data) {\n        return {\n          version: data[0],\n          flags: new Uint8Array(data.subarray(1, 4))\n        };\n      },\n      vmhd: function (data) {\n        var view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n        return {\n          version: data[0],\n          flags: new Uint8Array(data.subarray(1, 4)),\n          graphicsmode: view.getUint16(4),\n          opcolor: new Uint16Array([view.getUint16(6), view.getUint16(8), view.getUint16(10)])\n        };\n      }\n    };\n  /**\n   * Return a javascript array of box objects parsed from an ISO base\n   * media file.\n   * @param data {Uint8Array} the binary data of the media to be inspected\n   * @return {array} a javascript array of potentially nested box objects\n   */\n\n  inspectMp4 = function (data) {\n    var i = 0,\n      result = [],\n      view,\n      size,\n      type,\n      end,\n      box; // Convert data from Uint8Array to ArrayBuffer, to follow Dataview API\n\n    var ab = new ArrayBuffer(data.length);\n    var v = new Uint8Array(ab);\n    for (var z = 0; z < data.length; ++z) {\n      v[z] = data[z];\n    }\n    view = new DataView(ab);\n    while (i < data.byteLength) {\n      // parse box data\n      size = view.getUint32(i);\n      type = parseType$2(data.subarray(i + 4, i + 8));\n      end = size > 1 ? i + size : data.byteLength; // parse type-specific data\n\n      box = (parse[type] || function (data) {\n        return {\n          data: data\n        };\n      })(data.subarray(i + 8, end));\n      box.size = size;\n      box.type = type; // store this box and move to the next\n\n      result.push(box);\n      i = end;\n    }\n    return result;\n  };\n  /**\n   * Returns a textual representation of the javascript represtentation\n   * of an MP4 file. You can use it as an alternative to\n   * JSON.stringify() to compare inspected MP4s.\n   * @param inspectedMp4 {array} the parsed array of boxes in an MP4\n   * file\n   * @param depth {number} (optional) the number of ancestor boxes of\n   * the elements of inspectedMp4. Assumed to be zero if unspecified.\n   * @return {string} a text representation of the parsed MP4\n   */\n\n  textifyMp4 = function (inspectedMp4, depth) {\n    var indent;\n    depth = depth || 0;\n    indent = new Array(depth * 2 + 1).join(' '); // iterate over all the boxes\n\n    return inspectedMp4.map(function (box, index) {\n      // list the box type first at the current indentation level\n      return indent + box.type + '\\n' +\n      // the type is already included and handle child boxes separately\n      Object.keys(box).filter(function (key) {\n        return key !== 'type' && key !== 'boxes'; // output all the box properties\n      }).map(function (key) {\n        var prefix = indent + '  ' + key + ': ',\n          value = box[key]; // print out raw bytes as hexademical\n\n        if (value instanceof Uint8Array || value instanceof Uint32Array) {\n          var bytes = Array.prototype.slice.call(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)).map(function (byte) {\n            return ' ' + ('00' + byte.toString(16)).slice(-2);\n          }).join('').match(/.{1,24}/g);\n          if (!bytes) {\n            return prefix + '<>';\n          }\n          if (bytes.length === 1) {\n            return prefix + '<' + bytes.join('').slice(1) + '>';\n          }\n          return prefix + '<\\n' + bytes.map(function (line) {\n            return indent + '  ' + line;\n          }).join('\\n') + '\\n' + indent + '  >';\n        } // stringify generic objects\n\n        return prefix + JSON.stringify(value, null, 2).split('\\n').map(function (line, index) {\n          if (index === 0) {\n            return line;\n          }\n          return indent + '  ' + line;\n        }).join('\\n');\n      }).join('\\n') + (\n      // recursively textify the child boxes\n      box.boxes ? '\\n' + textifyMp4(box.boxes, depth + 1) : '');\n    }).join('\\n');\n  };\n  var mp4Inspector = {\n    inspect: inspectMp4,\n    textify: textifyMp4,\n    parseType: parseType$2,\n    findBox: findBox$4,\n    parseTraf: parse.traf,\n    parseTfdt: parse.tfdt,\n    parseHdlr: parse.hdlr,\n    parseTfhd: parse.tfhd,\n    parseTrun: parse.trun,\n    parseSidx: parse.sidx\n  };\n  /**\n   * Returns the first string in the data array ending with a null char '\\0'\n   * @param {UInt8} data \n   * @returns the string with the null char\n   */\n\n  var uint8ToCString$1 = function (data) {\n    var index = 0;\n    var curChar = String.fromCharCode(data[index]);\n    var retString = '';\n    while (curChar !== '\\0') {\n      retString += curChar;\n      index++;\n      curChar = String.fromCharCode(data[index]);\n    } // Add nullChar\n\n    retString += curChar;\n    return retString;\n  };\n  var string = {\n    uint8ToCString: uint8ToCString$1\n  };\n  var uint8ToCString = string.uint8ToCString;\n  var getUint64$1 = numbers.getUint64;\n  /**\n   * Based on: ISO/IEC 23009 Section: 5.10.3.3\n   * References:\n   * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format\n   * https://aomediacodec.github.io/id3-emsg/\n   * \n   * Takes emsg box data as a uint8 array and returns a emsg box object\n   * @param {UInt8Array} boxData data from emsg box\n   * @returns A parsed emsg box object\n   */\n\n  var parseEmsgBox = function (boxData) {\n    // version + flags\n    var offset = 4;\n    var version = boxData[0];\n    var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;\n    if (version === 0) {\n      scheme_id_uri = uint8ToCString(boxData.subarray(offset));\n      offset += scheme_id_uri.length;\n      value = uint8ToCString(boxData.subarray(offset));\n      offset += value.length;\n      var dv = new DataView(boxData.buffer);\n      timescale = dv.getUint32(offset);\n      offset += 4;\n      presentation_time_delta = dv.getUint32(offset);\n      offset += 4;\n      event_duration = dv.getUint32(offset);\n      offset += 4;\n      id = dv.getUint32(offset);\n      offset += 4;\n    } else if (version === 1) {\n      var dv = new DataView(boxData.buffer);\n      timescale = dv.getUint32(offset);\n      offset += 4;\n      presentation_time = getUint64$1(boxData.subarray(offset));\n      offset += 8;\n      event_duration = dv.getUint32(offset);\n      offset += 4;\n      id = dv.getUint32(offset);\n      offset += 4;\n      scheme_id_uri = uint8ToCString(boxData.subarray(offset));\n      offset += scheme_id_uri.length;\n      value = uint8ToCString(boxData.subarray(offset));\n      offset += value.length;\n    }\n    message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));\n    var emsgBox = {\n      scheme_id_uri,\n      value,\n      // if timescale is undefined or 0 set to 1 \n      timescale: timescale ? timescale : 1,\n      presentation_time,\n      presentation_time_delta,\n      event_duration,\n      id,\n      message_data\n    };\n    return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;\n  };\n  /**\n   * Scales a presentation time or time delta with an offset with a provided timescale\n   * @param {number} presentationTime \n   * @param {number} timescale \n   * @param {number} timeDelta \n   * @param {number} offset \n   * @returns the scaled time as a number\n   */\n\n  var scaleTime = function (presentationTime, timescale, timeDelta, offset) {\n    return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;\n  };\n  /**\n   * Checks the emsg box data for validity based on the version\n   * @param {number} version of the emsg box to validate\n   * @param {Object} emsg the emsg data to validate\n   * @returns if the box is valid as a boolean\n   */\n\n  var isValidEmsgBox = function (version, emsg) {\n    var hasScheme = emsg.scheme_id_uri !== '\\0';\n    var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;\n    var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1\n\n    return !(version > 1) && isValidV0Box || isValidV1Box;\n  }; // Utility function to check if an object is defined\n\n  var isDefined = function (data) {\n    return data !== undefined || data !== null;\n  };\n  var emsg$1 = {\n    parseEmsgBox: parseEmsgBox,\n    scaleTime: scaleTime\n  };\n  var win;\n  if (typeof window !== \"undefined\") {\n    win = window;\n  } else if (typeof commonjsGlobal !== \"undefined\") {\n    win = commonjsGlobal;\n  } else if (typeof self !== \"undefined\") {\n    win = self;\n  } else {\n    win = {};\n  }\n  var window_1 = win;\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Utilities to detect basic properties and metadata about MP4s.\n   */\n\n  var toUnsigned = bin.toUnsigned;\n  var toHexString = bin.toHexString;\n  var findBox$3 = findBox_1;\n  var parseType$1 = parseType_1;\n  var emsg = emsg$1;\n  var parseTfhd$1 = parseTfhd$2;\n  var parseTrun$1 = parseTrun$2;\n  var parseTfdt$2 = parseTfdt$3;\n  var getUint64 = numbers.getUint64;\n  var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader$1, getEmsgID3;\n  var window$2 = window_1;\n  var parseId3Frames = parseId3.parseId3Frames;\n  /**\n   * Parses an MP4 initialization segment and extracts the timescale\n   * values for any declared tracks. Timescale values indicate the\n   * number of clock ticks per second to assume for time-based values\n   * elsewhere in the MP4.\n   *\n   * To determine the start time of an MP4, you need two pieces of\n   * information: the timescale unit and the earliest base media decode\n   * time. Multiple timescales can be specified within an MP4 but the\n   * base media decode time is always expressed in the timescale from\n   * the media header box for the track:\n   * ```\n   * moov > trak > mdia > mdhd.timescale\n   * ```\n   * @param init {Uint8Array} the bytes of the init segment\n   * @return {object} a hash of track ids to timescale values or null if\n   * the init segment is malformed.\n   */\n\n  timescale = function (init) {\n    var result = {},\n      traks = findBox$3(init, ['moov', 'trak']); // mdhd timescale\n\n    return traks.reduce(function (result, trak) {\n      var tkhd, version, index, id, mdhd;\n      tkhd = findBox$3(trak, ['tkhd'])[0];\n      if (!tkhd) {\n        return null;\n      }\n      version = tkhd[0];\n      index = version === 0 ? 12 : 20;\n      id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);\n      mdhd = findBox$3(trak, ['mdia', 'mdhd'])[0];\n      if (!mdhd) {\n        return null;\n      }\n      version = mdhd[0];\n      index = version === 0 ? 12 : 20;\n      result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);\n      return result;\n    }, result);\n  };\n  /**\n   * Determine the base media decode start time, in seconds, for an MP4\n   * fragment. If multiple fragments are specified, the earliest time is\n   * returned.\n   *\n   * The base media decode time can be parsed from track fragment\n   * metadata:\n   * ```\n   * moof > traf > tfdt.baseMediaDecodeTime\n   * ```\n   * It requires the timescale value from the mdhd to interpret.\n   *\n   * @param timescale {object} a hash of track ids to timescale values.\n   * @return {number} the earliest base media decode start time for the\n   * fragment, in seconds\n   */\n\n  startTime = function (timescale, fragment) {\n    var trafs; // we need info from two childrend of each track fragment box\n\n    trafs = findBox$3(fragment, ['moof', 'traf']); // determine the start times for each track\n\n    var lowestTime = trafs.reduce(function (acc, traf) {\n      var tfhd = findBox$3(traf, ['tfhd'])[0]; // get the track id from the tfhd\n\n      var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified\n\n      var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt\n\n      var tfdt = findBox$3(traf, ['tfdt'])[0];\n      var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);\n      var baseTime; // version 1 is 64 bit\n\n      if (tfdt[0] === 1) {\n        baseTime = getUint64(tfdt.subarray(4, 12));\n      } else {\n        baseTime = dv.getUint32(4);\n      } // convert base time to seconds if it is a valid number.\n\n      let seconds;\n      if (typeof baseTime === 'bigint') {\n        seconds = baseTime / window$2.BigInt(scale);\n      } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {\n        seconds = baseTime / scale;\n      }\n      if (seconds < Number.MAX_SAFE_INTEGER) {\n        seconds = Number(seconds);\n      }\n      if (seconds < acc) {\n        acc = seconds;\n      }\n      return acc;\n    }, Infinity);\n    return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;\n  };\n  /**\n   * Determine the composition start, in seconds, for an MP4\n   * fragment.\n   *\n   * The composition start time of a fragment can be calculated using the base\n   * media decode time, composition time offset, and timescale, as follows:\n   *\n   * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale\n   *\n   * All of the aforementioned information is contained within a media fragment's\n   * `traf` box, except for timescale info, which comes from the initialization\n   * segment, so a track id (also contained within a `traf`) is also necessary to\n   * associate it with a timescale\n   *\n   *\n   * @param timescales {object} - a hash of track ids to timescale values.\n   * @param fragment {Unit8Array} - the bytes of a media segment\n   * @return {number} the composition start time for the fragment, in seconds\n   **/\n\n  compositionStartTime = function (timescales, fragment) {\n    var trafBoxes = findBox$3(fragment, ['moof', 'traf']);\n    var baseMediaDecodeTime = 0;\n    var compositionTimeOffset = 0;\n    var trackId;\n    if (trafBoxes && trafBoxes.length) {\n      // The spec states that track run samples contained within a `traf` box are contiguous, but\n      // it does not explicitly state whether the `traf` boxes themselves are contiguous.\n      // We will assume that they are, so we only need the first to calculate start time.\n      var tfhd = findBox$3(trafBoxes[0], ['tfhd'])[0];\n      var trun = findBox$3(trafBoxes[0], ['trun'])[0];\n      var tfdt = findBox$3(trafBoxes[0], ['tfdt'])[0];\n      if (tfhd) {\n        var parsedTfhd = parseTfhd$1(tfhd);\n        trackId = parsedTfhd.trackId;\n      }\n      if (tfdt) {\n        var parsedTfdt = parseTfdt$2(tfdt);\n        baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;\n      }\n      if (trun) {\n        var parsedTrun = parseTrun$1(trun);\n        if (parsedTrun.samples && parsedTrun.samples.length) {\n          compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;\n        }\n      }\n    } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was\n    // specified.\n\n    var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds\n\n    if (typeof baseMediaDecodeTime === 'bigint') {\n      compositionTimeOffset = window$2.BigInt(compositionTimeOffset);\n      timescale = window$2.BigInt(timescale);\n    }\n    var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;\n    if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {\n      result = Number(result);\n    }\n    return result;\n  };\n  /**\n    * Find the trackIds of the video tracks in this source.\n    * Found by parsing the Handler Reference and Track Header Boxes:\n    *   moov > trak > mdia > hdlr\n    *   moov > trak > tkhd\n    *\n    * @param {Uint8Array} init - The bytes of the init segment for this source\n    * @return {Number[]} A list of trackIds\n    *\n    * @see ISO-BMFF-12/2015, Section 8.4.3\n   **/\n\n  getVideoTrackIds = function (init) {\n    var traks = findBox$3(init, ['moov', 'trak']);\n    var videoTrackIds = [];\n    traks.forEach(function (trak) {\n      var hdlrs = findBox$3(trak, ['mdia', 'hdlr']);\n      var tkhds = findBox$3(trak, ['tkhd']);\n      hdlrs.forEach(function (hdlr, index) {\n        var handlerType = parseType$1(hdlr.subarray(8, 12));\n        var tkhd = tkhds[index];\n        var view;\n        var version;\n        var trackId;\n        if (handlerType === 'vide') {\n          view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);\n          version = view.getUint8(0);\n          trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);\n          videoTrackIds.push(trackId);\n        }\n      });\n    });\n    return videoTrackIds;\n  };\n  getTimescaleFromMediaHeader$1 = function (mdhd) {\n    // mdhd is a FullBox, meaning it will have its own version as the first byte\n    var version = mdhd[0];\n    var index = version === 0 ? 12 : 20;\n    return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);\n  };\n  /**\n   * Get all the video, audio, and hint tracks from a non fragmented\n   * mp4 segment\n   */\n\n  getTracks = function (init) {\n    var traks = findBox$3(init, ['moov', 'trak']);\n    var tracks = [];\n    traks.forEach(function (trak) {\n      var track = {};\n      var tkhd = findBox$3(trak, ['tkhd'])[0];\n      var view, tkhdVersion; // id\n\n      if (tkhd) {\n        view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);\n        tkhdVersion = view.getUint8(0);\n        track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);\n      }\n      var hdlr = findBox$3(trak, ['mdia', 'hdlr'])[0]; // type\n\n      if (hdlr) {\n        var type = parseType$1(hdlr.subarray(8, 12));\n        if (type === 'vide') {\n          track.type = 'video';\n        } else if (type === 'soun') {\n          track.type = 'audio';\n        } else {\n          track.type = type;\n        }\n      } // codec\n\n      var stsd = findBox$3(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n      if (stsd) {\n        var sampleDescriptions = stsd.subarray(8); // gives the codec type string\n\n        track.codec = parseType$1(sampleDescriptions.subarray(4, 8));\n        var codecBox = findBox$3(sampleDescriptions, [track.codec])[0];\n        var codecConfig, codecConfigType;\n        if (codecBox) {\n          // https://tools.ietf.org/html/rfc6381#section-3.3\n          if (/^[asm]vc[1-9]$/i.test(track.codec)) {\n            // we don't need anything but the \"config\" parameter of the\n            // avc1 codecBox\n            codecConfig = codecBox.subarray(78);\n            codecConfigType = parseType$1(codecConfig.subarray(4, 8));\n            if (codecConfigType === 'avcC' && codecConfig.length > 11) {\n              track.codec += '.'; // left padded with zeroes for single digit hex\n              // profile idc\n\n              track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags\n\n              track.codec += toHexString(codecConfig[10]); // level idc\n\n              track.codec += toHexString(codecConfig[11]);\n            } else {\n              // TODO: show a warning that we couldn't parse the codec\n              // and are using the default\n              track.codec = 'avc1.4d400d';\n            }\n          } else if (/^mp4[a,v]$/i.test(track.codec)) {\n            // we do not need anything but the streamDescriptor of the mp4a codecBox\n            codecConfig = codecBox.subarray(28);\n            codecConfigType = parseType$1(codecConfig.subarray(4, 8));\n            if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {\n              track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit\n\n              track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');\n            } else {\n              // TODO: show a warning that we couldn't parse the codec\n              // and are using the default\n              track.codec = 'mp4a.40.2';\n            }\n          } else {\n            // flac, opus, etc\n            track.codec = track.codec.toLowerCase();\n          }\n        }\n      }\n      var mdhd = findBox$3(trak, ['mdia', 'mdhd'])[0];\n      if (mdhd) {\n        track.timescale = getTimescaleFromMediaHeader$1(mdhd);\n      }\n      tracks.push(track);\n    });\n    return tracks;\n  };\n  /**\n   * Returns an array of emsg ID3 data from the provided segmentData.\n   * An offset can also be provided as the Latest Arrival Time to calculate \n   * the Event Start Time of v0 EMSG boxes. \n   * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing\n   * \n   * @param {Uint8Array} segmentData the segment byte array.\n   * @param {number} offset the segment start time or Latest Arrival Time, \n   * @return {Object[]} an array of ID3 parsed from EMSG boxes\n   */\n\n  getEmsgID3 = function (segmentData, offset = 0) {\n    var emsgBoxes = findBox$3(segmentData, ['emsg']);\n    return emsgBoxes.map(data => {\n      var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));\n      var parsedId3Frames = parseId3Frames(parsedBox.message_data);\n      return {\n        cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),\n        duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),\n        frames: parsedId3Frames\n      };\n    });\n  };\n  var probe$2 = {\n    // export mp4 inspector's findBox and parseType for backwards compatibility\n    findBox: findBox$3,\n    parseType: parseType$1,\n    timescale: timescale,\n    startTime: startTime,\n    compositionStartTime: compositionStartTime,\n    videoTrackIds: getVideoTrackIds,\n    tracks: getTracks,\n    getTimescaleFromMediaHeader: getTimescaleFromMediaHeader$1,\n    getEmsgID3: getEmsgID3\n  };\n  const {\n    parseTrun\n  } = mp4Inspector;\n  const {\n    findBox: findBox$2\n  } = probe$2;\n  var window$1 = window_1;\n  /**\n   * Utility function for parsing data from mdat boxes.\n   * @param {Array<Uint8Array>} segment the segment data to create mdat/traf pairs from.\n   * @returns mdat and traf boxes paired up for easier parsing.\n   */\n\n  var getMdatTrafPairs$2 = function (segment) {\n    var trafs = findBox$2(segment, ['moof', 'traf']);\n    var mdats = findBox$2(segment, ['mdat']);\n    var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs\n\n    mdats.forEach(function (mdat, index) {\n      var matchingTraf = trafs[index];\n      mdatTrafPairs.push({\n        mdat: mdat,\n        traf: matchingTraf\n      });\n    });\n    return mdatTrafPairs;\n  };\n  /**\n    * Parses sample information out of Track Run Boxes and calculates\n    * the absolute presentation and decode timestamps of each sample.\n    *\n    * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed\n    * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt\n        @see ISO-BMFF-12/2015, Section 8.8.12\n    * @param {Object} tfhd - The parsed Track Fragment Header\n    *   @see inspect.parseTfhd\n    * @return {Object[]} the parsed samples\n    *\n    * @see ISO-BMFF-12/2015, Section 8.8.8\n   **/\n\n  var parseSamples$2 = function (truns, baseMediaDecodeTime, tfhd) {\n    var currentDts = baseMediaDecodeTime;\n    var defaultSampleDuration = tfhd.defaultSampleDuration || 0;\n    var defaultSampleSize = tfhd.defaultSampleSize || 0;\n    var trackId = tfhd.trackId;\n    var allSamples = [];\n    truns.forEach(function (trun) {\n      // Note: We currently do not parse the sample table as well\n      // as the trun. It's possible some sources will require this.\n      // moov > trak > mdia > minf > stbl\n      var trackRun = parseTrun(trun);\n      var samples = trackRun.samples;\n      samples.forEach(function (sample) {\n        if (sample.duration === undefined) {\n          sample.duration = defaultSampleDuration;\n        }\n        if (sample.size === undefined) {\n          sample.size = defaultSampleSize;\n        }\n        sample.trackId = trackId;\n        sample.dts = currentDts;\n        if (sample.compositionTimeOffset === undefined) {\n          sample.compositionTimeOffset = 0;\n        }\n        if (typeof currentDts === 'bigint') {\n          sample.pts = currentDts + window$1.BigInt(sample.compositionTimeOffset);\n          currentDts += window$1.BigInt(sample.duration);\n        } else {\n          sample.pts = currentDts + sample.compositionTimeOffset;\n          currentDts += sample.duration;\n        }\n      });\n      allSamples = allSamples.concat(samples);\n    });\n    return allSamples;\n  };\n  var samples = {\n    getMdatTrafPairs: getMdatTrafPairs$2,\n    parseSamples: parseSamples$2\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Reads in-band CEA-708 captions out of FMP4 segments.\n   * @see https://en.wikipedia.org/wiki/CEA-708\n   */\n\n  var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;\n  var CaptionStream = captionStream.CaptionStream;\n  var findBox$1 = findBox_1;\n  var parseTfdt$1 = parseTfdt$3;\n  var parseTfhd = parseTfhd$2;\n  var {\n    getMdatTrafPairs: getMdatTrafPairs$1,\n    parseSamples: parseSamples$1\n  } = samples;\n  /**\n    * Maps an offset in the mdat to a sample based on the the size of the samples.\n    * Assumes that `parseSamples` has been called first.\n    *\n    * @param {Number} offset - The offset into the mdat\n    * @param {Object[]} samples - An array of samples, parsed using `parseSamples`\n    * @return {?Object} The matching sample, or null if no match was found.\n    *\n    * @see ISO-BMFF-12/2015, Section 8.8.8\n   **/\n\n  var mapToSample = function (offset, samples) {\n    var approximateOffset = offset;\n    for (var i = 0; i < samples.length; i++) {\n      var sample = samples[i];\n      if (approximateOffset < sample.size) {\n        return sample;\n      }\n      approximateOffset -= sample.size;\n    }\n    return null;\n  };\n  /**\n    * Finds SEI nal units contained in a Media Data Box.\n    * Assumes that `parseSamples` has been called first.\n    *\n    * @param {Uint8Array} avcStream - The bytes of the mdat\n    * @param {Object[]} samples - The samples parsed out by `parseSamples`\n    * @param {Number} trackId - The trackId of this video track\n    * @return {Object[]} seiNals - the parsed SEI NALUs found.\n    *   The contents of the seiNal should match what is expected by\n    *   CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)\n    *\n    * @see ISO-BMFF-12/2015, Section 8.1.1\n    * @see Rec. ITU-T H.264, 7.3.2.3.1\n   **/\n\n  var findSeiNals = function (avcStream, samples, trackId) {\n    var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),\n      result = {\n        logs: [],\n        seiNals: []\n      },\n      seiNal,\n      i,\n      length,\n      lastMatchedSample;\n    for (i = 0; i + 4 < avcStream.length; i += length) {\n      length = avcView.getUint32(i);\n      i += 4; // Bail if this doesn't appear to be an H264 stream\n\n      if (length <= 0) {\n        continue;\n      }\n      switch (avcStream[i] & 0x1F) {\n        case 0x06:\n          var data = avcStream.subarray(i + 1, i + 1 + length);\n          var matchingSample = mapToSample(i, samples);\n          seiNal = {\n            nalUnitType: 'sei_rbsp',\n            size: length,\n            data: data,\n            escapedRBSP: discardEmulationPreventionBytes(data),\n            trackId: trackId\n          };\n          if (matchingSample) {\n            seiNal.pts = matchingSample.pts;\n            seiNal.dts = matchingSample.dts;\n            lastMatchedSample = matchingSample;\n          } else if (lastMatchedSample) {\n            // If a matching sample cannot be found, use the last\n            // sample's values as they should be as close as possible\n            seiNal.pts = lastMatchedSample.pts;\n            seiNal.dts = lastMatchedSample.dts;\n          } else {\n            result.logs.push({\n              level: 'warn',\n              message: 'We\\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'\n            });\n            break;\n          }\n          result.seiNals.push(seiNal);\n          break;\n      }\n    }\n    return result;\n  };\n  /**\n    * Parses out caption nals from an FMP4 segment's video tracks.\n    *\n    * @param {Uint8Array} segment - The bytes of a single segment\n    * @param {Number} videoTrackId - The trackId of a video track in the segment\n    * @return {Object.<Number, Object[]>} A mapping of video trackId to\n    *   a list of seiNals found in that track\n   **/\n\n  var parseCaptionNals = function (segment, videoTrackId) {\n    var captionNals = {};\n    var mdatTrafPairs = getMdatTrafPairs$1(segment);\n    mdatTrafPairs.forEach(function (pair) {\n      var mdat = pair.mdat;\n      var traf = pair.traf;\n      var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf\n\n      var headerInfo = parseTfhd(tfhd[0]);\n      var trackId = headerInfo.trackId;\n      var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf\n\n      var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;\n      var truns = findBox$1(traf, ['trun']);\n      var samples;\n      var result; // Only parse video data for the chosen video track\n\n      if (videoTrackId === trackId && truns.length > 0) {\n        samples = parseSamples$1(truns, baseMediaDecodeTime, headerInfo);\n        result = findSeiNals(mdat, samples, trackId);\n        if (!captionNals[trackId]) {\n          captionNals[trackId] = {\n            seiNals: [],\n            logs: []\n          };\n        }\n        captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);\n        captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);\n      }\n    });\n    return captionNals;\n  };\n  /**\n    * Parses out inband captions from an MP4 container and returns\n    * caption objects that can be used by WebVTT and the TextTrack API.\n    * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue\n    * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack\n    * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first\n    *\n    * @param {Uint8Array} segment - The fmp4 segment containing embedded captions\n    * @param {Number} trackId - The id of the video track to parse\n    * @param {Number} timescale - The timescale for the video track from the init segment\n    *\n    * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks\n    * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds\n    * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds\n    * @return {Object[]} parsedCaptions[].content - A list of individual caption segments\n    * @return {String} parsedCaptions[].content.text - The visible content of the caption segment\n    * @return {Number} parsedCaptions[].content.line - The line height from 1-15 for positioning of the caption segment\n    * @return {Number} parsedCaptions[].content.position - The column indent percentage for cue positioning from 10-80\n   **/\n\n  var parseEmbeddedCaptions = function (segment, trackId, timescale) {\n    var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there\n\n    if (trackId === null) {\n      return null;\n    }\n    captionNals = parseCaptionNals(segment, trackId);\n    var trackNals = captionNals[trackId] || {};\n    return {\n      seiNals: trackNals.seiNals,\n      logs: trackNals.logs,\n      timescale: timescale\n    };\n  };\n  /**\n    * Converts SEI NALUs into captions that can be used by video.js\n   **/\n\n  var CaptionParser = function () {\n    var isInitialized = false;\n    var captionStream; // Stores segments seen before trackId and timescale are set\n\n    var segmentCache; // Stores video track ID of the track being parsed\n\n    var trackId; // Stores the timescale of the track being parsed\n\n    var timescale; // Stores captions parsed so far\n\n    var parsedCaptions; // Stores whether we are receiving partial data or not\n\n    var parsingPartial;\n    /**\n      * A method to indicate whether a CaptionParser has been initalized\n      * @returns {Boolean}\n     **/\n\n    this.isInitialized = function () {\n      return isInitialized;\n    };\n    /**\n      * Initializes the underlying CaptionStream, SEI NAL parsing\n      * and management, and caption collection\n     **/\n\n    this.init = function (options) {\n      captionStream = new CaptionStream();\n      isInitialized = true;\n      parsingPartial = options ? options.isPartial : false; // Collect dispatched captions\n\n      captionStream.on('data', function (event) {\n        // Convert to seconds in the source's timescale\n        event.startTime = event.startPts / timescale;\n        event.endTime = event.endPts / timescale;\n        parsedCaptions.captions.push(event);\n        parsedCaptions.captionStreams[event.stream] = true;\n      });\n      captionStream.on('log', function (log) {\n        parsedCaptions.logs.push(log);\n      });\n    };\n    /**\n      * Determines if a new video track will be selected\n      * or if the timescale changed\n      * @return {Boolean}\n     **/\n\n    this.isNewInit = function (videoTrackIds, timescales) {\n      if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {\n        return false;\n      }\n      return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];\n    };\n    /**\n      * Parses out SEI captions and interacts with underlying\n      * CaptionStream to return dispatched captions\n      *\n      * @param {Uint8Array} segment - The fmp4 segment containing embedded captions\n      * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment\n      * @param {Object.<Number, Number>} timescales - The timescales found in the init segment\n      * @see parseEmbeddedCaptions\n      * @see m2ts/caption-stream.js\n     **/\n\n    this.parse = function (segment, videoTrackIds, timescales) {\n      var parsedData;\n      if (!this.isInitialized()) {\n        return null; // This is not likely to be a video segment\n      } else if (!videoTrackIds || !timescales) {\n        return null;\n      } else if (this.isNewInit(videoTrackIds, timescales)) {\n        // Use the first video track only as there is no\n        // mechanism to switch to other video tracks\n        trackId = videoTrackIds[0];\n        timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment\n        // data until we have one.\n        // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there\n      } else if (trackId === null || !timescale) {\n        segmentCache.push(segment);\n        return null;\n      } // Now that a timescale and trackId is set, parse cached segments\n\n      while (segmentCache.length > 0) {\n        var cachedSegment = segmentCache.shift();\n        this.parse(cachedSegment, videoTrackIds, timescales);\n      }\n      parsedData = parseEmbeddedCaptions(segment, trackId, timescale);\n      if (parsedData && parsedData.logs) {\n        parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);\n      }\n      if (parsedData === null || !parsedData.seiNals) {\n        if (parsedCaptions.logs.length) {\n          return {\n            logs: parsedCaptions.logs,\n            captions: [],\n            captionStreams: []\n          };\n        }\n        return null;\n      }\n      this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched\n\n      this.flushStream();\n      return parsedCaptions;\n    };\n    /**\n      * Pushes SEI NALUs onto CaptionStream\n      * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`\n      * Assumes that `parseCaptionNals` has been called first\n      * @see m2ts/caption-stream.js\n      **/\n\n    this.pushNals = function (nals) {\n      if (!this.isInitialized() || !nals || nals.length === 0) {\n        return null;\n      }\n      nals.forEach(function (nal) {\n        captionStream.push(nal);\n      });\n    };\n    /**\n      * Flushes underlying CaptionStream to dispatch processed, displayable captions\n      * @see m2ts/caption-stream.js\n     **/\n\n    this.flushStream = function () {\n      if (!this.isInitialized()) {\n        return null;\n      }\n      if (!parsingPartial) {\n        captionStream.flush();\n      } else {\n        captionStream.partialFlush();\n      }\n    };\n    /**\n      * Reset caption buckets for new data\n     **/\n\n    this.clearParsedCaptions = function () {\n      parsedCaptions.captions = [];\n      parsedCaptions.captionStreams = {};\n      parsedCaptions.logs = [];\n    };\n    /**\n      * Resets underlying CaptionStream\n      * @see m2ts/caption-stream.js\n     **/\n\n    this.resetCaptionStream = function () {\n      if (!this.isInitialized()) {\n        return null;\n      }\n      captionStream.reset();\n    };\n    /**\n      * Convenience method to clear all captions flushed from the\n      * CaptionStream and still being parsed\n      * @see m2ts/caption-stream.js\n     **/\n\n    this.clearAllCaptions = function () {\n      this.clearParsedCaptions();\n      this.resetCaptionStream();\n    };\n    /**\n      * Reset caption parser\n     **/\n\n    this.reset = function () {\n      segmentCache = [];\n      trackId = null;\n      timescale = null;\n      if (!parsedCaptions) {\n        parsedCaptions = {\n          captions: [],\n          // CC1, CC2, CC3, CC4\n          captionStreams: {},\n          logs: []\n        };\n      } else {\n        this.clearParsedCaptions();\n      }\n      this.resetCaptionStream();\n    };\n    this.reset();\n  };\n  var captionParser = CaptionParser;\n  const {\n    parseTfdt\n  } = mp4Inspector;\n  const findBox = findBox_1;\n  const {\n    getTimescaleFromMediaHeader\n  } = probe$2;\n  const {\n    parseSamples,\n    getMdatTrafPairs\n  } = samples;\n  /**\n   * Module for parsing WebVTT text and styles from FMP4 segments.\n   * Based on the ISO/IEC 14496-30.\n   */\n\n  const WebVttParser = function () {\n    // default timescale to 90k\n    let timescale = 90e3;\n    /**\n     * Parses the timescale from the init segment.\n     * @param {Array<Uint8Array>} segment The initialization segment to parse the timescale from.\n     */\n\n    this.init = function (segment) {\n      // We just need the timescale from the init segment.\n      const mdhd = findBox(segment, ['moov', 'trak', 'mdia', 'mdhd'])[0];\n      if (mdhd) {\n        timescale = getTimescaleFromMediaHeader(mdhd);\n      }\n    };\n    /**\n     * Parses a WebVTT FMP4 segment.\n     * @param {Array<Uint8Array>} segment The content segment to parse the WebVTT cues from.\n     * @returns The WebVTT cue text, styling, and timing info as an array of cue objects.\n     */\n\n    this.parseSegment = function (segment) {\n      const vttCues = [];\n      const mdatTrafPairs = getMdatTrafPairs(segment);\n      let baseMediaDecodeTime = 0;\n      mdatTrafPairs.forEach(function (pair) {\n        const mdatBox = pair.mdat;\n        const trafBox = pair.traf; // zero or one.\n\n        const tfdtBox = findBox(trafBox, ['tfdt'])[0]; // zero or one.\n\n        const tfhdBox = findBox(trafBox, ['tfhd'])[0]; // zero or more.\n\n        const trunBoxes = findBox(trafBox, ['trun']);\n        if (tfdtBox) {\n          const tfdt = parseTfdt(tfdtBox);\n          baseMediaDecodeTime = tfdt.baseMediaDecodeTime;\n        }\n        if (trunBoxes.length && tfhdBox) {\n          const samples = parseSamples(trunBoxes, baseMediaDecodeTime, tfhdBox);\n          let mdatOffset = 0;\n          samples.forEach(function (sample) {\n            // decode utf8 payload\n            const UTF_8 = 'utf-8';\n            const textDecoder = new TextDecoder(UTF_8); // extract sample data from the mdat box.\n            // WebVTT Sample format:\n            // Exactly one VTTEmptyCueBox box\n            // OR one or more VTTCueBox boxes.\n\n            const sampleData = mdatBox.slice(mdatOffset, mdatOffset + sample.size); // single vtte box.\n\n            const vtteBox = findBox(sampleData, ['vtte'])[0]; // empty box\n\n            if (vtteBox) {\n              mdatOffset += sample.size;\n              return;\n            } // TODO: Support 'vtta' boxes.\n            // VTTAdditionalTextBoxes can be interleaved between VTTCueBoxes.\n\n            const vttcBoxes = findBox(sampleData, ['vttc']);\n            vttcBoxes.forEach(function (vttcBox) {\n              // mandatory payload box.\n              const paylBox = findBox(vttcBox, ['payl'])[0]; // optional settings box\n\n              const sttgBox = findBox(vttcBox, ['sttg'])[0];\n              const start = sample.pts / timescale;\n              const end = (sample.pts + sample.duration) / timescale;\n              let cueText, settings; // contains cue text.\n\n              if (paylBox) {\n                try {\n                  cueText = textDecoder.decode(paylBox);\n                } catch (e) {\n                  console.error(e);\n                }\n              } // settings box contains styling.\n\n              if (sttgBox) {\n                try {\n                  settings = textDecoder.decode(sttgBox);\n                } catch (e) {\n                  console.error(e);\n                }\n              }\n              if (sample.duration && cueText) {\n                vttCues.push({\n                  cueText,\n                  start,\n                  end,\n                  settings\n                });\n              }\n            });\n            mdatOffset += sample.size;\n          });\n        }\n      });\n      return vttCues;\n    };\n  };\n  var webvttParser = WebVttParser;\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Utilities to detect basic properties and metadata about TS Segments.\n   */\n\n  var StreamTypes$1 = streamTypes;\n  var parsePid = function (packet) {\n    var pid = packet[1] & 0x1f;\n    pid <<= 8;\n    pid |= packet[2];\n    return pid;\n  };\n  var parsePayloadUnitStartIndicator = function (packet) {\n    return !!(packet[1] & 0x40);\n  };\n  var parseAdaptionField = function (packet) {\n    var offset = 0; // if an adaption field is present, its length is specified by the\n    // fifth byte of the TS packet header. The adaptation field is\n    // used to add stuffing to PES packets that don't fill a complete\n    // TS packet, and to specify some forms of timing and control data\n    // that we do not currently use.\n\n    if ((packet[3] & 0x30) >>> 4 > 0x01) {\n      offset += packet[4] + 1;\n    }\n    return offset;\n  };\n  var parseType = function (packet, pmtPid) {\n    var pid = parsePid(packet);\n    if (pid === 0) {\n      return 'pat';\n    } else if (pid === pmtPid) {\n      return 'pmt';\n    } else if (pmtPid) {\n      return 'pes';\n    }\n    return null;\n  };\n  var parsePat = function (packet) {\n    var pusi = parsePayloadUnitStartIndicator(packet);\n    var offset = 4 + parseAdaptionField(packet);\n    if (pusi) {\n      offset += packet[offset] + 1;\n    }\n    return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];\n  };\n  var parsePmt = function (packet) {\n    var programMapTable = {};\n    var pusi = parsePayloadUnitStartIndicator(packet);\n    var payloadOffset = 4 + parseAdaptionField(packet);\n    if (pusi) {\n      payloadOffset += packet[payloadOffset] + 1;\n    } // PMTs can be sent ahead of the time when they should actually\n    // take effect. We don't believe this should ever be the case\n    // for HLS but we'll ignore \"forward\" PMT declarations if we see\n    // them. Future PMT declarations have the current_next_indicator\n    // set to zero.\n\n    if (!(packet[payloadOffset + 5] & 0x01)) {\n      return;\n    }\n    var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section\n\n    sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];\n    tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how\n    // long the program info descriptors are\n\n    programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table\n\n    var offset = 12 + programInfoLength;\n    while (offset < tableEnd) {\n      var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type\n\n      programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry\n      // skip past the elementary stream descriptors, if present\n\n      offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;\n    }\n    return programMapTable;\n  };\n  var parsePesType = function (packet, programMapTable) {\n    var pid = parsePid(packet);\n    var type = programMapTable[pid];\n    switch (type) {\n      case StreamTypes$1.H264_STREAM_TYPE:\n        return 'video';\n      case StreamTypes$1.ADTS_STREAM_TYPE:\n        return 'audio';\n      case StreamTypes$1.METADATA_STREAM_TYPE:\n        return 'timed-metadata';\n      default:\n        return null;\n    }\n  };\n  var parsePesTime = function (packet) {\n    var pusi = parsePayloadUnitStartIndicator(packet);\n    if (!pusi) {\n      return null;\n    }\n    var offset = 4 + parseAdaptionField(packet);\n    if (offset >= packet.byteLength) {\n      // From the H 222.0 MPEG-TS spec\n      // \"For transport stream packets carrying PES packets, stuffing is needed when there\n      //  is insufficient PES packet data to completely fill the transport stream packet\n      //  payload bytes. Stuffing is accomplished by defining an adaptation field longer than\n      //  the sum of the lengths of the data elements in it, so that the payload bytes\n      //  remaining after the adaptation field exactly accommodates the available PES packet\n      //  data.\"\n      //\n      // If the offset is >= the length of the packet, then the packet contains no data\n      // and instead is just adaption field stuffing bytes\n      return null;\n    }\n    var pes = null;\n    var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value\n    // and a DTS value. Determine what combination of values is\n    // available to work with.\n\n    ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number.  Javascript\n    // performs all bitwise operations on 32-bit integers but javascript\n    // supports a much greater range (52-bits) of integer using standard\n    // mathematical operations.\n    // We construct a 31-bit value using bitwise operators over the 31\n    // most significant bits and then multiply by 4 (equal to a left-shift\n    // of 2) before we add the final 2 least significant bits of the\n    // timestamp (equal to an OR.)\n\n    if (ptsDtsFlags & 0xC0) {\n      pes = {}; // the PTS and DTS are not written out directly. For information\n      // on how they are encoded, see\n      // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n\n      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;\n      pes.pts *= 4; // Left shift by 2\n\n      pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs\n\n      pes.dts = pes.pts;\n      if (ptsDtsFlags & 0x40) {\n        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;\n        pes.dts *= 4; // Left shift by 2\n\n        pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs\n      }\n    }\n    return pes;\n  };\n  var parseNalUnitType = function (type) {\n    switch (type) {\n      case 0x05:\n        return 'slice_layer_without_partitioning_rbsp_idr';\n      case 0x06:\n        return 'sei_rbsp';\n      case 0x07:\n        return 'seq_parameter_set_rbsp';\n      case 0x08:\n        return 'pic_parameter_set_rbsp';\n      case 0x09:\n        return 'access_unit_delimiter_rbsp';\n      default:\n        return null;\n    }\n  };\n  var videoPacketContainsKeyFrame = function (packet) {\n    var offset = 4 + parseAdaptionField(packet);\n    var frameBuffer = packet.subarray(offset);\n    var frameI = 0;\n    var frameSyncPoint = 0;\n    var foundKeyFrame = false;\n    var nalType; // advance the sync point to a NAL start, if necessary\n\n    for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {\n      if (frameBuffer[frameSyncPoint + 2] === 1) {\n        // the sync point is properly aligned\n        frameI = frameSyncPoint + 5;\n        break;\n      }\n    }\n    while (frameI < frameBuffer.byteLength) {\n      // look at the current byte to determine if we've hit the end of\n      // a NAL unit boundary\n      switch (frameBuffer[frameI]) {\n        case 0:\n          // skip past non-sync sequences\n          if (frameBuffer[frameI - 1] !== 0) {\n            frameI += 2;\n            break;\n          } else if (frameBuffer[frameI - 2] !== 0) {\n            frameI++;\n            break;\n          }\n          if (frameSyncPoint + 3 !== frameI - 2) {\n            nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);\n            if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {\n              foundKeyFrame = true;\n            }\n          } // drop trailing zeroes\n\n          do {\n            frameI++;\n          } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);\n          frameSyncPoint = frameI - 2;\n          frameI += 3;\n          break;\n        case 1:\n          // skip past non-sync sequences\n          if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {\n            frameI += 3;\n            break;\n          }\n          nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);\n          if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {\n            foundKeyFrame = true;\n          }\n          frameSyncPoint = frameI - 2;\n          frameI += 3;\n          break;\n        default:\n          // the current byte isn't a one or zero, so it cannot be part\n          // of a sync sequence\n          frameI += 3;\n          break;\n      }\n    }\n    frameBuffer = frameBuffer.subarray(frameSyncPoint);\n    frameI -= frameSyncPoint;\n    frameSyncPoint = 0; // parse the final nal\n\n    if (frameBuffer && frameBuffer.byteLength > 3) {\n      nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);\n      if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {\n        foundKeyFrame = true;\n      }\n    }\n    return foundKeyFrame;\n  };\n  var probe$1 = {\n    parseType: parseType,\n    parsePat: parsePat,\n    parsePmt: parsePmt,\n    parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,\n    parsePesType: parsePesType,\n    parsePesTime: parsePesTime,\n    videoPacketContainsKeyFrame: videoPacketContainsKeyFrame\n  };\n  /**\n   * mux.js\n   *\n   * Copyright (c) Brightcove\n   * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE\n   *\n   * Parse mpeg2 transport stream packets to extract basic timing information\n   */\n\n  var StreamTypes = streamTypes;\n  var handleRollover = timestampRolloverStream.handleRollover;\n  var probe = {};\n  probe.ts = probe$1;\n  probe.aac = utils;\n  var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;\n  var MP2T_PACKET_LENGTH = 188,\n    // bytes\n    SYNC_BYTE = 0x47;\n  /**\n   * walks through segment data looking for pat and pmt packets to parse out\n   * program map table information\n   */\n\n  var parsePsi_ = function (bytes, pmt) {\n    var startIndex = 0,\n      endIndex = MP2T_PACKET_LENGTH,\n      packet,\n      type;\n    while (endIndex < bytes.byteLength) {\n      // Look for a pair of start and end sync bytes in the data..\n      if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {\n        // We found a packet\n        packet = bytes.subarray(startIndex, endIndex);\n        type = probe.ts.parseType(packet, pmt.pid);\n        switch (type) {\n          case 'pat':\n            pmt.pid = probe.ts.parsePat(packet);\n            break;\n          case 'pmt':\n            var table = probe.ts.parsePmt(packet);\n            pmt.table = pmt.table || {};\n            Object.keys(table).forEach(function (key) {\n              pmt.table[key] = table[key];\n            });\n            break;\n        }\n        startIndex += MP2T_PACKET_LENGTH;\n        endIndex += MP2T_PACKET_LENGTH;\n        continue;\n      } // If we get here, we have somehow become de-synchronized and we need to step\n      // forward one byte at a time until we find a pair of sync bytes that denote\n      // a packet\n\n      startIndex++;\n      endIndex++;\n    }\n  };\n  /**\n   * walks through the segment data from the start and end to get timing information\n   * for the first and last audio pes packets\n   */\n\n  var parseAudioPes_ = function (bytes, pmt, result) {\n    var startIndex = 0,\n      endIndex = MP2T_PACKET_LENGTH,\n      packet,\n      type,\n      pesType,\n      pusi,\n      parsed;\n    var endLoop = false; // Start walking from start of segment to get first audio packet\n\n    while (endIndex <= bytes.byteLength) {\n      // Look for a pair of start and end sync bytes in the data..\n      if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {\n        // We found a packet\n        packet = bytes.subarray(startIndex, endIndex);\n        type = probe.ts.parseType(packet, pmt.pid);\n        switch (type) {\n          case 'pes':\n            pesType = probe.ts.parsePesType(packet, pmt.table);\n            pusi = probe.ts.parsePayloadUnitStartIndicator(packet);\n            if (pesType === 'audio' && pusi) {\n              parsed = probe.ts.parsePesTime(packet);\n              if (parsed) {\n                parsed.type = 'audio';\n                result.audio.push(parsed);\n                endLoop = true;\n              }\n            }\n            break;\n        }\n        if (endLoop) {\n          break;\n        }\n        startIndex += MP2T_PACKET_LENGTH;\n        endIndex += MP2T_PACKET_LENGTH;\n        continue;\n      } // If we get here, we have somehow become de-synchronized and we need to step\n      // forward one byte at a time until we find a pair of sync bytes that denote\n      // a packet\n\n      startIndex++;\n      endIndex++;\n    } // Start walking from end of segment to get last audio packet\n\n    endIndex = bytes.byteLength;\n    startIndex = endIndex - MP2T_PACKET_LENGTH;\n    endLoop = false;\n    while (startIndex >= 0) {\n      // Look for a pair of start and end sync bytes in the data..\n      if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {\n        // We found a packet\n        packet = bytes.subarray(startIndex, endIndex);\n        type = probe.ts.parseType(packet, pmt.pid);\n        switch (type) {\n          case 'pes':\n            pesType = probe.ts.parsePesType(packet, pmt.table);\n            pusi = probe.ts.parsePayloadUnitStartIndicator(packet);\n            if (pesType === 'audio' && pusi) {\n              parsed = probe.ts.parsePesTime(packet);\n              if (parsed) {\n                parsed.type = 'audio';\n                result.audio.push(parsed);\n                endLoop = true;\n              }\n            }\n            break;\n        }\n        if (endLoop) {\n          break;\n        }\n        startIndex -= MP2T_PACKET_LENGTH;\n        endIndex -= MP2T_PACKET_LENGTH;\n        continue;\n      } // If we get here, we have somehow become de-synchronized and we need to step\n      // forward one byte at a time until we find a pair of sync bytes that denote\n      // a packet\n\n      startIndex--;\n      endIndex--;\n    }\n  };\n  /**\n   * walks through the segment data from the start and end to get timing information\n   * for the first and last video pes packets as well as timing information for the first\n   * key frame.\n   */\n\n  var parseVideoPes_ = function (bytes, pmt, result) {\n    var startIndex = 0,\n      endIndex = MP2T_PACKET_LENGTH,\n      packet,\n      type,\n      pesType,\n      pusi,\n      parsed,\n      frame,\n      i,\n      pes;\n    var endLoop = false;\n    var currentFrame = {\n      data: [],\n      size: 0\n    }; // Start walking from start of segment to get first video packet\n\n    while (endIndex < bytes.byteLength) {\n      // Look for a pair of start and end sync bytes in the data..\n      if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {\n        // We found a packet\n        packet = bytes.subarray(startIndex, endIndex);\n        type = probe.ts.parseType(packet, pmt.pid);\n        switch (type) {\n          case 'pes':\n            pesType = probe.ts.parsePesType(packet, pmt.table);\n            pusi = probe.ts.parsePayloadUnitStartIndicator(packet);\n            if (pesType === 'video') {\n              if (pusi && !endLoop) {\n                parsed = probe.ts.parsePesTime(packet);\n                if (parsed) {\n                  parsed.type = 'video';\n                  result.video.push(parsed);\n                  endLoop = true;\n                }\n              }\n              if (!result.firstKeyFrame) {\n                if (pusi) {\n                  if (currentFrame.size !== 0) {\n                    frame = new Uint8Array(currentFrame.size);\n                    i = 0;\n                    while (currentFrame.data.length) {\n                      pes = currentFrame.data.shift();\n                      frame.set(pes, i);\n                      i += pes.byteLength;\n                    }\n                    if (probe.ts.videoPacketContainsKeyFrame(frame)) {\n                      var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting\n                      // the keyframe seems to work fine with HLS playback\n                      // and definitely preferable to a crash with TypeError...\n\n                      if (firstKeyFrame) {\n                        result.firstKeyFrame = firstKeyFrame;\n                        result.firstKeyFrame.type = 'video';\n                      } else {\n                        // eslint-disable-next-line\n                        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.');\n                      }\n                    }\n                    currentFrame.size = 0;\n                  }\n                }\n                currentFrame.data.push(packet);\n                currentFrame.size += packet.byteLength;\n              }\n            }\n            break;\n        }\n        if (endLoop && result.firstKeyFrame) {\n          break;\n        }\n        startIndex += MP2T_PACKET_LENGTH;\n        endIndex += MP2T_PACKET_LENGTH;\n        continue;\n      } // If we get here, we have somehow become de-synchronized and we need to step\n      // forward one byte at a time until we find a pair of sync bytes that denote\n      // a packet\n\n      startIndex++;\n      endIndex++;\n    } // Start walking from end of segment to get last video packet\n\n    endIndex = bytes.byteLength;\n    startIndex = endIndex - MP2T_PACKET_LENGTH;\n    endLoop = false;\n    while (startIndex >= 0) {\n      // Look for a pair of start and end sync bytes in the data..\n      if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {\n        // We found a packet\n        packet = bytes.subarray(startIndex, endIndex);\n        type = probe.ts.parseType(packet, pmt.pid);\n        switch (type) {\n          case 'pes':\n            pesType = probe.ts.parsePesType(packet, pmt.table);\n            pusi = probe.ts.parsePayloadUnitStartIndicator(packet);\n            if (pesType === 'video' && pusi) {\n              parsed = probe.ts.parsePesTime(packet);\n              if (parsed) {\n                parsed.type = 'video';\n                result.video.push(parsed);\n                endLoop = true;\n              }\n            }\n            break;\n        }\n        if (endLoop) {\n          break;\n        }\n        startIndex -= MP2T_PACKET_LENGTH;\n        endIndex -= MP2T_PACKET_LENGTH;\n        continue;\n      } // If we get here, we have somehow become de-synchronized and we need to step\n      // forward one byte at a time until we find a pair of sync bytes that denote\n      // a packet\n\n      startIndex--;\n      endIndex--;\n    }\n  };\n  /**\n   * Adjusts the timestamp information for the segment to account for\n   * rollover and convert to seconds based on pes packet timescale (90khz clock)\n   */\n\n  var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {\n    if (segmentInfo.audio && segmentInfo.audio.length) {\n      var audioBaseTimestamp = baseTimestamp;\n      if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {\n        audioBaseTimestamp = segmentInfo.audio[0].dts;\n      }\n      segmentInfo.audio.forEach(function (info) {\n        info.dts = handleRollover(info.dts, audioBaseTimestamp);\n        info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds\n\n        info.dtsTime = info.dts / ONE_SECOND_IN_TS;\n        info.ptsTime = info.pts / ONE_SECOND_IN_TS;\n      });\n    }\n    if (segmentInfo.video && segmentInfo.video.length) {\n      var videoBaseTimestamp = baseTimestamp;\n      if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {\n        videoBaseTimestamp = segmentInfo.video[0].dts;\n      }\n      segmentInfo.video.forEach(function (info) {\n        info.dts = handleRollover(info.dts, videoBaseTimestamp);\n        info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds\n\n        info.dtsTime = info.dts / ONE_SECOND_IN_TS;\n        info.ptsTime = info.pts / ONE_SECOND_IN_TS;\n      });\n      if (segmentInfo.firstKeyFrame) {\n        var frame = segmentInfo.firstKeyFrame;\n        frame.dts = handleRollover(frame.dts, videoBaseTimestamp);\n        frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds\n\n        frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;\n        frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;\n      }\n    }\n  };\n  /**\n   * inspects the aac data stream for start and end time information\n   */\n\n  var inspectAac_ = function (bytes) {\n    var endLoop = false,\n      audioCount = 0,\n      sampleRate = null,\n      timestamp = null,\n      frameSize = 0,\n      byteIndex = 0,\n      packet;\n    while (bytes.length - byteIndex >= 3) {\n      var type = probe.aac.parseType(bytes, byteIndex);\n      switch (type) {\n        case 'timed-metadata':\n          // Exit early because we don't have enough to parse\n          // the ID3 tag header\n          if (bytes.length - byteIndex < 10) {\n            endLoop = true;\n            break;\n          }\n          frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer\n          // to emit a full packet\n\n          if (frameSize > bytes.length) {\n            endLoop = true;\n            break;\n          }\n          if (timestamp === null) {\n            packet = bytes.subarray(byteIndex, byteIndex + frameSize);\n            timestamp = probe.aac.parseAacTimestamp(packet);\n          }\n          byteIndex += frameSize;\n          break;\n        case 'audio':\n          // Exit early because we don't have enough to parse\n          // the ADTS frame header\n          if (bytes.length - byteIndex < 7) {\n            endLoop = true;\n            break;\n          }\n          frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer\n          // to emit a full packet\n\n          if (frameSize > bytes.length) {\n            endLoop = true;\n            break;\n          }\n          if (sampleRate === null) {\n            packet = bytes.subarray(byteIndex, byteIndex + frameSize);\n            sampleRate = probe.aac.parseSampleRate(packet);\n          }\n          audioCount++;\n          byteIndex += frameSize;\n          break;\n        default:\n          byteIndex++;\n          break;\n      }\n      if (endLoop) {\n        return null;\n      }\n    }\n    if (sampleRate === null || timestamp === null) {\n      return null;\n    }\n    var audioTimescale = ONE_SECOND_IN_TS / sampleRate;\n    var result = {\n      audio: [{\n        type: 'audio',\n        dts: timestamp,\n        pts: timestamp\n      }, {\n        type: 'audio',\n        dts: timestamp + audioCount * 1024 * audioTimescale,\n        pts: timestamp + audioCount * 1024 * audioTimescale\n      }]\n    };\n    return result;\n  };\n  /**\n   * inspects the transport stream segment data for start and end time information\n   * of the audio and video tracks (when present) as well as the first key frame's\n   * start time.\n   */\n\n  var inspectTs_ = function (bytes) {\n    var pmt = {\n      pid: null,\n      table: null\n    };\n    var result = {};\n    parsePsi_(bytes, pmt);\n    for (var pid in pmt.table) {\n      if (pmt.table.hasOwnProperty(pid)) {\n        var type = pmt.table[pid];\n        switch (type) {\n          case StreamTypes.H264_STREAM_TYPE:\n            result.video = [];\n            parseVideoPes_(bytes, pmt, result);\n            if (result.video.length === 0) {\n              delete result.video;\n            }\n            break;\n          case StreamTypes.ADTS_STREAM_TYPE:\n            result.audio = [];\n            parseAudioPes_(bytes, pmt, result);\n            if (result.audio.length === 0) {\n              delete result.audio;\n            }\n            break;\n        }\n      }\n    }\n    return result;\n  };\n  /**\n   * Inspects segment byte data and returns an object with start and end timing information\n   *\n   * @param {Uint8Array} bytes The segment byte data\n   * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame\n   *  timestamps for rollover. This value must be in 90khz clock.\n   * @return {Object} Object containing start and end frame timing info of segment.\n   */\n\n  var inspect = function (bytes, baseTimestamp) {\n    var isAacData = probe.aac.isLikelyAacData(bytes);\n    var result;\n    if (isAacData) {\n      result = inspectAac_(bytes);\n    } else {\n      result = inspectTs_(bytes);\n    }\n    if (!result || !result.audio && !result.video) {\n      return null;\n    }\n    adjustTimestamp_(result, baseTimestamp);\n    return result;\n  };\n  var tsInspector = {\n    inspect: inspect,\n    parseAudioPes_: parseAudioPes_\n  };\n  /* global self */\n\n  /**\n   * Re-emits transmuxer events by converting them into messages to the\n   * world outside the worker.\n   *\n   * @param {Object} transmuxer the transmuxer to wire events on\n   * @private\n   */\n\n  const wireTransmuxerEvents = function (self, transmuxer) {\n    transmuxer.on('data', function (segment) {\n      // transfer ownership of the underlying ArrayBuffer\n      // instead of doing a copy to save memory\n      // ArrayBuffers are transferable but generic TypedArrays are not\n      // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)\n      const initArray = segment.initSegment;\n      segment.initSegment = {\n        data: initArray.buffer,\n        byteOffset: initArray.byteOffset,\n        byteLength: initArray.byteLength\n      };\n      const typedArray = segment.data;\n      segment.data = typedArray.buffer;\n      self.postMessage({\n        action: 'data',\n        segment,\n        byteOffset: typedArray.byteOffset,\n        byteLength: typedArray.byteLength\n      }, [segment.data]);\n    });\n    transmuxer.on('done', function (data) {\n      self.postMessage({\n        action: 'done'\n      });\n    });\n    transmuxer.on('gopInfo', function (gopInfo) {\n      self.postMessage({\n        action: 'gopInfo',\n        gopInfo\n      });\n    });\n    transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {\n      const videoSegmentTimingInfo = {\n        start: {\n          decode: clock$2.videoTsToSeconds(timingInfo.start.dts),\n          presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)\n        },\n        end: {\n          decode: clock$2.videoTsToSeconds(timingInfo.end.dts),\n          presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)\n        },\n        baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)\n      };\n      if (timingInfo.prependedContentDuration) {\n        videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);\n      }\n      self.postMessage({\n        action: 'videoSegmentTimingInfo',\n        videoSegmentTimingInfo\n      });\n    });\n    transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {\n      // Note that all times for [audio/video]SegmentTimingInfo events are in video clock\n      const audioSegmentTimingInfo = {\n        start: {\n          decode: clock$2.videoTsToSeconds(timingInfo.start.dts),\n          presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)\n        },\n        end: {\n          decode: clock$2.videoTsToSeconds(timingInfo.end.dts),\n          presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)\n        },\n        baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)\n      };\n      if (timingInfo.prependedContentDuration) {\n        audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);\n      }\n      self.postMessage({\n        action: 'audioSegmentTimingInfo',\n        audioSegmentTimingInfo\n      });\n    });\n    transmuxer.on('id3Frame', function (id3Frame) {\n      self.postMessage({\n        action: 'id3Frame',\n        id3Frame\n      });\n    });\n    transmuxer.on('caption', function (caption) {\n      self.postMessage({\n        action: 'caption',\n        caption\n      });\n    });\n    transmuxer.on('trackinfo', function (trackInfo) {\n      self.postMessage({\n        action: 'trackinfo',\n        trackInfo\n      });\n    });\n    transmuxer.on('audioTimingInfo', function (audioTimingInfo) {\n      // convert to video TS since we prioritize video time over audio\n      self.postMessage({\n        action: 'audioTimingInfo',\n        audioTimingInfo: {\n          start: clock$2.videoTsToSeconds(audioTimingInfo.start),\n          end: clock$2.videoTsToSeconds(audioTimingInfo.end)\n        }\n      });\n    });\n    transmuxer.on('videoTimingInfo', function (videoTimingInfo) {\n      self.postMessage({\n        action: 'videoTimingInfo',\n        videoTimingInfo: {\n          start: clock$2.videoTsToSeconds(videoTimingInfo.start),\n          end: clock$2.videoTsToSeconds(videoTimingInfo.end)\n        }\n      });\n    });\n    transmuxer.on('log', function (log) {\n      self.postMessage({\n        action: 'log',\n        log\n      });\n    });\n  };\n  /**\n   * All incoming messages route through this hash. If no function exists\n   * to handle an incoming message, then we ignore the message.\n   *\n   * @class MessageHandlers\n   * @param {Object} options the options to initialize with\n   */\n\n  class MessageHandlers {\n    constructor(self, options) {\n      this.options = options || {};\n      this.self = self;\n      this.init();\n    }\n    /**\n     * initialize our web worker and wire all the events.\n     */\n\n    init() {\n      if (this.transmuxer) {\n        this.transmuxer.dispose();\n      }\n      this.transmuxer = new transmuxer.Transmuxer(this.options);\n      wireTransmuxerEvents(this.self, this.transmuxer);\n    }\n    pushMp4Captions(data) {\n      if (!this.captionParser) {\n        this.captionParser = new captionParser();\n        this.captionParser.init();\n      }\n      const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);\n      const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);\n      this.self.postMessage({\n        action: 'mp4Captions',\n        captions: parsed && parsed.captions || [],\n        logs: parsed && parsed.logs || [],\n        data: segment.buffer\n      }, [segment.buffer]);\n    }\n    /**\n     * Initializes the WebVttParser and passes the init segment.\n     *\n     * @param {Uint8Array} data mp4 boxed WebVTT init segment data\n     */\n\n    initMp4WebVttParser(data) {\n      if (!this.webVttParser) {\n        this.webVttParser = new webvttParser();\n      }\n      const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength); // Set the timescale for the parser.\n      // This can be called repeatedly in order to set and re-set the timescale.\n\n      this.webVttParser.init(segment);\n    }\n    /**\n     * Parse an mp4 encapsulated WebVTT segment and return an array of cues.\n     *\n     * @param {Uint8Array} data a text/webvtt segment\n     * @return {Object[]} an array of parsed cue objects\n     */\n\n    getMp4WebVttText(data) {\n      if (!this.webVttParser) {\n        // timescale might not be set yet if the parser is created before an init segment is passed.\n        // default timescale is 90k.\n        this.webVttParser = new webvttParser();\n      }\n      const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);\n      const parsed = this.webVttParser.parseSegment(segment);\n      this.self.postMessage({\n        action: 'getMp4WebVttText',\n        mp4VttCues: parsed || [],\n        data: segment.buffer\n      }, [segment.buffer]);\n    }\n    probeMp4StartTime({\n      timescales,\n      data\n    }) {\n      const startTime = probe$2.startTime(timescales, data);\n      this.self.postMessage({\n        action: 'probeMp4StartTime',\n        startTime,\n        data\n      }, [data.buffer]);\n    }\n    probeMp4Tracks({\n      data\n    }) {\n      const tracks = probe$2.tracks(data);\n      this.self.postMessage({\n        action: 'probeMp4Tracks',\n        tracks,\n        data\n      }, [data.buffer]);\n    }\n    /**\n     * Probes an mp4 segment for EMSG boxes containing ID3 data.\n     * https://aomediacodec.github.io/id3-emsg/\n     *\n     * @param {Uint8Array} data segment data\n     * @param {number} offset segment start time\n     * @return {Object[]} an array of ID3 frames\n     */\n\n    probeEmsgID3({\n      data,\n      offset\n    }) {\n      const id3Frames = probe$2.getEmsgID3(data, offset);\n      this.self.postMessage({\n        action: 'probeEmsgID3',\n        id3Frames,\n        emsgData: data\n      }, [data.buffer]);\n    }\n    /**\n     * Probe an mpeg2-ts segment to determine the start time of the segment in it's\n     * internal \"media time,\" as well as whether it contains video and/or audio.\n     *\n     * @private\n     * @param {Uint8Array} bytes - segment bytes\n     * @param {number} baseStartTime\n     *        Relative reference timestamp used when adjusting frame timestamps for rollover.\n     *        This value should be in seconds, as it's converted to a 90khz clock within the\n     *        function body.\n     * @return {Object} The start time of the current segment in \"media time\" as well as\n     *                  whether it contains video and/or audio\n     */\n\n    probeTs({\n      data,\n      baseStartTime\n    }) {\n      const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;\n      const timeInfo = tsInspector.inspect(data, tsStartTime);\n      let result = null;\n      if (timeInfo) {\n        result = {\n          // each type's time info comes back as an array of 2 times, start and end\n          hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,\n          hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false\n        };\n        if (result.hasVideo) {\n          result.videoStart = timeInfo.video[0].ptsTime;\n        }\n        if (result.hasAudio) {\n          result.audioStart = timeInfo.audio[0].ptsTime;\n        }\n      }\n      this.self.postMessage({\n        action: 'probeTs',\n        result,\n        data\n      }, [data.buffer]);\n    }\n    clearAllMp4Captions() {\n      if (this.captionParser) {\n        this.captionParser.clearAllCaptions();\n      }\n    }\n    clearParsedMp4Captions() {\n      if (this.captionParser) {\n        this.captionParser.clearParsedCaptions();\n      }\n    }\n    /**\n     * Adds data (a ts segment) to the start of the transmuxer pipeline for\n     * processing.\n     *\n     * @param {ArrayBuffer} data data to push into the muxer\n     */\n\n    push(data) {\n      // Cast array buffer to correct type for transmuxer\n      const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);\n      this.transmuxer.push(segment);\n    }\n    /**\n     * Recreate the transmuxer so that the next segment added via `push`\n     * start with a fresh transmuxer.\n     */\n\n    reset() {\n      this.transmuxer.reset();\n    }\n    /**\n     * Set the value that will be used as the `baseMediaDecodeTime` time for the\n     * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`\n     * set relative to the first based on the PTS values.\n     *\n     * @param {Object} data used to set the timestamp offset in the muxer\n     */\n\n    setTimestampOffset(data) {\n      const timestampOffset = data.timestampOffset || 0;\n      this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));\n    }\n    setAudioAppendStart(data) {\n      this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));\n    }\n    setRemux(data) {\n      this.transmuxer.setRemux(data.remux);\n    }\n    /**\n     * Forces the pipeline to finish processing the last segment and emit it's\n     * results.\n     *\n     * @param {Object} data event data, not really used\n     */\n\n    flush(data) {\n      this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed\n\n      self.postMessage({\n        action: 'done',\n        type: 'transmuxed'\n      });\n    }\n    endTimeline() {\n      this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their\n      // timelines\n\n      self.postMessage({\n        action: 'endedtimeline',\n        type: 'transmuxed'\n      });\n    }\n    alignGopsWith(data) {\n      this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());\n    }\n  }\n  /**\n   * Our web worker interface so that things can talk to mux.js\n   * that will be running in a web worker. the scope is passed to this by\n   * webworkify.\n   *\n   * @param {Object} self the scope for the web worker\n   */\n\n  self.onmessage = function (event) {\n    if (event.data.action === 'init' && event.data.options) {\n      this.messageHandlers = new MessageHandlers(self, event.data.options);\n      return;\n    }\n    if (!this.messageHandlers) {\n      this.messageHandlers = new MessageHandlers(self);\n    }\n    if (event.data && event.data.action && event.data.action !== 'init') {\n      if (this.messageHandlers[event.data.action]) {\n        this.messageHandlers[event.data.action](event.data);\n      }\n    }\n  };\n}));\nvar TransmuxWorker = factory(workerCode$1);\n/* rollup-plugin-worker-factory end for worker!/home/runner/work/http-streaming/http-streaming/src/transmuxer-worker.js */\n\nconst handleData_ = (event, transmuxedData, callback) => {\n  const {\n    type,\n    initSegment,\n    captions,\n    captionStreams,\n    metadata,\n    videoFrameDtsTime,\n    videoFramePtsTime\n  } = event.data.segment;\n  transmuxedData.buffer.push({\n    captions,\n    captionStreams,\n    metadata\n  });\n  const boxes = event.data.segment.boxes || {\n    data: event.data.segment.data\n  };\n  const result = {\n    type,\n    // cast ArrayBuffer to TypedArray\n    data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),\n    initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)\n  };\n  if (typeof videoFrameDtsTime !== 'undefined') {\n    result.videoFrameDtsTime = videoFrameDtsTime;\n  }\n  if (typeof videoFramePtsTime !== 'undefined') {\n    result.videoFramePtsTime = videoFramePtsTime;\n  }\n  callback(result);\n};\nconst handleDone_ = ({\n  transmuxedData,\n  callback\n}) => {\n  // Previously we only returned data on data events,\n  // not on done events. Clear out the buffer to keep that consistent.\n  transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we\n  // have received\n\n  callback(transmuxedData);\n};\nconst handleGopInfo_ = (event, transmuxedData) => {\n  transmuxedData.gopInfo = event.data.gopInfo;\n};\nconst processTransmux = options => {\n  const {\n    transmuxer,\n    bytes,\n    audioAppendStart,\n    gopsToAlignWith,\n    remux,\n    onData,\n    onTrackInfo,\n    onAudioTimingInfo,\n    onVideoTimingInfo,\n    onVideoSegmentTimingInfo,\n    onAudioSegmentTimingInfo,\n    onId3,\n    onCaptions,\n    onDone,\n    onEndedTimeline,\n    onTransmuxerLog,\n    isEndOfTimeline,\n    segment,\n    triggerSegmentEventFn\n  } = options;\n  const transmuxedData = {\n    buffer: []\n  };\n  let waitForEndedTimelineEvent = isEndOfTimeline;\n  const handleMessage = event => {\n    if (transmuxer.currentTransmux !== options) {\n      // disposed\n      return;\n    }\n    if (event.data.action === 'data') {\n      handleData_(event, transmuxedData, onData);\n    }\n    if (event.data.action === 'trackinfo') {\n      onTrackInfo(event.data.trackInfo);\n    }\n    if (event.data.action === 'gopInfo') {\n      handleGopInfo_(event, transmuxedData);\n    }\n    if (event.data.action === 'audioTimingInfo') {\n      onAudioTimingInfo(event.data.audioTimingInfo);\n    }\n    if (event.data.action === 'videoTimingInfo') {\n      onVideoTimingInfo(event.data.videoTimingInfo);\n    }\n    if (event.data.action === 'videoSegmentTimingInfo') {\n      onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);\n    }\n    if (event.data.action === 'audioSegmentTimingInfo') {\n      onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);\n    }\n    if (event.data.action === 'id3Frame') {\n      onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);\n    }\n    if (event.data.action === 'caption') {\n      onCaptions(event.data.caption);\n    }\n    if (event.data.action === 'endedtimeline') {\n      waitForEndedTimelineEvent = false;\n      onEndedTimeline();\n    }\n    if (event.data.action === 'log') {\n      onTransmuxerLog(event.data.log);\n    } // wait for the transmuxed event since we may have audio and video\n\n    if (event.data.type !== 'transmuxed') {\n      return;\n    } // If the \"endedtimeline\" event has not yet fired, and this segment represents the end\n    // of a timeline, that means there may still be data events before the segment\n    // processing can be considerred complete. In that case, the final event should be\n    // an \"endedtimeline\" event with the type \"transmuxed.\"\n\n    if (waitForEndedTimelineEvent) {\n      return;\n    }\n    transmuxer.onmessage = null;\n    handleDone_({\n      transmuxedData,\n      callback: onDone\n    });\n    /* eslint-disable no-use-before-define */\n\n    dequeue(transmuxer);\n    /* eslint-enable */\n  };\n  const handleError = () => {\n    const error = {\n      message: 'Received an error message from the transmuxer worker',\n      metadata: {\n        errorType: videojs.Error.StreamingFailedToTransmuxSegment,\n        segmentInfo: segmentInfoPayload({\n          segment\n        })\n      }\n    };\n    onDone(null, error);\n  };\n  transmuxer.onmessage = handleMessage;\n  transmuxer.onerror = handleError;\n  if (audioAppendStart) {\n    transmuxer.postMessage({\n      action: 'setAudioAppendStart',\n      appendStart: audioAppendStart\n    });\n  } // allow empty arrays to be passed to clear out GOPs\n\n  if (Array.isArray(gopsToAlignWith)) {\n    transmuxer.postMessage({\n      action: 'alignGopsWith',\n      gopsToAlignWith\n    });\n  }\n  if (typeof remux !== 'undefined') {\n    transmuxer.postMessage({\n      action: 'setRemux',\n      remux\n    });\n  }\n  if (bytes.byteLength) {\n    const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;\n    const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;\n    triggerSegmentEventFn({\n      type: 'segmenttransmuxingstart',\n      segment\n    });\n    transmuxer.postMessage({\n      action: 'push',\n      // Send the typed-array of data as an ArrayBuffer so that\n      // it can be sent as a \"Transferable\" and avoid the costly\n      // memory copy\n      data: buffer,\n      // To recreate the original typed-array, we need information\n      // about what portion of the ArrayBuffer it was a view into\n      byteOffset,\n      byteLength: bytes.byteLength\n    }, [buffer]);\n  }\n  if (isEndOfTimeline) {\n    transmuxer.postMessage({\n      action: 'endTimeline'\n    });\n  } // even if we didn't push any bytes, we have to make sure we flush in case we reached\n  // the end of the segment\n\n  transmuxer.postMessage({\n    action: 'flush'\n  });\n};\nconst dequeue = transmuxer => {\n  transmuxer.currentTransmux = null;\n  if (transmuxer.transmuxQueue.length) {\n    transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();\n    if (typeof transmuxer.currentTransmux === 'function') {\n      transmuxer.currentTransmux();\n    } else {\n      processTransmux(transmuxer.currentTransmux);\n    }\n  }\n};\nconst processAction = (transmuxer, action) => {\n  transmuxer.postMessage({\n    action\n  });\n  dequeue(transmuxer);\n};\nconst enqueueAction = (action, transmuxer) => {\n  if (!transmuxer.currentTransmux) {\n    transmuxer.currentTransmux = action;\n    processAction(transmuxer, action);\n    return;\n  }\n  transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));\n};\nconst reset = transmuxer => {\n  enqueueAction('reset', transmuxer);\n};\nconst endTimeline = transmuxer => {\n  enqueueAction('endTimeline', transmuxer);\n};\nconst transmux = options => {\n  if (!options.transmuxer.currentTransmux) {\n    options.transmuxer.currentTransmux = options;\n    processTransmux(options);\n    return;\n  }\n  options.transmuxer.transmuxQueue.push(options);\n};\nconst createTransmuxer = options => {\n  const transmuxer = new TransmuxWorker();\n  transmuxer.currentTransmux = null;\n  transmuxer.transmuxQueue = [];\n  const term = transmuxer.terminate;\n  transmuxer.terminate = () => {\n    transmuxer.currentTransmux = null;\n    transmuxer.transmuxQueue.length = 0;\n    return term.call(transmuxer);\n  };\n  transmuxer.postMessage({\n    action: 'init',\n    options\n  });\n  return transmuxer;\n};\nvar segmentTransmuxer = {\n  reset,\n  endTimeline,\n  transmux,\n  createTransmuxer\n};\nconst workerCallback = function (options) {\n  const transmuxer = options.transmuxer;\n  const endAction = options.endAction || options.action;\n  const callback = options.callback;\n  const message = _extends({}, options, {\n    endAction: null,\n    transmuxer: null,\n    callback: null\n  });\n  const listenForEndEvent = event => {\n    if (event.data.action !== endAction) {\n      return;\n    }\n    transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.\n\n    if (event.data.data) {\n      event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);\n      if (options.data) {\n        options.data = event.data.data;\n      }\n    }\n    callback(event.data);\n  };\n  transmuxer.addEventListener('message', listenForEndEvent);\n  if (options.data) {\n    const isArrayBuffer = options.data instanceof ArrayBuffer;\n    message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;\n    message.byteLength = options.data.byteLength;\n    const transfers = [isArrayBuffer ? options.data : options.data.buffer];\n    transmuxer.postMessage(message, transfers);\n  } else {\n    transmuxer.postMessage(message);\n  }\n};\nconst REQUEST_ERRORS = {\n  FAILURE: 2,\n  TIMEOUT: -101,\n  ABORTED: -102\n};\nconst WEB_VTT_CODEC = 'wvtt';\n/**\n * Abort all requests\n *\n * @param {Object} activeXhrs - an object that tracks all XHR requests\n */\n\nconst abortAll = activeXhrs => {\n  activeXhrs.forEach(xhr => {\n    xhr.abort();\n  });\n};\n/**\n * Gather important bandwidth stats once a request has completed\n *\n * @param {Object} request - the XHR request from which to gather stats\n */\n\nconst getRequestStats = request => {\n  return {\n    bandwidth: request.bandwidth,\n    bytesReceived: request.bytesReceived || 0,\n    roundTripTime: request.roundTripTime || 0\n  };\n};\n/**\n * If possible gather bandwidth stats as a request is in\n * progress\n *\n * @param {Event} progressEvent - an event object from an XHR's progress event\n */\n\nconst getProgressStats = progressEvent => {\n  const request = progressEvent.target;\n  const roundTripTime = Date.now() - request.requestTime;\n  const stats = {\n    bandwidth: Infinity,\n    bytesReceived: 0,\n    roundTripTime: roundTripTime || 0\n  };\n  stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok\n  // because we should only use bandwidth stats on progress to determine when\n  // abort a request early due to insufficient bandwidth\n\n  stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);\n  return stats;\n};\n/**\n * Handle all error conditions in one place and return an object\n * with all the information\n *\n * @param {Error|null} error - if non-null signals an error occured with the XHR\n * @param {Object} request -  the XHR request that possibly generated the error\n */\n\nconst handleErrors = (error, request) => {\n  const {\n    requestType\n  } = request;\n  const metadata = getStreamingNetworkErrorMetadata({\n    requestType,\n    request,\n    error\n  });\n  if (request.timedout) {\n    return {\n      status: request.status,\n      message: 'HLS request timed-out at URL: ' + request.uri,\n      code: REQUEST_ERRORS.TIMEOUT,\n      xhr: request,\n      metadata\n    };\n  }\n  if (request.aborted) {\n    return {\n      status: request.status,\n      message: 'HLS request aborted at URL: ' + request.uri,\n      code: REQUEST_ERRORS.ABORTED,\n      xhr: request,\n      metadata\n    };\n  }\n  if (error) {\n    return {\n      status: request.status,\n      message: 'HLS request errored at URL: ' + request.uri,\n      code: REQUEST_ERRORS.FAILURE,\n      xhr: request,\n      metadata\n    };\n  }\n  if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {\n    return {\n      status: request.status,\n      message: 'Empty HLS response at URL: ' + request.uri,\n      code: REQUEST_ERRORS.FAILURE,\n      xhr: request,\n      metadata\n    };\n  }\n  return null;\n};\n/**\n * Handle responses for key data and convert the key data to the correct format\n * for the decryption step later\n *\n * @param {Object} segment - a simplified copy of the segmentInfo object\n *                           from SegmentLoader\n * @param {Array} objects - objects to add the key bytes to.\n * @param {Function} finishProcessingFn - a callback to execute to continue processing\n *                                        this request\n */\n\nconst handleKeyResponse = (segment, objects, finishProcessingFn, triggerSegmentEventFn) => (error, request) => {\n  const response = request.response;\n  const errorObj = handleErrors(error, request);\n  if (errorObj) {\n    return finishProcessingFn(errorObj, segment);\n  }\n  if (response.byteLength !== 16) {\n    return finishProcessingFn({\n      status: request.status,\n      message: 'Invalid HLS key at URL: ' + request.uri,\n      code: REQUEST_ERRORS.FAILURE,\n      xhr: request\n    }, segment);\n  }\n  const view = new DataView(response);\n  const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);\n  for (let i = 0; i < objects.length; i++) {\n    objects[i].bytes = bytes;\n  }\n  const keyInfo = {\n    uri: request.uri\n  };\n  triggerSegmentEventFn({\n    type: 'segmentkeyloadcomplete',\n    segment,\n    keyInfo\n  });\n  return finishProcessingFn(null, segment);\n};\n/**\n * Processes an mp4 init segment depending on the codec through the transmuxer.\n *\n * @param {Object} segment init segment to process\n * @param {string} codec the codec of the text segments\n */\n\nconst initMp4Text = (segment, codec) => {\n  if (codec === WEB_VTT_CODEC) {\n    segment.transmuxer.postMessage({\n      action: 'initMp4WebVttParser',\n      data: segment.map.bytes\n    });\n  }\n};\n/**\n * Parses an mp4 text segment with the transmuxer and calls the doneFn from\n * the segment loader.\n *\n * @param {Object} segment the text segment to parse\n * @param {string} codec the codec of the text segment\n * @param {Function} doneFn the doneFn passed from the segment loader\n */\n\nconst parseMp4TextSegment = (segment, codec, doneFn) => {\n  if (codec === WEB_VTT_CODEC) {\n    workerCallback({\n      action: 'getMp4WebVttText',\n      data: segment.bytes,\n      transmuxer: segment.transmuxer,\n      callback: ({\n        data,\n        mp4VttCues\n      }) => {\n        segment.bytes = data;\n        doneFn(null, segment, {\n          mp4VttCues\n        });\n      }\n    });\n  }\n};\nconst parseInitSegment = (segment, callback) => {\n  const type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we\n  // only know how to parse mp4 init segments at the moment\n\n  if (type !== 'mp4') {\n    const uri = segment.map.resolvedUri || segment.map.uri;\n    const mediaType = type || 'unknown';\n    return callback({\n      internal: true,\n      message: `Found unsupported ${mediaType} container for initialization segment at URL: ${uri}`,\n      code: REQUEST_ERRORS.FAILURE,\n      metadata: {\n        mediaType\n      }\n    });\n  }\n  workerCallback({\n    action: 'probeMp4Tracks',\n    data: segment.map.bytes,\n    transmuxer: segment.transmuxer,\n    callback: ({\n      tracks,\n      data\n    }) => {\n      // transfer bytes back to us\n      segment.map.bytes = data;\n      tracks.forEach(function (track) {\n        segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now\n\n        if (segment.map.tracks[track.type]) {\n          return;\n        }\n        segment.map.tracks[track.type] = track;\n        if (typeof track.id === 'number' && track.timescale) {\n          segment.map.timescales = segment.map.timescales || {};\n          segment.map.timescales[track.id] = track.timescale;\n        }\n        if (track.type === 'text') {\n          initMp4Text(segment, track.codec);\n        }\n      });\n      return callback(null);\n    }\n  });\n};\n/**\n * Handle init-segment responses\n *\n * @param {Object} segment - a simplified copy of the segmentInfo object\n *                           from SegmentLoader\n * @param {Function} finishProcessingFn - a callback to execute to continue processing\n *                                        this request\n */\n\nconst handleInitSegmentResponse = ({\n  segment,\n  finishProcessingFn,\n  triggerSegmentEventFn\n}) => (error, request) => {\n  const errorObj = handleErrors(error, request);\n  if (errorObj) {\n    return finishProcessingFn(errorObj, segment);\n  }\n  const bytes = new Uint8Array(request.response);\n  triggerSegmentEventFn({\n    type: 'segmentloaded',\n    segment\n  }); // init segment is encypted, we will have to wait\n  // until the key request is done to decrypt.\n\n  if (segment.map.key) {\n    segment.map.encryptedBytes = bytes;\n    return finishProcessingFn(null, segment);\n  }\n  segment.map.bytes = bytes;\n  parseInitSegment(segment, function (parseError) {\n    if (parseError) {\n      parseError.xhr = request;\n      parseError.status = request.status;\n      return finishProcessingFn(parseError, segment);\n    }\n    finishProcessingFn(null, segment);\n  });\n};\n/**\n * Response handler for segment-requests being sure to set the correct\n * property depending on whether the segment is encryped or not\n * Also records and keeps track of stats that are used for ABR purposes\n *\n * @param {Object} segment - a simplified copy of the segmentInfo object\n *                           from SegmentLoader\n * @param {Function} finishProcessingFn - a callback to execute to continue processing\n *                                        this request\n */\n\nconst handleSegmentResponse = ({\n  segment,\n  finishProcessingFn,\n  responseType,\n  triggerSegmentEventFn\n}) => (error, request) => {\n  const errorObj = handleErrors(error, request);\n  if (errorObj) {\n    return finishProcessingFn(errorObj, segment);\n  }\n  triggerSegmentEventFn({\n    type: 'segmentloaded',\n    segment\n  });\n  const newBytes =\n  // although responseText \"should\" exist, this guard serves to prevent an error being\n  // thrown for two primary cases:\n  // 1. the mime type override stops working, or is not implemented for a specific\n  //    browser\n  // 2. when using mock XHR libraries like sinon that do not allow the override behavior\n  responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));\n  segment.stats = getRequestStats(request);\n  if (segment.key) {\n    segment.encryptedBytes = new Uint8Array(newBytes);\n  } else {\n    segment.bytes = new Uint8Array(newBytes);\n  }\n  return finishProcessingFn(null, segment);\n};\nconst transmuxAndNotify = ({\n  segment,\n  bytes,\n  trackInfoFn,\n  timingInfoFn,\n  videoSegmentTimingInfoFn,\n  audioSegmentTimingInfoFn,\n  id3Fn,\n  captionsFn,\n  isEndOfTimeline,\n  endedTimelineFn,\n  dataFn,\n  doneFn,\n  onTransmuxerLog,\n  triggerSegmentEventFn\n}) => {\n  const fmp4Tracks = segment.map && segment.map.tracks || {};\n  const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.\n  // One reason for this is that in the case of full segments, we want to trust start\n  // times from the probe, rather than the transmuxer.\n\n  let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');\n  const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');\n  let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');\n  const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');\n  const finish = () => transmux({\n    bytes,\n    transmuxer: segment.transmuxer,\n    audioAppendStart: segment.audioAppendStart,\n    gopsToAlignWith: segment.gopsToAlignWith,\n    remux: isMuxed,\n    onData: result => {\n      result.type = result.type === 'combined' ? 'video' : result.type;\n      dataFn(segment, result);\n    },\n    onTrackInfo: trackInfo => {\n      if (trackInfoFn) {\n        if (isMuxed) {\n          trackInfo.isMuxed = true;\n        }\n        trackInfoFn(segment, trackInfo);\n      }\n    },\n    onAudioTimingInfo: audioTimingInfo => {\n      // we only want the first start value we encounter\n      if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {\n        audioStartFn(audioTimingInfo.start);\n        audioStartFn = null;\n      } // we want to continually update the end time\n\n      if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {\n        audioEndFn(audioTimingInfo.end);\n      }\n    },\n    onVideoTimingInfo: videoTimingInfo => {\n      // we only want the first start value we encounter\n      if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {\n        videoStartFn(videoTimingInfo.start);\n        videoStartFn = null;\n      } // we want to continually update the end time\n\n      if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {\n        videoEndFn(videoTimingInfo.end);\n      }\n    },\n    onVideoSegmentTimingInfo: videoSegmentTimingInfo => {\n      const timingInfo = {\n        pts: {\n          start: videoSegmentTimingInfo.start.presentation,\n          end: videoSegmentTimingInfo.end.presentation\n        },\n        dts: {\n          start: videoSegmentTimingInfo.start.decode,\n          end: videoSegmentTimingInfo.end.decode\n        }\n      };\n      triggerSegmentEventFn({\n        type: 'segmenttransmuxingtiminginfoavailable',\n        segment,\n        timingInfo\n      });\n      videoSegmentTimingInfoFn(videoSegmentTimingInfo);\n    },\n    onAudioSegmentTimingInfo: audioSegmentTimingInfo => {\n      const timingInfo = {\n        pts: {\n          start: audioSegmentTimingInfo.start.pts,\n          end: audioSegmentTimingInfo.end.pts\n        },\n        dts: {\n          start: audioSegmentTimingInfo.start.dts,\n          end: audioSegmentTimingInfo.end.dts\n        }\n      };\n      triggerSegmentEventFn({\n        type: 'segmenttransmuxingtiminginfoavailable',\n        segment,\n        timingInfo\n      });\n      audioSegmentTimingInfoFn(audioSegmentTimingInfo);\n    },\n    onId3: (id3Frames, dispatchType) => {\n      id3Fn(segment, id3Frames, dispatchType);\n    },\n    onCaptions: captions => {\n      captionsFn(segment, [captions]);\n    },\n    isEndOfTimeline,\n    onEndedTimeline: () => {\n      endedTimelineFn();\n    },\n    onTransmuxerLog,\n    onDone: (result, error) => {\n      if (!doneFn) {\n        return;\n      }\n      result.type = result.type === 'combined' ? 'video' : result.type;\n      triggerSegmentEventFn({\n        type: 'segmenttransmuxingcomplete',\n        segment\n      });\n      doneFn(error, segment, result);\n    },\n    segment,\n    triggerSegmentEventFn\n  }); // In the transmuxer, we don't yet have the ability to extract a \"proper\" start time.\n  // Meaning cached frame data may corrupt our notion of where this segment\n  // really starts. To get around this, probe for the info needed.\n\n  workerCallback({\n    action: 'probeTs',\n    transmuxer: segment.transmuxer,\n    data: bytes,\n    baseStartTime: segment.baseStartTime,\n    callback: data => {\n      segment.bytes = bytes = data.data;\n      const probeResult = data.result;\n      if (probeResult) {\n        trackInfoFn(segment, {\n          hasAudio: probeResult.hasAudio,\n          hasVideo: probeResult.hasVideo,\n          isMuxed\n        });\n        trackInfoFn = null;\n      }\n      finish();\n    }\n  });\n};\nconst handleSegmentBytes = ({\n  segment,\n  bytes,\n  trackInfoFn,\n  timingInfoFn,\n  videoSegmentTimingInfoFn,\n  audioSegmentTimingInfoFn,\n  id3Fn,\n  captionsFn,\n  isEndOfTimeline,\n  endedTimelineFn,\n  dataFn,\n  doneFn,\n  onTransmuxerLog,\n  triggerSegmentEventFn\n}) => {\n  let bytesAsUint8Array = new Uint8Array(bytes); // TODO:\n  // We should have a handler that fetches the number of bytes required\n  // to check if something is fmp4. This will allow us to save bandwidth\n  // because we can only exclude a playlist and abort requests\n  // by codec after trackinfo triggers.\n\n  if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {\n    segment.isFmp4 = true;\n    const {\n      tracks\n    } = segment.map;\n    const isMp4TextSegment = tracks.text && (!tracks.audio || !tracks.video);\n    if (isMp4TextSegment) {\n      dataFn(segment, {\n        data: bytesAsUint8Array,\n        type: 'text'\n      });\n      parseMp4TextSegment(segment, tracks.text.codec, doneFn);\n      return;\n    }\n    const trackInfo = {\n      isFmp4: true,\n      hasVideo: !!tracks.video,\n      hasAudio: !!tracks.audio\n    }; // if we have a audio track, with a codec that is not set to\n    // encrypted audio\n\n    if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {\n      trackInfo.audioCodec = tracks.audio.codec;\n    } // if we have a video track, with a codec that is not set to\n    // encrypted video\n\n    if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {\n      trackInfo.videoCodec = tracks.video.codec;\n    }\n    if (tracks.video && tracks.audio) {\n      trackInfo.isMuxed = true;\n    } // since we don't support appending fmp4 data on progress, we know we have the full\n    // segment here\n\n    trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start\n    // time. The end time can be roughly calculated by the receiver using the duration.\n    //\n    // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as\n    // that is the true start of the segment (where the playback engine should begin\n    // decoding).\n\n    const finishLoading = (captions, id3Frames) => {\n      // if the track still has audio at this point it is only possible\n      // for it to be audio only. See `tracks.video && tracks.audio` if statement\n      // above.\n      // we make sure to use segment.bytes here as that\n      dataFn(segment, {\n        data: bytesAsUint8Array,\n        type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'\n      });\n      if (id3Frames && id3Frames.length) {\n        id3Fn(segment, id3Frames);\n      }\n      if (captions && captions.length) {\n        captionsFn(segment, captions);\n      }\n      doneFn(null, segment, {});\n    };\n    workerCallback({\n      action: 'probeMp4StartTime',\n      timescales: segment.map.timescales,\n      data: bytesAsUint8Array,\n      transmuxer: segment.transmuxer,\n      callback: ({\n        data,\n        startTime\n      }) => {\n        // transfer bytes back to us\n        bytes = data.buffer;\n        segment.bytes = bytesAsUint8Array = data;\n        if (trackInfo.hasAudio && !trackInfo.isMuxed) {\n          timingInfoFn(segment, 'audio', 'start', startTime);\n        }\n        if (trackInfo.hasVideo) {\n          timingInfoFn(segment, 'video', 'start', startTime);\n        }\n        workerCallback({\n          action: 'probeEmsgID3',\n          data: bytesAsUint8Array,\n          transmuxer: segment.transmuxer,\n          offset: startTime,\n          callback: ({\n            emsgData,\n            id3Frames\n          }) => {\n            // transfer bytes back to us\n            bytes = emsgData.buffer;\n            segment.bytes = bytesAsUint8Array = emsgData; // Run through the CaptionParser in case there are captions.\n            // Initialize CaptionParser if it hasn't been yet\n\n            if (!tracks.video || !emsgData.byteLength || !segment.transmuxer) {\n              finishLoading(undefined, id3Frames);\n              return;\n            }\n            workerCallback({\n              action: 'pushMp4Captions',\n              endAction: 'mp4Captions',\n              transmuxer: segment.transmuxer,\n              data: bytesAsUint8Array,\n              timescales: segment.map.timescales,\n              trackIds: [tracks.video.id],\n              callback: message => {\n                // transfer bytes back to us\n                bytes = message.data.buffer;\n                segment.bytes = bytesAsUint8Array = message.data;\n                message.logs.forEach(function (log) {\n                  onTransmuxerLog(merge(log, {\n                    stream: 'mp4CaptionParser'\n                  }));\n                });\n                finishLoading(message.captions, id3Frames);\n              }\n            });\n          }\n        });\n      }\n    });\n    return;\n  } // VTT or other segments that don't need processing\n\n  if (!segment.transmuxer) {\n    doneFn(null, segment, {});\n    return;\n  }\n  if (typeof segment.container === 'undefined') {\n    segment.container = detectContainerForBytes(bytesAsUint8Array);\n  }\n  if (segment.container !== 'ts' && segment.container !== 'aac') {\n    trackInfoFn(segment, {\n      hasAudio: false,\n      hasVideo: false\n    });\n    doneFn(null, segment, {});\n    return;\n  } // ts or aac\n\n  transmuxAndNotify({\n    segment,\n    bytes,\n    trackInfoFn,\n    timingInfoFn,\n    videoSegmentTimingInfoFn,\n    audioSegmentTimingInfoFn,\n    id3Fn,\n    captionsFn,\n    isEndOfTimeline,\n    endedTimelineFn,\n    dataFn,\n    doneFn,\n    onTransmuxerLog,\n    triggerSegmentEventFn\n  });\n};\nconst decrypt = function ({\n  id,\n  key,\n  encryptedBytes,\n  decryptionWorker,\n  segment,\n  doneFn\n}, callback) {\n  const decryptionHandler = event => {\n    if (event.data.source === id) {\n      decryptionWorker.removeEventListener('message', decryptionHandler);\n      const decrypted = event.data.decrypted;\n      callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));\n    }\n  };\n  decryptionWorker.onerror = () => {\n    const message = 'An error occurred in the decryption worker';\n    const segmentInfo = segmentInfoPayload({\n      segment\n    });\n    const decryptError = {\n      message,\n      metadata: {\n        error: new Error(message),\n        errorType: videojs.Error.StreamingFailedToDecryptSegment,\n        segmentInfo,\n        keyInfo: {\n          uri: segment.key.resolvedUri || segment.map.key.resolvedUri\n        }\n      }\n    };\n    doneFn(decryptError, segment);\n  };\n  decryptionWorker.addEventListener('message', decryptionHandler);\n  let keyBytes;\n  if (key.bytes.slice) {\n    keyBytes = key.bytes.slice();\n  } else {\n    keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));\n  } // incrementally decrypt the bytes\n\n  decryptionWorker.postMessage(createTransferableMessage({\n    source: id,\n    encrypted: encryptedBytes,\n    key: keyBytes,\n    iv: key.iv\n  }), [encryptedBytes.buffer, keyBytes.buffer]);\n};\n/**\n * Decrypt the segment via the decryption web worker\n *\n * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption\n *                                       routines\n * @param {Object} segment - a simplified copy of the segmentInfo object\n *                           from SegmentLoader\n * @param {Function} trackInfoFn - a callback that receives track info\n * @param {Function} timingInfoFn - a callback that receives timing info\n * @param {Function} videoSegmentTimingInfoFn\n *                   a callback that receives video timing info based on media times and\n *                   any adjustments made by the transmuxer\n * @param {Function} audioSegmentTimingInfoFn\n *                   a callback that receives audio timing info based on media times and\n *                   any adjustments made by the transmuxer\n * @param {boolean}  isEndOfTimeline\n *                   true if this segment represents the last segment in a timeline\n * @param {Function} endedTimelineFn\n *                   a callback made when a timeline is ended, will only be called if\n *                   isEndOfTimeline is true\n * @param {Function} dataFn - a callback that is executed when segment bytes are available\n *                            and ready to use\n * @param {Function} doneFn - a callback that is executed after decryption has completed\n */\n\nconst decryptSegment = ({\n  decryptionWorker,\n  segment,\n  trackInfoFn,\n  timingInfoFn,\n  videoSegmentTimingInfoFn,\n  audioSegmentTimingInfoFn,\n  id3Fn,\n  captionsFn,\n  isEndOfTimeline,\n  endedTimelineFn,\n  dataFn,\n  doneFn,\n  onTransmuxerLog,\n  triggerSegmentEventFn\n}) => {\n  triggerSegmentEventFn({\n    type: 'segmentdecryptionstart'\n  });\n  decrypt({\n    id: segment.requestId,\n    key: segment.key,\n    encryptedBytes: segment.encryptedBytes,\n    decryptionWorker,\n    segment,\n    doneFn\n  }, decryptedBytes => {\n    segment.bytes = decryptedBytes;\n    triggerSegmentEventFn({\n      type: 'segmentdecryptioncomplete',\n      segment\n    });\n    handleSegmentBytes({\n      segment,\n      bytes: segment.bytes,\n      trackInfoFn,\n      timingInfoFn,\n      videoSegmentTimingInfoFn,\n      audioSegmentTimingInfoFn,\n      id3Fn,\n      captionsFn,\n      isEndOfTimeline,\n      endedTimelineFn,\n      dataFn,\n      doneFn,\n      onTransmuxerLog,\n      triggerSegmentEventFn\n    });\n  });\n};\n/**\n * This function waits for all XHRs to finish (with either success or failure)\n * before continueing processing via it's callback. The function gathers errors\n * from each request into a single errors array so that the error status for\n * each request can be examined later.\n *\n * @param {Object} activeXhrs - an object that tracks all XHR requests\n * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption\n *                                       routines\n * @param {Function} trackInfoFn - a callback that receives track info\n * @param {Function} timingInfoFn - a callback that receives timing info\n * @param {Function} videoSegmentTimingInfoFn\n *                   a callback that receives video timing info based on media times and\n *                   any adjustments made by the transmuxer\n * @param {Function} audioSegmentTimingInfoFn\n *                   a callback that receives audio timing info based on media times and\n *                   any adjustments made by the transmuxer\n * @param {Function} id3Fn - a callback that receives ID3 metadata\n * @param {Function} captionsFn - a callback that receives captions\n * @param {boolean}  isEndOfTimeline\n *                   true if this segment represents the last segment in a timeline\n * @param {Function} endedTimelineFn\n *                   a callback made when a timeline is ended, will only be called if\n *                   isEndOfTimeline is true\n * @param {Function} dataFn - a callback that is executed when segment bytes are available\n *                            and ready to use\n * @param {Function} doneFn - a callback that is executed after all resources have been\n *                            downloaded and any decryption completed\n */\n\nconst waitForCompletion = ({\n  activeXhrs,\n  decryptionWorker,\n  trackInfoFn,\n  timingInfoFn,\n  videoSegmentTimingInfoFn,\n  audioSegmentTimingInfoFn,\n  id3Fn,\n  captionsFn,\n  isEndOfTimeline,\n  endedTimelineFn,\n  dataFn,\n  doneFn,\n  onTransmuxerLog,\n  triggerSegmentEventFn\n}) => {\n  let count = 0;\n  let didError = false;\n  return (error, segment) => {\n    if (didError) {\n      return;\n    }\n    if (error) {\n      didError = true; // If there are errors, we have to abort any outstanding requests\n\n      abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we\n      // handle the aborted events from those requests, there are some cases where we may\n      // never get an aborted event. For instance, if the network connection is lost and\n      // there were two requests, the first may have triggered an error immediately, while\n      // the second request remains unsent. In that case, the aborted algorithm will not\n      // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method\n      //\n      // We also can't rely on the ready state of the XHR, since the request that\n      // triggered the connection error may also show as a ready state of 0 (unsent).\n      // Therefore, we have to finish this group of requests immediately after the first\n      // seen error.\n\n      return doneFn(error, segment);\n    }\n    count += 1;\n    if (count === activeXhrs.length) {\n      const segmentFinish = function () {\n        if (segment.encryptedBytes) {\n          return decryptSegment({\n            decryptionWorker,\n            segment,\n            trackInfoFn,\n            timingInfoFn,\n            videoSegmentTimingInfoFn,\n            audioSegmentTimingInfoFn,\n            id3Fn,\n            captionsFn,\n            isEndOfTimeline,\n            endedTimelineFn,\n            dataFn,\n            doneFn,\n            onTransmuxerLog,\n            triggerSegmentEventFn\n          });\n        } // Otherwise, everything is ready just continue\n\n        handleSegmentBytes({\n          segment,\n          bytes: segment.bytes,\n          trackInfoFn,\n          timingInfoFn,\n          videoSegmentTimingInfoFn,\n          audioSegmentTimingInfoFn,\n          id3Fn,\n          captionsFn,\n          isEndOfTimeline,\n          endedTimelineFn,\n          dataFn,\n          doneFn,\n          onTransmuxerLog,\n          triggerSegmentEventFn\n        });\n      }; // Keep track of when *all* of the requests have completed\n\n      segment.endOfAllRequests = Date.now();\n      if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {\n        triggerSegmentEventFn({\n          type: 'segmentdecryptionstart',\n          segment\n        });\n        return decrypt({\n          decryptionWorker,\n          // add -init to the \"id\" to differentiate between segment\n          // and init segment decryption, just in case they happen\n          // at the same time at some point in the future.\n          id: segment.requestId + '-init',\n          encryptedBytes: segment.map.encryptedBytes,\n          key: segment.map.key,\n          segment,\n          doneFn\n        }, decryptedBytes => {\n          segment.map.bytes = decryptedBytes;\n          triggerSegmentEventFn({\n            type: 'segmentdecryptioncomplete',\n            segment\n          });\n          parseInitSegment(segment, parseError => {\n            if (parseError) {\n              abortAll(activeXhrs);\n              return doneFn(parseError, segment);\n            }\n            segmentFinish();\n          });\n        });\n      }\n      segmentFinish();\n    }\n  };\n};\n/**\n * Calls the abort callback if any request within the batch was aborted. Will only call\n * the callback once per batch of requests, even if multiple were aborted.\n *\n * @param {Object} loadendState - state to check to see if the abort function was called\n * @param {Function} abortFn - callback to call for abort\n */\n\nconst handleLoadEnd = ({\n  loadendState,\n  abortFn\n}) => event => {\n  const request = event.target;\n  if (request.aborted && abortFn && !loadendState.calledAbortFn) {\n    abortFn();\n    loadendState.calledAbortFn = true;\n  }\n};\n/**\n * Simple progress event callback handler that gathers some stats before\n * executing a provided callback with the `segment` object\n *\n * @param {Object} segment - a simplified copy of the segmentInfo object\n *                           from SegmentLoader\n * @param {Function} progressFn - a callback that is executed each time a progress event\n *                                is received\n * @param {Function} trackInfoFn - a callback that receives track info\n * @param {Function} timingInfoFn - a callback that receives timing info\n * @param {Function} videoSegmentTimingInfoFn\n *                   a callback that receives video timing info based on media times and\n *                   any adjustments made by the transmuxer\n * @param {Function} audioSegmentTimingInfoFn\n *                   a callback that receives audio timing info based on media times and\n *                   any adjustments made by the transmuxer\n * @param {boolean}  isEndOfTimeline\n *                   true if this segment represents the last segment in a timeline\n * @param {Function} endedTimelineFn\n *                   a callback made when a timeline is ended, will only be called if\n *                   isEndOfTimeline is true\n * @param {Function} dataFn - a callback that is executed when segment bytes are available\n *                            and ready to use\n * @param {Event} event - the progress event object from XMLHttpRequest\n */\n\nconst handleProgress = ({\n  segment,\n  progressFn,\n  trackInfoFn,\n  timingInfoFn,\n  videoSegmentTimingInfoFn,\n  audioSegmentTimingInfoFn,\n  id3Fn,\n  captionsFn,\n  isEndOfTimeline,\n  endedTimelineFn,\n  dataFn\n}) => event => {\n  const request = event.target;\n  if (request.aborted) {\n    return;\n  }\n  segment.stats = merge(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data\n\n  if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {\n    segment.stats.firstBytesReceivedAt = Date.now();\n  }\n  return progressFn(event, segment);\n};\n/**\n * Load all resources and does any processing necessary for a media-segment\n *\n * Features:\n *   decrypts the media-segment if it has a key uri and an iv\n *   aborts *all* requests if *any* one request fails\n *\n * The segment object, at minimum, has the following format:\n * {\n *   resolvedUri: String,\n *   [transmuxer]: Object,\n *   [byterange]: {\n *     offset: Number,\n *     length: Number\n *   },\n *   [key]: {\n *     resolvedUri: String\n *     [byterange]: {\n *       offset: Number,\n *       length: Number\n *     },\n *     iv: {\n *       bytes: Uint32Array\n *     }\n *   },\n *   [map]: {\n *     resolvedUri: String,\n *     [byterange]: {\n *       offset: Number,\n *       length: Number\n *     },\n *     [bytes]: Uint8Array\n *   }\n * }\n * ...where [name] denotes optional properties\n *\n * @param {Function} xhr - an instance of the xhr wrapper in xhr.js\n * @param {Object} xhrOptions - the base options to provide to all xhr requests\n * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128\n *                                       decryption routines\n * @param {Object} segment - a simplified copy of the segmentInfo object\n *                           from SegmentLoader\n * @param {Function} abortFn - a callback called (only once) if any piece of a request was\n *                             aborted\n * @param {Function} progressFn - a callback that receives progress events from the main\n *                                segment's xhr request\n * @param {Function} trackInfoFn - a callback that receives track info\n * @param {Function} timingInfoFn - a callback that receives timing info\n * @param {Function} videoSegmentTimingInfoFn\n *                   a callback that receives video timing info based on media times and\n *                   any adjustments made by the transmuxer\n * @param {Function} audioSegmentTimingInfoFn\n *                   a callback that receives audio timing info based on media times and\n *                   any adjustments made by the transmuxer\n * @param {Function} id3Fn - a callback that receives ID3 metadata\n * @param {Function} captionsFn - a callback that receives captions\n * @param {boolean}  isEndOfTimeline\n *                   true if this segment represents the last segment in a timeline\n * @param {Function} endedTimelineFn\n *                   a callback made when a timeline is ended, will only be called if\n *                   isEndOfTimeline is true\n * @param {Function} dataFn - a callback that receives data from the main segment's xhr\n *                            request, transmuxed if needed\n * @param {Function} doneFn - a callback that is executed only once all requests have\n *                            succeeded or failed\n * @return {Function} a function that, when invoked, immediately aborts all\n *                     outstanding requests\n */\n\nconst mediaSegmentRequest = ({\n  xhr,\n  xhrOptions,\n  decryptionWorker,\n  segment,\n  abortFn,\n  progressFn,\n  trackInfoFn,\n  timingInfoFn,\n  videoSegmentTimingInfoFn,\n  audioSegmentTimingInfoFn,\n  id3Fn,\n  captionsFn,\n  isEndOfTimeline,\n  endedTimelineFn,\n  dataFn,\n  doneFn,\n  onTransmuxerLog,\n  triggerSegmentEventFn\n}) => {\n  const activeXhrs = [];\n  const finishProcessingFn = waitForCompletion({\n    activeXhrs,\n    decryptionWorker,\n    trackInfoFn,\n    timingInfoFn,\n    videoSegmentTimingInfoFn,\n    audioSegmentTimingInfoFn,\n    id3Fn,\n    captionsFn,\n    isEndOfTimeline,\n    endedTimelineFn,\n    dataFn,\n    doneFn,\n    onTransmuxerLog,\n    triggerSegmentEventFn\n  }); // optionally, request the decryption key\n\n  if (segment.key && !segment.key.bytes) {\n    const objects = [segment.key];\n    if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {\n      objects.push(segment.map.key);\n    }\n    const keyRequestOptions = merge(xhrOptions, {\n      uri: segment.key.resolvedUri,\n      responseType: 'arraybuffer',\n      requestType: 'segment-key'\n    });\n    const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn, triggerSegmentEventFn);\n    const keyInfo = {\n      uri: segment.key.resolvedUri\n    };\n    triggerSegmentEventFn({\n      type: 'segmentkeyloadstart',\n      segment,\n      keyInfo\n    });\n    const keyXhr = xhr(keyRequestOptions, keyRequestCallback);\n    activeXhrs.push(keyXhr);\n  } // optionally, request the associated media init segment\n\n  if (segment.map && !segment.map.bytes) {\n    const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);\n    if (differentMapKey) {\n      const mapKeyRequestOptions = merge(xhrOptions, {\n        uri: segment.map.key.resolvedUri,\n        responseType: 'arraybuffer',\n        requestType: 'segment-key'\n      });\n      const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn, triggerSegmentEventFn);\n      const keyInfo = {\n        uri: segment.map.key.resolvedUri\n      };\n      triggerSegmentEventFn({\n        type: 'segmentkeyloadstart',\n        segment,\n        keyInfo\n      });\n      const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);\n      activeXhrs.push(mapKeyXhr);\n    }\n    const initSegmentOptions = merge(xhrOptions, {\n      uri: segment.map.resolvedUri,\n      responseType: 'arraybuffer',\n      headers: segmentXhrHeaders(segment.map),\n      requestType: 'segment-media-initialization'\n    });\n    const initSegmentRequestCallback = handleInitSegmentResponse({\n      segment,\n      finishProcessingFn,\n      triggerSegmentEventFn\n    });\n    triggerSegmentEventFn({\n      type: 'segmentloadstart',\n      segment\n    });\n    const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);\n    activeXhrs.push(initSegmentXhr);\n  }\n  const segmentRequestOptions = merge(xhrOptions, {\n    uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,\n    responseType: 'arraybuffer',\n    headers: segmentXhrHeaders(segment),\n    requestType: 'segment'\n  });\n  const segmentRequestCallback = handleSegmentResponse({\n    segment,\n    finishProcessingFn,\n    responseType: segmentRequestOptions.responseType,\n    triggerSegmentEventFn\n  });\n  triggerSegmentEventFn({\n    type: 'segmentloadstart',\n    segment\n  });\n  const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);\n  segmentXhr.addEventListener('progress', handleProgress({\n    segment,\n    progressFn,\n    trackInfoFn,\n    timingInfoFn,\n    videoSegmentTimingInfoFn,\n    audioSegmentTimingInfoFn,\n    id3Fn,\n    captionsFn,\n    isEndOfTimeline,\n    endedTimelineFn,\n    dataFn\n  }));\n  activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks\n  // multiple times, provide a shared state object\n\n  const loadendState = {};\n  activeXhrs.forEach(activeXhr => {\n    activeXhr.addEventListener('loadend', handleLoadEnd({\n      loadendState,\n      abortFn\n    }));\n  });\n  return () => abortAll(activeXhrs);\n};\nconst logFn = logger('PlaylistSelector');\nconst representationToString = function (representation) {\n  if (!representation || !representation.playlist) {\n    return;\n  }\n  const playlist = representation.playlist;\n  return JSON.stringify({\n    id: playlist.id,\n    bandwidth: representation.bandwidth,\n    width: representation.width,\n    height: representation.height,\n    codecs: playlist.attributes && playlist.attributes.CODECS || ''\n  });\n}; // Utilities\n\n/**\n * Returns the CSS value for the specified property on an element\n * using `getComputedStyle`. Firefox has a long-standing issue where\n * getComputedStyle() may return null when running in an iframe with\n * `display: none`.\n *\n * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397\n * @param {HTMLElement} el the htmlelement to work on\n * @param {string} the proprety to get the style for\n */\n\nconst safeGetComputedStyle = function (el, property) {\n  if (!el) {\n    return '';\n  }\n  const result = window$1.getComputedStyle(el);\n  if (!result) {\n    return '';\n  }\n  return result[property];\n};\n/**\n * Resuable stable sort function\n *\n * @param {Playlists} array\n * @param {Function} sortFn Different comparators\n * @function stableSort\n */\n\nconst stableSort = function (array, sortFn) {\n  const newArray = array.slice();\n  array.sort(function (left, right) {\n    const cmp = sortFn(left, right);\n    if (cmp === 0) {\n      return newArray.indexOf(left) - newArray.indexOf(right);\n    }\n    return cmp;\n  });\n};\n/**\n * A comparator function to sort two playlist object by bandwidth.\n *\n * @param {Object} left a media playlist object\n * @param {Object} right a media playlist object\n * @return {number} Greater than zero if the bandwidth attribute of\n * left is greater than the corresponding attribute of right. Less\n * than zero if the bandwidth of right is greater than left and\n * exactly zero if the two are equal.\n */\n\nconst comparePlaylistBandwidth = function (left, right) {\n  let leftBandwidth;\n  let rightBandwidth;\n  if (left.attributes.BANDWIDTH) {\n    leftBandwidth = left.attributes.BANDWIDTH;\n  }\n  leftBandwidth = leftBandwidth || window$1.Number.MAX_VALUE;\n  if (right.attributes.BANDWIDTH) {\n    rightBandwidth = right.attributes.BANDWIDTH;\n  }\n  rightBandwidth = rightBandwidth || window$1.Number.MAX_VALUE;\n  return leftBandwidth - rightBandwidth;\n};\n/**\n * A comparator function to sort two playlist object by resolution (width).\n *\n * @param {Object} left a media playlist object\n * @param {Object} right a media playlist object\n * @return {number} Greater than zero if the resolution.width attribute of\n * left is greater than the corresponding attribute of right. Less\n * than zero if the resolution.width of right is greater than left and\n * exactly zero if the two are equal.\n */\n\nconst comparePlaylistResolution = function (left, right) {\n  let leftWidth;\n  let rightWidth;\n  if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {\n    leftWidth = left.attributes.RESOLUTION.width;\n  }\n  leftWidth = leftWidth || window$1.Number.MAX_VALUE;\n  if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {\n    rightWidth = right.attributes.RESOLUTION.width;\n  }\n  rightWidth = rightWidth || window$1.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions\n  // have the same media dimensions/ resolution\n\n  if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {\n    return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;\n  }\n  return leftWidth - rightWidth;\n};\n/**\n * Chooses the appropriate media playlist based on bandwidth and player size\n *\n * @param {Object} settings\n *        Object of information required to use this selector\n * @param {Object} settings.main\n *        Object representation of the main manifest\n * @param {number} settings.bandwidth\n *        Current calculated bandwidth of the player\n * @param {number} settings.playerWidth\n *        Current width of the player element (should account for the device pixel ratio)\n * @param {number} settings.playerHeight\n *        Current height of the player element (should account for the device pixel ratio)\n * @param {number} settings.playerObjectFit\n *        Current value of the video element's object-fit CSS property. Allows taking into\n *        account that the video might be scaled up to cover the media element when selecting\n *        media playlists based on player size.\n * @param {boolean} settings.limitRenditionByPlayerDimensions\n *        True if the player width and height should be used during the selection, false otherwise\n * @param {Object} settings.playlistController\n *        the current playlistController object\n * @return {Playlist} the highest bitrate playlist less than the\n * currently detected bandwidth, accounting for some amount of\n * bandwidth variance\n */\n\nlet simpleSelector = function (settings) {\n  const {\n    main,\n    bandwidth: playerBandwidth,\n    playerWidth,\n    playerHeight,\n    playerObjectFit,\n    limitRenditionByPlayerDimensions,\n    playlistController\n  } = settings; // If we end up getting called before `main` is available, exit early\n\n  if (!main) {\n    return;\n  }\n  const options = {\n    bandwidth: playerBandwidth,\n    width: playerWidth,\n    height: playerHeight,\n    limitRenditionByPlayerDimensions\n  };\n  let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.\n\n  if (Playlist.isAudioOnly(main)) {\n    playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true\n    // at the buttom of this function for debugging.\n\n    options.audioOnly = true;\n  } // convert the playlists to an intermediary representation to make comparisons easier\n\n  let sortedPlaylistReps = playlists.map(playlist => {\n    let bandwidth;\n    const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;\n    const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;\n    bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;\n    bandwidth = bandwidth || window$1.Number.MAX_VALUE;\n    return {\n      bandwidth,\n      width,\n      height,\n      playlist\n    };\n  });\n  stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to\n  // incompatible configurations\n\n  sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations\n  // api or excluded temporarily due to playback errors.\n\n  let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));\n  if (!enabledPlaylistReps.length) {\n    // if there are no enabled playlists, then they have all been excluded or disabled\n    // by the user through the representations api. In this case, ignore exclusion and\n    // fallback to what the user wants by using playlists the user has not disabled.\n    enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));\n  } // filter out any variant that has greater effective bitrate\n  // than the current estimated bandwidth\n\n  const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);\n  let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth\n  // and then taking the very first element\n\n  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.\n\n  if (limitRenditionByPlayerDimensions === false) {\n    const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];\n    if (chosenRep && chosenRep.playlist) {\n      let type = 'sortedPlaylistReps';\n      if (bandwidthBestRep) {\n        type = 'bandwidthBestRep';\n      }\n      if (enabledPlaylistReps[0]) {\n        type = 'enabledPlaylistReps';\n      }\n      logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);\n      return chosenRep.playlist;\n    }\n    logFn('could not choose a playlist with options', options);\n    return null;\n  } // filter out playlists without resolution information\n\n  const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution\n\n  stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it\n\n  const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);\n  highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution\n\n  const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];\n  let resolutionPlusOneList;\n  let resolutionPlusOneSmallest;\n  let resolutionPlusOneRep; // find the smallest variant that is larger than the player\n  // if there is no match of exact resolution\n\n  if (!resolutionBestRep) {\n    resolutionPlusOneList = haveResolution.filter(rep => {\n      if (playerObjectFit === 'cover') {\n        // video will be scaled up to cover the player. We need to\n        // make sure rendition is at least as wide and as high as the\n        // player.\n        return rep.width > playerWidth && rep.height > playerHeight;\n      } // video will be scaled down to fit inside the player soon as\n      // its resolution exceeds player size in at least one dimension.\n\n      return rep.width > playerWidth || rep.height > playerHeight;\n    }); // find all the variants have the same smallest resolution\n\n    resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that\n    // is just-larger-than the video player\n\n    highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];\n    resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];\n  }\n  let leastPixelDiffRep; // If this selector proves to be better than others,\n  // resolutionPlusOneRep and resolutionBestRep and all\n  // the code involving them should be removed.\n\n  if (playlistController.leastPixelDiffSelector) {\n    // find the variant that is closest to the player's pixel size\n    const leastPixelDiffList = haveResolution.map(rep => {\n      rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);\n      return rep;\n    }); // get the highest bandwidth, closest resolution playlist\n\n    stableSort(leastPixelDiffList, (left, right) => {\n      // sort by highest bandwidth if pixelDiff is the same\n      if (left.pixelDiff === right.pixelDiff) {\n        return right.bandwidth - left.bandwidth;\n      }\n      return left.pixelDiff - right.pixelDiff;\n    });\n    leastPixelDiffRep = leastPixelDiffList[0];\n  } // fallback chain of variants\n\n  const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];\n  if (chosenRep && chosenRep.playlist) {\n    let type = 'sortedPlaylistReps';\n    if (leastPixelDiffRep) {\n      type = 'leastPixelDiffRep';\n    } else if (resolutionPlusOneRep) {\n      type = 'resolutionPlusOneRep';\n    } else if (resolutionBestRep) {\n      type = 'resolutionBestRep';\n    } else if (bandwidthBestRep) {\n      type = 'bandwidthBestRep';\n    } else if (enabledPlaylistReps[0]) {\n      type = 'enabledPlaylistReps';\n    }\n    logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);\n    return chosenRep.playlist;\n  }\n  logFn('could not choose a playlist with options', options);\n  return null;\n};\n\n/**\n * Chooses the appropriate media playlist based on the most recent\n * bandwidth estimate and the player size.\n *\n * Expects to be called within the context of an instance of VhsHandler\n *\n * @return {Playlist} the highest bitrate playlist less than the\n * currently detected bandwidth, accounting for some amount of\n * bandwidth variance\n */\n\nconst lastBandwidthSelector = function () {\n  let pixelRatio = this.useDevicePixelRatio ? window$1.devicePixelRatio || 1 : 1;\n  if (!isNaN(this.customPixelRatio)) {\n    pixelRatio = this.customPixelRatio;\n  }\n  return simpleSelector({\n    main: this.playlists.main,\n    bandwidth: this.systemBandwidth,\n    playerWidth: parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio,\n    playerHeight: parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio,\n    playerObjectFit: this.usePlayerObjectFit ? safeGetComputedStyle(this.tech_.el(), 'objectFit') : '',\n    limitRenditionByPlayerDimensions: this.limitRenditionByPlayerDimensions,\n    playlistController: this.playlistController_\n  });\n};\n/**\n * Chooses the appropriate media playlist based on an\n * exponential-weighted moving average of the bandwidth after\n * filtering for player size.\n *\n * Expects to be called within the context of an instance of VhsHandler\n *\n * @param {number} decay - a number between 0 and 1. Higher values of\n * this parameter will cause previous bandwidth estimates to lose\n * significance more quickly.\n * @return {Function} a function which can be invoked to create a new\n * playlist selector function.\n * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n */\n\nconst movingAverageBandwidthSelector = function (decay) {\n  let average = -1;\n  let lastSystemBandwidth = -1;\n  if (decay < 0 || decay > 1) {\n    throw new Error('Moving average bandwidth decay must be between 0 and 1.');\n  }\n  return function () {\n    let pixelRatio = this.useDevicePixelRatio ? window$1.devicePixelRatio || 1 : 1;\n    if (!isNaN(this.customPixelRatio)) {\n      pixelRatio = this.customPixelRatio;\n    }\n    if (average < 0) {\n      average = this.systemBandwidth;\n      lastSystemBandwidth = this.systemBandwidth;\n    } // stop the average value from decaying for every 250ms\n    // when the systemBandwidth is constant\n    // and\n    // stop average from setting to a very low value when the\n    // systemBandwidth becomes 0 in case of chunk cancellation\n\n    if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {\n      average = decay * this.systemBandwidth + (1 - decay) * average;\n      lastSystemBandwidth = this.systemBandwidth;\n    }\n    return simpleSelector({\n      main: this.playlists.main,\n      bandwidth: average,\n      playerWidth: parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio,\n      playerHeight: parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio,\n      playerObjectFit: this.usePlayerObjectFit ? safeGetComputedStyle(this.tech_.el(), 'objectFit') : '',\n      limitRenditionByPlayerDimensions: this.limitRenditionByPlayerDimensions,\n      playlistController: this.playlistController_\n    });\n  };\n};\n/**\n * Chooses the appropriate media playlist based on the potential to rebuffer\n *\n * @param {Object} settings\n *        Object of information required to use this selector\n * @param {Object} settings.main\n *        Object representation of the main manifest\n * @param {number} settings.currentTime\n *        The current time of the player\n * @param {number} settings.bandwidth\n *        Current measured bandwidth\n * @param {number} settings.duration\n *        Duration of the media\n * @param {number} settings.segmentDuration\n *        Segment duration to be used in round trip time calculations\n * @param {number} settings.timeUntilRebuffer\n *        Time left in seconds until the player has to rebuffer\n * @param {number} settings.currentTimeline\n *        The current timeline segments are being loaded from\n * @param {SyncController} settings.syncController\n *        SyncController for determining if we have a sync point for a given playlist\n * @return {Object|null}\n *         {Object} return.playlist\n *         The highest bandwidth playlist with the least amount of rebuffering\n *         {Number} return.rebufferingImpact\n *         The amount of time in seconds switching to this playlist will rebuffer. A\n *         negative value means that switching will cause zero rebuffering.\n */\n\nconst minRebufferMaxBandwidthSelector = function (settings) {\n  const {\n    main,\n    currentTime,\n    bandwidth,\n    duration,\n    segmentDuration,\n    timeUntilRebuffer,\n    currentTimeline,\n    syncController\n  } = settings; // filter out any playlists that have been excluded due to\n  // incompatible configurations\n\n  const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations\n  // api or excluded temporarily due to playback errors.\n\n  let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);\n  if (!enabledPlaylists.length) {\n    // if there are no enabled playlists, then they have all been excluded or disabled\n    // by the user through the representations api. In this case, ignore exclusion and\n    // fallback to what the user wants by using playlists the user has not disabled.\n    enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));\n  }\n  const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));\n  const rebufferingEstimates = bandwidthPlaylists.map(playlist => {\n    const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a\n    // sync request first. This will double the request time\n\n    const numRequests = syncPoint ? 1 : 2;\n    const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);\n    const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;\n    return {\n      playlist,\n      rebufferingImpact\n    };\n  });\n  const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC\n\n  stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));\n  if (noRebufferingPlaylists.length) {\n    return noRebufferingPlaylists[0];\n  }\n  stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);\n  return rebufferingEstimates[0] || null;\n};\n/**\n * Chooses the appropriate media playlist, which in this case is the lowest bitrate\n * one with video.  If no renditions with video exist, return the lowest audio rendition.\n *\n * Expects to be called within the context of an instance of VhsHandler\n *\n * @return {Object|null}\n *         {Object} return.playlist\n *         The lowest bitrate playlist that contains a video codec.  If no such rendition\n *         exists pick the lowest audio rendition.\n */\n\nconst lowestBitrateCompatibleVariantSelector = function () {\n  // filter out any playlists that have been excluded due to\n  // incompatible configurations or playback errors\n  const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate\n\n  stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video\n  // (this is not necessarily true, although it is generally true).\n  //\n  // If an entire manifest has no valid videos everything will get filtered\n  // out.\n\n  const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);\n  return playlistsWithVideo[0] || null;\n};\n\n/**\n * Combine all segments into a single Uint8Array\n *\n * @param {Object} segmentObj\n * @return {Uint8Array} concatenated bytes\n * @private\n */\nconst concatSegments = segmentObj => {\n  let offset = 0;\n  let tempBuffer;\n  if (segmentObj.bytes) {\n    tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array\n\n    segmentObj.segments.forEach(segment => {\n      tempBuffer.set(segment, offset);\n      offset += segment.byteLength;\n    });\n  }\n  return tempBuffer;\n};\n/**\n * Example:\n * https://host.com/path1/path2/path3/segment.ts?arg1=val1\n * -->\n * path3/segment.ts\n *\n * @param resolvedUri\n * @return {string}\n */\n\nfunction compactSegmentUrlDescription(resolvedUri) {\n  try {\n    return new URL(resolvedUri).pathname.split('/').slice(-2).join('/');\n  } catch (e) {\n    return '';\n  }\n}\n\n/**\n * @file text-tracks.js\n */\n/**\n * Create captions text tracks on video.js if they do not exist\n *\n * @param {Object} inbandTextTracks a reference to current inbandTextTracks\n * @param {Object} tech the video.js tech\n * @param {Object} captionStream the caption stream to create\n * @private\n */\n\nconst createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {\n  if (!inbandTextTracks[captionStream]) {\n    tech.trigger({\n      type: 'usage',\n      name: 'vhs-608'\n    });\n    let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them\n\n    if (/^cc708_/.test(captionStream)) {\n      instreamId = 'SERVICE' + captionStream.split('_')[1];\n    }\n    const track = tech.textTracks().getTrackById(instreamId);\n    if (track) {\n      // Resuse an existing track with a CC# id because this was\n      // very likely created by videojs-contrib-hls from information\n      // in the m3u8 for us to use\n      inbandTextTracks[captionStream] = track;\n    } else {\n      // This section gets called when we have caption services that aren't specified in the manifest.\n      // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.\n      const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};\n      let label = captionStream;\n      let language = captionStream;\n      let def = false;\n      const captionService = captionServices[instreamId];\n      if (captionService) {\n        label = captionService.label;\n        language = captionService.language;\n        def = captionService.default;\n      } // Otherwise, create a track with the default `CC#` label and\n      // without a language\n\n      inbandTextTracks[captionStream] = tech.addRemoteTextTrack({\n        kind: 'captions',\n        id: instreamId,\n        // TODO: investigate why this doesn't seem to turn the caption on by default\n        default: def,\n        label,\n        language\n      }, false).track;\n    }\n  }\n};\n/**\n * Add caption text track data to a source handler given an array of captions\n *\n * @param {Object}\n *   @param {Object} inbandTextTracks the inband text tracks\n *   @param {number} timestampOffset the timestamp offset of the source buffer\n *   @param {Array} captionArray an array of caption data\n * @private\n */\n\nconst addCaptionData = function ({\n  inbandTextTracks,\n  captionArray,\n  timestampOffset\n}) {\n  if (!captionArray) {\n    return;\n  }\n  const Cue = window$1.WebKitDataCue || window$1.VTTCue;\n  captionArray.forEach(caption => {\n    const track = caption.stream; // in CEA 608 captions, video.js/mux.js sends a content array\n    // with positioning data\n\n    if (caption.content) {\n      caption.content.forEach(value => {\n        const cue = new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, value.text);\n        cue.line = value.line;\n        cue.align = 'left';\n        cue.position = value.position;\n        cue.positionAlign = 'line-left';\n        inbandTextTracks[track].addCue(cue);\n      });\n    } else {\n      // otherwise, a text value with combined captions is sent\n      inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));\n    }\n  });\n};\n/**\n * Define properties on a cue for backwards compatability,\n * but warn the user that the way that they are using it\n * is depricated and will be removed at a later date.\n *\n * @param {Cue} cue the cue to add the properties on\n * @private\n */\n\nconst deprecateOldCue = function (cue) {\n  Object.defineProperties(cue.frame, {\n    id: {\n      get() {\n        videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');\n        return cue.value.key;\n      }\n    },\n    value: {\n      get() {\n        videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');\n        return cue.value.data;\n      }\n    },\n    privateData: {\n      get() {\n        videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');\n        return cue.value.data;\n      }\n    }\n  });\n};\n/**\n * Add metadata text track data to a source handler given an array of metadata\n *\n * @param {Object}\n *   @param {Object} inbandTextTracks the inband text tracks\n *   @param {Array} metadataArray an array of meta data\n *   @param {number} timestampOffset the timestamp offset of the source buffer\n *   @param {number} videoDuration the duration of the video\n * @private\n */\n\nconst addMetadata = ({\n  inbandTextTracks,\n  metadataArray,\n  timestampOffset,\n  videoDuration\n}) => {\n  if (!metadataArray) {\n    return;\n  }\n  const Cue = window$1.WebKitDataCue || window$1.VTTCue;\n  const metadataTrack = inbandTextTracks.metadataTrack_;\n  if (!metadataTrack) {\n    return;\n  }\n  metadataArray.forEach(metadata => {\n    const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,\n    // ignore this bit of metadata.\n    // This likely occurs when you have an non-timed ID3 tag like TIT2,\n    // which is the \"Title/Songname/Content description\" frame\n\n    if (typeof time !== 'number' || window$1.isNaN(time) || time < 0 || !(time < Infinity)) {\n      return;\n    } // If we have no frames, we can't create a cue.\n\n    if (!metadata.frames || !metadata.frames.length) {\n      return;\n    }\n    metadata.frames.forEach(frame => {\n      const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');\n      cue.frame = frame;\n      cue.value = frame;\n      deprecateOldCue(cue);\n      metadataTrack.addCue(cue);\n    });\n  });\n  if (!metadataTrack.cues || !metadataTrack.cues.length) {\n    return;\n  } // Updating the metadeta cues so that\n  // the endTime of each cue is the startTime of the next cue\n  // the endTime of last cue is the duration of the video\n\n  const cues = metadataTrack.cues;\n  const cuesArray = []; // Create a copy of the TextTrackCueList...\n  // ...disregarding cues with a falsey value\n\n  for (let i = 0; i < cues.length; i++) {\n    if (cues[i]) {\n      cuesArray.push(cues[i]);\n    }\n  } // Group cues by their startTime value\n\n  const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {\n    const timeSlot = obj[cue.startTime] || [];\n    timeSlot.push(cue);\n    obj[cue.startTime] = timeSlot;\n    return obj;\n  }, {}); // Sort startTimes by ascending order\n\n  const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime\n\n  sortedStartTimes.forEach((startTime, idx) => {\n    const cueGroup = cuesGroupedByStartTime[startTime];\n    const finiteDuration = isFinite(videoDuration) ? videoDuration : startTime;\n    const nextTime = Number(sortedStartTimes[idx + 1]) || finiteDuration; // Map each cue's endTime the next group's startTime\n\n    cueGroup.forEach(cue => {\n      cue.endTime = nextTime;\n    });\n  });\n}; // object for mapping daterange attributes\n\nconst dateRangeAttr = {\n  id: 'ID',\n  class: 'CLASS',\n  startDate: 'START-DATE',\n  duration: 'DURATION',\n  endDate: 'END-DATE',\n  endOnNext: 'END-ON-NEXT',\n  plannedDuration: 'PLANNED-DURATION',\n  scte35Out: 'SCTE35-OUT',\n  scte35In: 'SCTE35-IN'\n};\nconst dateRangeKeysToOmit = new Set(['id', 'class', 'startDate', 'duration', 'endDate', 'endOnNext', 'startTime', 'endTime', 'processDateRange']);\n/**\n * Add DateRange metadata text track to a source handler given an array of metadata\n *\n * @param {Object}\n *   @param {Object} inbandTextTracks the inband text tracks\n *   @param {Array} dateRanges parsed media playlist\n * @private\n */\n\nconst addDateRangeMetadata = ({\n  inbandTextTracks,\n  dateRanges\n}) => {\n  const metadataTrack = inbandTextTracks.metadataTrack_;\n  if (!metadataTrack) {\n    return;\n  }\n  const Cue = window$1.WebKitDataCue || window$1.VTTCue;\n  dateRanges.forEach(dateRange => {\n    // we generate multiple cues for each date range with different attributes\n    for (const key of Object.keys(dateRange)) {\n      if (dateRangeKeysToOmit.has(key)) {\n        continue;\n      }\n      const cue = new Cue(dateRange.startTime, dateRange.endTime, '');\n      cue.id = dateRange.id;\n      cue.type = 'com.apple.quicktime.HLS';\n      cue.value = {\n        key: dateRangeAttr[key],\n        data: dateRange[key]\n      };\n      if (key === 'scte35Out' || key === 'scte35In') {\n        cue.value.data = new Uint8Array(cue.value.data.match(/[\\da-f]{2}/gi)).buffer;\n      }\n      metadataTrack.addCue(cue);\n    }\n    dateRange.processDateRange();\n  });\n};\n/**\n * Create metadata text track on video.js if it does not exist\n *\n * @param {Object} inbandTextTracks a reference to current inbandTextTracks\n * @param {string} dispatchType the inband metadata track dispatch type\n * @param {Object} tech the video.js tech\n * @private\n */\n\nconst createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {\n  if (inbandTextTracks.metadataTrack_) {\n    return;\n  }\n  inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({\n    kind: 'metadata',\n    label: 'Timed Metadata'\n  }, false).track;\n  if (!videojs.browser.IS_ANY_SAFARI) {\n    inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;\n  }\n};\n/**\n * Remove cues from a track on video.js.\n *\n * @param {Double} start start of where we should remove the cue\n * @param {Double} end end of where the we should remove the cue\n * @param {Object} track the text track to remove the cues from\n * @private\n */\n\nconst removeCuesFromTrack = function (start, end, track) {\n  let i;\n  let cue;\n  if (!track) {\n    return;\n  }\n  if (!track.cues) {\n    return;\n  }\n  i = track.cues.length;\n  while (i--) {\n    cue = track.cues[i]; // Remove any cue within the provided start and end time\n\n    if (cue.startTime >= start && cue.endTime <= end) {\n      track.removeCue(cue);\n    }\n  }\n};\n/**\n * Remove duplicate cues from a track on video.js (a cue is considered a\n * duplicate if it has the same time interval and text as another)\n *\n * @param {Object} track the text track to remove the duplicate cues from\n * @private\n */\n\nconst removeDuplicateCuesFromTrack = function (track) {\n  const cues = track.cues;\n  if (!cues) {\n    return;\n  }\n  const uniqueCues = {};\n  for (let i = cues.length - 1; i >= 0; i--) {\n    const cue = cues[i];\n    const cueKey = `${cue.startTime}-${cue.endTime}-${cue.text}`;\n    if (uniqueCues[cueKey]) {\n      track.removeCue(cue);\n    } else {\n      uniqueCues[cueKey] = cue;\n    }\n  }\n};\n\n/**\n * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in\n * front of current time.\n *\n * @param {Array} buffer\n *        The current buffer of gop information\n * @param {number} currentTime\n *        The current time\n * @param {Double} mapping\n *        Offset to map display time to stream presentation time\n * @return {Array}\n *         List of gops considered safe to append over\n */\n\nconst gopsSafeToAlignWith = (buffer, currentTime, mapping) => {\n  if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {\n    return [];\n  } // pts value for current time + 3 seconds to give a bit more wiggle room\n\n  const currentTimePts = Math.ceil((currentTime - mapping + 3) * ONE_SECOND_IN_TS);\n  let i;\n  for (i = 0; i < buffer.length; i++) {\n    if (buffer[i].pts > currentTimePts) {\n      break;\n    }\n  }\n  return buffer.slice(i);\n};\n/**\n * Appends gop information (timing and byteLength) received by the transmuxer for the\n * gops appended in the last call to appendBuffer\n *\n * @param {Array} buffer\n *        The current buffer of gop information\n * @param {Array} gops\n *        List of new gop information\n * @param {boolean} replace\n *        If true, replace the buffer with the new gop information. If false, append the\n *        new gop information to the buffer in the right location of time.\n * @return {Array}\n *         Updated list of gop information\n */\n\nconst updateGopBuffer = (buffer, gops, replace) => {\n  if (!gops.length) {\n    return buffer;\n  }\n  if (replace) {\n    // If we are in safe append mode, then completely overwrite the gop buffer\n    // with the most recent appeneded data. This will make sure that when appending\n    // future segments, we only try to align with gops that are both ahead of current\n    // time and in the last segment appended.\n    return gops.slice();\n  }\n  const start = gops[0].pts;\n  let i = 0;\n  for (i; i < buffer.length; i++) {\n    if (buffer[i].pts >= start) {\n      break;\n    }\n  }\n  return buffer.slice(0, i).concat(gops);\n};\n/**\n * Removes gop information in buffer that overlaps with provided start and end\n *\n * @param {Array} buffer\n *        The current buffer of gop information\n * @param {Double} start\n *        position to start the remove at\n * @param {Double} end\n *        position to end the remove at\n * @param {Double} mapping\n *        Offset to map display time to stream presentation time\n */\n\nconst removeGopBuffer = (buffer, start, end, mapping) => {\n  const startPts = Math.ceil((start - mapping) * ONE_SECOND_IN_TS);\n  const endPts = Math.ceil((end - mapping) * ONE_SECOND_IN_TS);\n  const updatedBuffer = buffer.slice();\n  let i = buffer.length;\n  while (i--) {\n    if (buffer[i].pts <= endPts) {\n      break;\n    }\n  }\n  if (i === -1) {\n    // no removal because end of remove range is before start of buffer\n    return updatedBuffer;\n  }\n  let j = i + 1;\n  while (j--) {\n    if (buffer[j].pts <= startPts) {\n      break;\n    }\n  } // clamp remove range start to 0 index\n\n  j = Math.max(j, 0);\n  updatedBuffer.splice(j, i - j + 1);\n  return updatedBuffer;\n};\nconst shallowEqual = function (a, b) {\n  // if both are undefined\n  // or one or the other is undefined\n  // they are not equal\n  if (!a && !b || !a && b || a && !b) {\n    return false;\n  } // they are the same object and thus, equal\n\n  if (a === b) {\n    return true;\n  } // sort keys so we can make sure they have\n  // all the same keys later.\n\n  const akeys = Object.keys(a).sort();\n  const bkeys = Object.keys(b).sort(); // different number of keys, not equal\n\n  if (akeys.length !== bkeys.length) {\n    return false;\n  }\n  for (let i = 0; i < akeys.length; i++) {\n    const key = akeys[i]; // different sorted keys, not equal\n\n    if (key !== bkeys[i]) {\n      return false;\n    } // different values, not equal\n\n    if (a[key] !== b[key]) {\n      return false;\n    }\n  }\n  return true;\n};\n\n/**\n * The segment loader has no recourse except to fetch a segment in the\n * current playlist and use the internal timestamps in that segment to\n * generate a syncPoint. This function returns a good candidate index\n * for that process.\n *\n * @param {Array} segments - the segments array from a playlist.\n * @return {number} An index of a segment from the playlist to load\n */\n\nconst getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {\n  segments = segments || [];\n  const timelineSegments = [];\n  let time = 0;\n  for (let i = 0; i < segments.length; i++) {\n    const segment = segments[i];\n    if (currentTimeline === segment.timeline) {\n      timelineSegments.push(i);\n      time += segment.duration;\n      if (time > targetTime) {\n        return i;\n      }\n    }\n  }\n  if (timelineSegments.length === 0) {\n    return 0;\n  } // default to the last timeline segment\n\n  return timelineSegments[timelineSegments.length - 1];\n}; // In the event of a quota exceeded error, keep at least one second of back buffer. This\n// number was arbitrarily chosen and may be updated in the future, but seemed reasonable\n// as a start to prevent any potential issues with removing content too close to the\n// playhead.\n\nconst MIN_BACK_BUFFER = 1; // in ms\n\nconst CHECK_BUFFER_DELAY = 500;\nconst finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half\n// frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will\n// not accurately reflect the rest of the content.\n\nconst MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;\nconst illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {\n  // Although these checks should most likely cover non 'main' types, for now it narrows\n  // the scope of our checks.\n  if (loaderType !== 'main' || !startingMedia || !trackInfo) {\n    return null;\n  }\n  if (!trackInfo.hasAudio && !trackInfo.hasVideo) {\n    return 'Neither audio nor video found in segment.';\n  }\n  if (startingMedia.hasVideo && !trackInfo.hasVideo) {\n    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.';\n  }\n  if (!startingMedia.hasVideo && trackInfo.hasVideo) {\n    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.';\n  }\n  return null;\n};\n/**\n * Calculates a time value that is safe to remove from the back buffer without interrupting\n * playback.\n *\n * @param {TimeRange} seekable\n *        The current seekable range\n * @param {number} currentTime\n *        The current time of the player\n * @param {number} targetDuration\n *        The target duration of the current playlist\n * @return {number}\n *         Time that is safe to remove from the back buffer without interrupting playback\n */\n\nconst safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {\n  // 30 seconds before the playhead provides a safe default for trimming.\n  //\n  // Choosing a reasonable default is particularly important for high bitrate content and\n  // VOD videos/live streams with large windows, as the buffer may end up overfilled and\n  // throw an APPEND_BUFFER_ERR.\n  let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;\n  if (seekable.length) {\n    // Some live playlists may have a shorter window of content than the full allowed back\n    // buffer. For these playlists, don't save content that's no longer within the window.\n    trimTime = Math.max(trimTime, seekable.start(0));\n  } // Don't remove within target duration of the current time to avoid the possibility of\n  // removing the GOP currently being played, as removing it can cause playback stalls.\n\n  const maxTrimTime = currentTime - targetDuration;\n  return Math.min(maxTrimTime, trimTime);\n};\nconst segmentInfoString = segmentInfo => {\n  const {\n    startOfSegment,\n    duration,\n    segment,\n    part,\n    playlist: {\n      mediaSequence: seq,\n      id,\n      segments = []\n    },\n    mediaIndex: index,\n    partIndex,\n    timeline\n  } = segmentInfo;\n  const segmentLen = segments.length - 1;\n  let selection = 'mediaIndex/partIndex increment';\n  if (segmentInfo.getMediaInfoForTime) {\n    selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;\n  } else if (segmentInfo.isSyncRequest) {\n    selection = 'getSyncSegmentCandidate (isSyncRequest)';\n  }\n  if (segmentInfo.independent) {\n    selection += ` with independent ${segmentInfo.independent}`;\n  }\n  const hasPartIndex = typeof partIndex === 'number';\n  const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';\n  const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({\n    preloadSegment: segment\n  }) - 1 : 0;\n  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}]`;\n};\nconst timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;\n/**\n * Returns the timestamp offset to use for the segment.\n *\n * @param {number} segmentTimeline\n *        The timeline of the segment\n * @param {number} currentTimeline\n *        The timeline currently being followed by the loader\n * @param {number} startOfSegment\n *        The estimated segment start\n * @param {TimeRange[]} buffered\n *        The loader's buffer\n * @param {boolean} overrideCheck\n *        If true, no checks are made to see if the timestamp offset value should be set,\n *        but sets it directly to a value.\n *\n * @return {number|null}\n *         Either a number representing a new timestamp offset, or null if the segment is\n *         part of the same timeline\n */\n\nconst timestampOffsetForSegment = ({\n  segmentTimeline,\n  currentTimeline,\n  startOfSegment,\n  buffered,\n  overrideCheck\n}) => {\n  // Check to see if we are crossing a discontinuity to see if we need to set the\n  // timestamp offset on the transmuxer and source buffer.\n  //\n  // Previously, we changed the timestampOffset if the start of this segment was less than\n  // the currently set timestampOffset, but this isn't desirable as it can produce bad\n  // behavior, especially around long running live streams.\n  if (!overrideCheck && segmentTimeline === currentTimeline) {\n    return null;\n  } // When changing renditions, it's possible to request a segment on an older timeline. For\n  // instance, given two renditions with the following:\n  //\n  // #EXTINF:10\n  // segment1\n  // #EXT-X-DISCONTINUITY\n  // #EXTINF:10\n  // segment2\n  // #EXTINF:10\n  // segment3\n  //\n  // And the current player state:\n  //\n  // current time: 8\n  // buffer: 0 => 20\n  //\n  // The next segment on the current rendition would be segment3, filling the buffer from\n  // 20s onwards. However, if a rendition switch happens after segment2 was requested,\n  // then the next segment to be requested will be segment1 from the new rendition in\n  // order to fill time 8 and onwards. Using the buffered end would result in repeated\n  // content (since it would position segment1 of the new rendition starting at 20s). This\n  // case can be identified when the new segment's timeline is a prior value. Instead of\n  // using the buffered end, the startOfSegment can be used, which, hopefully, will be\n  // more accurate to the actual start time of the segment.\n\n  if (segmentTimeline < currentTimeline) {\n    return startOfSegment;\n  } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that\n  // value uses the end of the last segment if it is available. While this value\n  // should often be correct, it's better to rely on the buffered end, as the new\n  // content post discontinuity should line up with the buffered end as if it were\n  // time 0 for the new content.\n\n  return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;\n};\n/**\n * Returns whether or not the loader should wait for a timeline change from the timeline\n * change controller before processing the segment.\n *\n * Primary timing in VHS goes by video. This is different from most media players, as\n * audio is more often used as the primary timing source. For the foreseeable future, VHS\n * will continue to use video as the primary timing source, due to the current logic and\n * expectations built around it.\n\n * Since the timing follows video, in order to maintain sync, the video loader is\n * responsible for setting both audio and video source buffer timestamp offsets.\n *\n * Setting different values for audio and video source buffers could lead to\n * desyncing. The following examples demonstrate some of the situations where this\n * distinction is important. Note that all of these cases involve demuxed content. When\n * content is muxed, the audio and video are packaged together, therefore syncing\n * separate media playlists is not an issue.\n *\n * CASE 1: Audio prepares to load a new timeline before video:\n *\n * Timeline:       0                 1\n * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9\n * Audio Loader:                     ^\n * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9\n * Video Loader              ^\n *\n * In the above example, the audio loader is preparing to load the 6th segment, the first\n * after a discontinuity, while the video loader is still loading the 5th segment, before\n * the discontinuity.\n *\n * If the audio loader goes ahead and loads and appends the 6th segment before the video\n * loader crosses the discontinuity, then when appended, the 6th audio segment will use\n * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,\n * the audio loader must provide the audioAppendStart value to trim the content in the\n * transmuxer, and that value relies on the audio timestamp offset. Since the audio\n * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the\n * segment until that value is provided.\n *\n * CASE 2: Video prepares to load a new timeline before audio:\n *\n * Timeline:       0                 1\n * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9\n * Audio Loader:             ^\n * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9\n * Video Loader                      ^\n *\n * In the above example, the video loader is preparing to load the 6th segment, the first\n * after a discontinuity, while the audio loader is still loading the 5th segment, before\n * the discontinuity.\n *\n * If the video loader goes ahead and loads and appends the 6th segment, then once the\n * segment is loaded and processed, both the video and audio timestamp offsets will be\n * set, since video is used as the primary timing source. This is to ensure content lines\n * up appropriately, as any modifications to the video timing are reflected by audio when\n * the video loader sets the audio and video timestamp offsets to the same value. However,\n * setting the timestamp offset for audio before audio has had a chance to change\n * timelines will likely lead to desyncing, as the audio loader will append segment 5 with\n * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.\n *\n * CASE 3: When seeking, audio prepares to load a new timeline before video\n *\n * Timeline:       0                 1\n * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9\n * Audio Loader:           ^\n * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9\n * Video Loader            ^\n *\n * In the above example, both audio and video loaders are loading segments from timeline\n * 0, but imagine that the seek originated from timeline 1.\n *\n * When seeking to a new timeline, the timestamp offset will be set based on the expected\n * segment start of the loaded video segment. In order to maintain sync, the audio loader\n * must wait for the video loader to load its segment and update both the audio and video\n * timestamp offsets before it may load and append its own segment. This is the case\n * whether the seek results in a mismatched segment request (e.g., the audio loader\n * chooses to load segment 3 and the video loader chooses to load segment 4) or the\n * loaders choose to load the same segment index from each playlist, as the segments may\n * not be aligned perfectly, even for matching segment indexes.\n *\n * @param {Object} timelinechangeController\n * @param {number} currentTimeline\n *        The timeline currently being followed by the loader\n * @param {number} segmentTimeline\n *        The timeline of the segment being loaded\n * @param {('main'|'audio')} loaderType\n *        The loader type\n * @param {boolean} audioDisabled\n *        Whether the audio is disabled for the loader. This should only be true when the\n *        loader may have muxed audio in its segment, but should not append it, e.g., for\n *        the main loader when an alternate audio playlist is active.\n *\n * @return {boolean}\n *         Whether the loader should wait for a timeline change from the timeline change\n *         controller before processing the segment\n */\n\nconst shouldWaitForTimelineChange = ({\n  timelineChangeController,\n  currentTimeline,\n  segmentTimeline,\n  loaderType,\n  audioDisabled\n}) => {\n  if (currentTimeline === segmentTimeline) {\n    return false;\n  }\n  if (loaderType === 'audio') {\n    const lastMainTimelineChange = timelineChangeController.lastTimelineChange({\n      type: 'main'\n    }); // Audio loader should wait if:\n    //\n    // * main hasn't had a timeline change yet (thus has not loaded its first segment)\n    // * main hasn't yet changed to the timeline audio is looking to load\n\n    return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;\n  } // The main loader only needs to wait for timeline changes if there's demuxed audio.\n  // Otherwise, there's nothing to wait for, since audio would be muxed into the main\n  // loader's segments (or the content is audio/video only and handled by the main\n  // loader).\n\n  if (loaderType === 'main' && audioDisabled) {\n    const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({\n      type: 'audio'\n    }); // Main loader should wait for the audio loader if audio is not pending a timeline\n    // change to the current timeline.\n    //\n    // Since the main loader is responsible for setting the timestamp offset for both\n    // audio and video, the main loader must wait for audio to be about to change to its\n    // timeline before setting the offset, otherwise, if audio is behind in loading,\n    // segments from the previous timeline would be adjusted by the new timestamp offset.\n    //\n    // This requirement means that video will not cross a timeline until the audio is\n    // about to cross to it, so that way audio and video will always cross the timeline\n    // together.\n    //\n    // In addition to normal timeline changes, these rules also apply to the start of a\n    // stream (going from a non-existent timeline, -1, to timeline 0). It's important\n    // that these rules apply to the first timeline change because if they did not, it's\n    // possible that the main loader will cross two timelines before the audio loader has\n    // crossed one. Logic may be implemented to handle the startup as a special case, but\n    // it's easier to simply treat all timeline changes the same.\n\n    if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {\n      return false;\n    }\n    return true;\n  }\n  return false;\n};\nconst shouldFixBadTimelineChanges = timelineChangeController => {\n  if (!timelineChangeController) {\n    return false;\n  }\n  const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({\n    type: 'audio'\n  });\n  const pendingMainTimelineChange = timelineChangeController.pendingTimelineChange({\n    type: 'main'\n  });\n  const hasPendingTimelineChanges = pendingAudioTimelineChange && pendingMainTimelineChange;\n  const differentPendingChanges = hasPendingTimelineChanges && pendingAudioTimelineChange.to !== pendingMainTimelineChange.to;\n  const isNotInitialPendingTimelineChange = hasPendingTimelineChanges && pendingAudioTimelineChange.from !== -1 && pendingMainTimelineChange.from !== -1;\n  if (isNotInitialPendingTimelineChange && differentPendingChanges) {\n    return true;\n  }\n  return false;\n};\n/**\n * Check if the pending audio timeline change is behind the\n * pending main timeline change.\n *\n * @param {SegmentLoader} segmentLoader\n * @return {boolean}\n */\n\nconst isAudioTimelineBehind = segmentLoader => {\n  const pendingAudioTimelineChange = segmentLoader.timelineChangeController_.pendingTimelineChange({\n    type: 'audio'\n  });\n  const pendingMainTimelineChange = segmentLoader.timelineChangeController_.pendingTimelineChange({\n    type: 'main'\n  });\n  const hasPendingTimelineChanges = pendingAudioTimelineChange && pendingMainTimelineChange;\n  return hasPendingTimelineChanges && pendingAudioTimelineChange.to < pendingMainTimelineChange.to;\n};\n/**\n * A method to check if the player is waiting for a timeline change, and fixes\n * certain scenarios where the timelines need to be updated.\n *\n * @param {SegmentLoader} segmentLoader\n */\n\nconst checkAndFixTimelines = segmentLoader => {\n  const segmentInfo = segmentLoader.pendingSegment_;\n  if (!segmentInfo) {\n    return;\n  }\n  const waitingForTimelineChange = shouldWaitForTimelineChange({\n    timelineChangeController: segmentLoader.timelineChangeController_,\n    currentTimeline: segmentLoader.currentTimeline_,\n    segmentTimeline: segmentInfo.timeline,\n    loaderType: segmentLoader.loaderType_,\n    audioDisabled: segmentLoader.audioDisabled_\n  });\n  if (waitingForTimelineChange && shouldFixBadTimelineChanges(segmentLoader.timelineChangeController_)) {\n    if (isAudioTimelineBehind(segmentLoader)) {\n      segmentLoader.timelineChangeController_.trigger('audioTimelineBehind');\n      return;\n    }\n    segmentLoader.timelineChangeController_.trigger('fixBadTimelineChange');\n  }\n};\nconst mediaDuration = timingInfos => {\n  let maxDuration = 0;\n  ['video', 'audio'].forEach(function (type) {\n    const typeTimingInfo = timingInfos[`${type}TimingInfo`];\n    if (!typeTimingInfo) {\n      return;\n    }\n    const {\n      start,\n      end\n    } = typeTimingInfo;\n    let duration;\n    if (typeof start === 'bigint' || typeof end === 'bigint') {\n      duration = window$1.BigInt(end) - window$1.BigInt(start);\n    } else if (typeof start === 'number' && typeof end === 'number') {\n      duration = end - start;\n    }\n    if (typeof duration !== 'undefined' && duration > maxDuration) {\n      maxDuration = duration;\n    }\n  }); // convert back to a number if it is lower than MAX_SAFE_INTEGER\n  // as we only need BigInt when we are above that.\n\n  if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {\n    maxDuration = Number(maxDuration);\n  }\n  return maxDuration;\n};\nconst segmentTooLong = ({\n  segmentDuration,\n  maxDuration\n}) => {\n  // 0 duration segments are most likely due to metadata only segments or a lack of\n  // information.\n  if (!segmentDuration) {\n    return false;\n  } // For HLS:\n  //\n  // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1\n  // The EXTINF duration of each Media Segment in the Playlist\n  // file, when rounded to the nearest integer, MUST be less than or equal\n  // to the target duration; longer segments can trigger playback stalls\n  // or other errors.\n  //\n  // For DASH, the mpd-parser uses the largest reported segment duration as the target\n  // duration. Although that reported duration is occasionally approximate (i.e., not\n  // exact), a strict check may report that a segment is too long more often in DASH.\n\n  return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;\n};\nconst getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {\n  // Right now we aren't following DASH's timing model exactly, so only perform\n  // this check for HLS content.\n  if (sourceType !== 'hls') {\n    return null;\n  }\n  const segmentDuration = mediaDuration({\n    audioTimingInfo: segmentInfo.audioTimingInfo,\n    videoTimingInfo: segmentInfo.videoTimingInfo\n  }); // Don't report if we lack information.\n  //\n  // If the segment has a duration of 0 it is either a lack of information or a\n  // metadata only segment and shouldn't be reported here.\n\n  if (!segmentDuration) {\n    return null;\n  }\n  const targetDuration = segmentInfo.playlist.targetDuration;\n  const isSegmentWayTooLong = segmentTooLong({\n    segmentDuration,\n    maxDuration: targetDuration * 2\n  });\n  const isSegmentSlightlyTooLong = segmentTooLong({\n    segmentDuration,\n    maxDuration: targetDuration\n  });\n  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';\n  if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {\n    return {\n      severity: isSegmentWayTooLong ? 'warn' : 'info',\n      message: segmentTooLongMessage\n    };\n  }\n  return null;\n};\n/**\n *\n * @param {Object} options type of segment loader and segment either segmentInfo or simple segment\n * @return a segmentInfo payload for events or errors.\n */\n\nconst segmentInfoPayload = ({\n  type,\n  segment\n}) => {\n  if (!segment) {\n    return;\n  }\n  const isEncrypted = Boolean(segment.key || segment.map && segment.map.ke);\n  const isMediaInitialization = Boolean(segment.map && !segment.map.bytes);\n  const start = segment.startOfSegment === undefined ? segment.start : segment.startOfSegment;\n  return {\n    type: type || segment.type,\n    uri: segment.resolvedUri || segment.uri,\n    start,\n    duration: segment.duration,\n    isEncrypted,\n    isMediaInitialization\n  };\n};\n/**\n * An object that manages segment loading and appending.\n *\n * @class SegmentLoader\n * @param {Object} options required and optional options\n * @extends videojs.EventTarget\n */\n\nclass SegmentLoader extends videojs.EventTarget {\n  constructor(settings, options = {}) {\n    super(); // check pre-conditions\n\n    if (!settings) {\n      throw new TypeError('Initialization settings are required');\n    }\n    if (typeof settings.currentTime !== 'function') {\n      throw new TypeError('No currentTime getter specified');\n    }\n    if (!settings.mediaSource) {\n      throw new TypeError('No MediaSource specified');\n    } // public properties\n\n    this.bandwidth = settings.bandwidth;\n    this.throughput = {\n      rate: 0,\n      count: 0\n    };\n    this.roundTrip = NaN;\n    this.resetStats_();\n    this.mediaIndex = null;\n    this.partIndex = null; // private settings\n\n    this.hasPlayed_ = settings.hasPlayed;\n    this.currentTime_ = settings.currentTime;\n    this.seekable_ = settings.seekable;\n    this.seeking_ = settings.seeking;\n    this.duration_ = settings.duration;\n    this.mediaSource_ = settings.mediaSource;\n    this.vhs_ = settings.vhs;\n    this.loaderType_ = settings.loaderType;\n    this.currentMediaInfo_ = void 0;\n    this.startingMediaInfo_ = void 0;\n    this.segmentMetadataTrack_ = settings.segmentMetadataTrack;\n    this.goalBufferLength_ = settings.goalBufferLength;\n    this.sourceType_ = settings.sourceType;\n    this.sourceUpdater_ = settings.sourceUpdater;\n    this.inbandTextTracks_ = settings.inbandTextTracks;\n    this.state_ = 'INIT';\n    this.timelineChangeController_ = settings.timelineChangeController;\n    this.shouldSaveSegmentTimingInfo_ = true;\n    this.parse708captions_ = settings.parse708captions;\n    this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;\n    this.captionServices_ = settings.captionServices;\n    this.exactManifestTimings = settings.exactManifestTimings;\n    this.addMetadataToTextTrack = settings.addMetadataToTextTrack; // private instance variables\n\n    this.checkBufferTimeout_ = null;\n    this.error_ = void 0;\n    this.currentTimeline_ = -1;\n    this.shouldForceTimestampOffsetAfterResync_ = false;\n    this.pendingSegment_ = null;\n    this.xhrOptions_ = null;\n    this.pendingSegments_ = [];\n    this.audioDisabled_ = false;\n    this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller\n\n    this.gopBuffer_ = [];\n    this.timeMapping_ = 0;\n    this.safeAppend_ = false;\n    this.appendInitSegment_ = {\n      audio: true,\n      video: true\n    };\n    this.playlistOfLastInitSegment_ = {\n      audio: null,\n      video: null\n    };\n    this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough\n    // information yet to start the loading process (e.g., if the audio loader wants to\n    // load a segment from the next timeline but the main loader hasn't yet crossed that\n    // timeline), then the load call will be added to the queue until it is ready to be\n    // processed.\n\n    this.loadQueue_ = [];\n    this.metadataQueue_ = {\n      id3: [],\n      caption: []\n    };\n    this.waitingOnRemove_ = false;\n    this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback\n\n    this.activeInitSegmentId_ = null;\n    this.initSegments_ = {}; // HLSe playback\n\n    this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;\n    this.keyCache_ = {};\n    this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings\n    // between a time in the display time and a segment index within\n    // a playlist\n\n    this.syncController_ = settings.syncController;\n    this.syncPoint_ = {\n      segmentIndex: 0,\n      time: 0\n    };\n    this.transmuxer_ = this.createTransmuxer_();\n    this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');\n    this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);\n    this.mediaSource_.addEventListener('sourceopen', () => {\n      if (!this.isEndOfStream_()) {\n        this.ended_ = false;\n      }\n    }); // ...for determining the fetch location\n\n    this.fetchAtBuffer_ = false;\n    this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);\n    Object.defineProperty(this, 'state', {\n      get() {\n        return this.state_;\n      },\n      set(newState) {\n        if (newState !== this.state_) {\n          this.logger_(`${this.state_} -> ${newState}`);\n          this.state_ = newState;\n          this.trigger('statechange');\n        }\n      }\n    });\n    this.sourceUpdater_.on('ready', () => {\n      if (this.hasEnoughInfoToAppend_()) {\n        this.processCallQueue_();\n      } else {\n        checkAndFixTimelines(this);\n      }\n    });\n    this.sourceUpdater_.on('codecschange', metadata => {\n      this.trigger(_extends({\n        type: 'codecschange'\n      }, metadata));\n    }); // Only the main loader needs to listen for pending timeline changes, as the main\n    // loader should wait for audio to be ready to change its timeline so that both main\n    // and audio timelines change together. For more details, see the\n    // shouldWaitForTimelineChange function.\n\n    if (this.loaderType_ === 'main') {\n      this.timelineChangeController_.on('pendingtimelinechange', () => {\n        if (this.hasEnoughInfoToAppend_()) {\n          this.processCallQueue_();\n        } else {\n          checkAndFixTimelines(this);\n        }\n      });\n    } // The main loader only listens on pending timeline changes, but the audio loader,\n    // since its loads follow main, needs to listen on timeline changes. For more details,\n    // see the shouldWaitForTimelineChange function.\n\n    if (this.loaderType_ === 'audio') {\n      this.timelineChangeController_.on('timelinechange', metadata => {\n        this.trigger(_extends({\n          type: 'timelinechange'\n        }, metadata));\n        if (this.hasEnoughInfoToLoad_()) {\n          this.processLoadQueue_();\n        } else {\n          checkAndFixTimelines(this);\n        }\n        if (this.hasEnoughInfoToAppend_()) {\n          this.processCallQueue_();\n        } else {\n          checkAndFixTimelines(this);\n        }\n      });\n    }\n  }\n  /**\n   * TODO: Current sync controller consists of many hls-specific strategies\n   * media sequence sync is also hls-specific, and we would like to be protocol-agnostic on this level\n   * this should be a part of the sync-controller and sync controller should expect different strategy list based on the protocol.\n   *\n   * @return {MediaSequenceSync|null}\n   * @private\n   */\n\n  get mediaSequenceSync_() {\n    return this.syncController_.getMediaSequenceSync(this.loaderType_);\n  }\n  createTransmuxer_() {\n    return segmentTransmuxer.createTransmuxer({\n      remux: false,\n      alignGopsAtEnd: this.safeAppend_,\n      keepOriginalTimestamps: true,\n      parse708captions: this.parse708captions_,\n      captionServices: this.captionServices_\n    });\n  }\n  /**\n   * reset all of our media stats\n   *\n   * @private\n   */\n\n  resetStats_() {\n    this.mediaBytesTransferred = 0;\n    this.mediaRequests = 0;\n    this.mediaRequestsAborted = 0;\n    this.mediaRequestsTimedout = 0;\n    this.mediaRequestsErrored = 0;\n    this.mediaTransferDuration = 0;\n    this.mediaSecondsLoaded = 0;\n    this.mediaAppends = 0;\n  }\n  /**\n   * dispose of the SegmentLoader and reset to the default state\n   */\n\n  dispose() {\n    this.trigger('dispose');\n    this.state = 'DISPOSED';\n    this.pause();\n    this.abort_();\n    if (this.transmuxer_) {\n      this.transmuxer_.terminate();\n    }\n    this.resetStats_();\n    if (this.checkBufferTimeout_) {\n      window$1.clearTimeout(this.checkBufferTimeout_);\n    }\n    if (this.syncController_ && this.triggerSyncInfoUpdate_) {\n      this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);\n    }\n    this.off();\n  }\n  setAudio(enable) {\n    this.audioDisabled_ = !enable;\n    if (enable) {\n      this.appendInitSegment_.audio = true;\n    } else {\n      // remove current track audio if it gets disabled\n      this.sourceUpdater_.removeAudio(0, this.duration_());\n    }\n  }\n  /**\n   * abort anything that is currently doing on with the SegmentLoader\n   * and reset to a default state\n   */\n\n  abort() {\n    if (this.state !== 'WAITING') {\n      if (this.pendingSegment_) {\n        this.pendingSegment_ = null;\n      }\n      this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);\n      return;\n    }\n    this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY\n    // since we are no longer \"waiting\" on any requests. XHR callback is not always run\n    // when the request is aborted. This will prevent the loader from being stuck in the\n    // WAITING state indefinitely.\n\n    this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the\n    // next segment\n\n    if (!this.paused()) {\n      this.monitorBuffer_();\n    }\n  }\n  /**\n   * abort all pending xhr requests and null any pending segements\n   *\n   * @private\n   */\n\n  abort_() {\n    if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {\n      this.pendingSegment_.abortRequests();\n    } // clear out the segment being processed\n\n    this.pendingSegment_ = null;\n    this.callQueue_ = [];\n    this.loadQueue_ = [];\n    this.metadataQueue_.id3 = [];\n    this.metadataQueue_.caption = [];\n    this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);\n    this.waitingOnRemove_ = false;\n    window$1.clearTimeout(this.quotaExceededErrorRetryTimeout_);\n    this.quotaExceededErrorRetryTimeout_ = null;\n  }\n  checkForAbort_(requestId) {\n    // If the state is APPENDING, then aborts will not modify the state, meaning the first\n    // callback that happens should reset the state to READY so that loading can continue.\n    if (this.state === 'APPENDING' && !this.pendingSegment_) {\n      this.state = 'READY';\n      return true;\n    }\n    if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {\n      return true;\n    }\n    return false;\n  }\n  /**\n   * set an error on the segment loader and null out any pending segements\n   *\n   * @param {Error} error the error to set on the SegmentLoader\n   * @return {Error} the error that was set or that is currently set\n   */\n\n  error(error) {\n    if (typeof error !== 'undefined') {\n      this.logger_('error occurred:', error);\n      this.error_ = error;\n    }\n    this.pendingSegment_ = null;\n    return this.error_;\n  }\n  endOfStream() {\n    this.ended_ = true;\n    if (this.transmuxer_) {\n      // need to clear out any cached data to prepare for the new segment\n      segmentTransmuxer.reset(this.transmuxer_);\n    }\n    this.gopBuffer_.length = 0;\n    this.pause();\n    this.trigger('ended');\n  }\n  /**\n   * Indicates which time ranges are buffered\n   *\n   * @return {TimeRange}\n   *         TimeRange object representing the current buffered ranges\n   */\n\n  buffered_() {\n    const trackInfo = this.getMediaInfo_();\n    if (!this.sourceUpdater_ || !trackInfo) {\n      return createTimeRanges();\n    }\n    if (this.loaderType_ === 'main') {\n      const {\n        hasAudio,\n        hasVideo,\n        isMuxed\n      } = trackInfo;\n      if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {\n        return this.sourceUpdater_.buffered();\n      }\n      if (hasVideo) {\n        return this.sourceUpdater_.videoBuffered();\n      }\n    } // One case that can be ignored for now is audio only with alt audio,\n    // as we don't yet have proper support for that.\n\n    return this.sourceUpdater_.audioBuffered();\n  }\n  /**\n   * Gets and sets init segment for the provided map\n   *\n   * @param {Object} map\n   *        The map object representing the init segment to get or set\n   * @param {boolean=} set\n   *        If true, the init segment for the provided map should be saved\n   * @return {Object}\n   *         map object for desired init segment\n   */\n\n  initSegmentForMap(map, set = false) {\n    if (!map) {\n      return null;\n    }\n    const id = initSegmentId(map);\n    let storedMap = this.initSegments_[id];\n    if (set && !storedMap && map.bytes) {\n      this.initSegments_[id] = storedMap = {\n        resolvedUri: map.resolvedUri,\n        byterange: map.byterange,\n        bytes: map.bytes,\n        tracks: map.tracks,\n        timescales: map.timescales\n      };\n    }\n    return storedMap || map;\n  }\n  /**\n   * Gets and sets key for the provided key\n   *\n   * @param {Object} key\n   *        The key object representing the key to get or set\n   * @param {boolean=} set\n   *        If true, the key for the provided key should be saved\n   * @return {Object}\n   *         Key object for desired key\n   */\n\n  segmentKey(key, set = false) {\n    if (!key) {\n      return null;\n    }\n    const id = segmentKeyId(key);\n    let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per\n    // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3\n\n    if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {\n      this.keyCache_[id] = storedKey = {\n        resolvedUri: key.resolvedUri,\n        bytes: key.bytes\n      };\n    }\n    const result = {\n      resolvedUri: (storedKey || key).resolvedUri\n    };\n    if (storedKey) {\n      result.bytes = storedKey.bytes;\n    }\n    return result;\n  }\n  /**\n   * Returns true if all configuration required for loading is present, otherwise false.\n   *\n   * @return {boolean} True if the all configuration is ready for loading\n   * @private\n   */\n\n  couldBeginLoading_() {\n    return this.playlist_ && !this.paused();\n  }\n  /**\n   * load a playlist and start to fill the buffer\n   */\n\n  load() {\n    // un-pause\n    this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be\n    // specified\n\n    if (!this.playlist_) {\n      return;\n    } // if all the configuration is ready, initialize and begin loading\n\n    if (this.state === 'INIT' && this.couldBeginLoading_()) {\n      return this.init_();\n    } // if we're in the middle of processing a segment already, don't\n    // kick off an additional segment request\n\n    if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {\n      return;\n    }\n    this.state = 'READY';\n  }\n  /**\n   * Once all the starting parameters have been specified, begin\n   * operation. This method should only be invoked from the INIT\n   * state.\n   *\n   * @private\n   */\n\n  init_() {\n    this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old\n    // audio data from the muxed content should be removed\n\n    this.resetEverything();\n    return this.monitorBuffer_();\n  }\n  /**\n   * set a playlist on the segment loader\n   *\n   * @param {PlaylistLoader} media the playlist to set on the segment loader\n   */\n\n  playlist(newPlaylist, options = {}) {\n    if (!newPlaylist) {\n      return;\n    }\n    if (this.playlist_ && this.playlist_.endList && newPlaylist.endList && this.playlist_.uri === newPlaylist.uri) {\n      // skip update if both prev and new are vod and have the same URI\n      return;\n    }\n    const oldPlaylist = this.playlist_;\n    const segmentInfo = this.pendingSegment_;\n    this.playlist_ = newPlaylist;\n    this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist\n    // is always our zero-time so force a sync update each time the playlist\n    // is refreshed from the server\n    //\n    // Use the INIT state to determine if playback has started, as the playlist sync info\n    // should be fixed once requests begin (as sync points are generated based on sync\n    // info), but not before then.\n\n    if (this.state === 'INIT') {\n      newPlaylist.syncInfo = {\n        mediaSequence: newPlaylist.mediaSequence,\n        time: 0\n      }; // Setting the date time mapping means mapping the program date time (if available)\n      // to time 0 on the player's timeline. The playlist's syncInfo serves a similar\n      // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can\n      // be updated as the playlist is refreshed before the loader starts loading, the\n      // program date time mapping needs to be updated as well.\n      //\n      // This mapping is only done for the main loader because a program date time should\n      // map equivalently between playlists.\n\n      if (this.loaderType_ === 'main') {\n        this.syncController_.setDateTimeMappingForStart(newPlaylist);\n      }\n    }\n    let oldId = null;\n    if (oldPlaylist) {\n      if (oldPlaylist.id) {\n        oldId = oldPlaylist.id;\n      } else if (oldPlaylist.uri) {\n        oldId = oldPlaylist.uri;\n      }\n    }\n    this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`);\n    if (this.mediaSequenceSync_) {\n      this.mediaSequenceSync_.update(newPlaylist, this.currentTime_());\n      this.logger_(`Playlist update:\ncurrentTime: ${this.currentTime_()}\nbufferedEnd: ${lastBufferedEnd(this.buffered_())}\n`, this.mediaSequenceSync_.diagnostics);\n    } // in VOD, this is always a rendition switch (or we updated our syncInfo above)\n    // in LIVE, we always want to update with new playlists (including refreshes)\n\n    this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start\n    // buffering now\n\n    if (this.state === 'INIT' && this.couldBeginLoading_()) {\n      return this.init_();\n    }\n    if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {\n      if (this.mediaIndex !== null) {\n        // we must reset/resync the segment loader when we switch renditions and\n        // the segment loader is already synced to the previous rendition\n        // We only want to reset the loader here for LLHLS playback, as resetLoader sets fetchAtBuffer_\n        // to false, resulting in fetching segments at currentTime and causing repeated\n        // same-segment requests on playlist change. This erroneously drives up the playback watcher\n        // stalled segment count, as re-requesting segments at the currentTime or browser cached segments\n        // will not change the buffer.\n        // Reference for LLHLS fixes: https://github.com/videojs/http-streaming/pull/1201\n        const isLLHLS = !newPlaylist.endList && typeof newPlaylist.partTargetDuration === 'number';\n        if (isLLHLS) {\n          this.resetLoader();\n        } else {\n          this.resyncLoader();\n        }\n      }\n      this.currentMediaInfo_ = void 0;\n      this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined\n\n      return;\n    } // we reloaded the same playlist so we are in a live scenario\n    // and we will likely need to adjust the mediaIndex\n\n    const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;\n    this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader\n    // this is important because we can abort a request and this value must be\n    // equal to the last appended mediaIndex\n\n    if (this.mediaIndex !== null) {\n      this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist\n      // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the\n      // new playlist was incremented by 1.\n\n      if (this.mediaIndex < 0) {\n        this.mediaIndex = null;\n        this.partIndex = null;\n      } else {\n        const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment\n        // unless parts fell off of the playlist for this segment.\n        // In that case we need to reset partIndex and resync\n\n        if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {\n          const mediaIndex = this.mediaIndex;\n          this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);\n          this.resetLoader(); // We want to throw away the partIndex and the data associated with it,\n          // as the part was dropped from our current playlists segment.\n          // The mediaIndex will still be valid so keep that around.\n\n          this.mediaIndex = mediaIndex;\n        }\n      }\n    } // update the mediaIndex on the SegmentInfo object\n    // this is important because we will update this.mediaIndex with this value\n    // in `handleAppendsDone_` after the segment has been successfully appended\n\n    if (segmentInfo) {\n      segmentInfo.mediaIndex -= mediaSequenceDiff;\n      if (segmentInfo.mediaIndex < 0) {\n        segmentInfo.mediaIndex = null;\n        segmentInfo.partIndex = null;\n      } else {\n        // we need to update the referenced segment so that timing information is\n        // saved for the new playlist's segment, however, if the segment fell off the\n        // playlist, we can leave the old reference and just lose the timing info\n        if (segmentInfo.mediaIndex >= 0) {\n          segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];\n        }\n        if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {\n          segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];\n        }\n      }\n    }\n    this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);\n  }\n  /**\n   * Prevent the loader from fetching additional segments. If there\n   * is a segment request outstanding, it will finish processing\n   * before the loader halts. A segment loader can be unpaused by\n   * calling load().\n   */\n\n  pause() {\n    if (this.checkBufferTimeout_) {\n      window$1.clearTimeout(this.checkBufferTimeout_);\n      this.checkBufferTimeout_ = null;\n    }\n  }\n  /**\n   * Returns whether the segment loader is fetching additional\n   * segments when given the opportunity. This property can be\n   * modified through calls to pause() and load().\n   */\n\n  paused() {\n    return this.checkBufferTimeout_ === null;\n  }\n  /**\n   * Delete all the buffered data and reset the SegmentLoader\n   *\n   * @param {Function} [done] an optional callback to be executed when the remove\n   * operation is complete\n   */\n\n  resetEverything(done) {\n    this.ended_ = false;\n    this.activeInitSegmentId_ = null;\n    this.appendInitSegment_ = {\n      audio: true,\n      video: true\n    };\n    this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.\n    // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,\n    // we then clamp the value to duration if necessary.\n\n    this.remove(0, Infinity, done); // clears fmp4 captions\n\n    if (this.transmuxer_) {\n      this.transmuxer_.postMessage({\n        action: 'clearAllMp4Captions'\n      }); // reset the cache in the transmuxer\n\n      this.transmuxer_.postMessage({\n        action: 'reset'\n      });\n    }\n  }\n  /**\n   * Force the SegmentLoader to resync and start loading around the currentTime instead\n   * of starting at the end of the buffer\n   *\n   * Useful for fast quality changes\n   */\n\n  resetLoader() {\n    this.fetchAtBuffer_ = false;\n    if (this.mediaSequenceSync_) {\n      this.mediaSequenceSync_.resetAppendedStatus();\n    }\n    this.resyncLoader();\n  }\n  /**\n   * Force the SegmentLoader to restart synchronization and make a conservative guess\n   * before returning to the simple walk-forward method\n   */\n\n  resyncLoader() {\n    if (this.transmuxer_) {\n      // need to clear out any cached data to prepare for the new segment\n      segmentTransmuxer.reset(this.transmuxer_);\n    }\n    this.mediaIndex = null;\n    this.partIndex = null;\n    this.syncPoint_ = null;\n    this.isPendingTimestampOffset_ = false; // this is mainly to sync timing-info when switching between renditions with and without timestamp-rollover,\n    // so we don't want it for DASH or fragmented mp4 segments.\n\n    const isFmp4 = this.currentMediaInfo_ && this.currentMediaInfo_.isFmp4;\n    const isHlsTs = this.sourceType_ === 'hls' && !isFmp4;\n    if (isHlsTs) {\n      this.shouldForceTimestampOffsetAfterResync_ = true;\n    }\n    this.callQueue_ = [];\n    this.loadQueue_ = [];\n    this.metadataQueue_.id3 = [];\n    this.metadataQueue_.caption = [];\n    this.abort();\n    if (this.transmuxer_) {\n      this.transmuxer_.postMessage({\n        action: 'clearParsedMp4Captions'\n      });\n    }\n  }\n  /**\n   * Remove any data in the source buffer between start and end times\n   *\n   * @param {number} start - the start time of the region to remove from the buffer\n   * @param {number} end - the end time of the region to remove from the buffer\n   * @param {Function} [done] - an optional callback to be executed when the remove\n   * @param {boolean} force - force all remove operations to happen\n   * operation is complete\n   */\n\n  remove(start, end, done = () => {}, force = false) {\n    // clamp end to duration if we need to remove everything.\n    // This is due to a browser bug that causes issues if we remove to Infinity.\n    // videojs/videojs-contrib-hls#1225\n    if (end === Infinity) {\n      end = this.duration_();\n    } // skip removes that would throw an error\n    // commonly happens during a rendition switch at the start of a video\n    // from start 0 to end 0\n\n    if (end <= start) {\n      this.logger_('skipping remove because end ${end} is <= start ${start}');\n      return;\n    }\n    if (!this.sourceUpdater_ || !this.getMediaInfo_()) {\n      this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media\n\n      return;\n    } // set it to one to complete this function's removes\n\n    let removesRemaining = 1;\n    const removeFinished = () => {\n      removesRemaining--;\n      if (removesRemaining === 0) {\n        done();\n      }\n    };\n    if (force || !this.audioDisabled_) {\n      removesRemaining++;\n      this.sourceUpdater_.removeAudio(start, end, removeFinished);\n    } // While it would be better to only remove video if the main loader has video, this\n    // should be safe with audio only as removeVideo will call back even if there's no\n    // video buffer.\n    //\n    // In theory we can check to see if there's video before calling the remove, but in\n    // the event that we're switching between renditions and from video to audio only\n    // (when we add support for that), we may need to clear the video contents despite\n    // what the new media will contain.\n\n    if (force || this.loaderType_ === 'main') {\n      this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);\n      removesRemaining++;\n      this.sourceUpdater_.removeVideo(start, end, removeFinished);\n    } // remove any captions and ID3 tags\n\n    for (const track in this.inbandTextTracks_) {\n      removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);\n    }\n    removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes\n\n    removeFinished();\n  }\n  /**\n   * (re-)schedule monitorBufferTick_ to run as soon as possible\n   *\n   * @private\n   */\n\n  monitorBuffer_() {\n    if (this.checkBufferTimeout_) {\n      window$1.clearTimeout(this.checkBufferTimeout_);\n    }\n    this.checkBufferTimeout_ = window$1.setTimeout(this.monitorBufferTick_.bind(this), 1);\n  }\n  /**\n   * As long as the SegmentLoader is in the READY state, periodically\n   * invoke fillBuffer_().\n   *\n   * @private\n   */\n\n  monitorBufferTick_() {\n    if (this.state === 'READY') {\n      this.fillBuffer_();\n    }\n    if (this.checkBufferTimeout_) {\n      window$1.clearTimeout(this.checkBufferTimeout_);\n    }\n    this.checkBufferTimeout_ = window$1.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);\n  }\n  /**\n   * fill the buffer with segements unless the sourceBuffers are\n   * currently updating\n   *\n   * Note: this function should only ever be called by monitorBuffer_\n   * and never directly\n   *\n   * @private\n   */\n\n  fillBuffer_() {\n    // TODO since the source buffer maintains a queue, and we shouldn't call this function\n    // except when we're ready for the next segment, this check can most likely be removed\n    if (this.sourceUpdater_.updating()) {\n      return;\n    } // see if we need to begin loading immediately\n\n    const segmentInfo = this.chooseNextRequest_();\n    if (!segmentInfo) {\n      return;\n    }\n    const metadata = {\n      segmentInfo: segmentInfoPayload({\n        type: this.loaderType_,\n        segment: segmentInfo\n      })\n    };\n    this.trigger({\n      type: 'segmentselected',\n      metadata\n    });\n    if (typeof segmentInfo.timestampOffset === 'number') {\n      this.isPendingTimestampOffset_ = false;\n      this.timelineChangeController_.pendingTimelineChange({\n        type: this.loaderType_,\n        from: this.currentTimeline_,\n        to: segmentInfo.timeline\n      });\n    }\n    this.loadSegment_(segmentInfo);\n  }\n  /**\n   * Determines if we should call endOfStream on the media source based\n   * on the state of the buffer or if appened segment was the final\n   * segment in the playlist.\n   *\n   * @param {number} [mediaIndex] the media index of segment we last appended\n   * @param {Object} [playlist] a media playlist object\n   * @return {boolean} do we need to call endOfStream on the MediaSource\n   */\n\n  isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {\n    if (!playlist || !this.mediaSource_) {\n      return false;\n    }\n    const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based\n\n    const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.\n\n    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\n    // so that MediaSources can trigger the `ended` event when it runs out of\n    // buffered data instead of waiting for me\n\n    return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;\n  }\n  /**\n   * Determines what request should be made given current segment loader state.\n   *\n   * @return {Object} a request object that describes the segment/part to load\n   */\n\n  chooseNextRequest_() {\n    const buffered = this.buffered_();\n    const bufferedEnd = lastBufferedEnd(buffered) || 0;\n    const bufferedTime = timeAheadOf(buffered, this.currentTime_());\n    const preloaded = !this.hasPlayed_() && bufferedTime >= 1;\n    const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();\n    const segments = this.playlist_.segments; // return no segment if:\n    // 1. we don't have segments\n    // 2. The video has not yet played and we already downloaded a segment\n    // 3. we already have enough buffered time\n\n    if (!segments.length || preloaded || haveEnoughBuffer) {\n      return null;\n    }\n    this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_(), this.loaderType_);\n    const next = {\n      partIndex: null,\n      mediaIndex: null,\n      startOfSegment: null,\n      playlist: this.playlist_,\n      isSyncRequest: Boolean(!this.syncPoint_)\n    };\n    if (next.isSyncRequest) {\n      next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);\n      this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${next.mediaIndex}`);\n    } else if (this.mediaIndex !== null) {\n      const segment = segments[this.mediaIndex];\n      const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;\n      next.startOfSegment = segment.end ? segment.end : bufferedEnd;\n      if (segment.parts && segment.parts[partIndex + 1]) {\n        next.mediaIndex = this.mediaIndex;\n        next.partIndex = partIndex + 1;\n      } else {\n        next.mediaIndex = this.mediaIndex + 1;\n      }\n    } else {\n      let segmentIndex;\n      let partIndex;\n      let startTime;\n      const targetTime = this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_();\n      if (this.mediaSequenceSync_) {\n        this.logger_(`chooseNextRequest_ request after Quality Switch:\nFor TargetTime: ${targetTime}.\nCurrentTime: ${this.currentTime_()}\nBufferedEnd: ${bufferedEnd}\nFetch At Buffer: ${this.fetchAtBuffer_}\n`, this.mediaSequenceSync_.diagnostics);\n      }\n      if (this.mediaSequenceSync_ && this.mediaSequenceSync_.isReliable) {\n        const syncInfo = this.getSyncInfoFromMediaSequenceSync_(targetTime);\n        if (!syncInfo) {\n          const message = 'No sync info found while using media sequence sync';\n          this.error({\n            message,\n            metadata: {\n              errorType: videojs.Error.StreamingFailedToSelectNextSegment,\n              error: new Error(message)\n            }\n          });\n          this.logger_('chooseNextRequest_ - no sync info found using media sequence sync'); // no match\n\n          return null;\n        }\n        this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${syncInfo.start} --> ${syncInfo.end})`);\n        segmentIndex = syncInfo.segmentIndex;\n        partIndex = syncInfo.partIndex;\n        startTime = syncInfo.start;\n      } else {\n        this.logger_('chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.'); // fallback\n\n        const mediaInfoForTime = Playlist.getMediaInfoForTime({\n          exactManifestTimings: this.exactManifestTimings,\n          playlist: this.playlist_,\n          currentTime: targetTime,\n          startingPartIndex: this.syncPoint_.partIndex,\n          startingSegmentIndex: this.syncPoint_.segmentIndex,\n          startTime: this.syncPoint_.time\n        });\n        segmentIndex = mediaInfoForTime.segmentIndex;\n        partIndex = mediaInfoForTime.partIndex;\n        startTime = mediaInfoForTime.startTime;\n      }\n      next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${targetTime}` : `currentTime ${targetTime}`;\n      next.mediaIndex = segmentIndex;\n      next.startOfSegment = startTime;\n      next.partIndex = partIndex;\n      this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${next.mediaIndex} `);\n    }\n    const nextSegment = segments[next.mediaIndex];\n    let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or\n    // the next partIndex is invalid do not choose a next segment.\n\n    if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {\n      return null;\n    } // if the next segment has parts, and we don't have a partIndex.\n    // Set partIndex to 0\n\n    if (typeof next.partIndex !== 'number' && nextSegment.parts) {\n      next.partIndex = 0;\n      nextPart = nextSegment.parts[0];\n    } // independentSegments applies to every segment in a playlist. If independentSegments appears in a main playlist,\n    // it applies to each segment in each media playlist.\n    // https://datatracker.ietf.org/doc/html/draft-pantos-http-live-streaming-23#section-4.3.5.1\n\n    const hasIndependentSegments = this.vhs_.playlists && this.vhs_.playlists.main && this.vhs_.playlists.main.independentSegments || this.playlist_.independentSegments; // if we have no buffered data then we need to make sure\n    // that the next part we append is \"independent\" if possible.\n    // So we check if the previous part is independent, and request\n    // it if it is.\n\n    if (!bufferedTime && nextPart && !hasIndependentSegments && !nextPart.independent) {\n      if (next.partIndex === 0) {\n        const lastSegment = segments[next.mediaIndex - 1];\n        const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];\n        if (lastSegmentLastPart && lastSegmentLastPart.independent) {\n          next.mediaIndex -= 1;\n          next.partIndex = lastSegment.parts.length - 1;\n          next.independent = 'previous segment';\n        }\n      } else if (nextSegment.parts[next.partIndex - 1].independent) {\n        next.partIndex -= 1;\n        next.independent = 'previous part';\n      }\n    }\n    const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:\n    // 1. this is the last segment in the playlist\n    // 2. end of stream has been called on the media source already\n    // 3. the player is not seeking\n\n    if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {\n      return null;\n    }\n    if (this.shouldForceTimestampOffsetAfterResync_) {\n      this.shouldForceTimestampOffsetAfterResync_ = false;\n      next.forceTimestampOffset = true;\n      this.logger_('choose next request. Force timestamp offset after loader resync');\n    }\n    return this.generateSegmentInfo_(next);\n  }\n  getSyncInfoFromMediaSequenceSync_(targetTime) {\n    if (!this.mediaSequenceSync_) {\n      return null;\n    } // we should pull the target time to the least available time if we drop out of sync for any reason\n\n    const finalTargetTime = Math.max(targetTime, this.mediaSequenceSync_.start);\n    if (targetTime !== finalTargetTime) {\n      this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${targetTime} to ${finalTargetTime}`);\n    }\n    const mediaSequenceSyncInfo = this.mediaSequenceSync_.getSyncInfoForTime(finalTargetTime);\n    if (!mediaSequenceSyncInfo) {\n      // no match at all\n      return null;\n    }\n    if (!mediaSequenceSyncInfo.isAppended) {\n      // has a perfect match\n      return mediaSequenceSyncInfo;\n    } // has match, but segment was already appended.\n    // attempt to auto-advance to the nearest next segment:\n\n    const nextMediaSequenceSyncInfo = this.mediaSequenceSync_.getSyncInfoForTime(mediaSequenceSyncInfo.end);\n    if (!nextMediaSequenceSyncInfo) {\n      // no match at all\n      return null;\n    }\n    if (nextMediaSequenceSyncInfo.isAppended) {\n      this.logger_('getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!');\n    } // got match with the nearest next segment\n\n    return nextMediaSequenceSyncInfo;\n  }\n  generateSegmentInfo_(options) {\n    const {\n      independent,\n      playlist,\n      mediaIndex,\n      startOfSegment,\n      isSyncRequest,\n      partIndex,\n      forceTimestampOffset,\n      getMediaInfoForTime\n    } = options;\n    const segment = playlist.segments[mediaIndex];\n    const part = typeof partIndex === 'number' && segment.parts[partIndex];\n    const segmentInfo = {\n      requestId: 'segment-loader-' + Math.random(),\n      // resolve the segment URL relative to the playlist\n      uri: part && part.resolvedUri || segment.resolvedUri,\n      // the segment's mediaIndex at the time it was requested\n      mediaIndex,\n      partIndex: part ? partIndex : null,\n      // whether or not to update the SegmentLoader's state with this\n      // segment's mediaIndex\n      isSyncRequest,\n      startOfSegment,\n      // the segment's playlist\n      playlist,\n      // unencrypted bytes of the segment\n      bytes: null,\n      // when a key is defined for this segment, the encrypted bytes\n      encryptedBytes: null,\n      // The target timestampOffset for this segment when we append it\n      // to the source buffer\n      timestampOffset: null,\n      // The timeline that the segment is in\n      timeline: segment.timeline,\n      // The expected duration of the segment in seconds\n      duration: part && part.duration || segment.duration,\n      // retain the segment in case the playlist updates while doing an async process\n      segment,\n      part,\n      byteLength: 0,\n      transmuxer: this.transmuxer_,\n      // type of getMediaInfoForTime that was used to get this segment\n      getMediaInfoForTime,\n      independent\n    };\n    const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;\n    segmentInfo.timestampOffset = this.timestampOffsetForSegment_({\n      segmentTimeline: segment.timeline,\n      currentTimeline: this.currentTimeline_,\n      startOfSegment,\n      buffered: this.buffered_(),\n      overrideCheck\n    });\n    const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());\n    if (typeof audioBufferedEnd === 'number') {\n      // since the transmuxer is using the actual timing values, but the buffer is\n      // adjusted by the timestamp offset, we must adjust the value here\n      segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();\n    }\n    if (this.sourceUpdater_.videoBuffered().length) {\n      segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_,\n      // since the transmuxer is using the actual timing values, but the time is\n      // adjusted by the timestmap offset, we must adjust the value here\n      this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);\n    }\n    return segmentInfo;\n  } // get the timestampoffset for a segment,\n  // added so that vtt segment loader can override and prevent\n  // adding timestamp offsets.\n\n  timestampOffsetForSegment_(options) {\n    return timestampOffsetForSegment(options);\n  }\n  /**\n   * Determines if the network has enough bandwidth to complete the current segment\n   * request in a timely manner. If not, the request will be aborted early and bandwidth\n   * updated to trigger a playlist switch.\n   *\n   * @param {Object} stats\n   *        Object containing stats about the request timing and size\n   * @private\n   */\n\n  earlyAbortWhenNeeded_(stats) {\n    if (this.vhs_.tech_.paused() ||\n    // Don't abort if the current playlist is on the lowestEnabledRendition\n    // TODO: Replace using timeout with a boolean indicating whether this playlist is\n    //       the lowestEnabledRendition.\n    !this.xhrOptions_.timeout ||\n    // Don't abort if we have no bandwidth information to estimate segment sizes\n    !this.playlist_.attributes.BANDWIDTH) {\n      return;\n    } // Wait at least 1 second since the first byte of data has been received before\n    // using the calculated bandwidth from the progress event to allow the bitrate\n    // to stabilize\n\n    if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {\n      return;\n    }\n    const currentTime = this.currentTime_();\n    const measuredBandwidth = stats.bandwidth;\n    const segmentDuration = this.pendingSegment_.duration;\n    const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort\n    // if we are only left with less than 1 second when the request completes.\n    // A negative timeUntilRebuffering indicates we are already rebuffering\n\n    const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download\n    // is larger than the estimated time until the player runs out of forward buffer\n\n    if (requestTimeRemaining <= timeUntilRebuffer$1) {\n      return;\n    }\n    const switchCandidate = minRebufferMaxBandwidthSelector({\n      main: this.vhs_.playlists.main,\n      currentTime,\n      bandwidth: measuredBandwidth,\n      duration: this.duration_(),\n      segmentDuration,\n      timeUntilRebuffer: timeUntilRebuffer$1,\n      currentTimeline: this.currentTimeline_,\n      syncController: this.syncController_\n    });\n    if (!switchCandidate) {\n      return;\n    }\n    const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;\n    const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;\n    let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the\n    // potential round trip time of the new request so that we are not too aggressive\n    // with switching to a playlist that might save us a fraction of a second.\n\n    if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {\n      minimumTimeSaving = 1;\n    }\n    if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {\n      return;\n    } // set the bandwidth to that of the desired playlist being sure to scale by\n    // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it\n    // don't trigger a bandwidthupdate as the bandwidth is artifial\n\n    this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;\n    this.trigger('earlyabort');\n  }\n  handleAbort_(segmentInfo) {\n    this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);\n    this.mediaRequestsAborted += 1;\n  }\n  /**\n   * XHR `progress` event handler\n   *\n   * @param {Event}\n   *        The XHR `progress` event\n   * @param {Object} simpleSegment\n   *        A simplified segment object copy\n   * @private\n   */\n\n  handleProgress_(event, simpleSegment) {\n    this.earlyAbortWhenNeeded_(simpleSegment.stats);\n    if (this.checkForAbort_(simpleSegment.requestId)) {\n      return;\n    }\n    this.trigger('progress');\n  }\n  handleTrackInfo_(simpleSegment, trackInfo) {\n    const {\n      hasAudio,\n      hasVideo\n    } = trackInfo;\n    const metadata = {\n      segmentInfo: segmentInfoPayload({\n        type: this.loaderType_,\n        segment: simpleSegment\n      }),\n      trackInfo: {\n        hasAudio,\n        hasVideo\n      }\n    };\n    this.trigger({\n      type: 'segmenttransmuxingtrackinfoavailable',\n      metadata\n    });\n    this.earlyAbortWhenNeeded_(simpleSegment.stats);\n    if (this.checkForAbort_(simpleSegment.requestId)) {\n      return;\n    }\n    if (this.checkForIllegalMediaSwitch(trackInfo)) {\n      return;\n    }\n    trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.\n    // Guard against cases where we're not getting track info at all until we are\n    // certain that all streams will provide it.\n\n    if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {\n      this.appendInitSegment_ = {\n        audio: true,\n        video: true\n      };\n      this.startingMediaInfo_ = trackInfo;\n      this.currentMediaInfo_ = trackInfo;\n      this.logger_('trackinfo update', trackInfo);\n      this.trigger('trackinfo');\n    } // trackinfo may cause an abort if the trackinfo\n    // causes a codec change to an unsupported codec.\n\n    if (this.checkForAbort_(simpleSegment.requestId)) {\n      return;\n    } // set trackinfo on the pending segment so that\n    // it can append.\n\n    this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info\n\n    if (this.hasEnoughInfoToAppend_()) {\n      this.processCallQueue_();\n    } else {\n      checkAndFixTimelines(this);\n    }\n  }\n  handleTimingInfo_(simpleSegment, mediaType, timeType, time) {\n    this.earlyAbortWhenNeeded_(simpleSegment.stats);\n    if (this.checkForAbort_(simpleSegment.requestId)) {\n      return;\n    }\n    const segmentInfo = this.pendingSegment_;\n    const timingInfoProperty = timingInfoPropertyForMedia(mediaType);\n    segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};\n    segmentInfo[timingInfoProperty][timeType] = time;\n    this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info\n\n    if (this.hasEnoughInfoToAppend_()) {\n      this.processCallQueue_();\n    } else {\n      checkAndFixTimelines(this);\n    }\n  }\n  handleCaptions_(simpleSegment, captionData) {\n    this.earlyAbortWhenNeeded_(simpleSegment.stats);\n    if (this.checkForAbort_(simpleSegment.requestId)) {\n      return;\n    } // This could only happen with fmp4 segments, but\n    // should still not happen in general\n\n    if (captionData.length === 0) {\n      this.logger_('SegmentLoader received no captions from a caption event');\n      return;\n    }\n    const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing\n    // can be adjusted by the timestamp offset\n\n    if (!segmentInfo.hasAppendedData_) {\n      this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));\n      return;\n    }\n    const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();\n    const captionTracks = {}; // get total start/end and captions for each track/stream\n\n    captionData.forEach(caption => {\n      // caption.stream is actually a track name...\n      // set to the existing values in tracks or default values\n      captionTracks[caption.stream] = captionTracks[caption.stream] || {\n        // Infinity, as any other value will be less than this\n        startTime: Infinity,\n        captions: [],\n        // 0 as an other value will be more than this\n        endTime: 0\n      };\n      const captionTrack = captionTracks[caption.stream];\n      captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);\n      captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);\n      captionTrack.captions.push(caption);\n    });\n    Object.keys(captionTracks).forEach(trackName => {\n      const {\n        startTime,\n        endTime,\n        captions\n      } = captionTracks[trackName];\n      const inbandTextTracks = this.inbandTextTracks_;\n      this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);\n      createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.\n      // We do this because a rendition change that also changes the timescale for captions\n      // will result in captions being re-parsed for certain segments. If we add them again\n      // without clearing we will have two of the same captions visible.\n\n      removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);\n      addCaptionData({\n        captionArray: captions,\n        inbandTextTracks,\n        timestampOffset\n      });\n    }); // Reset stored captions since we added parsed\n    // captions to a text track at this point\n\n    if (this.transmuxer_) {\n      this.transmuxer_.postMessage({\n        action: 'clearParsedMp4Captions'\n      });\n    }\n  }\n  handleId3_(simpleSegment, id3Frames, dispatchType) {\n    this.earlyAbortWhenNeeded_(simpleSegment.stats);\n    if (this.checkForAbort_(simpleSegment.requestId)) {\n      return;\n    }\n    const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set\n\n    if (!segmentInfo.hasAppendedData_) {\n      this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));\n      return;\n    }\n    this.addMetadataToTextTrack(dispatchType, id3Frames, this.duration_());\n  }\n  processMetadataQueue_() {\n    this.metadataQueue_.id3.forEach(fn => fn());\n    this.metadataQueue_.caption.forEach(fn => fn());\n    this.metadataQueue_.id3 = [];\n    this.metadataQueue_.caption = [];\n  }\n  processCallQueue_() {\n    const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the\n    // functions may check the length of the load queue and default to pushing themselves\n    // back onto the queue.\n\n    this.callQueue_ = [];\n    callQueue.forEach(fun => fun());\n  }\n  processLoadQueue_() {\n    const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the\n    // functions may check the length of the load queue and default to pushing themselves\n    // back onto the queue.\n\n    this.loadQueue_ = [];\n    loadQueue.forEach(fun => fun());\n  }\n  /**\n   * Determines whether the loader has enough info to load the next segment.\n   *\n   * @return {boolean}\n   *         Whether or not the loader has enough info to load the next segment\n   */\n\n  hasEnoughInfoToLoad_() {\n    // Since primary timing goes by video, only the audio loader potentially needs to wait\n    // to load.\n    if (this.loaderType_ !== 'audio') {\n      return true;\n    }\n    const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's\n    // enough info to load.\n\n    if (!segmentInfo) {\n      return false;\n    } // The first segment can and should be loaded immediately so that source buffers are\n    // created together (before appending). Source buffer creation uses the presence of\n    // audio and video data to determine whether to create audio/video source buffers, and\n    // uses processed (transmuxed or parsed) media to determine the types required.\n\n    if (!this.getCurrentMediaInfo_()) {\n      return true;\n    }\n    if (\n    // Technically, instead of waiting to load a segment on timeline changes, a segment\n    // can be requested and downloaded and only wait before it is transmuxed or parsed.\n    // But in practice, there are a few reasons why it is better to wait until a loader\n    // is ready to append that segment before requesting and downloading:\n    //\n    // 1. Because audio and main loaders cross discontinuities together, if this loader\n    //    is waiting for the other to catch up, then instead of requesting another\n    //    segment and using up more bandwidth, by not yet loading, more bandwidth is\n    //    allotted to the loader currently behind.\n    // 2. media-segment-request doesn't have to have logic to consider whether a segment\n    // is ready to be processed or not, isolating the queueing behavior to the loader.\n    // 3. The audio loader bases some of its segment properties on timing information\n    //    provided by the main loader, meaning that, if the logic for waiting on\n    //    processing was in media-segment-request, then it would also need to know how\n    //    to re-generate the segment information after the main loader caught up.\n    shouldWaitForTimelineChange({\n      timelineChangeController: this.timelineChangeController_,\n      currentTimeline: this.currentTimeline_,\n      segmentTimeline: segmentInfo.timeline,\n      loaderType: this.loaderType_,\n      audioDisabled: this.audioDisabled_\n    })) {\n      return false;\n    }\n    return true;\n  }\n  getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {\n    return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;\n  }\n  getMediaInfo_(segmentInfo = this.pendingSegment_) {\n    return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;\n  }\n  getPendingSegmentPlaylist() {\n    return this.pendingSegment_ ? this.pendingSegment_.playlist : null;\n  }\n  hasEnoughInfoToAppend_() {\n    if (!this.sourceUpdater_.ready()) {\n      return false;\n    } // If content needs to be removed or the loader is waiting on an append reattempt,\n    // then no additional content should be appended until the prior append is resolved.\n\n    if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {\n      return false;\n    }\n    const segmentInfo = this.pendingSegment_;\n    const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or\n    // we do not have information on this specific\n    // segment yet\n\n    if (!segmentInfo || !trackInfo) {\n      return false;\n    }\n    const {\n      hasAudio,\n      hasVideo,\n      isMuxed\n    } = trackInfo;\n    if (hasVideo && !segmentInfo.videoTimingInfo) {\n      return false;\n    } // muxed content only relies on video timing information for now.\n\n    if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {\n      return false;\n    } // we need to allow an append here even if we're moving to different timelines.\n\n    if (shouldWaitForTimelineChange({\n      timelineChangeController: this.timelineChangeController_,\n      currentTimeline: this.currentTimeline_,\n      segmentTimeline: segmentInfo.timeline,\n      loaderType: this.loaderType_,\n      audioDisabled: this.audioDisabled_\n    })) {\n      return false;\n    }\n    return true;\n  }\n  handleData_(simpleSegment, result) {\n    this.earlyAbortWhenNeeded_(simpleSegment.stats);\n    if (this.checkForAbort_(simpleSegment.requestId)) {\n      return;\n    } // If there's anything in the call queue, then this data came later and should be\n    // executed after the calls currently queued.\n\n    if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {\n      checkAndFixTimelines(this);\n      this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));\n      return;\n    }\n    const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time\n\n    this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats\n\n    this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort\n    // logic may change behavior depending on the state, and changing state too early may\n    // inflate our estimates of bandwidth. In the future this should be re-examined to\n    // note more granular states.\n    // don't process and append data if the mediaSource is closed\n\n    if (this.mediaSource_.readyState === 'closed') {\n      return;\n    } // if this request included an initialization segment, save that data\n    // to the initSegment cache\n\n    if (simpleSegment.map) {\n      simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request\n\n      segmentInfo.segment.map = simpleSegment.map;\n    } // if this request included a segment key, save that data in the cache\n\n    if (simpleSegment.key) {\n      this.segmentKey(simpleSegment.key, true);\n    }\n    segmentInfo.isFmp4 = simpleSegment.isFmp4;\n    segmentInfo.timingInfo = segmentInfo.timingInfo || {};\n    if (segmentInfo.isFmp4) {\n      this.trigger('fmp4');\n      segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;\n    } else {\n      const trackInfo = this.getCurrentMediaInfo_();\n      const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;\n      let firstVideoFrameTimeForData;\n      if (useVideoTimingInfo) {\n        firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;\n      } // Segment loader knows more about segment timing than the transmuxer (in certain\n      // aspects), so make any changes required for a more accurate start time.\n      // Don't set the end time yet, as the segment may not be finished processing.\n\n      segmentInfo.timingInfo.start = this.trueSegmentStart_({\n        currentStart: segmentInfo.timingInfo.start,\n        playlist: segmentInfo.playlist,\n        mediaIndex: segmentInfo.mediaIndex,\n        currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),\n        useVideoTimingInfo,\n        firstVideoFrameTimeForData,\n        videoTimingInfo: segmentInfo.videoTimingInfo,\n        audioTimingInfo: segmentInfo.audioTimingInfo\n      });\n    } // Init segments for audio and video only need to be appended in certain cases. Now\n    // that data is about to be appended, we can check the final cases to determine\n    // whether we should append an init segment.\n\n    this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,\n    // as we use the start of the segment to offset the best guess (playlist provided)\n    // timestamp offset.\n\n    this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should\n    // be appended or not.\n\n    if (segmentInfo.isSyncRequest) {\n      // first save/update our timing info for this segment.\n      // this is what allows us to choose an accurate segment\n      // and the main reason we make a sync request.\n      this.updateTimingInfoEnd_(segmentInfo);\n      this.syncController_.saveSegmentTimingInfo({\n        segmentInfo,\n        shouldSaveTimelineMapping: this.loaderType_ === 'main'\n      });\n      const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next\n      // after taking into account its timing info, do not append it.\n\n      if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {\n        this.logger_('sync segment was incorrect, not appending');\n        return;\n      } // otherwise append it like any other segment as our guess was correct.\n\n      this.logger_('sync segment was correct, appending');\n    } // Save some state so that in the future anything waiting on first append (and/or\n    // timestamp offset(s)) can process immediately. While the extra state isn't optimal,\n    // we need some notion of whether the timestamp offset or other relevant information\n    // has had a chance to be set.\n\n    segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.\n\n    this.processMetadataQueue_();\n    this.appendData_(segmentInfo, result);\n  }\n  updateAppendInitSegmentStatus(segmentInfo, type) {\n    // alt audio doesn't manage timestamp offset\n    if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' &&\n    // in the case that we're handling partial data, we don't want to append an init\n    // segment for each chunk\n    !segmentInfo.changedTimestampOffset) {\n      // if the timestamp offset changed, the timeline may have changed, so we have to re-\n      // append init segments\n      this.appendInitSegment_ = {\n        audio: true,\n        video: true\n      };\n    }\n    if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {\n      // make sure we append init segment on playlist changes, in case the media config\n      // changed\n      this.appendInitSegment_[type] = true;\n    }\n  }\n  getInitSegmentAndUpdateState_({\n    type,\n    initSegment,\n    map,\n    playlist\n  }) {\n    // \"The EXT-X-MAP tag specifies how to obtain the Media Initialization Section\n    // (Section 3) required to parse the applicable Media Segments.  It applies to every\n    // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag\n    // or until the end of the playlist.\"\n    // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5\n    if (map) {\n      const id = initSegmentId(map);\n      if (this.activeInitSegmentId_ === id) {\n        // don't need to re-append the init segment if the ID matches\n        return null;\n      } // a map-specified init segment takes priority over any transmuxed (or otherwise\n      // obtained) init segment\n      //\n      // this also caches the init segment for later use\n\n      initSegment = this.initSegmentForMap(map, true).bytes;\n      this.activeInitSegmentId_ = id;\n    } // We used to always prepend init segments for video, however, that shouldn't be\n    // necessary. Instead, we should only append on changes, similar to what we've always\n    // done for audio. This is more important (though may not be that important) for\n    // frame-by-frame appending for LHLS, simply because of the increased quantity of\n    // appends.\n\n    if (initSegment && this.appendInitSegment_[type]) {\n      // Make sure we track the playlist that we last used for the init segment, so that\n      // we can re-append the init segment in the event that we get data from a new\n      // playlist. Discontinuities and track changes are handled in other sections.\n      this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.\n\n      this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since\n      // we are appending the muxer init segment\n\n      this.activeInitSegmentId_ = null;\n      return initSegment;\n    }\n    return null;\n  }\n  handleQuotaExceededError_({\n    segmentInfo,\n    type,\n    bytes\n  }, error) {\n    const audioBuffered = this.sourceUpdater_.audioBuffered();\n    const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,\n    // should be cleared out during the buffer removals. However, log in case it helps\n    // debug.\n\n    if (audioBuffered.length > 1) {\n      this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));\n    }\n    if (videoBuffered.length > 1) {\n      this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));\n    }\n    const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;\n    const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;\n    const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;\n    const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;\n    if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {\n      // Can't remove enough buffer to make room for new segment (or the browser doesn't\n      // allow for appends of segments this size). In the future, it may be possible to\n      // split up the segment and append in pieces, but for now, error out this playlist\n      // in an attempt to switch to a more manageable rendition.\n      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(', ')}, `);\n      this.error({\n        message: 'Quota exceeded error with append of a single segment of content',\n        excludeUntil: Infinity\n      });\n      this.trigger('error');\n      return;\n    } // To try to resolve the quota exceeded error, clear back buffer and retry. This means\n    // that the segment-loader should block on future events until this one is handled, so\n    // that it doesn't keep moving onto further segments. Adding the call to the call\n    // queue will prevent further appends until waitingOnRemove_ and\n    // quotaExceededErrorRetryTimeout_ are cleared.\n    //\n    // Note that this will only block the current loader. In the case of demuxed content,\n    // the other load may keep filling as fast as possible. In practice, this should be\n    // OK, as it is a rare case when either audio has a high enough bitrate to fill up a\n    // source buffer, or video fills without enough room for audio to append (and without\n    // the availability of clearing out seconds of back buffer to make room for audio).\n    // But it might still be good to handle this case in the future as a TODO.\n\n    this.waitingOnRemove_ = true;\n    this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {\n      segmentInfo,\n      type,\n      bytes\n    }));\n    const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content\n    // before retrying.\n\n    const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;\n    this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);\n    this.remove(0, timeToRemoveUntil, () => {\n      this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);\n      this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted\n      // attempts (since we can't clear less than the minimum)\n\n      this.quotaExceededErrorRetryTimeout_ = window$1.setTimeout(() => {\n        this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');\n        this.quotaExceededErrorRetryTimeout_ = null;\n        this.processCallQueue_();\n      }, MIN_BACK_BUFFER * 1000);\n    }, true);\n  }\n  handleAppendError_({\n    segmentInfo,\n    type,\n    bytes\n  }, error) {\n    // if there's no error, nothing to do\n    if (!error) {\n      return;\n    }\n    if (error.code === QUOTA_EXCEEDED_ERR) {\n      this.handleQuotaExceededError_({\n        segmentInfo,\n        type,\n        bytes\n      }); // A quota exceeded error should be recoverable with a future re-append, so no need\n      // to trigger an append error.\n\n      return;\n    }\n    this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error); // If an append errors, we often can't recover.\n    // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).\n    //\n    // Trigger a special error so that it can be handled separately from normal,\n    // recoverable errors.\n\n    this.error({\n      message: `${type} append of ${bytes.length}b failed for segment ` + `#${segmentInfo.mediaIndex} in playlist ${segmentInfo.playlist.id}`,\n      metadata: {\n        errorType: videojs.Error.StreamingFailedToAppendSegment\n      }\n    });\n    this.trigger('appenderror');\n  }\n  appendToSourceBuffer_({\n    segmentInfo,\n    type,\n    initSegment,\n    data,\n    bytes\n  }) {\n    // If this is a re-append, bytes were already created and don't need to be recreated\n    if (!bytes) {\n      const segments = [data];\n      let byteLength = data.byteLength;\n      if (initSegment) {\n        // if the media initialization segment is changing, append it before the content\n        // segment\n        segments.unshift(initSegment);\n        byteLength += initSegment.byteLength;\n      } // Technically we should be OK appending the init segment separately, however, we\n      // haven't yet tested that, and prepending is how we have always done things.\n\n      bytes = concatSegments({\n        bytes: byteLength,\n        segments\n      });\n    }\n    const metadata = {\n      segmentInfo: segmentInfoPayload({\n        type: this.loaderType_,\n        segment: segmentInfo\n      })\n    };\n    this.trigger({\n      type: 'segmentappendstart',\n      metadata\n    });\n    this.sourceUpdater_.appendBuffer({\n      segmentInfo,\n      type,\n      bytes\n    }, this.handleAppendError_.bind(this, {\n      segmentInfo,\n      type,\n      bytes\n    }));\n  }\n  handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {\n    if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {\n      return;\n    }\n    const segment = this.pendingSegment_.segment;\n    const timingInfoProperty = `${type}TimingInfo`;\n    if (!segment[timingInfoProperty]) {\n      segment[timingInfoProperty] = {};\n    }\n    segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;\n    segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;\n    segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;\n    segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;\n    segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging\n\n    segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;\n  }\n  appendData_(segmentInfo, result) {\n    const {\n      type,\n      data\n    } = result;\n    if (!data || !data.byteLength) {\n      return;\n    }\n    if (type === 'audio' && this.audioDisabled_) {\n      return;\n    }\n    const initSegment = this.getInitSegmentAndUpdateState_({\n      type,\n      initSegment: result.initSegment,\n      playlist: segmentInfo.playlist,\n      map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null\n    });\n    this.appendToSourceBuffer_({\n      segmentInfo,\n      type,\n      initSegment,\n      data\n    });\n  }\n  /**\n   * load a specific segment from a request into the buffer\n   *\n   * @private\n   */\n\n  loadSegment_(segmentInfo) {\n    this.state = 'WAITING';\n    this.pendingSegment_ = segmentInfo;\n    this.trimBackBuffer_(segmentInfo);\n    if (typeof segmentInfo.timestampOffset === 'number') {\n      if (this.transmuxer_) {\n        this.transmuxer_.postMessage({\n          action: 'clearAllMp4Captions'\n        });\n      }\n    }\n    if (!this.hasEnoughInfoToLoad_()) {\n      checkAndFixTimelines(this);\n      this.loadQueue_.push(() => {\n        // regenerate the audioAppendStart, timestampOffset, etc as they\n        // may have changed since this function was added to the queue.\n        const options = _extends({}, segmentInfo, {\n          forceTimestampOffset: true\n        });\n        _extends(segmentInfo, this.generateSegmentInfo_(options));\n        this.isPendingTimestampOffset_ = false;\n        this.updateTransmuxerAndRequestSegment_(segmentInfo);\n      });\n      return;\n    }\n    this.updateTransmuxerAndRequestSegment_(segmentInfo);\n  }\n  updateTransmuxerAndRequestSegment_(segmentInfo) {\n    // We'll update the source buffer's timestamp offset once we have transmuxed data, but\n    // the transmuxer still needs to be updated before then.\n    //\n    // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp\n    // offset must be passed to the transmuxer for stream correcting adjustments.\n    if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {\n      this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared\n\n      segmentInfo.gopsToAlignWith = [];\n      this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh\n\n      this.transmuxer_.postMessage({\n        action: 'reset'\n      });\n      this.transmuxer_.postMessage({\n        action: 'setTimestampOffset',\n        timestampOffset: segmentInfo.timestampOffset\n      });\n    }\n    const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);\n    const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);\n    const isWalkingForward = this.mediaIndex !== null;\n    const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ &&\n    // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,\n    // the first timeline\n    segmentInfo.timeline > 0;\n    const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;\n    this.logger_(`Requesting\n${compactSegmentUrlDescription(segmentInfo.uri)}\n${segmentInfoString(segmentInfo)}`); // If there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),\n    // then this init segment has never been seen before and should be appended.\n    //\n    // At this point the content type (audio/video or both) is not yet known, but it should be safe to set\n    // both to true and leave the decision of whether to append the init segment to append time.\n\n    if (simpleSegment.map && !simpleSegment.map.bytes) {\n      this.logger_('going to request init segment.');\n      this.appendInitSegment_ = {\n        video: true,\n        audio: true\n      };\n    }\n    segmentInfo.abortRequests = mediaSegmentRequest({\n      xhr: this.vhs_.xhr,\n      xhrOptions: this.xhrOptions_,\n      decryptionWorker: this.decrypter_,\n      segment: simpleSegment,\n      abortFn: this.handleAbort_.bind(this, segmentInfo),\n      progressFn: this.handleProgress_.bind(this),\n      trackInfoFn: this.handleTrackInfo_.bind(this),\n      timingInfoFn: this.handleTimingInfo_.bind(this),\n      videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),\n      audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),\n      captionsFn: this.handleCaptions_.bind(this),\n      isEndOfTimeline,\n      endedTimelineFn: () => {\n        this.logger_('received endedtimeline callback');\n      },\n      id3Fn: this.handleId3_.bind(this),\n      dataFn: this.handleData_.bind(this),\n      doneFn: this.segmentRequestFinished_.bind(this),\n      onTransmuxerLog: ({\n        message,\n        level,\n        stream\n      }) => {\n        this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);\n      },\n      triggerSegmentEventFn: ({\n        type,\n        segment,\n        keyInfo,\n        trackInfo,\n        timingInfo\n      }) => {\n        const segInfo = segmentInfoPayload({\n          segment\n        });\n        const metadata = {\n          segmentInfo: segInfo\n        }; // add other properties if necessary.\n\n        if (keyInfo) {\n          metadata.keyInfo = keyInfo;\n        }\n        if (trackInfo) {\n          metadata.trackInfo = trackInfo;\n        }\n        if (timingInfo) {\n          metadata.timingInfo = timingInfo;\n        }\n        this.trigger({\n          type,\n          metadata\n        });\n      }\n    });\n  }\n  /**\n   * trim the back buffer so that we don't have too much data\n   * in the source buffer\n   *\n   * @private\n   *\n   * @param {Object} segmentInfo - the current segment\n   */\n\n  trimBackBuffer_(segmentInfo) {\n    const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of\n    // buffer and a very conservative \"garbage collector\"\n    // We manually clear out the old buffer to ensure\n    // we don't trigger the QuotaExceeded error\n    // on the source buffer during subsequent appends\n\n    if (removeToTime > 0) {\n      this.remove(0, removeToTime);\n    }\n  }\n  /**\n   * created a simplified copy of the segment object with just the\n   * information necessary to perform the XHR and decryption\n   *\n   * @private\n   *\n   * @param {Object} segmentInfo - the current segment\n   * @return {Object} a simplified segment object copy\n   */\n\n  createSimplifiedSegmentObj_(segmentInfo) {\n    const segment = segmentInfo.segment;\n    const part = segmentInfo.part;\n    const isEncrypted = segmentInfo.segment.key || segmentInfo.segment.map && segmentInfo.segment.map.key;\n    const isMediaInitialization = segmentInfo.segment.map && !segmentInfo.segment.map.bytes;\n    const simpleSegment = {\n      resolvedUri: part ? part.resolvedUri : segment.resolvedUri,\n      byterange: part ? part.byterange : segment.byterange,\n      requestId: segmentInfo.requestId,\n      transmuxer: segmentInfo.transmuxer,\n      audioAppendStart: segmentInfo.audioAppendStart,\n      gopsToAlignWith: segmentInfo.gopsToAlignWith,\n      part: segmentInfo.part,\n      type: this.loaderType_,\n      start: segmentInfo.startOfSegment,\n      duration: segmentInfo.duration,\n      isEncrypted,\n      isMediaInitialization\n    };\n    const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];\n    if (previousSegment && previousSegment.timeline === segment.timeline) {\n      // The baseStartTime of a segment is used to handle rollover when probing the TS\n      // segment to retrieve timing information. Since the probe only looks at the media's\n      // times (e.g., PTS and DTS values of the segment), and doesn't consider the\n      // player's time (e.g., player.currentTime()), baseStartTime should reflect the\n      // media time as well. transmuxedDecodeEnd represents the end time of a segment, in\n      // seconds of media time, so should be used here. The previous segment is used since\n      // the end of the previous segment should represent the beginning of the current\n      // segment, so long as they are on the same timeline.\n      if (previousSegment.videoTimingInfo) {\n        simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;\n      } else if (previousSegment.audioTimingInfo) {\n        simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;\n      }\n    }\n    if (segment.key) {\n      // if the media sequence is greater than 2^32, the IV will be incorrect\n      // assuming 10s segments, that would be about 1300 years\n      const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);\n      simpleSegment.key = this.segmentKey(segment.key);\n      simpleSegment.key.iv = iv;\n    }\n    if (segment.map) {\n      simpleSegment.map = this.initSegmentForMap(segment.map);\n    }\n    return simpleSegment;\n  }\n  saveTransferStats_(stats) {\n    // every request counts as a media request even if it has been aborted\n    // or canceled due to a timeout\n    this.mediaRequests += 1;\n    if (stats) {\n      this.mediaBytesTransferred += stats.bytesReceived;\n      this.mediaTransferDuration += stats.roundTripTime;\n    }\n  }\n  saveBandwidthRelatedStats_(duration, stats) {\n    // byteLength will be used for throughput, and should be based on bytes receieved,\n    // which we only know at the end of the request and should reflect total bytes\n    // downloaded rather than just bytes processed from components of the segment\n    this.pendingSegment_.byteLength = stats.bytesReceived;\n    if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {\n      this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);\n      return;\n    }\n    const metadata = {\n      bandwidthInfo: {\n        from: this.bandwidth,\n        to: stats.bandwidth\n      }\n    }; // player event with payload\n\n    this.trigger({\n      type: 'bandwidthupdated',\n      metadata\n    });\n    this.bandwidth = stats.bandwidth;\n    this.roundTrip = stats.roundTripTime;\n  }\n  handleTimeout_() {\n    // although the VTT segment loader bandwidth isn't really used, it's good to\n    // maintain functinality between segment loaders\n    this.mediaRequestsTimedout += 1;\n    this.bandwidth = 1;\n    this.roundTrip = NaN;\n    this.trigger('bandwidthupdate');\n    this.trigger('timeout');\n  }\n  /**\n   * Handle the callback from the segmentRequest function and set the\n   * associated SegmentLoader state and errors if necessary\n   *\n   * @private\n   */\n\n  segmentRequestFinished_(error, simpleSegment, result) {\n    // TODO handle special cases, e.g., muxed audio/video but only audio in the segment\n    // check the call queue directly since this function doesn't need to deal with any\n    // data, and can continue even if the source buffers are not set up and we didn't get\n    // any data from the segment\n    if (this.callQueue_.length) {\n      this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));\n      return;\n    }\n    this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset\n\n    if (!this.pendingSegment_) {\n      return;\n    } // the request was aborted and the SegmentLoader has already started\n    // another request. this can happen when the timeout for an aborted\n    // request triggers due to a limitation in the XHR library\n    // do not count this as any sort of request or we risk double-counting\n\n    if (simpleSegment.requestId !== this.pendingSegment_.requestId) {\n      return;\n    } // an error occurred from the active pendingSegment_ so reset everything\n\n    if (error) {\n      this.pendingSegment_ = null;\n      this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done\n\n      if (error.code === REQUEST_ERRORS.ABORTED) {\n        return;\n      }\n      this.pause(); // the error is really just that at least one of the requests timed-out\n      // set the bandwidth to a very low value and trigger an ABR switch to\n      // take emergency action\n\n      if (error.code === REQUEST_ERRORS.TIMEOUT) {\n        this.handleTimeout_();\n        return;\n      } // if control-flow has arrived here, then the error is real\n      // emit an error event to exclude the current playlist\n\n      this.mediaRequestsErrored += 1;\n      this.error(error);\n      this.trigger('error');\n      return;\n    }\n    const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request\n    // generated for ABR purposes\n\n    this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);\n    segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;\n    if (result.gopInfo) {\n      this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);\n    } // Although we may have already started appending on progress, we shouldn't switch the\n    // state away from loading until we are officially done loading the segment data.\n\n    this.state = 'APPENDING'; // used for testing\n\n    this.trigger('appending');\n    this.waitForAppendsToComplete_(segmentInfo);\n  }\n  setTimeMapping_(timeline) {\n    const timelineMapping = this.syncController_.mappingForTimeline(timeline);\n    if (timelineMapping !== null) {\n      this.timeMapping_ = timelineMapping;\n    }\n  }\n  updateMediaSecondsLoaded_(segment) {\n    if (typeof segment.start === 'number' && typeof segment.end === 'number') {\n      this.mediaSecondsLoaded += segment.end - segment.start;\n    } else {\n      this.mediaSecondsLoaded += segment.duration;\n    }\n  }\n  shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {\n    if (timestampOffset === null) {\n      return false;\n    } // note that we're potentially using the same timestamp offset for both video and\n    // audio\n\n    if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {\n      return true;\n    }\n    if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {\n      return true;\n    }\n    return false;\n  }\n  trueSegmentStart_({\n    currentStart,\n    playlist,\n    mediaIndex,\n    firstVideoFrameTimeForData,\n    currentVideoTimestampOffset,\n    useVideoTimingInfo,\n    videoTimingInfo,\n    audioTimingInfo\n  }) {\n    if (typeof currentStart !== 'undefined') {\n      // if start was set once, keep using it\n      return currentStart;\n    }\n    if (!useVideoTimingInfo) {\n      return audioTimingInfo.start;\n    }\n    const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained\n    // within that segment. Since the transmuxer maintains a cache of incomplete data\n    // from and/or the last frame seen, the start time may reflect a frame that starts\n    // in the previous segment. Check for that case and ensure the start time is\n    // accurate for the segment.\n\n    if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {\n      return firstVideoFrameTimeForData;\n    }\n    return videoTimingInfo.start;\n  }\n  waitForAppendsToComplete_(segmentInfo) {\n    const trackInfo = this.getCurrentMediaInfo_(segmentInfo);\n    if (!trackInfo) {\n      this.error({\n        message: 'No starting media returned, likely due to an unsupported media format.',\n        playlistExclusionDuration: Infinity\n      });\n      this.trigger('error');\n      return;\n    } // Although transmuxing is done, appends may not yet be finished. Throw a marker\n    // on each queue this loader is responsible for to ensure that the appends are\n    // complete.\n\n    const {\n      hasAudio,\n      hasVideo,\n      isMuxed\n    } = trackInfo;\n    const waitForVideo = this.loaderType_ === 'main' && hasVideo;\n    const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;\n    segmentInfo.waitingOnAppends = 0; // segments with no data\n\n    if (!segmentInfo.hasAppendedData_) {\n      if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {\n        // When there's no audio or video data in the segment, there's no audio or video\n        // timing information.\n        //\n        // If there's no audio or video timing information, then the timestamp offset\n        // can't be adjusted to the appropriate value for the transmuxer and source\n        // buffers.\n        //\n        // Therefore, the next segment should be used to set the timestamp offset.\n        this.isPendingTimestampOffset_ = true;\n      } // override settings for metadata only segments\n\n      segmentInfo.timingInfo = {\n        start: 0\n      };\n      segmentInfo.waitingOnAppends++;\n      if (!this.isPendingTimestampOffset_) {\n        // update the timestampoffset\n        this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have\n        // no video/audio data.\n\n        this.processMetadataQueue_();\n      } // append is \"done\" instantly with no data.\n\n      this.checkAppendsDone_(segmentInfo);\n      return;\n    } // Since source updater could call back synchronously, do the increments first.\n\n    if (waitForVideo) {\n      segmentInfo.waitingOnAppends++;\n    }\n    if (waitForAudio) {\n      segmentInfo.waitingOnAppends++;\n    }\n    if (waitForVideo) {\n      this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));\n    }\n    if (waitForAudio) {\n      this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));\n    }\n  }\n  checkAppendsDone_(segmentInfo) {\n    if (this.checkForAbort_(segmentInfo.requestId)) {\n      return;\n    }\n    segmentInfo.waitingOnAppends--;\n    if (segmentInfo.waitingOnAppends === 0) {\n      this.handleAppendsDone_();\n    }\n  }\n  checkForIllegalMediaSwitch(trackInfo) {\n    const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);\n    if (illegalMediaSwitchError) {\n      this.error({\n        message: illegalMediaSwitchError,\n        playlistExclusionDuration: Infinity\n      });\n      this.trigger('error');\n      return true;\n    }\n    return false;\n  }\n  updateSourceBufferTimestampOffset_(segmentInfo) {\n    if (segmentInfo.timestampOffset === null ||\n    // we don't yet have the start for whatever media type (video or audio) has\n    // priority, timing-wise, so we must wait\n    typeof segmentInfo.timingInfo.start !== 'number' ||\n    // already updated the timestamp offset for this segment\n    segmentInfo.changedTimestampOffset ||\n    // the alt audio loader should not be responsible for setting the timestamp offset\n    this.loaderType_ !== 'main') {\n      return;\n    }\n    let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that\n    // the timing info here comes from video. In the event that the audio is longer than\n    // the video, this will trim the start of the audio.\n    // This also trims any offset from 0 at the beginning of the media\n\n    segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({\n      videoTimingInfo: segmentInfo.segment.videoTimingInfo,\n      audioTimingInfo: segmentInfo.segment.audioTimingInfo,\n      timingInfo: segmentInfo.timingInfo\n    }); // In the event that there are part segment downloads, each will try to update the\n    // timestamp offset. Retaining this bit of state prevents us from updating in the\n    // future (within the same segment), however, there may be a better way to handle it.\n\n    segmentInfo.changedTimestampOffset = true;\n    if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {\n      this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);\n      didChange = true;\n    }\n    if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {\n      this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);\n      didChange = true;\n    }\n    if (didChange) {\n      this.trigger('timestampoffset');\n    }\n  }\n  getSegmentStartTimeForTimestampOffsetCalculation_({\n    videoTimingInfo,\n    audioTimingInfo,\n    timingInfo\n  }) {\n    if (!this.useDtsForTimestampOffset_) {\n      return timingInfo.start;\n    }\n    if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {\n      return videoTimingInfo.transmuxedDecodeStart;\n    } // handle audio only\n\n    if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {\n      return audioTimingInfo.transmuxedDecodeStart;\n    } // handle content not transmuxed (e.g., MP4)\n\n    return timingInfo.start;\n  }\n  updateTimingInfoEnd_(segmentInfo) {\n    segmentInfo.timingInfo = segmentInfo.timingInfo || {};\n    const trackInfo = this.getMediaInfo_();\n    const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;\n    const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;\n    if (!prioritizedTimingInfo) {\n      return;\n    }\n    segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ?\n    // End time may not exist in a case where we aren't parsing the full segment (one\n    // current example is the case of fmp4), so use the rough duration to calculate an\n    // end time.\n    prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;\n  }\n  /**\n   * callback to run when appendBuffer is finished. detects if we are\n   * in a good state to do things with the data we got, or if we need\n   * to wait for more\n   *\n   * @private\n   */\n\n  handleAppendsDone_() {\n    // appendsdone can cause an abort\n    if (this.pendingSegment_) {\n      const metadata = {\n        segmentInfo: segmentInfoPayload({\n          type: this.loaderType_,\n          segment: this.pendingSegment_\n        })\n      };\n      this.trigger({\n        type: 'appendsdone',\n        metadata\n      });\n    }\n    if (!this.pendingSegment_) {\n      this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in\n      // all appending cases?\n\n      if (!this.paused()) {\n        this.monitorBuffer_();\n      }\n      return;\n    }\n    const segmentInfo = this.pendingSegment_;\n    if (segmentInfo.part && segmentInfo.part.syncInfo) {\n      // low-latency flow\n      segmentInfo.part.syncInfo.markAppended();\n    } else if (segmentInfo.segment.syncInfo) {\n      // normal flow\n      segmentInfo.segment.syncInfo.markAppended();\n    } // Now that the end of the segment has been reached, we can set the end time. It's\n    // best to wait until all appends are done so we're sure that the primary media is\n    // finished (and we have its end time).\n\n    this.updateTimingInfoEnd_(segmentInfo);\n    if (this.shouldSaveSegmentTimingInfo_) {\n      // Timeline mappings should only be saved for the main loader. This is for multiple\n      // reasons:\n      //\n      // 1) Only one mapping is saved per timeline, meaning that if both the audio loader\n      //    and the main loader try to save the timeline mapping, whichever comes later\n      //    will overwrite the first. In theory this is OK, as the mappings should be the\n      //    same, however, it breaks for (2)\n      // 2) In the event of a live stream, the initial live point will make for a somewhat\n      //    arbitrary mapping. If audio and video streams are not perfectly in-sync, then\n      //    the mapping will be off for one of the streams, dependent on which one was\n      //    first saved (see (1)).\n      // 3) Primary timing goes by video in VHS, so the mapping should be video.\n      //\n      // Since the audio loader will wait for the main loader to load the first segment,\n      // the main loader will save the first timeline mapping, and ensure that there won't\n      // be a case where audio loads two segments without saving a mapping (thus leading\n      // to missing segment timing info).\n      this.syncController_.saveSegmentTimingInfo({\n        segmentInfo,\n        shouldSaveTimelineMapping: this.loaderType_ === 'main'\n      });\n    }\n    const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);\n    if (segmentDurationMessage) {\n      if (segmentDurationMessage.severity === 'warn') {\n        videojs.log.warn(segmentDurationMessage.message);\n      } else {\n        this.logger_(segmentDurationMessage.message);\n      }\n    }\n    this.recordThroughput_(segmentInfo);\n    this.pendingSegment_ = null;\n    this.state = 'READY';\n    if (segmentInfo.isSyncRequest) {\n      this.trigger('syncinfoupdate'); // if the sync request was not appended\n      // then it was not the correct segment.\n      // throw it away and use the data it gave us\n      // to get the correct one.\n\n      if (!segmentInfo.hasAppendedData_) {\n        this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);\n        return;\n      }\n    }\n    this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);\n    this.addSegmentMetadataCue_(segmentInfo);\n    this.fetchAtBuffer_ = true;\n    if (this.currentTimeline_ !== segmentInfo.timeline) {\n      this.timelineChangeController_.lastTimelineChange({\n        type: this.loaderType_,\n        from: this.currentTimeline_,\n        to: segmentInfo.timeline\n      }); // If audio is not disabled, the main segment loader is responsible for updating\n      // the audio timeline as well. If the content is video only, this won't have any\n      // impact.\n\n      if (this.loaderType_ === 'main' && !this.audioDisabled_) {\n        this.timelineChangeController_.lastTimelineChange({\n          type: 'audio',\n          from: this.currentTimeline_,\n          to: segmentInfo.timeline\n        });\n      }\n    }\n    this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before\n    // the following conditional otherwise it may consider this a bad \"guess\"\n    // and attempt to resync when the post-update seekable window and live\n    // point would mean that this was the perfect segment to fetch\n\n    this.trigger('syncinfoupdate');\n    const segment = segmentInfo.segment;\n    const part = segmentInfo.part;\n    const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;\n    const badPartGuess = part && part.end && this.currentTime_() - part.end > segmentInfo.playlist.partTargetDuration * 3; // If we previously appended a segment/part that ends more than 3 part/targetDurations before\n    // the currentTime_ that means that our conservative guess was too conservative.\n    // In that case, reset the loader state so that we try to use any information gained\n    // from the previous request to create a new, more accurate, sync-point.\n\n    if (badSegmentGuess || badPartGuess) {\n      this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);\n      this.resetEverything();\n      return;\n    }\n    const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment\n    // and conservatively guess\n\n    if (isWalkingForward) {\n      this.trigger('bandwidthupdate');\n    }\n    this.trigger('progress');\n    this.mediaIndex = segmentInfo.mediaIndex;\n    this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the\n    // buffer, end the stream. this ensures the \"ended\" event will\n    // fire if playback reaches that point.\n\n    if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {\n      this.endOfStream();\n    } // used for testing\n\n    this.trigger('appended');\n    if (segmentInfo.hasAppendedData_) {\n      this.mediaAppends++;\n    }\n    if (!this.paused()) {\n      this.monitorBuffer_();\n    }\n  }\n  /**\n   * Records the current throughput of the decrypt, transmux, and append\n   * portion of the semgment pipeline. `throughput.rate` is a the cumulative\n   * moving average of the throughput. `throughput.count` is the number of\n   * data points in the average.\n   *\n   * @private\n   * @param {Object} segmentInfo the object returned by loadSegment\n   */\n\n  recordThroughput_(segmentInfo) {\n    if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {\n      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}`);\n      return;\n    }\n    const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide\n    // by zero in the case where the throughput is ridiculously high\n\n    const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second\n\n    const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:\n    //   newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)\n\n    this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;\n  }\n  /**\n   * Adds a cue to the segment-metadata track with some metadata information about the\n   * segment\n   *\n   * @private\n   * @param {Object} segmentInfo\n   *        the object returned by loadSegment\n   * @method addSegmentMetadataCue_\n   */\n\n  addSegmentMetadataCue_(segmentInfo) {\n    if (!this.segmentMetadataTrack_) {\n      return;\n    }\n    const segment = segmentInfo.segment;\n    const start = segment.start;\n    const end = segment.end; // Do not try adding the cue if the start and end times are invalid.\n\n    if (!finite(start) || !finite(end)) {\n      return;\n    }\n    removeCuesFromTrack(start, end, this.segmentMetadataTrack_);\n    const Cue = window$1.WebKitDataCue || window$1.VTTCue;\n    const value = {\n      custom: segment.custom,\n      dateTimeObject: segment.dateTimeObject,\n      dateTimeString: segment.dateTimeString,\n      programDateTime: segment.programDateTime,\n      bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,\n      resolution: segmentInfo.playlist.attributes.RESOLUTION,\n      codecs: segmentInfo.playlist.attributes.CODECS,\n      byteLength: segmentInfo.byteLength,\n      uri: segmentInfo.uri,\n      timeline: segmentInfo.timeline,\n      playlist: segmentInfo.playlist.id,\n      start,\n      end\n    };\n    const data = JSON.stringify(value);\n    const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between\n    // the differences of WebKitDataCue in safari and VTTCue in other browsers\n\n    cue.value = value;\n    this.segmentMetadataTrack_.addCue(cue);\n  }\n}\nfunction noop() {}\nconst toTitleCase = function (string) {\n  if (typeof string !== 'string') {\n    return string;\n  }\n  return string.replace(/./, w => w.toUpperCase());\n};\n\n/**\n * @file source-updater.js\n */\nconst bufferTypes = ['video', 'audio'];\nconst updating = (type, sourceUpdater) => {\n  const sourceBuffer = sourceUpdater[`${type}Buffer`];\n  return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];\n};\nconst nextQueueIndexOfType = (type, queue) => {\n  for (let i = 0; i < queue.length; i++) {\n    const queueEntry = queue[i];\n    if (queueEntry.type === 'mediaSource') {\n      // If the next entry is a media source entry (uses multiple source buffers), block\n      // processing to allow it to go through first.\n      return null;\n    }\n    if (queueEntry.type === type) {\n      return i;\n    }\n  }\n  return null;\n};\nconst shiftQueue = (type, sourceUpdater) => {\n  if (sourceUpdater.queue.length === 0) {\n    return;\n  }\n  let queueIndex = 0;\n  let queueEntry = sourceUpdater.queue[queueIndex];\n  if (queueEntry.type === 'mediaSource') {\n    if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {\n      sourceUpdater.queue.shift();\n      queueEntry.action(sourceUpdater);\n      if (queueEntry.doneFn) {\n        queueEntry.doneFn();\n      } // Only specific source buffer actions must wait for async updateend events. Media\n      // Source actions process synchronously. Therefore, both audio and video source\n      // buffers are now clear to process the next queue entries.\n\n      shiftQueue('audio', sourceUpdater);\n      shiftQueue('video', sourceUpdater);\n    } // Media Source actions require both source buffers, so if the media source action\n    // couldn't process yet (because one or both source buffers are busy), block other\n    // queue actions until both are available and the media source action can process.\n\n    return;\n  }\n  if (type === 'mediaSource') {\n    // If the queue was shifted by a media source action (this happens when pushing a\n    // media source action onto the queue), then it wasn't from an updateend event from an\n    // audio or video source buffer, so there's no change from previous state, and no\n    // processing should be done.\n    return;\n  } // Media source queue entries don't need to consider whether the source updater is\n  // started (i.e., source buffers are created) as they don't need the source buffers, but\n  // source buffer queue entries do.\n\n  if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {\n    return;\n  }\n  if (queueEntry.type !== type) {\n    queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);\n    if (queueIndex === null) {\n      // Either there's no queue entry that uses this source buffer type in the queue, or\n      // there's a media source queue entry before the next entry of this type, in which\n      // case wait for that action to process first.\n      return;\n    }\n    queueEntry = sourceUpdater.queue[queueIndex];\n  }\n  sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.\n  //\n  // The queue pending operation must be set before the action is performed in the event\n  // that the action results in a synchronous event that is acted upon. For instance, if\n  // an exception is thrown that can be handled, it's possible that new actions will be\n  // appended to an empty queue and immediately executed, but would not have the correct\n  // pending information if this property was set after the action was performed.\n\n  sourceUpdater.queuePending[type] = queueEntry;\n  queueEntry.action(type, sourceUpdater);\n  if (!queueEntry.doneFn) {\n    // synchronous operation, process next entry\n    sourceUpdater.queuePending[type] = null;\n    shiftQueue(type, sourceUpdater);\n    return;\n  }\n};\nconst cleanupBuffer = (type, sourceUpdater) => {\n  const buffer = sourceUpdater[`${type}Buffer`];\n  const titleType = toTitleCase(type);\n  if (!buffer) {\n    return;\n  }\n  buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);\n  buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);\n  sourceUpdater.codecs[type] = null;\n  sourceUpdater[`${type}Buffer`] = null;\n};\nconst inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;\nconst actions = {\n  appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {\n    const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null\n    // or the media source does not contain this source buffer.\n\n    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {\n      return;\n    }\n    sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);\n    try {\n      sourceBuffer.appendBuffer(bytes);\n    } catch (e) {\n      sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);\n      sourceUpdater.queuePending[type] = null;\n      onError(e);\n    }\n  },\n  remove: (start, end) => (type, sourceUpdater) => {\n    const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null\n    // or the media source does not contain this source buffer.\n\n    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {\n      return;\n    }\n    sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);\n    try {\n      sourceBuffer.remove(start, end);\n    } catch (e) {\n      sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);\n    }\n  },\n  timestampOffset: offset => (type, sourceUpdater) => {\n    const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null\n    // or the media source does not contain this source buffer.\n\n    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {\n      return;\n    }\n    sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);\n    sourceBuffer.timestampOffset = offset;\n  },\n  callback: callback => (type, sourceUpdater) => {\n    callback();\n  },\n  endOfStream: error => sourceUpdater => {\n    if (sourceUpdater.mediaSource.readyState !== 'open') {\n      return;\n    }\n    sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);\n    try {\n      sourceUpdater.mediaSource.endOfStream(error);\n    } catch (e) {\n      videojs.log.warn('Failed to call media source endOfStream', e);\n    }\n  },\n  duration: duration => sourceUpdater => {\n    sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);\n    try {\n      sourceUpdater.mediaSource.duration = duration;\n    } catch (e) {\n      videojs.log.warn('Failed to set media source duration', e);\n    }\n  },\n  abort: () => (type, sourceUpdater) => {\n    if (sourceUpdater.mediaSource.readyState !== 'open') {\n      return;\n    }\n    const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null\n    // or the media source does not contain this source buffer.\n\n    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {\n      return;\n    }\n    sourceUpdater.logger_(`calling abort on ${type}Buffer`);\n    try {\n      sourceBuffer.abort();\n    } catch (e) {\n      videojs.log.warn(`Failed to abort on ${type}Buffer`, e);\n    }\n  },\n  addSourceBuffer: (type, codec) => sourceUpdater => {\n    const titleType = toTitleCase(type);\n    const mime = getMimeForCodec(codec);\n    sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);\n    const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);\n    sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);\n    sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);\n    sourceUpdater.codecs[type] = codec;\n    sourceUpdater[`${type}Buffer`] = sourceBuffer;\n  },\n  removeSourceBuffer: type => sourceUpdater => {\n    const sourceBuffer = sourceUpdater[`${type}Buffer`];\n    cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null\n    // or the media source does not contain this source buffer.\n\n    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {\n      return;\n    }\n    sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);\n    try {\n      sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);\n    } catch (e) {\n      videojs.log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);\n    }\n  },\n  changeType: codec => (type, sourceUpdater) => {\n    const sourceBuffer = sourceUpdater[`${type}Buffer`];\n    const mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null\n    // or the media source does not contain this source buffer.\n\n    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {\n      return;\n    } // do not update codec if we don't need to.\n    // Only update if we change the codec base.\n    // For example, going from avc1.640028 to avc1.64001f does not require a changeType call.\n\n    const newCodecBase = codec.substring(0, codec.indexOf('.'));\n    const oldCodec = sourceUpdater.codecs[type];\n    const oldCodecBase = oldCodec.substring(0, oldCodec.indexOf('.'));\n    if (oldCodecBase === newCodecBase) {\n      return;\n    }\n    const metadata = {\n      codecsChangeInfo: {\n        from: oldCodec,\n        to: codec\n      }\n    };\n    sourceUpdater.trigger({\n      type: 'codecschange',\n      metadata\n    });\n    sourceUpdater.logger_(`changing ${type}Buffer codec from ${oldCodec} to ${codec}`); // check if change to the provided type is supported\n\n    try {\n      sourceBuffer.changeType(mime);\n      sourceUpdater.codecs[type] = codec;\n    } catch (e) {\n      metadata.errorType = videojs.Error.StreamingCodecsChangeError;\n      metadata.error = e;\n      e.metadata = metadata;\n      sourceUpdater.error_ = e;\n      sourceUpdater.trigger('error');\n      videojs.log.warn(`Failed to changeType on ${type}Buffer`, e);\n    }\n  }\n};\nconst pushQueue = ({\n  type,\n  sourceUpdater,\n  action,\n  doneFn,\n  name\n}) => {\n  sourceUpdater.queue.push({\n    type,\n    action,\n    doneFn,\n    name\n  });\n  shiftQueue(type, sourceUpdater);\n};\nconst onUpdateend = (type, sourceUpdater) => e => {\n  // Although there should, in theory, be a pending action for any updateend receieved,\n  // there are some actions that may trigger updateend events without set definitions in\n  // the w3c spec. For instance, setting the duration on the media source may trigger\n  // updateend events on source buffers. This does not appear to be in the spec. As such,\n  // if we encounter an updateend without a corresponding pending action from our queue\n  // for that source buffer type, process the next action.\n  const bufferedRangesForType = sourceUpdater[`${type}Buffered`]();\n  const descriptiveString = bufferedRangesToString(bufferedRangesForType);\n  sourceUpdater.logger_(`received \"updateend\" event for ${type} Source Buffer: `, descriptiveString);\n  if (sourceUpdater.queuePending[type]) {\n    const doneFn = sourceUpdater.queuePending[type].doneFn;\n    sourceUpdater.queuePending[type] = null;\n    if (doneFn) {\n      // if there's an error, report it\n      doneFn(sourceUpdater[`${type}Error_`]);\n    }\n  }\n  shiftQueue(type, sourceUpdater);\n};\n/**\n * A queue of callbacks to be serialized and applied when a\n * MediaSource and its associated SourceBuffers are not in the\n * updating state. It is used by the segment loader to update the\n * underlying SourceBuffers when new data is loaded, for instance.\n *\n * @class SourceUpdater\n * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from\n * @param {string} mimeType the desired MIME type of the underlying SourceBuffer\n */\n\nclass SourceUpdater extends videojs.EventTarget {\n  constructor(mediaSource) {\n    super();\n    this.mediaSource = mediaSource;\n    this.sourceopenListener_ = () => shiftQueue('mediaSource', this);\n    this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);\n    this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0\n\n    this.audioTimestampOffset_ = 0;\n    this.videoTimestampOffset_ = 0;\n    this.queue = [];\n    this.queuePending = {\n      audio: null,\n      video: null\n    };\n    this.delayedAudioAppendQueue_ = [];\n    this.videoAppendQueued_ = false;\n    this.codecs = {};\n    this.onVideoUpdateEnd_ = onUpdateend('video', this);\n    this.onAudioUpdateEnd_ = onUpdateend('audio', this);\n    this.onVideoError_ = e => {\n      // used for debugging\n      this.videoError_ = e;\n    };\n    this.onAudioError_ = e => {\n      // used for debugging\n      this.audioError_ = e;\n    };\n    this.createdSourceBuffers_ = false;\n    this.initializedEme_ = false;\n    this.triggeredReady_ = false;\n  }\n  initializedEme() {\n    this.initializedEme_ = true;\n    this.triggerReady();\n  }\n  hasCreatedSourceBuffers() {\n    // if false, likely waiting on one of the segment loaders to get enough data to create\n    // source buffers\n    return this.createdSourceBuffers_;\n  }\n  hasInitializedAnyEme() {\n    return this.initializedEme_;\n  }\n  ready() {\n    return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();\n  }\n  createSourceBuffers(codecs) {\n    if (this.hasCreatedSourceBuffers()) {\n      // already created them before\n      return;\n    } // the intial addOrChangeSourceBuffers will always be\n    // two add buffers.\n\n    this.addOrChangeSourceBuffers(codecs);\n    this.createdSourceBuffers_ = true;\n    this.trigger('createdsourcebuffers');\n    this.triggerReady();\n  }\n  triggerReady() {\n    // only allow ready to be triggered once, this prevents the case\n    // where:\n    // 1. we trigger createdsourcebuffers\n    // 2. ie 11 synchronously initializates eme\n    // 3. the synchronous initialization causes us to trigger ready\n    // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.\n    if (this.ready() && !this.triggeredReady_) {\n      this.triggeredReady_ = true;\n      this.trigger('ready');\n    }\n  }\n  /**\n   * Add a type of source buffer to the media source.\n   *\n   * @param {string} type\n   *        The type of source buffer to add.\n   *\n   * @param {string} codec\n   *        The codec to add the source buffer with.\n   */\n\n  addSourceBuffer(type, codec) {\n    pushQueue({\n      type: 'mediaSource',\n      sourceUpdater: this,\n      action: actions.addSourceBuffer(type, codec),\n      name: 'addSourceBuffer'\n    });\n  }\n  /**\n   * call abort on a source buffer.\n   *\n   * @param {string} type\n   *        The type of source buffer to call abort on.\n   */\n\n  abort(type) {\n    pushQueue({\n      type,\n      sourceUpdater: this,\n      action: actions.abort(type),\n      name: 'abort'\n    });\n  }\n  /**\n   * Call removeSourceBuffer and remove a specific type\n   * of source buffer on the mediaSource.\n   *\n   * @param {string} type\n   *        The type of source buffer to remove.\n   */\n\n  removeSourceBuffer(type) {\n    if (!this.canRemoveSourceBuffer()) {\n      videojs.log.error('removeSourceBuffer is not supported!');\n      return;\n    }\n    pushQueue({\n      type: 'mediaSource',\n      sourceUpdater: this,\n      action: actions.removeSourceBuffer(type),\n      name: 'removeSourceBuffer'\n    });\n  }\n  /**\n   * Whether or not the removeSourceBuffer function is supported\n   * on the mediaSource.\n   *\n   * @return {boolean}\n   *          if removeSourceBuffer can be called.\n   */\n\n  canRemoveSourceBuffer() {\n    // As of Firefox 83 removeSourceBuffer\n    // throws errors, so we report that it does not support this.\n    return !videojs.browser.IS_FIREFOX && window$1.MediaSource && window$1.MediaSource.prototype && typeof window$1.MediaSource.prototype.removeSourceBuffer === 'function';\n  }\n  /**\n   * Whether or not the changeType function is supported\n   * on our SourceBuffers.\n   *\n   * @return {boolean}\n   *         if changeType can be called.\n   */\n\n  static canChangeType() {\n    return window$1.SourceBuffer && window$1.SourceBuffer.prototype && typeof window$1.SourceBuffer.prototype.changeType === 'function';\n  }\n  /**\n   * Whether or not the changeType function is supported\n   * on our SourceBuffers.\n   *\n   * @return {boolean}\n   *         if changeType can be called.\n   */\n\n  canChangeType() {\n    return this.constructor.canChangeType();\n  }\n  /**\n   * Call the changeType function on a source buffer, given the code and type.\n   *\n   * @param {string} type\n   *        The type of source buffer to call changeType on.\n   *\n   * @param {string} codec\n   *        The codec string to change type with on the source buffer.\n   */\n\n  changeType(type, codec) {\n    if (!this.canChangeType()) {\n      videojs.log.error('changeType is not supported!');\n      return;\n    }\n    pushQueue({\n      type,\n      sourceUpdater: this,\n      action: actions.changeType(codec),\n      name: 'changeType'\n    });\n  }\n  /**\n   * Add source buffers with a codec or, if they are already created,\n   * call changeType on source buffers using changeType.\n   *\n   * @param {Object} codecs\n   *        Codecs to switch to\n   */\n\n  addOrChangeSourceBuffers(codecs) {\n    if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {\n      throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');\n    }\n    Object.keys(codecs).forEach(type => {\n      const codec = codecs[type];\n      if (!this.hasCreatedSourceBuffers()) {\n        return this.addSourceBuffer(type, codec);\n      }\n      if (this.canChangeType()) {\n        this.changeType(type, codec);\n      }\n    });\n  }\n  /**\n   * Queue an update to append an ArrayBuffer.\n   *\n   * @param {MediaObject} object containing audioBytes and/or videoBytes\n   * @param {Function} done the function to call when done\n   * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data\n   */\n\n  appendBuffer(options, doneFn) {\n    const {\n      segmentInfo,\n      type,\n      bytes\n    } = options;\n    this.processedAppend_ = true;\n    if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {\n      this.delayedAudioAppendQueue_.push([options, doneFn]);\n      this.logger_(`delayed audio append of ${bytes.length} until video append`);\n      return;\n    } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will\n    // not be fired. This means that the queue will be blocked until the next action\n    // taken by the segment-loader. Provide a mechanism for segment-loader to handle\n    // these errors by calling the doneFn with the specific error.\n\n    const onError = doneFn;\n    pushQueue({\n      type,\n      sourceUpdater: this,\n      action: actions.appendBuffer(bytes, segmentInfo || {\n        mediaIndex: -1\n      }, onError),\n      doneFn,\n      name: 'appendBuffer'\n    });\n    if (type === 'video') {\n      this.videoAppendQueued_ = true;\n      if (!this.delayedAudioAppendQueue_.length) {\n        return;\n      }\n      const queue = this.delayedAudioAppendQueue_.slice();\n      this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);\n      this.delayedAudioAppendQueue_.length = 0;\n      queue.forEach(que => {\n        this.appendBuffer.apply(this, que);\n      });\n    }\n  }\n  /**\n   * Get the audio buffer's buffered timerange.\n   *\n   * @return {TimeRange}\n   *         The audio buffer's buffered time range\n   */\n\n  audioBuffered() {\n    // no media source/source buffer or it isn't in the media sources\n    // source buffer list\n    if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {\n      return createTimeRanges();\n    }\n    return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();\n  }\n  /**\n   * Get the video buffer's buffered timerange.\n   *\n   * @return {TimeRange}\n   *         The video buffer's buffered time range\n   */\n\n  videoBuffered() {\n    // no media source/source buffer or it isn't in the media sources\n    // source buffer list\n    if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {\n      return createTimeRanges();\n    }\n    return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();\n  }\n  /**\n   * Get a combined video/audio buffer's buffered timerange.\n   *\n   * @return {TimeRange}\n   *         the combined time range\n   */\n\n  buffered() {\n    const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;\n    const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;\n    if (audio && !video) {\n      return this.audioBuffered();\n    }\n    if (video && !audio) {\n      return this.videoBuffered();\n    }\n    return bufferIntersection(this.audioBuffered(), this.videoBuffered());\n  }\n  /**\n   * Add a callback to the queue that will set duration on the mediaSource.\n   *\n   * @param {number} duration\n   *        The duration to set\n   *\n   * @param {Function} [doneFn]\n   *        function to run after duration has been set.\n   */\n\n  setDuration(duration, doneFn = noop) {\n    // In order to set the duration on the media source, it's necessary to wait for all\n    // source buffers to no longer be updating. \"If the updating attribute equals true on\n    // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and\n    // abort these steps.\" (source: https://www.w3.org/TR/media-source/#attributes).\n    pushQueue({\n      type: 'mediaSource',\n      sourceUpdater: this,\n      action: actions.duration(duration),\n      name: 'duration',\n      doneFn\n    });\n  }\n  /**\n   * Add a mediaSource endOfStream call to the queue\n   *\n   * @param {Error} [error]\n   *        Call endOfStream with an error\n   *\n   * @param {Function} [doneFn]\n   *        A function that should be called when the\n   *        endOfStream call has finished.\n   */\n\n  endOfStream(error = null, doneFn = noop) {\n    if (typeof error !== 'string') {\n      error = undefined;\n    } // In order to set the duration on the media source, it's necessary to wait for all\n    // source buffers to no longer be updating. \"If the updating attribute equals true on\n    // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and\n    // abort these steps.\" (source: https://www.w3.org/TR/media-source/#attributes).\n\n    pushQueue({\n      type: 'mediaSource',\n      sourceUpdater: this,\n      action: actions.endOfStream(error),\n      name: 'endOfStream',\n      doneFn\n    });\n  }\n  /**\n   * Queue an update to remove a time range from the buffer.\n   *\n   * @param {number} start where to start the removal\n   * @param {number} end where to end the removal\n   * @param {Function} [done=noop] optional callback to be executed when the remove\n   * operation is complete\n   * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end\n   */\n\n  removeAudio(start, end, done = noop) {\n    if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {\n      done();\n      return;\n    }\n    pushQueue({\n      type: 'audio',\n      sourceUpdater: this,\n      action: actions.remove(start, end),\n      doneFn: done,\n      name: 'remove'\n    });\n  }\n  /**\n   * Queue an update to remove a time range from the buffer.\n   *\n   * @param {number} start where to start the removal\n   * @param {number} end where to end the removal\n   * @param {Function} [done=noop] optional callback to be executed when the remove\n   * operation is complete\n   * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end\n   */\n\n  removeVideo(start, end, done = noop) {\n    if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {\n      done();\n      return;\n    }\n    pushQueue({\n      type: 'video',\n      sourceUpdater: this,\n      action: actions.remove(start, end),\n      doneFn: done,\n      name: 'remove'\n    });\n  }\n  /**\n   * Whether the underlying sourceBuffer is updating or not\n   *\n   * @return {boolean} the updating status of the SourceBuffer\n   */\n\n  updating() {\n    // the audio/video source buffer is updating\n    if (updating('audio', this) || updating('video', this)) {\n      return true;\n    }\n    return false;\n  }\n  /**\n   * Set/get the timestampoffset on the audio SourceBuffer\n   *\n   * @return {number} the timestamp offset\n   */\n\n  audioTimestampOffset(offset) {\n    if (typeof offset !== 'undefined' && this.audioBuffer &&\n    // no point in updating if it's the same\n    this.audioTimestampOffset_ !== offset) {\n      pushQueue({\n        type: 'audio',\n        sourceUpdater: this,\n        action: actions.timestampOffset(offset),\n        name: 'timestampOffset'\n      });\n      this.audioTimestampOffset_ = offset;\n    }\n    return this.audioTimestampOffset_;\n  }\n  /**\n   * Set/get the timestampoffset on the video SourceBuffer\n   *\n   * @return {number} the timestamp offset\n   */\n\n  videoTimestampOffset(offset) {\n    if (typeof offset !== 'undefined' && this.videoBuffer &&\n    // no point in updating if it's the same\n    this.videoTimestampOffset_ !== offset) {\n      pushQueue({\n        type: 'video',\n        sourceUpdater: this,\n        action: actions.timestampOffset(offset),\n        name: 'timestampOffset'\n      });\n      this.videoTimestampOffset_ = offset;\n    }\n    return this.videoTimestampOffset_;\n  }\n  /**\n   * Add a function to the queue that will be called\n   * when it is its turn to run in the audio queue.\n   *\n   * @param {Function} callback\n   *        The callback to queue.\n   */\n\n  audioQueueCallback(callback) {\n    if (!this.audioBuffer) {\n      return;\n    }\n    pushQueue({\n      type: 'audio',\n      sourceUpdater: this,\n      action: actions.callback(callback),\n      name: 'callback'\n    });\n  }\n  /**\n   * Add a function to the queue that will be called\n   * when it is its turn to run in the video queue.\n   *\n   * @param {Function} callback\n   *        The callback to queue.\n   */\n\n  videoQueueCallback(callback) {\n    if (!this.videoBuffer) {\n      return;\n    }\n    pushQueue({\n      type: 'video',\n      sourceUpdater: this,\n      action: actions.callback(callback),\n      name: 'callback'\n    });\n  }\n  /**\n   * dispose of the source updater and the underlying sourceBuffer\n   */\n\n  dispose() {\n    this.trigger('dispose');\n    bufferTypes.forEach(type => {\n      this.abort(type);\n      if (this.canRemoveSourceBuffer()) {\n        this.removeSourceBuffer(type);\n      } else {\n        this[`${type}QueueCallback`](() => cleanupBuffer(type, this));\n      }\n    });\n    this.videoAppendQueued_ = false;\n    this.delayedAudioAppendQueue_.length = 0;\n    if (this.sourceopenListener_) {\n      this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);\n    }\n    this.off();\n  }\n}\nconst uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));\nconst bufferToHexString = buffer => {\n  const uInt8Buffer = new Uint8Array(buffer);\n  return Array.from(uInt8Buffer).map(byte => byte.toString(16).padStart(2, '0')).join('');\n};\n\n/**\n * @file vtt-segment-loader.js\n */\nconst VTT_LINE_TERMINATORS = new Uint8Array('\\n\\n'.split('').map(char => char.charCodeAt(0)));\nclass NoVttJsError extends Error {\n  constructor() {\n    super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');\n  }\n}\n/**\n * An object that manages segment loading and appending.\n *\n * @class VTTSegmentLoader\n * @param {Object} options required and optional options\n * @extends videojs.EventTarget\n */\n\nclass VTTSegmentLoader extends SegmentLoader {\n  constructor(settings, options = {}) {\n    super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;\n    // however, VTTSegmentLoader has no need of a media source, so delete the reference\n\n    this.mediaSource_ = null;\n    this.subtitlesTrack_ = null;\n    this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;\n    this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in\n    // the sync controller leads to improper behavior.\n\n    this.shouldSaveSegmentTimingInfo_ = false;\n  }\n  /**\n   * Indicates which time ranges are buffered\n   *\n   * @return {TimeRange}\n   *         TimeRange object representing the current buffered ranges\n   */\n\n  buffered_() {\n    if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {\n      return createTimeRanges();\n    }\n    const cues = this.subtitlesTrack_.cues;\n    const start = cues[0].startTime;\n    const end = cues[cues.length - 1].startTime;\n    return createTimeRanges([[start, end]]);\n  }\n  /**\n   * Gets and sets init segment for the provided map\n   *\n   * @param {Object} map\n   *        The map object representing the init segment to get or set\n   * @param {boolean=} set\n   *        If true, the init segment for the provided map should be saved\n   * @return {Object}\n   *         map object for desired init segment\n   */\n\n  initSegmentForMap(map, set = false) {\n    if (!map) {\n      return null;\n    }\n    const id = initSegmentId(map);\n    let storedMap = this.initSegments_[id];\n    if (set && !storedMap && map.bytes) {\n      // append WebVTT line terminators to the media initialization segment if it exists\n      // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that\n      // requires two or more WebVTT line terminators between the WebVTT header and the\n      // rest of the file\n      const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;\n      const combinedSegment = new Uint8Array(combinedByteLength);\n      combinedSegment.set(map.bytes);\n      combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);\n      this.initSegments_[id] = storedMap = {\n        resolvedUri: map.resolvedUri,\n        byterange: map.byterange,\n        bytes: combinedSegment\n      };\n    }\n    return storedMap || map;\n  }\n  /**\n   * Returns true if all configuration required for loading is present, otherwise false.\n   *\n   * @return {boolean} True if the all configuration is ready for loading\n   * @private\n   */\n\n  couldBeginLoading_() {\n    return this.playlist_ && this.subtitlesTrack_ && !this.paused();\n  }\n  /**\n   * Once all the starting parameters have been specified, begin\n   * operation. This method should only be invoked from the INIT\n   * state.\n   *\n   * @private\n   */\n\n  init_() {\n    this.state = 'READY';\n    this.resetEverything();\n    return this.monitorBuffer_();\n  }\n  /**\n   * Set a subtitle track on the segment loader to add subtitles to\n   *\n   * @param {TextTrack=} track\n   *        The text track to add loaded subtitles to\n   * @return {TextTrack}\n   *        Returns the subtitles track\n   */\n\n  track(track) {\n    if (typeof track === 'undefined') {\n      return this.subtitlesTrack_;\n    }\n    this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start\n    // buffering now\n\n    if (this.state === 'INIT' && this.couldBeginLoading_()) {\n      this.init_();\n    }\n    return this.subtitlesTrack_;\n  }\n  /**\n   * Remove any data in the source buffer between start and end times\n   *\n   * @param {number} start - the start time of the region to remove from the buffer\n   * @param {number} end - the end time of the region to remove from the buffer\n   */\n\n  remove(start, end) {\n    removeCuesFromTrack(start, end, this.subtitlesTrack_);\n  }\n  /**\n   * fill the buffer with segements unless the sourceBuffers are\n   * currently updating\n   *\n   * Note: this function should only ever be called by monitorBuffer_\n   * and never directly\n   *\n   * @private\n   */\n\n  fillBuffer_() {\n    // see if we need to begin loading immediately\n    const segmentInfo = this.chooseNextRequest_();\n    if (!segmentInfo) {\n      return;\n    }\n    if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {\n      // We don't have the timestamp offset that we need to sync subtitles.\n      // Rerun on a timestamp offset or user interaction.\n      const checkTimestampOffset = () => {\n        this.state = 'READY';\n        if (!this.paused()) {\n          // if not paused, queue a buffer check as soon as possible\n          this.monitorBuffer_();\n        }\n      };\n      this.syncController_.one('timestampoffset', checkTimestampOffset);\n      this.state = 'WAITING_ON_TIMELINE';\n      return;\n    }\n    this.loadSegment_(segmentInfo);\n  } // never set a timestamp offset for vtt segments.\n\n  timestampOffsetForSegment_() {\n    return null;\n  }\n  chooseNextRequest_() {\n    return this.skipEmptySegments_(super.chooseNextRequest_());\n  }\n  /**\n   * Prevents the segment loader from requesting segments we know contain no subtitles\n   * by walking forward until we find the next segment that we don't know whether it is\n   * empty or not.\n   *\n   * @param {Object} segmentInfo\n   *        a segment info object that describes the current segment\n   * @return {Object}\n   *         a segment info object that describes the current segment\n   */\n\n  skipEmptySegments_(segmentInfo) {\n    while (segmentInfo && segmentInfo.segment.empty) {\n      // stop at the last possible segmentInfo\n      if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {\n        segmentInfo = null;\n        break;\n      }\n      segmentInfo = this.generateSegmentInfo_({\n        playlist: segmentInfo.playlist,\n        mediaIndex: segmentInfo.mediaIndex + 1,\n        startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,\n        isSyncRequest: segmentInfo.isSyncRequest\n      });\n    }\n    return segmentInfo;\n  }\n  stopForError(error) {\n    this.error(error);\n    this.state = 'READY';\n    this.pause();\n    this.trigger('error');\n  }\n  /**\n   * append a decrypted segement to the SourceBuffer through a SourceUpdater\n   *\n   * @private\n   */\n\n  segmentRequestFinished_(error, simpleSegment, result) {\n    if (!this.subtitlesTrack_) {\n      this.state = 'READY';\n      return;\n    }\n    this.saveTransferStats_(simpleSegment.stats); // the request was aborted\n\n    if (!this.pendingSegment_) {\n      this.state = 'READY';\n      this.mediaRequestsAborted += 1;\n      return;\n    }\n    if (error) {\n      if (error.code === REQUEST_ERRORS.TIMEOUT) {\n        this.handleTimeout_();\n      }\n      if (error.code === REQUEST_ERRORS.ABORTED) {\n        this.mediaRequestsAborted += 1;\n      } else {\n        this.mediaRequestsErrored += 1;\n      }\n      this.stopForError(error);\n      return;\n    }\n    const segmentInfo = this.pendingSegment_;\n    const isMp4WebVttSegmentWithCues = result.mp4VttCues && result.mp4VttCues.length;\n    if (isMp4WebVttSegmentWithCues) {\n      segmentInfo.mp4VttCues = result.mp4VttCues;\n    } // although the VTT segment loader bandwidth isn't really used, it's good to\n    // maintain functionality between segment loaders\n\n    this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache\n\n    if (simpleSegment.key) {\n      this.segmentKey(simpleSegment.key, true);\n    }\n    this.state = 'APPENDING'; // used for tests\n\n    this.trigger('appending');\n    const segment = segmentInfo.segment;\n    if (segment.map) {\n      segment.map.bytes = simpleSegment.map.bytes;\n    }\n    segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading\n\n    if (typeof window$1.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {\n      this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times\n      // script will be loaded once but multiple listeners will be added to the queue, which is expected.\n\n      this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({\n        message: 'Error loading vtt.js'\n      }));\n      return;\n    }\n    segment.requested = true;\n    try {\n      this.parseVTTCues_(segmentInfo);\n    } catch (e) {\n      this.stopForError({\n        message: e.message,\n        metadata: {\n          errorType: videojs.Error.StreamingVttParserError,\n          error: e\n        }\n      });\n      return;\n    }\n    if (!isMp4WebVttSegmentWithCues) {\n      this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);\n    }\n    if (segmentInfo.cues.length) {\n      segmentInfo.timingInfo = {\n        start: segmentInfo.cues[0].startTime,\n        end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime\n      };\n    } else {\n      segmentInfo.timingInfo = {\n        start: segmentInfo.startOfSegment,\n        end: segmentInfo.startOfSegment + segmentInfo.duration\n      };\n    }\n    if (segmentInfo.isSyncRequest) {\n      this.trigger('syncinfoupdate');\n      this.pendingSegment_ = null;\n      this.state = 'READY';\n      return;\n    }\n    segmentInfo.byteLength = segmentInfo.bytes.byteLength;\n    this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to\n    // the subtitle track\n\n    segmentInfo.cues.forEach(cue => {\n      this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window$1.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);\n    }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows\n    // cues to have identical time-intervals, but if the text is also identical\n    // we can safely assume it is a duplicate that can be removed (ex. when a cue\n    // \"overlaps\" VTT segments)\n\n    removeDuplicateCuesFromTrack(this.subtitlesTrack_);\n    this.handleAppendsDone_();\n  }\n  handleData_(simpleSegment, result) {\n    const isVttType = simpleSegment && simpleSegment.type === 'vtt';\n    const isTextResult = result && result.type === 'text';\n    const isFmp4VttSegment = isVttType && isTextResult; // handle segment data for fmp4 encapsulated webvtt\n\n    if (isFmp4VttSegment) {\n      super.handleData_(simpleSegment, result);\n    }\n  }\n  updateTimingInfoEnd_() {// noop\n  }\n  /**\n   * Utility function for converting mp4 webvtt cue objects into VTTCues.\n   *\n   * @param {Object} segmentInfo with mp4 webvtt cues for parsing into VTTCue objecs\n   */\n\n  parseMp4VttCues_(segmentInfo) {\n    const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();\n    segmentInfo.mp4VttCues.forEach(cue => {\n      const start = cue.start + timestampOffset;\n      const end = cue.end + timestampOffset;\n      const vttCue = new window$1.VTTCue(start, end, cue.cueText);\n      if (cue.settings) {\n        cue.settings.split(' ').forEach(cueSetting => {\n          const keyValString = cueSetting.split(':');\n          const key = keyValString[0];\n          const value = keyValString[1];\n          vttCue[key] = isNaN(value) ? value : Number(value);\n        });\n      }\n      segmentInfo.cues.push(vttCue);\n    });\n  }\n  /**\n   * Uses the WebVTT parser to parse the segment response\n   *\n   * @throws NoVttJsError\n   *\n   * @param {Object} segmentInfo\n   *        a segment info object that describes the current segment\n   * @private\n   */\n\n  parseVTTCues_(segmentInfo) {\n    let decoder;\n    let decodeBytesToString = false;\n    if (typeof window$1.WebVTT !== 'function') {\n      // caller is responsible for exception handling.\n      throw new NoVttJsError();\n    }\n    segmentInfo.cues = [];\n    segmentInfo.timestampmap = {\n      MPEGTS: 0,\n      LOCAL: 0\n    };\n    if (segmentInfo.mp4VttCues) {\n      this.parseMp4VttCues_(segmentInfo);\n      return;\n    }\n    if (typeof window$1.TextDecoder === 'function') {\n      decoder = new window$1.TextDecoder('utf8');\n    } else {\n      decoder = window$1.WebVTT.StringDecoder();\n      decodeBytesToString = true;\n    }\n    const parser = new window$1.WebVTT.Parser(window$1, window$1.vttjs, decoder);\n    parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);\n    parser.ontimestampmap = map => {\n      segmentInfo.timestampmap = map;\n    };\n    parser.onparsingerror = error => {\n      videojs.log.warn('Error encountered when parsing cues: ' + error.message);\n    };\n    if (segmentInfo.segment.map) {\n      let mapData = segmentInfo.segment.map.bytes;\n      if (decodeBytesToString) {\n        mapData = uint8ToUtf8(mapData);\n      }\n      parser.parse(mapData);\n    }\n    let segmentData = segmentInfo.bytes;\n    if (decodeBytesToString) {\n      segmentData = uint8ToUtf8(segmentData);\n    }\n    parser.parse(segmentData);\n    parser.flush();\n  }\n  /**\n   * Updates the start and end times of any cues parsed by the WebVTT parser using\n   * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping\n   * from the SyncController\n   *\n   * @param {Object} segmentInfo\n   *        a segment info object that describes the current segment\n   * @param {Object} mappingObj\n   *        object containing a mapping from TS to media time\n   * @param {Object} playlist\n   *        the playlist object containing the segment\n   * @private\n   */\n\n  updateTimeMapping_(segmentInfo, mappingObj, playlist) {\n    const segment = segmentInfo.segment;\n    if (!mappingObj) {\n      // If the sync controller does not have a mapping of TS to Media Time for the\n      // timeline, then we don't have enough information to update the cue\n      // start/end times\n      return;\n    }\n    if (!segmentInfo.cues.length) {\n      // If there are no cues, we also do not have enough information to figure out\n      // segment timing. Mark that the segment contains no cues so we don't re-request\n      // an empty segment.\n      segment.empty = true;\n      return;\n    }\n    const {\n      MPEGTS,\n      LOCAL\n    } = segmentInfo.timestampmap;\n    /**\n     * From the spec:\n     * The MPEGTS media timestamp MUST use a 90KHz timescale,\n     * even when non-WebVTT Media Segments use a different timescale.\n     */\n\n    const mpegTsInSeconds = MPEGTS / ONE_SECOND_IN_TS;\n    const diff = mpegTsInSeconds - LOCAL + mappingObj.mapping;\n    segmentInfo.cues.forEach(cue => {\n      const duration = cue.endTime - cue.startTime;\n      const startTime = this.handleRollover_(cue.startTime + diff, mappingObj.time);\n      cue.startTime = Math.max(startTime, 0);\n      cue.endTime = Math.max(startTime + duration, 0);\n    });\n    if (!playlist.syncInfo) {\n      const firstStart = segmentInfo.cues[0].startTime;\n      const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;\n      playlist.syncInfo = {\n        mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,\n        time: Math.min(firstStart, lastStart - segment.duration)\n      };\n    }\n  }\n  /**\n   * MPEG-TS PES timestamps are limited to 2^33.\n   * Once they reach 2^33, they roll over to 0.\n   * mux.js handles PES timestamp rollover for the following scenarios:\n   * [forward rollover(right)] ->\n   *    PES timestamps monotonically increase, and once they reach 2^33, they roll over to 0\n   * [backward rollover(left)] -->\n   *    we seek back to position before rollover.\n   *\n   * According to the HLS SPEC:\n   * When synchronizing WebVTT with PES timestamps, clients SHOULD account\n   * for cases where the 33-bit PES timestamps have wrapped and the WebVTT\n   * cue times have not.  When the PES timestamp wraps, the WebVTT Segment\n   * SHOULD have a X-TIMESTAMP-MAP header that maps the current WebVTT\n   * time to the new (low valued) PES timestamp.\n   *\n   * So we want to handle rollover here and align VTT Cue start/end time to the player's time.\n   */\n\n  handleRollover_(value, reference) {\n    if (reference === null) {\n      return value;\n    }\n    let valueIn90khz = value * ONE_SECOND_IN_TS;\n    const referenceIn90khz = reference * ONE_SECOND_IN_TS;\n    let offset;\n    if (referenceIn90khz < valueIn90khz) {\n      // - 2^33\n      offset = -8589934592;\n    } else {\n      // + 2^33\n      offset = 8589934592;\n    } // distance(value - reference) > 2^32\n\n    while (Math.abs(valueIn90khz - referenceIn90khz) > 4294967296) {\n      valueIn90khz += offset;\n    }\n    return valueIn90khz / ONE_SECOND_IN_TS;\n  }\n}\n\n/**\n * @file ad-cue-tags.js\n */\n/**\n * Searches for an ad cue that overlaps with the given mediaTime\n *\n * @param {Object} track\n *        the track to find the cue for\n *\n * @param {number} mediaTime\n *        the time to find the cue at\n *\n * @return {Object|null}\n *         the found cue or null\n */\n\nconst findAdCue = function (track, mediaTime) {\n  const cues = track.cues;\n  for (let i = 0; i < cues.length; i++) {\n    const cue = cues[i];\n    if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {\n      return cue;\n    }\n  }\n  return null;\n};\nconst updateAdCues = function (media, track, offset = 0) {\n  if (!media.segments) {\n    return;\n  }\n  let mediaTime = offset;\n  let cue;\n  for (let i = 0; i < media.segments.length; i++) {\n    const segment = media.segments[i];\n    if (!cue) {\n      // Since the cues will span for at least the segment duration, adding a fudge\n      // factor of half segment duration will prevent duplicate cues from being\n      // created when timing info is not exact (e.g. cue start time initialized\n      // at 10.006677, but next call mediaTime is 10.003332 )\n      cue = findAdCue(track, mediaTime + segment.duration / 2);\n    }\n    if (cue) {\n      if ('cueIn' in segment) {\n        // Found a CUE-IN so end the cue\n        cue.endTime = mediaTime;\n        cue.adEndTime = mediaTime;\n        mediaTime += segment.duration;\n        cue = null;\n        continue;\n      }\n      if (mediaTime < cue.endTime) {\n        // Already processed this mediaTime for this cue\n        mediaTime += segment.duration;\n        continue;\n      } // otherwise extend cue until a CUE-IN is found\n\n      cue.endTime += segment.duration;\n    } else {\n      if ('cueOut' in segment) {\n        cue = new window$1.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);\n        cue.adStartTime = mediaTime; // Assumes tag format to be\n        // #EXT-X-CUE-OUT:30\n\n        cue.adEndTime = mediaTime + parseFloat(segment.cueOut);\n        track.addCue(cue);\n      }\n      if ('cueOutCont' in segment) {\n        // Entered into the middle of an ad cue\n        // Assumes tag formate to be\n        // #EXT-X-CUE-OUT-CONT:10/30\n        const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);\n        cue = new window$1.VTTCue(mediaTime, mediaTime + segment.duration, '');\n        cue.adStartTime = mediaTime - adOffset;\n        cue.adEndTime = cue.adStartTime + adTotal;\n        track.addCue(cue);\n      }\n    }\n    mediaTime += segment.duration;\n  }\n};\nclass SyncInfo {\n  /**\n   * @param {number} start - media sequence start\n   * @param {number} end - media sequence end\n   * @param {number} segmentIndex - index for associated segment\n   * @param {number|null} [partIndex] - index for associated part\n   * @param {boolean} [appended] - appended indicator\n   *\n   */\n  constructor({\n    start,\n    end,\n    segmentIndex,\n    partIndex = null,\n    appended = false\n  }) {\n    this.start_ = start;\n    this.end_ = end;\n    this.segmentIndex_ = segmentIndex;\n    this.partIndex_ = partIndex;\n    this.appended_ = appended;\n  }\n  isInRange(targetTime) {\n    return targetTime >= this.start && targetTime < this.end;\n  }\n  markAppended() {\n    this.appended_ = true;\n  }\n  resetAppendedStatus() {\n    this.appended_ = false;\n  }\n  get isAppended() {\n    return this.appended_;\n  }\n  get start() {\n    return this.start_;\n  }\n  get end() {\n    return this.end_;\n  }\n  get segmentIndex() {\n    return this.segmentIndex_;\n  }\n  get partIndex() {\n    return this.partIndex_;\n  }\n}\nclass SyncInfoData {\n  /**\n   *\n   * @param {SyncInfo} segmentSyncInfo - sync info for a given segment\n   * @param {Array<SyncInfo>} [partsSyncInfo] - sync infos for a list of parts for a given segment\n   */\n  constructor(segmentSyncInfo, partsSyncInfo = []) {\n    this.segmentSyncInfo_ = segmentSyncInfo;\n    this.partsSyncInfo_ = partsSyncInfo;\n  }\n  get segmentSyncInfo() {\n    return this.segmentSyncInfo_;\n  }\n  get partsSyncInfo() {\n    return this.partsSyncInfo_;\n  }\n  get hasPartsSyncInfo() {\n    return this.partsSyncInfo_.length > 0;\n  }\n  resetAppendStatus() {\n    this.segmentSyncInfo_.resetAppendedStatus();\n    this.partsSyncInfo_.forEach(partSyncInfo => partSyncInfo.resetAppendedStatus());\n  }\n}\nclass MediaSequenceSync {\n  constructor() {\n    /**\n     * @type {Map<number, SyncInfoData>}\n     * @protected\n     */\n    this.storage_ = new Map();\n    this.diagnostics_ = '';\n    this.isReliable_ = false;\n    this.start_ = -Infinity;\n    this.end_ = Infinity;\n  }\n  get start() {\n    return this.start_;\n  }\n  get end() {\n    return this.end_;\n  }\n  get diagnostics() {\n    return this.diagnostics_;\n  }\n  get isReliable() {\n    return this.isReliable_;\n  }\n  resetAppendedStatus() {\n    this.storage_.forEach(syncInfoData => syncInfoData.resetAppendStatus());\n  }\n  /**\n   * update sync storage\n   *\n   * @param {Object} playlist\n   * @param {number} currentTime\n   *\n   * @return {void}\n   */\n\n  update(playlist, currentTime) {\n    const {\n      mediaSequence,\n      segments\n    } = playlist;\n    this.isReliable_ = this.isReliablePlaylist_(mediaSequence, segments);\n    if (!this.isReliable_) {\n      return;\n    }\n    return this.updateStorage_(segments, mediaSequence, this.calculateBaseTime_(mediaSequence, segments, currentTime));\n  }\n  /**\n   * @param {number} targetTime\n   * @return {SyncInfo|null}\n   */\n\n  getSyncInfoForTime(targetTime) {\n    for (const {\n      segmentSyncInfo,\n      partsSyncInfo\n    } of this.storage_.values()) {\n      // Normal segment flow:\n      if (!partsSyncInfo.length) {\n        if (segmentSyncInfo.isInRange(targetTime)) {\n          return segmentSyncInfo;\n        }\n      } else {\n        // Low latency flow:\n        for (const partSyncInfo of partsSyncInfo) {\n          if (partSyncInfo.isInRange(targetTime)) {\n            return partSyncInfo;\n          }\n        }\n      }\n    }\n    return null;\n  }\n  getSyncInfoForMediaSequence(mediaSequence) {\n    return this.storage_.get(mediaSequence);\n  }\n  updateStorage_(segments, startingMediaSequence, startingTime) {\n    const newStorage = new Map();\n    let newDiagnostics = '\\n';\n    let currentStart = startingTime;\n    let currentMediaSequence = startingMediaSequence;\n    this.start_ = currentStart;\n    segments.forEach((segment, segmentIndex) => {\n      const prevSyncInfoData = this.storage_.get(currentMediaSequence);\n      const segmentStart = currentStart;\n      const segmentEnd = segmentStart + segment.duration;\n      const segmentIsAppended = Boolean(prevSyncInfoData && prevSyncInfoData.segmentSyncInfo && prevSyncInfoData.segmentSyncInfo.isAppended);\n      const segmentSyncInfo = new SyncInfo({\n        start: segmentStart,\n        end: segmentEnd,\n        appended: segmentIsAppended,\n        segmentIndex\n      });\n      segment.syncInfo = segmentSyncInfo;\n      let currentPartStart = currentStart;\n      const partsSyncInfo = (segment.parts || []).map((part, partIndex) => {\n        const partStart = currentPartStart;\n        const partEnd = currentPartStart + part.duration;\n        const partIsAppended = Boolean(prevSyncInfoData && prevSyncInfoData.partsSyncInfo && prevSyncInfoData.partsSyncInfo[partIndex] && prevSyncInfoData.partsSyncInfo[partIndex].isAppended);\n        const partSyncInfo = new SyncInfo({\n          start: partStart,\n          end: partEnd,\n          appended: partIsAppended,\n          segmentIndex,\n          partIndex\n        });\n        currentPartStart = partEnd;\n        newDiagnostics += `Media Sequence: ${currentMediaSequence}.${partIndex} | Range: ${partStart} --> ${partEnd} | Appended: ${partIsAppended}\\n`;\n        part.syncInfo = partSyncInfo;\n        return partSyncInfo;\n      });\n      newStorage.set(currentMediaSequence, new SyncInfoData(segmentSyncInfo, partsSyncInfo));\n      newDiagnostics += `${compactSegmentUrlDescription(segment.resolvedUri)} | Media Sequence: ${currentMediaSequence} | Range: ${segmentStart} --> ${segmentEnd} | Appended: ${segmentIsAppended}\\n`;\n      currentMediaSequence++;\n      currentStart = segmentEnd;\n    });\n    this.end_ = currentStart;\n    this.storage_ = newStorage;\n    this.diagnostics_ = newDiagnostics;\n  }\n  calculateBaseTime_(mediaSequence, segments, fallback) {\n    if (!this.storage_.size) {\n      // Initial setup flow.\n      return 0;\n    }\n    if (this.storage_.has(mediaSequence)) {\n      // Normal flow.\n      return this.storage_.get(mediaSequence).segmentSyncInfo.start;\n    }\n    const minMediaSequenceFromStorage = Math.min(...this.storage_.keys()); // This case captures a race condition that can occur if we switch to a new media playlist that is out of date\n    // and still has an older Media Sequence. If this occurs, we extrapolate backwards to get the base time.\n\n    if (mediaSequence < minMediaSequenceFromStorage) {\n      const mediaSequenceDiff = minMediaSequenceFromStorage - mediaSequence;\n      let baseTime = this.storage_.get(minMediaSequenceFromStorage).segmentSyncInfo.start;\n      for (let i = 0; i < mediaSequenceDiff; i++) {\n        const segment = segments[i];\n        baseTime -= segment.duration;\n      }\n      return baseTime;\n    } // Fallback flow.\n    // There is a gap between last recorded playlist and a new one received.\n\n    return fallback;\n  }\n  isReliablePlaylist_(mediaSequence, segments) {\n    return mediaSequence !== undefined && mediaSequence !== null && Array.isArray(segments) && segments.length;\n  }\n}\nclass DependantMediaSequenceSync extends MediaSequenceSync {\n  constructor(parent) {\n    super();\n    this.parent_ = parent;\n  }\n  calculateBaseTime_(mediaSequence, segments, fallback) {\n    if (!this.storage_.size) {\n      const info = this.parent_.getSyncInfoForMediaSequence(mediaSequence);\n      if (info) {\n        return info.segmentSyncInfo.start;\n      }\n      return 0;\n    }\n    return super.calculateBaseTime_(mediaSequence, segments, fallback);\n  }\n}\n\n/**\n * @file sync-controller.js\n */\n// synchronize expired playlist segments.\n// the max media sequence diff is 48 hours of live stream\n// content with two second segments. Anything larger than that\n// will likely be invalid.\n\nconst MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;\nconst syncPointStrategies = [\n// Stategy \"VOD\": Handle the VOD-case where the sync-point is *always*\n//                the equivalence display-time 0 === segment-index 0\n{\n  name: 'VOD',\n  run: (syncController, playlist, duration, currentTimeline, currentTime) => {\n    if (duration !== Infinity) {\n      const syncPoint = {\n        time: 0,\n        segmentIndex: 0,\n        partIndex: null\n      };\n      return syncPoint;\n    }\n    return null;\n  }\n}, {\n  name: 'MediaSequence',\n  /**\n   * run media sequence strategy\n   *\n   * @param {SyncController} syncController\n   * @param {Object} playlist\n   * @param {number} duration\n   * @param {number} currentTimeline\n   * @param {number} currentTime\n   * @param {string} type\n   */\n  run: (syncController, playlist, duration, currentTimeline, currentTime, type) => {\n    const mediaSequenceSync = syncController.getMediaSequenceSync(type);\n    if (!mediaSequenceSync) {\n      return null;\n    }\n    if (!mediaSequenceSync.isReliable) {\n      return null;\n    }\n    const syncInfo = mediaSequenceSync.getSyncInfoForTime(currentTime);\n    if (!syncInfo) {\n      return null;\n    }\n    return {\n      time: syncInfo.start,\n      partIndex: syncInfo.partIndex,\n      segmentIndex: syncInfo.segmentIndex\n    };\n  }\n},\n// Stategy \"ProgramDateTime\": We have a program-date-time tag in this playlist\n{\n  name: 'ProgramDateTime',\n  run: (syncController, playlist, duration, currentTimeline, currentTime) => {\n    if (!Object.keys(syncController.timelineToDatetimeMappings).length) {\n      return null;\n    }\n    let syncPoint = null;\n    let lastDistance = null;\n    const partsAndSegments = getPartsAndSegments(playlist);\n    currentTime = currentTime || 0;\n    for (let i = 0; i < partsAndSegments.length; i++) {\n      // start from the end and loop backwards for live\n      // or start from the front and loop forwards for non-live\n      const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);\n      const partAndSegment = partsAndSegments[index];\n      const segment = partAndSegment.segment;\n      const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];\n      if (!datetimeMapping || !segment.dateTimeObject) {\n        continue;\n      }\n      const segmentTime = segment.dateTimeObject.getTime() / 1000;\n      let start = segmentTime + datetimeMapping; // take part duration into account.\n\n      if (segment.parts && typeof partAndSegment.partIndex === 'number') {\n        for (let z = 0; z < partAndSegment.partIndex; z++) {\n          start += segment.parts[z].duration;\n        }\n      }\n      const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed\n      // currentTime and can stop looking for better candidates\n\n      if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {\n        break;\n      }\n      lastDistance = distance;\n      syncPoint = {\n        time: start,\n        segmentIndex: partAndSegment.segmentIndex,\n        partIndex: partAndSegment.partIndex\n      };\n    }\n    return syncPoint;\n  }\n},\n// Stategy \"Segment\": We have a known time mapping for a timeline and a\n//                    segment in the current timeline with timing data\n{\n  name: 'Segment',\n  run: (syncController, playlist, duration, currentTimeline, currentTime) => {\n    let syncPoint = null;\n    let lastDistance = null;\n    currentTime = currentTime || 0;\n    const partsAndSegments = getPartsAndSegments(playlist);\n    for (let i = 0; i < partsAndSegments.length; i++) {\n      // start from the end and loop backwards for live\n      // or start from the front and loop forwards for non-live\n      const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);\n      const partAndSegment = partsAndSegments[index];\n      const segment = partAndSegment.segment;\n      const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;\n      if (segment.timeline === currentTimeline && typeof start !== 'undefined') {\n        const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed\n        // currentTime and can stop looking for better candidates\n\n        if (lastDistance !== null && lastDistance < distance) {\n          break;\n        }\n        if (!syncPoint || lastDistance === null || lastDistance >= distance) {\n          lastDistance = distance;\n          syncPoint = {\n            time: start,\n            segmentIndex: partAndSegment.segmentIndex,\n            partIndex: partAndSegment.partIndex\n          };\n        }\n      }\n    }\n    return syncPoint;\n  }\n},\n// Stategy \"Discontinuity\": We have a discontinuity with a known\n//                          display-time\n{\n  name: 'Discontinuity',\n  run: (syncController, playlist, duration, currentTimeline, currentTime) => {\n    let syncPoint = null;\n    currentTime = currentTime || 0;\n    if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {\n      let lastDistance = null;\n      for (let i = 0; i < playlist.discontinuityStarts.length; i++) {\n        const segmentIndex = playlist.discontinuityStarts[i];\n        const discontinuity = playlist.discontinuitySequence + i + 1;\n        const discontinuitySync = syncController.discontinuities[discontinuity];\n        if (discontinuitySync) {\n          const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed\n          // currentTime and can stop looking for better candidates\n\n          if (lastDistance !== null && lastDistance < distance) {\n            break;\n          }\n          if (!syncPoint || lastDistance === null || lastDistance >= distance) {\n            lastDistance = distance;\n            syncPoint = {\n              time: discontinuitySync.time,\n              segmentIndex,\n              partIndex: null\n            };\n          }\n        }\n      }\n    }\n    return syncPoint;\n  }\n},\n// Stategy \"Playlist\": We have a playlist with a known mapping of\n//                     segment index to display time\n{\n  name: 'Playlist',\n  run: (syncController, playlist, duration, currentTimeline, currentTime) => {\n    if (playlist.syncInfo) {\n      const syncPoint = {\n        time: playlist.syncInfo.time,\n        segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,\n        partIndex: null\n      };\n      return syncPoint;\n    }\n    return null;\n  }\n}];\nclass SyncController extends videojs.EventTarget {\n  constructor(options = {}) {\n    super(); // ...for synching across variants\n\n    this.timelines = [];\n    this.discontinuities = [];\n    this.timelineToDatetimeMappings = {}; // TODO: this map should be only available for HLS. Since only HLS has MediaSequence.\n    //  For some reason this map helps with syncing between quality switch for MPEG-DASH as well.\n    //  Moreover if we disable this map for MPEG-DASH - quality switch will be broken.\n    //  MPEG-DASH should have its own separate sync strategy\n\n    const main = new MediaSequenceSync();\n    const audio = new DependantMediaSequenceSync(main);\n    const vtt = new DependantMediaSequenceSync(main);\n    this.mediaSequenceStorage_ = {\n      main,\n      audio,\n      vtt\n    };\n    this.logger_ = logger('SyncController');\n  }\n  /**\n   *\n   * @param {string} loaderType\n   * @return {MediaSequenceSync|null}\n   */\n\n  getMediaSequenceSync(loaderType) {\n    return this.mediaSequenceStorage_[loaderType] || null;\n  }\n  /**\n   * Find a sync-point for the playlist specified\n   *\n   * A sync-point is defined as a known mapping from display-time to\n   * a segment-index in the current playlist.\n   *\n   * @param {Playlist} playlist\n   *        The playlist that needs a sync-point\n   * @param {number} duration\n   *        Duration of the MediaSource (Infinite if playing a live source)\n   * @param {number} currentTimeline\n   *        The last timeline from which a segment was loaded\n   * @param {number} currentTime\n   *        Current player's time\n   * @param {string} type\n   *        Segment loader type\n   * @return {Object}\n   *          A sync-point object\n   */\n\n  getSyncPoint(playlist, duration, currentTimeline, currentTime, type) {\n    // Always use VOD sync point for VOD\n    if (duration !== Infinity) {\n      const vodSyncPointStrategy = syncPointStrategies.find(({\n        name\n      }) => name === 'VOD');\n      return vodSyncPointStrategy.run(this, playlist, duration);\n    }\n    const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime, type);\n    if (!syncPoints.length) {\n      // Signal that we need to attempt to get a sync-point manually\n      // by fetching a segment in the playlist and constructing\n      // a sync-point from that information\n      return null;\n    } // If we have exact match just return it instead of finding the nearest distance\n\n    for (const syncPointInfo of syncPoints) {\n      const {\n        syncPoint,\n        strategy\n      } = syncPointInfo;\n      const {\n        segmentIndex,\n        time\n      } = syncPoint;\n      if (segmentIndex < 0) {\n        continue;\n      }\n      const selectedSegment = playlist.segments[segmentIndex];\n      const start = time;\n      const end = start + selectedSegment.duration;\n      this.logger_(`Strategy: ${strategy}. Current time: ${currentTime}. selected segment: ${segmentIndex}. Time: [${start} -> ${end}]}`);\n      if (currentTime >= start && currentTime < end) {\n        this.logger_('Found sync point with exact match: ', syncPoint);\n        return syncPoint;\n      }\n    } // Now find the sync-point that is closest to the currentTime because\n    // that should result in the most accurate guess about which segment\n    // to fetch\n\n    return this.selectSyncPoint_(syncPoints, {\n      key: 'time',\n      value: currentTime\n    });\n  }\n  /**\n   * Calculate the amount of time that has expired off the playlist during playback\n   *\n   * @param {Playlist} playlist\n   *        Playlist object to calculate expired from\n   * @param {number} duration\n   *        Duration of the MediaSource (Infinity if playling a live source)\n   * @return {number|null}\n   *          The amount of time that has expired off the playlist during playback. Null\n   *          if no sync-points for the playlist can be found.\n   */\n\n  getExpiredTime(playlist, duration) {\n    if (!playlist || !playlist.segments) {\n      return null;\n    }\n    const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time\n\n    if (!syncPoints.length) {\n      return null;\n    }\n    const syncPoint = this.selectSyncPoint_(syncPoints, {\n      key: 'segmentIndex',\n      value: 0\n    }); // If the sync-point is beyond the start of the playlist, we want to subtract the\n    // duration from index 0 to syncPoint.segmentIndex instead of adding.\n\n    if (syncPoint.segmentIndex > 0) {\n      syncPoint.time *= -1;\n    }\n    return Math.abs(syncPoint.time + sumDurations({\n      defaultDuration: playlist.targetDuration,\n      durationList: playlist.segments,\n      startIndex: syncPoint.segmentIndex,\n      endIndex: 0\n    }));\n  }\n  /**\n   * Runs each sync-point strategy and returns a list of sync-points returned by the\n   * strategies\n   *\n   * @private\n   * @param {Playlist} playlist\n   *        The playlist that needs a sync-point\n   * @param {number} duration\n   *        Duration of the MediaSource (Infinity if playing a live source)\n   * @param {number} currentTimeline\n   *        The last timeline from which a segment was loaded\n   * @param {number} currentTime\n   *        Current player's time\n   * @param {string} type\n   *        Segment loader type\n   * @return {Array}\n   *          A list of sync-point objects\n   */\n\n  runStrategies_(playlist, duration, currentTimeline, currentTime, type) {\n    const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...\n\n    for (let i = 0; i < syncPointStrategies.length; i++) {\n      const strategy = syncPointStrategies[i];\n      const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime, type);\n      if (syncPoint) {\n        syncPoint.strategy = strategy.name;\n        syncPoints.push({\n          strategy: strategy.name,\n          syncPoint\n        });\n      }\n    }\n    return syncPoints;\n  }\n  /**\n   * Selects the sync-point nearest the specified target\n   *\n   * @private\n   * @param {Array} syncPoints\n   *        List of sync-points to select from\n   * @param {Object} target\n   *        Object specifying the property and value we are targeting\n   * @param {string} target.key\n   *        Specifies the property to target. Must be either 'time' or 'segmentIndex'\n   * @param {number} target.value\n   *        The value to target for the specified key.\n   * @return {Object}\n   *          The sync-point nearest the target\n   */\n\n  selectSyncPoint_(syncPoints, target) {\n    let bestSyncPoint = syncPoints[0].syncPoint;\n    let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);\n    let bestStrategy = syncPoints[0].strategy;\n    for (let i = 1; i < syncPoints.length; i++) {\n      const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);\n      if (newDistance < bestDistance) {\n        bestDistance = newDistance;\n        bestSyncPoint = syncPoints[i].syncPoint;\n        bestStrategy = syncPoints[i].strategy;\n      }\n    }\n    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}` : '') + ']');\n    return bestSyncPoint;\n  }\n  /**\n   * Save any meta-data present on the segments when segments leave\n   * the live window to the playlist to allow for synchronization at the\n   * playlist level later.\n   *\n   * @param {Playlist} oldPlaylist - The previous active playlist\n   * @param {Playlist} newPlaylist - The updated and most current playlist\n   */\n\n  saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {\n    const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps\n\n    if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {\n      videojs.log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);\n      return;\n    } // When a segment expires from the playlist and it has a start time\n    // save that information as a possible sync-point reference in future\n\n    for (let i = mediaSequenceDiff - 1; i >= 0; i--) {\n      const lastRemovedSegment = oldPlaylist.segments[i];\n      if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {\n        newPlaylist.syncInfo = {\n          mediaSequence: oldPlaylist.mediaSequence + i,\n          time: lastRemovedSegment.start\n        };\n        this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);\n        this.trigger('syncinfoupdate');\n        break;\n      }\n    }\n  }\n  /**\n   * Save the mapping from playlist's ProgramDateTime to display. This should only happen\n   * before segments start to load.\n   *\n   * @param {Playlist} playlist - The currently active playlist\n   */\n\n  setDateTimeMappingForStart(playlist) {\n    // It's possible for the playlist to be updated before playback starts, meaning time\n    // zero is not yet set. If, during these playlist refreshes, a discontinuity is\n    // crossed, then the old time zero mapping (for the prior timeline) would be retained\n    // unless the mappings are cleared.\n    this.timelineToDatetimeMappings = {};\n    if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {\n      const firstSegment = playlist.segments[0];\n      const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;\n      this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;\n    }\n  }\n  /**\n   * Calculates and saves timeline mappings, playlist sync info, and segment timing values\n   * based on the latest timing information.\n   *\n   * @param {Object} options\n   *        Options object\n   * @param {SegmentInfo} options.segmentInfo\n   *        The current active request information\n   * @param {boolean} options.shouldSaveTimelineMapping\n   *        If there's a timeline change, determines if the timeline mapping should be\n   *        saved for timeline mapping and program date time mappings.\n   */\n\n  saveSegmentTimingInfo({\n    segmentInfo,\n    shouldSaveTimelineMapping\n  }) {\n    const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);\n    const segment = segmentInfo.segment;\n    if (didCalculateSegmentTimeMapping) {\n      this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information\n      // now with segment timing information\n\n      if (!segmentInfo.playlist.syncInfo) {\n        segmentInfo.playlist.syncInfo = {\n          mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,\n          time: segment.start\n        };\n      }\n    }\n    const dateTime = segment.dateTimeObject;\n    if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {\n      this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);\n    }\n  }\n  timestampOffsetForTimeline(timeline) {\n    if (typeof this.timelines[timeline] === 'undefined') {\n      return null;\n    }\n    return this.timelines[timeline].time;\n  }\n  mappingForTimeline(timeline) {\n    if (typeof this.timelines[timeline] === 'undefined') {\n      return null;\n    }\n    return this.timelines[timeline].mapping;\n  }\n  /**\n   * Use the \"media time\" for a segment to generate a mapping to \"display time\" and\n   * save that display time to the segment.\n   *\n   * @private\n   * @param {SegmentInfo} segmentInfo\n   *        The current active request information\n   * @param {Object} timingInfo\n   *        The start and end time of the current segment in \"media time\"\n   * @param {boolean} shouldSaveTimelineMapping\n   *        If there's a timeline change, determines if the timeline mapping should be\n   *        saved in timelines.\n   * @return {boolean}\n   *          Returns false if segment time mapping could not be calculated\n   */\n\n  calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {\n    // TODO: remove side effects\n    const segment = segmentInfo.segment;\n    const part = segmentInfo.part;\n    let mappingObj = this.timelines[segmentInfo.timeline];\n    let start;\n    let end;\n    if (typeof segmentInfo.timestampOffset === 'number') {\n      mappingObj = {\n        time: segmentInfo.startOfSegment,\n        mapping: segmentInfo.startOfSegment - timingInfo.start\n      };\n      if (shouldSaveTimelineMapping) {\n        this.timelines[segmentInfo.timeline] = mappingObj;\n        this.trigger('timestampoffset');\n        this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);\n      }\n      start = segmentInfo.startOfSegment;\n      end = timingInfo.end + mappingObj.mapping;\n    } else if (mappingObj) {\n      start = timingInfo.start + mappingObj.mapping;\n      end = timingInfo.end + mappingObj.mapping;\n    } else {\n      return false;\n    }\n    if (part) {\n      part.start = start;\n      part.end = end;\n    } // If we don't have a segment start yet or the start value we got\n    // is less than our current segment.start value, save a new start value.\n    // We have to do this because parts will have segment timing info saved\n    // multiple times and we want segment start to be the earliest part start\n    // value for that segment.\n\n    if (!segment.start || start < segment.start) {\n      segment.start = start;\n    }\n    segment.end = end;\n    return true;\n  }\n  /**\n   * Each time we have discontinuity in the playlist, attempt to calculate the location\n   * in display of the start of the discontinuity and save that. We also save an accuracy\n   * value so that we save values with the most accuracy (closest to 0.)\n   *\n   * @private\n   * @param {SegmentInfo} segmentInfo - The current active request information\n   */\n\n  saveDiscontinuitySyncInfo_(segmentInfo) {\n    const playlist = segmentInfo.playlist;\n    const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where\n    // the start of the range and it's accuracy is 0 (greater accuracy values\n    // mean more approximation)\n\n    if (segment.discontinuity) {\n      this.discontinuities[segment.timeline] = {\n        time: segment.start,\n        accuracy: 0\n      };\n    } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {\n      // Search for future discontinuities that we can provide better timing\n      // information for and save that information for sync purposes\n      for (let i = 0; i < playlist.discontinuityStarts.length; i++) {\n        const segmentIndex = playlist.discontinuityStarts[i];\n        const discontinuity = playlist.discontinuitySequence + i + 1;\n        const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;\n        const accuracy = Math.abs(mediaIndexDiff);\n        if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {\n          let time;\n          if (mediaIndexDiff < 0) {\n            time = segment.start - sumDurations({\n              defaultDuration: playlist.targetDuration,\n              durationList: playlist.segments,\n              startIndex: segmentInfo.mediaIndex,\n              endIndex: segmentIndex\n            });\n          } else {\n            time = segment.end + sumDurations({\n              defaultDuration: playlist.targetDuration,\n              durationList: playlist.segments,\n              startIndex: segmentInfo.mediaIndex + 1,\n              endIndex: segmentIndex\n            });\n          }\n          this.discontinuities[discontinuity] = {\n            time,\n            accuracy\n          };\n        }\n      }\n    }\n  }\n  dispose() {\n    this.trigger('dispose');\n    this.off();\n  }\n}\n\n/**\n * The TimelineChangeController acts as a source for segment loaders to listen for and\n * keep track of latest and pending timeline changes. This is useful to ensure proper\n * sync, as each loader may need to make a consideration for what timeline the other\n * loader is on before making changes which could impact the other loader's media.\n *\n * @class TimelineChangeController\n * @extends videojs.EventTarget\n */\n\nclass TimelineChangeController extends videojs.EventTarget {\n  constructor() {\n    super();\n    this.pendingTimelineChanges_ = {};\n    this.lastTimelineChanges_ = {};\n  }\n  clearPendingTimelineChange(type) {\n    this.pendingTimelineChanges_[type] = null;\n    this.trigger('pendingtimelinechange');\n  }\n  pendingTimelineChange({\n    type,\n    from,\n    to\n  }) {\n    if (typeof from === 'number' && typeof to === 'number') {\n      this.pendingTimelineChanges_[type] = {\n        type,\n        from,\n        to\n      };\n      this.trigger('pendingtimelinechange');\n    }\n    return this.pendingTimelineChanges_[type];\n  }\n  lastTimelineChange({\n    type,\n    from,\n    to\n  }) {\n    if (typeof from === 'number' && typeof to === 'number') {\n      this.lastTimelineChanges_[type] = {\n        type,\n        from,\n        to\n      };\n      delete this.pendingTimelineChanges_[type];\n      const metadata = {\n        timelineChangeInfo: {\n          from,\n          to\n        }\n      };\n      this.trigger({\n        type: 'timelinechange',\n        metadata\n      });\n    }\n    return this.lastTimelineChanges_[type];\n  }\n  dispose() {\n    this.trigger('dispose');\n    this.pendingTimelineChanges_ = {};\n    this.lastTimelineChanges_ = {};\n    this.off();\n  }\n}\n\n/* rollup-plugin-worker-factory start for worker!/home/runner/work/http-streaming/http-streaming/src/decrypter-worker.js */\nconst workerCode = transform(getWorkerString(function () {\n  /**\n   * @file stream.js\n   */\n\n  /**\n   * A lightweight readable stream implemention that handles event dispatching.\n   *\n   * @class Stream\n   */\n\n  var Stream = /*#__PURE__*/function () {\n    function Stream() {\n      this.listeners = {};\n    }\n    /**\n     * Add a listener for a specified event type.\n     *\n     * @param {string} type the event name\n     * @param {Function} listener the callback to be invoked when an event of\n     * the specified type occurs\n     */\n\n    var _proto = Stream.prototype;\n    _proto.on = function on(type, listener) {\n      if (!this.listeners[type]) {\n        this.listeners[type] = [];\n      }\n      this.listeners[type].push(listener);\n    }\n    /**\n     * Remove a listener for a specified event type.\n     *\n     * @param {string} type the event name\n     * @param {Function} listener  a function previously registered for this\n     * type of event through `on`\n     * @return {boolean} if we could turn it off or not\n     */;\n    _proto.off = function off(type, listener) {\n      if (!this.listeners[type]) {\n        return false;\n      }\n      var index = this.listeners[type].indexOf(listener); // TODO: which is better?\n      // In Video.js we slice listener functions\n      // on trigger so that it does not mess up the order\n      // while we loop through.\n      //\n      // Here we slice on off so that the loop in trigger\n      // can continue using it's old reference to loop without\n      // messing up the order.\n\n      this.listeners[type] = this.listeners[type].slice(0);\n      this.listeners[type].splice(index, 1);\n      return index > -1;\n    }\n    /**\n     * Trigger an event of the specified type on this stream. Any additional\n     * arguments to this function are passed as parameters to event listeners.\n     *\n     * @param {string} type the event name\n     */;\n    _proto.trigger = function trigger(type) {\n      var callbacks = this.listeners[type];\n      if (!callbacks) {\n        return;\n      } // Slicing the arguments on every invocation of this method\n      // can add a significant amount of overhead. Avoid the\n      // intermediate object creation for the common case of a\n      // single callback argument\n\n      if (arguments.length === 2) {\n        var length = callbacks.length;\n        for (var i = 0; i < length; ++i) {\n          callbacks[i].call(this, arguments[1]);\n        }\n      } else {\n        var args = Array.prototype.slice.call(arguments, 1);\n        var _length = callbacks.length;\n        for (var _i = 0; _i < _length; ++_i) {\n          callbacks[_i].apply(this, args);\n        }\n      }\n    }\n    /**\n     * Destroys the stream and cleans up.\n     */;\n    _proto.dispose = function dispose() {\n      this.listeners = {};\n    }\n    /**\n     * Forwards all `data` events on this stream to the destination stream. The\n     * destination stream should provide a method `push` to receive the data\n     * events as they arrive.\n     *\n     * @param {Stream} destination the stream that will receive all `data` events\n     * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options\n     */;\n    _proto.pipe = function pipe(destination) {\n      this.on('data', function (data) {\n        destination.push(data);\n      });\n    };\n    return Stream;\n  }();\n  /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */\n\n  /**\n   * Returns the subarray of a Uint8Array without PKCS#7 padding.\n   *\n   * @param padded {Uint8Array} unencrypted bytes that have been padded\n   * @return {Uint8Array} the unpadded bytes\n   * @see http://tools.ietf.org/html/rfc5652\n   */\n\n  function unpad(padded) {\n    return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);\n  }\n  /*! @name aes-decrypter @version 4.0.2 @license Apache-2.0 */\n\n  /**\n   * @file aes.js\n   *\n   * This file contains an adaptation of the AES decryption algorithm\n   * from the Standford Javascript Cryptography Library. That work is\n   * covered by the following copyright and permissions notice:\n   *\n   * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.\n   * All rights reserved.\n   *\n   * Redistribution and use in source and binary forms, with or without\n   * modification, are permitted provided that the following conditions are\n   * met:\n   *\n   * 1. Redistributions of source code must retain the above copyright\n   *    notice, this list of conditions and the following disclaimer.\n   *\n   * 2. Redistributions in binary form must reproduce the above\n   *    copyright notice, this list of conditions and the following\n   *    disclaimer in the documentation and/or other materials provided\n   *    with the distribution.\n   *\n   * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR\n   * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n   * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE\n   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n   * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n   * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n   * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n   * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n   *\n   * The views and conclusions contained in the software and documentation\n   * are those of the authors and should not be interpreted as representing\n   * official policies, either expressed or implied, of the authors.\n   */\n\n  /**\n   * Expand the S-box tables.\n   *\n   * @private\n   */\n\n  const precompute = function () {\n    const tables = [[[], [], [], [], []], [[], [], [], [], []]];\n    const encTable = tables[0];\n    const decTable = tables[1];\n    const sbox = encTable[4];\n    const sboxInv = decTable[4];\n    let i;\n    let x;\n    let xInv;\n    const d = [];\n    const th = [];\n    let x2;\n    let x4;\n    let x8;\n    let s;\n    let tEnc;\n    let tDec; // Compute double and third tables\n\n    for (i = 0; i < 256; i++) {\n      th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;\n    }\n    for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {\n      // Compute sbox\n      s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;\n      s = s >> 8 ^ s & 255 ^ 99;\n      sbox[x] = s;\n      sboxInv[s] = x; // Compute MixColumns\n\n      x8 = d[x4 = d[x2 = d[x]]];\n      tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;\n      tEnc = d[s] * 0x101 ^ s * 0x1010100;\n      for (i = 0; i < 4; i++) {\n        encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n        decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;\n      }\n    } // Compactify. Considerable speedup on Firefox.\n\n    for (i = 0; i < 5; i++) {\n      encTable[i] = encTable[i].slice(0);\n      decTable[i] = decTable[i].slice(0);\n    }\n    return tables;\n  };\n  let aesTables = null;\n  /**\n   * Schedule out an AES key for both encryption and decryption. This\n   * is a low-level class. Use a cipher mode to do bulk encryption.\n   *\n   * @class AES\n   * @param key {Array} The key as an array of 4, 6 or 8 words.\n   */\n\n  class AES {\n    constructor(key) {\n      /**\n      * The expanded S-box and inverse S-box tables. These will be computed\n      * on the client so that we don't have to send them down the wire.\n      *\n      * There are two tables, _tables[0] is for encryption and\n      * _tables[1] is for decryption.\n      *\n      * The first 4 sub-tables are the expanded S-box with MixColumns. The\n      * last (_tables[01][4]) is the S-box itself.\n      *\n      * @private\n      */\n      // if we have yet to precompute the S-box tables\n      // do so now\n      if (!aesTables) {\n        aesTables = precompute();\n      } // then make a copy of that object for use\n\n      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()]];\n      let i;\n      let j;\n      let tmp;\n      const sbox = this._tables[0][4];\n      const decTable = this._tables[1];\n      const keyLen = key.length;\n      let rcon = 1;\n      if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {\n        throw new Error('Invalid aes key size');\n      }\n      const encKey = key.slice(0);\n      const decKey = [];\n      this._key = [encKey, decKey]; // schedule encryption keys\n\n      for (i = keyLen; i < 4 * keyLen + 28; i++) {\n        tmp = encKey[i - 1]; // apply sbox\n\n        if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {\n          tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon\n\n          if (i % keyLen === 0) {\n            tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;\n            rcon = rcon << 1 ^ (rcon >> 7) * 283;\n          }\n        }\n        encKey[i] = encKey[i - keyLen] ^ tmp;\n      } // schedule decryption keys\n\n      for (j = 0; i; j++, i--) {\n        tmp = encKey[j & 3 ? i : i - 4];\n        if (i <= 4 || j < 4) {\n          decKey[j] = tmp;\n        } else {\n          decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];\n        }\n      }\n    }\n    /**\n     * Decrypt 16 bytes, specified as four 32-bit words.\n     *\n     * @param {number} encrypted0 the first word to decrypt\n     * @param {number} encrypted1 the second word to decrypt\n     * @param {number} encrypted2 the third word to decrypt\n     * @param {number} encrypted3 the fourth word to decrypt\n     * @param {Int32Array} out the array to write the decrypted words\n     * into\n     * @param {number} offset the offset into the output array to start\n     * writing results\n     * @return {Array} The plaintext.\n     */\n\n    decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {\n      const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data\n\n      let a = encrypted0 ^ key[0];\n      let b = encrypted3 ^ key[1];\n      let c = encrypted2 ^ key[2];\n      let d = encrypted1 ^ key[3];\n      let a2;\n      let b2;\n      let c2; // key.length === 2 ?\n\n      const nInnerRounds = key.length / 4 - 2;\n      let i;\n      let kIndex = 4;\n      const table = this._tables[1]; // load up the tables\n\n      const table0 = table[0];\n      const table1 = table[1];\n      const table2 = table[2];\n      const table3 = table[3];\n      const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.\n\n      for (i = 0; i < nInnerRounds; i++) {\n        a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];\n        b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];\n        c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];\n        d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];\n        kIndex += 4;\n        a = a2;\n        b = b2;\n        c = c2;\n      } // Last round.\n\n      for (i = 0; i < 4; i++) {\n        out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];\n        a2 = a;\n        a = b;\n        b = c;\n        c = d;\n        d = a2;\n      }\n    }\n  }\n  /**\n   * @file async-stream.js\n   */\n\n  /**\n   * A wrapper around the Stream class to use setTimeout\n   * and run stream \"jobs\" Asynchronously\n   *\n   * @class AsyncStream\n   * @extends Stream\n   */\n\n  class AsyncStream extends Stream {\n    constructor() {\n      super(Stream);\n      this.jobs = [];\n      this.delay = 1;\n      this.timeout_ = null;\n    }\n    /**\n     * process an async job\n     *\n     * @private\n     */\n\n    processJob_() {\n      this.jobs.shift()();\n      if (this.jobs.length) {\n        this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);\n      } else {\n        this.timeout_ = null;\n      }\n    }\n    /**\n     * push a job into the stream\n     *\n     * @param {Function} job the job to push into the stream\n     */\n\n    push(job) {\n      this.jobs.push(job);\n      if (!this.timeout_) {\n        this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);\n      }\n    }\n  }\n  /**\n   * @file decrypter.js\n   *\n   * An asynchronous implementation of AES-128 CBC decryption with\n   * PKCS#7 padding.\n   */\n\n  /**\n   * Convert network-order (big-endian) bytes into their little-endian\n   * representation.\n   */\n\n  const ntoh = function (word) {\n    return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;\n  };\n  /**\n   * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.\n   *\n   * @param {Uint8Array} encrypted the encrypted bytes\n   * @param {Uint32Array} key the bytes of the decryption key\n   * @param {Uint32Array} initVector the initialization vector (IV) to\n   * use for the first round of CBC.\n   * @return {Uint8Array} the decrypted bytes\n   *\n   * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard\n   * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29\n   * @see https://tools.ietf.org/html/rfc2315\n   */\n\n  const decrypt = function (encrypted, key, initVector) {\n    // word-level access to the encrypted bytes\n    const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);\n    const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output\n\n    const decrypted = new Uint8Array(encrypted.byteLength);\n    const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and\n    // decrypted data\n\n    let init0;\n    let init1;\n    let init2;\n    let init3;\n    let encrypted0;\n    let encrypted1;\n    let encrypted2;\n    let encrypted3; // iteration variable\n\n    let wordIx; // pull out the words of the IV to ensure we don't modify the\n    // passed-in reference and easier access\n\n    init0 = initVector[0];\n    init1 = initVector[1];\n    init2 = initVector[2];\n    init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)\n    // to each decrypted block\n\n    for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {\n      // convert big-endian (network order) words into little-endian\n      // (javascript order)\n      encrypted0 = ntoh(encrypted32[wordIx]);\n      encrypted1 = ntoh(encrypted32[wordIx + 1]);\n      encrypted2 = ntoh(encrypted32[wordIx + 2]);\n      encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block\n\n      decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the\n      // plaintext\n\n      decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);\n      decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);\n      decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);\n      decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round\n\n      init0 = encrypted0;\n      init1 = encrypted1;\n      init2 = encrypted2;\n      init3 = encrypted3;\n    }\n    return decrypted;\n  };\n  /**\n   * The `Decrypter` class that manages decryption of AES\n   * data through `AsyncStream` objects and the `decrypt`\n   * function\n   *\n   * @param {Uint8Array} encrypted the encrypted bytes\n   * @param {Uint32Array} key the bytes of the decryption key\n   * @param {Uint32Array} initVector the initialization vector (IV) to\n   * @param {Function} done the function to run when done\n   * @class Decrypter\n   */\n\n  class Decrypter {\n    constructor(encrypted, key, initVector, done) {\n      const step = Decrypter.STEP;\n      const encrypted32 = new Int32Array(encrypted.buffer);\n      const decrypted = new Uint8Array(encrypted.byteLength);\n      let i = 0;\n      this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously\n\n      this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));\n      for (i = step; i < encrypted32.length; i += step) {\n        initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);\n        this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));\n      } // invoke the done() callback when everything is finished\n\n      this.asyncStream_.push(function () {\n        // remove pkcs#7 padding from the decrypted bytes\n        done(null, unpad(decrypted));\n      });\n    }\n    /**\n     * a getter for step the maximum number of bytes to process at one time\n     *\n     * @return {number} the value of step 32000\n     */\n\n    static get STEP() {\n      // 4 * 8000;\n      return 32000;\n    }\n    /**\n     * @private\n     */\n\n    decryptChunk_(encrypted, key, initVector, decrypted) {\n      return function () {\n        const bytes = decrypt(encrypted, key, initVector);\n        decrypted.set(bytes, encrypted.byteOffset);\n      };\n    }\n  }\n  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n  var win;\n  if (typeof window !== \"undefined\") {\n    win = window;\n  } else if (typeof commonjsGlobal !== \"undefined\") {\n    win = commonjsGlobal;\n  } else if (typeof self !== \"undefined\") {\n    win = self;\n  } else {\n    win = {};\n  }\n  var window_1 = win;\n  var isArrayBufferView = function isArrayBufferView(obj) {\n    if (ArrayBuffer.isView === 'function') {\n      return ArrayBuffer.isView(obj);\n    }\n    return obj && obj.buffer instanceof ArrayBuffer;\n  };\n  var BigInt = window_1.BigInt || Number;\n  [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];\n  (function () {\n    var a = new Uint16Array([0xFFCC]);\n    var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n    if (b[0] === 0xFF) {\n      return 'big';\n    }\n    if (b[0] === 0xCC) {\n      return 'little';\n    }\n    return 'unknown';\n  })();\n  /**\n   * Creates an object for sending to a web worker modifying properties that are TypedArrays\n   * into a new object with seperated properties for the buffer, byteOffset, and byteLength.\n   *\n   * @param {Object} message\n   *        Object of properties and values to send to the web worker\n   * @return {Object}\n   *         Modified message with TypedArray values expanded\n   * @function createTransferableMessage\n   */\n\n  const createTransferableMessage = function (message) {\n    const transferable = {};\n    Object.keys(message).forEach(key => {\n      const value = message[key];\n      if (isArrayBufferView(value)) {\n        transferable[key] = {\n          bytes: value.buffer,\n          byteOffset: value.byteOffset,\n          byteLength: value.byteLength\n        };\n      } else {\n        transferable[key] = value;\n      }\n    });\n    return transferable;\n  };\n  /* global self */\n\n  /**\n   * Our web worker interface so that things can talk to aes-decrypter\n   * that will be running in a web worker. the scope is passed to this by\n   * webworkify.\n   */\n\n  self.onmessage = function (event) {\n    const data = event.data;\n    const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);\n    const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);\n    const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);\n    /* eslint-disable no-new, handle-callback-err */\n\n    new Decrypter(encrypted, key, iv, function (err, bytes) {\n      self.postMessage(createTransferableMessage({\n        source: data.source,\n        decrypted: bytes\n      }), [bytes.buffer]);\n    });\n    /* eslint-enable */\n  };\n}));\nvar Decrypter = factory(workerCode);\n/* rollup-plugin-worker-factory end for worker!/home/runner/work/http-streaming/http-streaming/src/decrypter-worker.js */\n\n/**\n * Convert the properties of an HLS track into an audioTrackKind.\n *\n * @private\n */\n\nconst audioTrackKind_ = properties => {\n  let kind = properties.default ? 'main' : 'alternative';\n  if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {\n    kind = 'main-desc';\n  }\n  return kind;\n};\n/**\n * Pause provided segment loader and playlist loader if active\n *\n * @param {SegmentLoader} segmentLoader\n *        SegmentLoader to pause\n * @param {Object} mediaType\n *        Active media type\n * @function stopLoaders\n */\n\nconst stopLoaders = (segmentLoader, mediaType) => {\n  segmentLoader.abort();\n  segmentLoader.pause();\n  if (mediaType && mediaType.activePlaylistLoader) {\n    mediaType.activePlaylistLoader.pause();\n    mediaType.activePlaylistLoader = null;\n  }\n};\n/**\n * Start loading provided segment loader and playlist loader\n *\n * @param {PlaylistLoader} playlistLoader\n *        PlaylistLoader to start loading\n * @param {Object} mediaType\n *        Active media type\n * @function startLoaders\n */\n\nconst startLoaders = (playlistLoader, mediaType) => {\n  // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the\n  // playlist loader\n  mediaType.activePlaylistLoader = playlistLoader;\n  playlistLoader.load();\n};\n/**\n * Returns a function to be called when the media group changes. It performs a\n * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a\n * change of group is merely a rendition switch of the same content at another encoding,\n * rather than a change of content, such as switching audio from English to Spanish.\n *\n * @param {string} type\n *        MediaGroup type\n * @param {Object} settings\n *        Object containing required information for media groups\n * @return {Function}\n *         Handler for a non-destructive resync of SegmentLoader when the active media\n *         group changes.\n * @function onGroupChanged\n */\n\nconst onGroupChanged = (type, settings) => () => {\n  const {\n    segmentLoaders: {\n      [type]: segmentLoader,\n      main: mainSegmentLoader\n    },\n    mediaTypes: {\n      [type]: mediaType\n    }\n  } = settings;\n  const activeTrack = mediaType.activeTrack();\n  const activeGroup = mediaType.getActiveGroup();\n  const previousActiveLoader = mediaType.activePlaylistLoader;\n  const lastGroup = mediaType.lastGroup_; // the group did not change do nothing\n\n  if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {\n    return;\n  }\n  mediaType.lastGroup_ = activeGroup;\n  mediaType.lastTrack_ = activeTrack;\n  stopLoaders(segmentLoader, mediaType);\n  if (!activeGroup || activeGroup.isMainPlaylist) {\n    // there is no group active or active group is a main playlist and won't change\n    return;\n  }\n  if (!activeGroup.playlistLoader) {\n    if (previousActiveLoader) {\n      // The previous group had a playlist loader but the new active group does not\n      // this means we are switching from demuxed to muxed audio. In this case we want to\n      // do a destructive reset of the main segment loader and not restart the audio\n      // loaders.\n      mainSegmentLoader.resetEverything();\n    }\n    return;\n  } // Non-destructive resync\n\n  segmentLoader.resyncLoader();\n  startLoaders(activeGroup.playlistLoader, mediaType);\n};\nconst onGroupChanging = (type, settings) => () => {\n  const {\n    segmentLoaders: {\n      [type]: segmentLoader\n    },\n    mediaTypes: {\n      [type]: mediaType\n    }\n  } = settings;\n  mediaType.lastGroup_ = null;\n  segmentLoader.abort();\n  segmentLoader.pause();\n};\n/**\n * Returns a function to be called when the media track changes. It performs a\n * destructive reset of the SegmentLoader to ensure we start loading as close to\n * currentTime as possible.\n *\n * @param {string} type\n *        MediaGroup type\n * @param {Object} settings\n *        Object containing required information for media groups\n * @return {Function}\n *         Handler for a destructive reset of SegmentLoader when the active media\n *         track changes.\n * @function onTrackChanged\n */\n\nconst onTrackChanged = (type, settings) => () => {\n  const {\n    mainPlaylistLoader,\n    segmentLoaders: {\n      [type]: segmentLoader,\n      main: mainSegmentLoader\n    },\n    mediaTypes: {\n      [type]: mediaType\n    }\n  } = settings;\n  const activeTrack = mediaType.activeTrack();\n  const activeGroup = mediaType.getActiveGroup();\n  const previousActiveLoader = mediaType.activePlaylistLoader;\n  const lastTrack = mediaType.lastTrack_; // track did not change, do nothing\n\n  if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {\n    return;\n  }\n  mediaType.lastGroup_ = activeGroup;\n  mediaType.lastTrack_ = activeTrack;\n  stopLoaders(segmentLoader, mediaType);\n  if (!activeGroup) {\n    // there is no group active so we do not want to restart loaders\n    return;\n  }\n  if (activeGroup.isMainPlaylist) {\n    // track did not change, do nothing\n    if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {\n      return;\n    }\n    const pc = settings.vhs.playlistController_;\n    const newPlaylist = pc.selectPlaylist(); // media will not change do nothing\n\n    if (pc.media() === newPlaylist) {\n      return;\n    }\n    mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);\n    mainPlaylistLoader.pause();\n    mainSegmentLoader.resetEverything();\n    pc.fastQualityChange_(newPlaylist);\n    return;\n  }\n  if (type === 'AUDIO') {\n    if (!activeGroup.playlistLoader) {\n      // when switching from demuxed audio/video to muxed audio/video (noted by no\n      // playlist loader for the audio group), we want to do a destructive reset of the\n      // main segment loader and not restart the audio loaders\n      mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since\n      // it should be stopped\n\n      mainSegmentLoader.resetEverything();\n      return;\n    } // although the segment loader is an audio segment loader, call the setAudio\n    // function to ensure it is prepared to re-append the init segment (or handle other\n    // config changes)\n\n    segmentLoader.setAudio(true);\n    mainSegmentLoader.setAudio(false);\n  }\n  if (previousActiveLoader === activeGroup.playlistLoader) {\n    // Nothing has actually changed. This can happen because track change events can fire\n    // multiple times for a \"single\" change. One for enabling the new active track, and\n    // one for disabling the track that was active\n    startLoaders(activeGroup.playlistLoader, mediaType);\n    return;\n  }\n  if (segmentLoader.track) {\n    // For WebVTT, set the new text track in the segmentloader\n    segmentLoader.track(activeTrack);\n  } // destructive reset\n\n  segmentLoader.resetEverything();\n  startLoaders(activeGroup.playlistLoader, mediaType);\n};\nconst onError = {\n  /**\n   * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters\n   * an error.\n   *\n   * @param {string} type\n   *        MediaGroup type\n   * @param {Object} settings\n   *        Object containing required information for media groups\n   * @return {Function}\n   *         Error handler. Logs warning (or error if the playlist is excluded) to\n   *         console and switches back to default audio track.\n   * @function onError.AUDIO\n   */\n  AUDIO: (type, settings) => () => {\n    const {\n      mediaTypes: {\n        [type]: mediaType\n      },\n      excludePlaylist\n    } = settings; // switch back to default audio track\n\n    const activeTrack = mediaType.activeTrack();\n    const activeGroup = mediaType.activeGroup();\n    const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;\n    const defaultTrack = mediaType.tracks[id];\n    if (activeTrack === defaultTrack) {\n      // Default track encountered an error. All we can do now is exclude the current\n      // rendition and hope another will switch audio groups\n      excludePlaylist({\n        error: {\n          message: 'Problem encountered loading the default audio track.'\n        }\n      });\n      return;\n    }\n    videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');\n    for (const trackId in mediaType.tracks) {\n      mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;\n    }\n    mediaType.onTrackChanged();\n  },\n  /**\n   * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters\n   * an error.\n   *\n   * @param {string} type\n   *        MediaGroup type\n   * @param {Object} settings\n   *        Object containing required information for media groups\n   * @return {Function}\n   *         Error handler. Logs warning to console and disables the active subtitle track\n   * @function onError.SUBTITLES\n   */\n  SUBTITLES: (type, settings) => () => {\n    const {\n      mediaTypes: {\n        [type]: mediaType\n      }\n    } = settings;\n    videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');\n    const track = mediaType.activeTrack();\n    if (track) {\n      track.mode = 'disabled';\n    }\n    mediaType.onTrackChanged();\n  }\n};\nconst setupListeners = {\n  /**\n   * Setup event listeners for audio playlist loader\n   *\n   * @param {string} type\n   *        MediaGroup type\n   * @param {PlaylistLoader|null} playlistLoader\n   *        PlaylistLoader to register listeners on\n   * @param {Object} settings\n   *        Object containing required information for media groups\n   * @function setupListeners.AUDIO\n   */\n  AUDIO: (type, playlistLoader, settings) => {\n    if (!playlistLoader) {\n      // no playlist loader means audio will be muxed with the video\n      return;\n    }\n    const {\n      tech,\n      requestOptions,\n      segmentLoaders: {\n        [type]: segmentLoader\n      }\n    } = settings;\n    playlistLoader.on('loadedmetadata', () => {\n      const media = playlistLoader.media();\n      segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload\n      // permits, start downloading segments\n\n      if (!tech.paused() || media.endList && tech.preload() !== 'none') {\n        segmentLoader.load();\n      }\n    });\n    playlistLoader.on('loadedplaylist', () => {\n      segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running\n\n      if (!tech.paused()) {\n        segmentLoader.load();\n      }\n    });\n    playlistLoader.on('error', onError[type](type, settings));\n  },\n  /**\n   * Setup event listeners for subtitle playlist loader\n   *\n   * @param {string} type\n   *        MediaGroup type\n   * @param {PlaylistLoader|null} playlistLoader\n   *        PlaylistLoader to register listeners on\n   * @param {Object} settings\n   *        Object containing required information for media groups\n   * @function setupListeners.SUBTITLES\n   */\n  SUBTITLES: (type, playlistLoader, settings) => {\n    const {\n      tech,\n      requestOptions,\n      segmentLoaders: {\n        [type]: segmentLoader\n      },\n      mediaTypes: {\n        [type]: mediaType\n      }\n    } = settings;\n    playlistLoader.on('loadedmetadata', () => {\n      const media = playlistLoader.media();\n      segmentLoader.playlist(media, requestOptions);\n      segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload\n      // permits, start downloading segments\n\n      if (!tech.paused() || media.endList && tech.preload() !== 'none') {\n        segmentLoader.load();\n      }\n    });\n    playlistLoader.on('loadedplaylist', () => {\n      segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running\n\n      if (!tech.paused()) {\n        segmentLoader.load();\n      }\n    });\n    playlistLoader.on('error', onError[type](type, settings));\n  }\n};\nconst initialize = {\n  /**\n   * Setup PlaylistLoaders and AudioTracks for the audio groups\n   *\n   * @param {string} type\n   *        MediaGroup type\n   * @param {Object} settings\n   *        Object containing required information for media groups\n   * @function initialize.AUDIO\n   */\n  'AUDIO': (type, settings) => {\n    const {\n      vhs,\n      sourceType,\n      segmentLoaders: {\n        [type]: segmentLoader\n      },\n      requestOptions,\n      main: {\n        mediaGroups\n      },\n      mediaTypes: {\n        [type]: {\n          groups,\n          tracks,\n          logger_\n        }\n      },\n      mainPlaylistLoader\n    } = settings;\n    const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none\n\n    if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {\n      mediaGroups[type] = {\n        main: {\n          default: {\n            default: true\n          }\n        }\n      };\n      if (audioOnlyMain) {\n        mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;\n      }\n    }\n    for (const groupId in mediaGroups[type]) {\n      if (!groups[groupId]) {\n        groups[groupId] = [];\n      }\n      for (const variantLabel in mediaGroups[type][groupId]) {\n        let properties = mediaGroups[type][groupId][variantLabel];\n        let playlistLoader;\n        if (audioOnlyMain) {\n          logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);\n          properties.isMainPlaylist = true;\n          playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,\n          // use the resolved media playlist object\n        } else if (sourceType === 'vhs-json' && properties.playlists) {\n          playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);\n        } else if (properties.resolvedUri) {\n          playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists\n          // should we even have properties.playlists in this check.\n        } else if (properties.playlists && sourceType === 'dash') {\n          playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);\n        } else {\n          // no resolvedUri means the audio is muxed with the video when using this\n          // audio track\n          playlistLoader = null;\n        }\n        properties = merge({\n          id: variantLabel,\n          playlistLoader\n        }, properties);\n        setupListeners[type](type, properties.playlistLoader, settings);\n        groups[groupId].push(properties);\n        if (typeof tracks[variantLabel] === 'undefined') {\n          const track = new videojs.AudioTrack({\n            id: variantLabel,\n            kind: audioTrackKind_(properties),\n            enabled: false,\n            language: properties.language,\n            default: properties.default,\n            label: variantLabel\n          });\n          tracks[variantLabel] = track;\n        }\n      }\n    } // setup single error event handler for the segment loader\n\n    segmentLoader.on('error', onError[type](type, settings));\n  },\n  /**\n   * Setup PlaylistLoaders and TextTracks for the subtitle groups\n   *\n   * @param {string} type\n   *        MediaGroup type\n   * @param {Object} settings\n   *        Object containing required information for media groups\n   * @function initialize.SUBTITLES\n   */\n  'SUBTITLES': (type, settings) => {\n    const {\n      tech,\n      vhs,\n      sourceType,\n      segmentLoaders: {\n        [type]: segmentLoader\n      },\n      requestOptions,\n      main: {\n        mediaGroups\n      },\n      mediaTypes: {\n        [type]: {\n          groups,\n          tracks\n        }\n      },\n      mainPlaylistLoader\n    } = settings;\n    for (const groupId in mediaGroups[type]) {\n      if (!groups[groupId]) {\n        groups[groupId] = [];\n      }\n      for (const variantLabel in mediaGroups[type][groupId]) {\n        if (!vhs.options_.useForcedSubtitles && mediaGroups[type][groupId][variantLabel].forced) {\n          // Subtitle playlists with the forced attribute are not selectable in Safari.\n          // According to Apple's HLS Authoring Specification:\n          //   If content has forced subtitles and regular subtitles in a given language,\n          //   the regular subtitles track in that language MUST contain both the forced\n          //   subtitles and the regular subtitles for that language.\n          // Because of this requirement and that Safari does not add forced subtitles,\n          // forced subtitles are skipped here to maintain consistent experience across\n          // all platforms\n          continue;\n        }\n        let properties = mediaGroups[type][groupId][variantLabel];\n        let playlistLoader;\n        if (sourceType === 'hls') {\n          playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);\n        } else if (sourceType === 'dash') {\n          const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);\n          if (!playlists.length) {\n            return;\n          }\n          playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);\n        } else if (sourceType === 'vhs-json') {\n          playlistLoader = new PlaylistLoader(\n          // if the vhs-json object included the media playlist, use the media playlist\n          // as provided, otherwise use the resolved URI to load the playlist\n          properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);\n        }\n        properties = merge({\n          id: variantLabel,\n          playlistLoader\n        }, properties);\n        setupListeners[type](type, properties.playlistLoader, settings);\n        groups[groupId].push(properties);\n        if (typeof tracks[variantLabel] === 'undefined') {\n          const track = tech.addRemoteTextTrack({\n            id: variantLabel,\n            kind: 'subtitles',\n            default: properties.default && properties.autoselect,\n            language: properties.language,\n            label: variantLabel\n          }, false).track;\n          tracks[variantLabel] = track;\n        }\n      }\n    } // setup single error event handler for the segment loader\n\n    segmentLoader.on('error', onError[type](type, settings));\n  },\n  /**\n   * Setup TextTracks for the closed-caption groups\n   *\n   * @param {String} type\n   *        MediaGroup type\n   * @param {Object} settings\n   *        Object containing required information for media groups\n   * @function initialize['CLOSED-CAPTIONS']\n   */\n  'CLOSED-CAPTIONS': (type, settings) => {\n    const {\n      tech,\n      main: {\n        mediaGroups\n      },\n      mediaTypes: {\n        [type]: {\n          groups,\n          tracks\n        }\n      }\n    } = settings;\n    for (const groupId in mediaGroups[type]) {\n      if (!groups[groupId]) {\n        groups[groupId] = [];\n      }\n      for (const variantLabel in mediaGroups[type][groupId]) {\n        const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services\n\n        if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {\n          continue;\n        }\n        const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};\n        let newProps = {\n          label: variantLabel,\n          language: properties.language,\n          instreamId: properties.instreamId,\n          default: properties.default && properties.autoselect\n        };\n        if (captionServices[newProps.instreamId]) {\n          newProps = merge(newProps, captionServices[newProps.instreamId]);\n        }\n        if (newProps.default === undefined) {\n          delete newProps.default;\n        } // No PlaylistLoader is required for Closed-Captions because the captions are\n        // embedded within the video stream\n\n        groups[groupId].push(merge({\n          id: variantLabel\n        }, properties));\n        if (typeof tracks[variantLabel] === 'undefined') {\n          const track = tech.addRemoteTextTrack({\n            id: newProps.instreamId,\n            kind: 'captions',\n            default: newProps.default,\n            language: newProps.language,\n            label: newProps.label\n          }, false).track;\n          tracks[variantLabel] = track;\n        }\n      }\n    }\n  }\n};\nconst groupMatch = (list, media) => {\n  for (let i = 0; i < list.length; i++) {\n    if (playlistMatch(media, list[i])) {\n      return true;\n    }\n    if (list[i].playlists && groupMatch(list[i].playlists, media)) {\n      return true;\n    }\n  }\n  return false;\n};\n/**\n * Returns a function used to get the active group of the provided type\n *\n * @param {string} type\n *        MediaGroup type\n * @param {Object} settings\n *        Object containing required information for media groups\n * @return {Function}\n *         Function that returns the active media group for the provided type. Takes an\n *         optional parameter {TextTrack} track. If no track is provided, a list of all\n *         variants in the group, otherwise the variant corresponding to the provided\n *         track is returned.\n * @function activeGroup\n */\n\nconst activeGroup = (type, settings) => track => {\n  const {\n    mainPlaylistLoader,\n    mediaTypes: {\n      [type]: {\n        groups\n      }\n    }\n  } = settings;\n  const media = mainPlaylistLoader.media();\n  if (!media) {\n    return null;\n  }\n  let variants = null; // set to variants to main media active group\n\n  if (media.attributes[type]) {\n    variants = groups[media.attributes[type]];\n  }\n  const groupKeys = Object.keys(groups);\n  if (!variants) {\n    // find the mainPlaylistLoader media\n    // that is in a media group if we are dealing\n    // with audio only\n    if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {\n      for (let i = 0; i < groupKeys.length; i++) {\n        const groupPropertyList = groups[groupKeys[i]];\n        if (groupMatch(groupPropertyList, media)) {\n          variants = groupPropertyList;\n          break;\n        }\n      } // use the main group if it exists\n    } else if (groups.main) {\n      variants = groups.main; // only one group, use that one\n    } else if (groupKeys.length === 1) {\n      variants = groups[groupKeys[0]];\n    }\n  }\n  if (typeof track === 'undefined') {\n    return variants;\n  }\n  if (track === null || !variants) {\n    // An active track was specified so a corresponding group is expected. track === null\n    // means no track is currently active so there is no corresponding group\n    return null;\n  }\n  return variants.filter(props => props.id === track.id)[0] || null;\n};\nconst activeTrack = {\n  /**\n   * Returns a function used to get the active track of type provided\n   *\n   * @param {string} type\n   *        MediaGroup type\n   * @param {Object} settings\n   *        Object containing required information for media groups\n   * @return {Function}\n   *         Function that returns the active media track for the provided type. Returns\n   *         null if no track is active\n   * @function activeTrack.AUDIO\n   */\n  AUDIO: (type, settings) => () => {\n    const {\n      mediaTypes: {\n        [type]: {\n          tracks\n        }\n      }\n    } = settings;\n    for (const id in tracks) {\n      if (tracks[id].enabled) {\n        return tracks[id];\n      }\n    }\n    return null;\n  },\n  /**\n   * Returns a function used to get the active track of type provided\n   *\n   * @param {string} type\n   *        MediaGroup type\n   * @param {Object} settings\n   *        Object containing required information for media groups\n   * @return {Function}\n   *         Function that returns the active media track for the provided type. Returns\n   *         null if no track is active\n   * @function activeTrack.SUBTITLES\n   */\n  SUBTITLES: (type, settings) => () => {\n    const {\n      mediaTypes: {\n        [type]: {\n          tracks\n        }\n      }\n    } = settings;\n    for (const id in tracks) {\n      if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {\n        return tracks[id];\n      }\n    }\n    return null;\n  }\n};\nconst getActiveGroup = (type, {\n  mediaTypes\n}) => () => {\n  const activeTrack_ = mediaTypes[type].activeTrack();\n  if (!activeTrack_) {\n    return null;\n  }\n  return mediaTypes[type].activeGroup(activeTrack_);\n};\n/**\n * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,\n * Closed-Captions) specified in the main manifest.\n *\n * @param {Object} settings\n *        Object containing required information for setting up the media groups\n * @param {Tech} settings.tech\n *        The tech of the player\n * @param {Object} settings.requestOptions\n *        XHR request options used by the segment loaders\n * @param {PlaylistLoader} settings.mainPlaylistLoader\n *        PlaylistLoader for the main source\n * @param {VhsHandler} settings.vhs\n *        VHS SourceHandler\n * @param {Object} settings.main\n *        The parsed main manifest\n * @param {Object} settings.mediaTypes\n *        Object to store the loaders, tracks, and utility methods for each media type\n * @param {Function} settings.excludePlaylist\n *        Excludes the current rendition and forces a rendition switch.\n * @function setupMediaGroups\n */\n\nconst setupMediaGroups = settings => {\n  ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {\n    initialize[type](type, settings);\n  });\n  const {\n    mediaTypes,\n    mainPlaylistLoader,\n    tech,\n    vhs,\n    segmentLoaders: {\n      ['AUDIO']: audioSegmentLoader,\n      main: mainSegmentLoader\n    }\n  } = settings; // setup active group and track getters and change event handlers\n\n  ['AUDIO', 'SUBTITLES'].forEach(type => {\n    mediaTypes[type].activeGroup = activeGroup(type, settings);\n    mediaTypes[type].activeTrack = activeTrack[type](type, settings);\n    mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);\n    mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);\n    mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);\n    mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);\n  }); // DO NOT enable the default subtitle or caption track.\n  // DO enable the default audio track\n\n  const audioGroup = mediaTypes.AUDIO.activeGroup();\n  if (audioGroup) {\n    const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;\n    mediaTypes.AUDIO.tracks[groupId].enabled = true;\n    mediaTypes.AUDIO.onGroupChanged();\n    mediaTypes.AUDIO.onTrackChanged();\n    const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the\n    // track is changed, but needs to be handled here since the track may not be considered\n    // changed on the first call to onTrackChanged\n\n    if (!activeAudioGroup.playlistLoader) {\n      // either audio is muxed with video or the stream is audio only\n      mainSegmentLoader.setAudio(true);\n    } else {\n      // audio is demuxed\n      mainSegmentLoader.setAudio(false);\n      audioSegmentLoader.setAudio(true);\n    }\n  }\n  mainPlaylistLoader.on('mediachange', () => {\n    ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());\n  });\n  mainPlaylistLoader.on('mediachanging', () => {\n    ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());\n  }); // custom audio track change event handler for usage event\n\n  const onAudioTrackChanged = () => {\n    mediaTypes.AUDIO.onTrackChanged();\n    tech.trigger({\n      type: 'usage',\n      name: 'vhs-audio-change'\n    });\n  };\n  tech.audioTracks().addEventListener('change', onAudioTrackChanged);\n  tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);\n  vhs.on('dispose', () => {\n    tech.audioTracks().removeEventListener('change', onAudioTrackChanged);\n    tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);\n  }); // clear existing audio tracks and add the ones we just created\n\n  tech.clearTracks('audio');\n  for (const id in mediaTypes.AUDIO.tracks) {\n    tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);\n  }\n};\n/**\n * Creates skeleton object used to store the loaders, tracks, and utility methods for each\n * media type\n *\n * @return {Object}\n *         Object to store the loaders, tracks, and utility methods for each media type\n * @function createMediaTypes\n */\n\nconst createMediaTypes = () => {\n  const mediaTypes = {};\n  ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {\n    mediaTypes[type] = {\n      groups: {},\n      tracks: {},\n      activePlaylistLoader: null,\n      activeGroup: noop,\n      activeTrack: noop,\n      getActiveGroup: noop,\n      onGroupChanged: noop,\n      onTrackChanged: noop,\n      lastTrack_: null,\n      logger_: logger(`MediaGroups[${type}]`)\n    };\n  });\n  return mediaTypes;\n};\n\n/**\n * A utility class for setting properties and maintaining the state of the content steering manifest.\n *\n * Content Steering manifest format:\n * VERSION: number (required) currently only version 1 is supported.\n * TTL: number in seconds (optional) until the next content steering manifest reload.\n * RELOAD-URI: string (optional) uri to fetch the next content steering manifest.\n * SERVICE-LOCATION-PRIORITY or PATHWAY-PRIORITY a non empty array of unique string values.\n * PATHWAY-CLONES: array (optional) (HLS only) pathway clone objects to copy from other playlists.\n */\n\nclass SteeringManifest {\n  constructor() {\n    this.priority_ = [];\n    this.pathwayClones_ = new Map();\n  }\n  set version(number) {\n    // Only version 1 is currently supported for both DASH and HLS.\n    if (number === 1) {\n      this.version_ = number;\n    }\n  }\n  set ttl(seconds) {\n    // TTL = time-to-live, default = 300 seconds.\n    this.ttl_ = seconds || 300;\n  }\n  set reloadUri(uri) {\n    if (uri) {\n      // reload URI can be relative to the previous reloadUri.\n      this.reloadUri_ = resolveUrl(this.reloadUri_, uri);\n    }\n  }\n  set priority(array) {\n    // priority must be non-empty and unique values.\n    if (array && array.length) {\n      this.priority_ = array;\n    }\n  }\n  set pathwayClones(array) {\n    // pathwayClones must be non-empty.\n    if (array && array.length) {\n      this.pathwayClones_ = new Map(array.map(clone => [clone.ID, clone]));\n    }\n  }\n  get version() {\n    return this.version_;\n  }\n  get ttl() {\n    return this.ttl_;\n  }\n  get reloadUri() {\n    return this.reloadUri_;\n  }\n  get priority() {\n    return this.priority_;\n  }\n  get pathwayClones() {\n    return this.pathwayClones_;\n  }\n}\n/**\n * This class represents a content steering manifest and associated state. See both HLS and DASH specifications.\n * HLS: https://developer.apple.com/streaming/HLSContentSteeringSpecification.pdf and\n * https://datatracker.ietf.org/doc/draft-pantos-hls-rfc8216bis/ section 4.4.6.6.\n * DASH: https://dashif.org/docs/DASH-IF-CTS-00XX-Content-Steering-Community-Review.pdf\n *\n * @param {function} xhr for making a network request from the browser.\n * @param {function} bandwidth for fetching the current bandwidth from the main segment loader.\n */\n\nclass ContentSteeringController extends videojs.EventTarget {\n  constructor(xhr, bandwidth) {\n    super();\n    this.currentPathway = null;\n    this.defaultPathway = null;\n    this.queryBeforeStart = false;\n    this.availablePathways_ = new Set();\n    this.steeringManifest = new SteeringManifest();\n    this.proxyServerUrl_ = null;\n    this.manifestType_ = null;\n    this.ttlTimeout_ = null;\n    this.request_ = null;\n    this.currentPathwayClones = new Map();\n    this.nextPathwayClones = new Map();\n    this.excludedSteeringManifestURLs = new Set();\n    this.logger_ = logger('Content Steering');\n    this.xhr_ = xhr;\n    this.getBandwidth_ = bandwidth;\n  }\n  /**\n   * Assigns the content steering tag properties to the steering controller\n   *\n   * @param {string} baseUrl the baseURL from the main manifest for resolving the steering manifest url\n   * @param {Object} steeringTag the content steering tag from the main manifest\n   */\n\n  assignTagProperties(baseUrl, steeringTag) {\n    this.manifestType_ = steeringTag.serverUri ? 'HLS' : 'DASH'; // serverUri is HLS serverURL is DASH\n\n    const steeringUri = steeringTag.serverUri || steeringTag.serverURL;\n    if (!steeringUri) {\n      this.logger_(`steering manifest URL is ${steeringUri}, cannot request steering manifest.`);\n      this.trigger('error');\n      return;\n    } // Content steering manifests can be encoded as a data URI. We can decode, parse and return early if that's the case.\n\n    if (steeringUri.startsWith('data:')) {\n      this.decodeDataUriManifest_(steeringUri.substring(steeringUri.indexOf(',') + 1));\n      return;\n    } // reloadUri is the resolution of the main manifest URL and steering URL.\n\n    this.steeringManifest.reloadUri = resolveUrl(baseUrl, steeringUri); // pathwayId is HLS defaultServiceLocation is DASH\n\n    this.defaultPathway = steeringTag.pathwayId || steeringTag.defaultServiceLocation; // currently only DASH supports the following properties on <ContentSteering> tags.\n\n    this.queryBeforeStart = steeringTag.queryBeforeStart;\n    this.proxyServerUrl_ = steeringTag.proxyServerURL; // trigger a steering event if we have a pathway from the content steering tag.\n    // this tells VHS which segment pathway to start with.\n    // If queryBeforeStart is true we need to wait for the steering manifest response.\n\n    if (this.defaultPathway && !this.queryBeforeStart) {\n      this.trigger('content-steering');\n    }\n  }\n  /**\n   * Requests the content steering manifest and parse the response. This should only be called after\n   * assignTagProperties was called with a content steering tag.\n   *\n   * @param {string} initialUri The optional uri to make the request with.\n   *    If set, the request should be made with exactly what is passed in this variable.\n   *    This scenario should only happen once on initalization.\n   */\n\n  requestSteeringManifest(initial) {\n    const reloadUri = this.steeringManifest.reloadUri;\n    if (!reloadUri) {\n      return;\n    } // We currently don't support passing MPD query parameters directly to the content steering URL as this requires\n    // ExtUrlQueryInfo tag support. See the DASH content steering spec section 8.1.\n    // This request URI accounts for manifest URIs that have been excluded.\n\n    const uri = initial ? reloadUri : this.getRequestURI(reloadUri); // If there are no valid manifest URIs, we should stop content steering.\n\n    if (!uri) {\n      this.logger_('No valid content steering manifest URIs. Stopping content steering.');\n      this.trigger('error');\n      this.dispose();\n      return;\n    }\n    const metadata = {\n      contentSteeringInfo: {\n        uri\n      }\n    };\n    this.trigger({\n      type: 'contentsteeringloadstart',\n      metadata\n    });\n    this.request_ = this.xhr_({\n      uri,\n      requestType: 'content-steering-manifest'\n    }, (error, errorInfo) => {\n      if (error) {\n        // If the client receives HTTP 410 Gone in response to a manifest request,\n        // it MUST NOT issue another request for that URI for the remainder of the\n        // playback session. It MAY continue to use the most-recently obtained set\n        // of Pathways.\n        if (errorInfo.status === 410) {\n          this.logger_(`manifest request 410 ${error}.`);\n          this.logger_(`There will be no more content steering requests to ${uri} this session.`);\n          this.excludedSteeringManifestURLs.add(uri);\n          return;\n        } // If the client receives HTTP 429 Too Many Requests with a Retry-After\n        // header in response to a manifest request, it SHOULD wait until the time\n        // specified by the Retry-After header to reissue the request.\n\n        if (errorInfo.status === 429) {\n          const retrySeconds = errorInfo.responseHeaders['retry-after'];\n          this.logger_(`manifest request 429 ${error}.`);\n          this.logger_(`content steering will retry in ${retrySeconds} seconds.`);\n          this.startTTLTimeout_(parseInt(retrySeconds, 10));\n          return;\n        } // If the Steering Manifest cannot be loaded and parsed correctly, the\n        // client SHOULD continue to use the previous values and attempt to reload\n        // it after waiting for the previously-specified TTL (or 5 minutes if\n        // none).\n\n        this.logger_(`manifest failed to load ${error}.`);\n        this.startTTLTimeout_();\n        return;\n      }\n      this.trigger({\n        type: 'contentsteeringloadcomplete',\n        metadata\n      });\n      let steeringManifestJson;\n      try {\n        steeringManifestJson = JSON.parse(this.request_.responseText);\n      } catch (parseError) {\n        const errorMetadata = {\n          errorType: videojs.Error.StreamingContentSteeringParserError,\n          error: parseError\n        };\n        this.trigger({\n          type: 'error',\n          metadata: errorMetadata\n        });\n      }\n      this.assignSteeringProperties_(steeringManifestJson);\n      const parsedMetadata = {\n        contentSteeringInfo: metadata.contentSteeringInfo,\n        contentSteeringManifest: {\n          version: this.steeringManifest.version,\n          reloadUri: this.steeringManifest.reloadUri,\n          priority: this.steeringManifest.priority\n        }\n      };\n      this.trigger({\n        type: 'contentsteeringparsed',\n        metadata: parsedMetadata\n      });\n      this.startTTLTimeout_();\n    });\n  }\n  /**\n   * Set the proxy server URL and add the steering manifest url as a URI encoded parameter.\n   *\n   * @param {string} steeringUrl the steering manifest url\n   * @return the steering manifest url to a proxy server with all parameters set\n   */\n\n  setProxyServerUrl_(steeringUrl) {\n    const steeringUrlObject = new window$1.URL(steeringUrl);\n    const proxyServerUrlObject = new window$1.URL(this.proxyServerUrl_);\n    proxyServerUrlObject.searchParams.set('url', encodeURI(steeringUrlObject.toString()));\n    return this.setSteeringParams_(proxyServerUrlObject.toString());\n  }\n  /**\n   * Decodes and parses the data uri encoded steering manifest\n   *\n   * @param {string} dataUri the data uri to be decoded and parsed.\n   */\n\n  decodeDataUriManifest_(dataUri) {\n    const steeringManifestJson = JSON.parse(window$1.atob(dataUri));\n    this.assignSteeringProperties_(steeringManifestJson);\n  }\n  /**\n   * Set the HLS or DASH content steering manifest request query parameters. For example:\n   * _HLS_pathway=\"<CURRENT-PATHWAY-ID>\" and _HLS_throughput=<THROUGHPUT>\n   * _DASH_pathway and _DASH_throughput\n   *\n   * @param {string} uri to add content steering server parameters to.\n   * @return a new uri as a string with the added steering query parameters.\n   */\n\n  setSteeringParams_(url) {\n    const urlObject = new window$1.URL(url);\n    const path = this.getPathway();\n    const networkThroughput = this.getBandwidth_();\n    if (path) {\n      const pathwayKey = `_${this.manifestType_}_pathway`;\n      urlObject.searchParams.set(pathwayKey, path);\n    }\n    if (networkThroughput) {\n      const throughputKey = `_${this.manifestType_}_throughput`;\n      urlObject.searchParams.set(throughputKey, networkThroughput);\n    }\n    return urlObject.toString();\n  }\n  /**\n   * Assigns the current steering manifest properties and to the SteeringManifest object\n   *\n   * @param {Object} steeringJson the raw JSON steering manifest\n   */\n\n  assignSteeringProperties_(steeringJson) {\n    this.steeringManifest.version = steeringJson.VERSION;\n    if (!this.steeringManifest.version) {\n      this.logger_(`manifest version is ${steeringJson.VERSION}, which is not supported.`);\n      this.trigger('error');\n      return;\n    }\n    this.steeringManifest.ttl = steeringJson.TTL;\n    this.steeringManifest.reloadUri = steeringJson['RELOAD-URI']; // HLS = PATHWAY-PRIORITY required. DASH = SERVICE-LOCATION-PRIORITY optional\n\n    this.steeringManifest.priority = steeringJson['PATHWAY-PRIORITY'] || steeringJson['SERVICE-LOCATION-PRIORITY']; // Pathway clones to be created/updated in HLS.\n    // See section 7.2 https://datatracker.ietf.org/doc/draft-pantos-hls-rfc8216bis/\n\n    this.steeringManifest.pathwayClones = steeringJson['PATHWAY-CLONES'];\n    this.nextPathwayClones = this.steeringManifest.pathwayClones; // 1. apply first pathway from the array.\n    // 2. if first pathway doesn't exist in manifest, try next pathway.\n    //    a. if all pathways are exhausted, ignore the steering manifest priority.\n    // 3. if segments fail from an established pathway, try all variants/renditions, then exclude the failed pathway.\n    //    a. exclude a pathway for a minimum of the last TTL duration. Meaning, from the next steering response,\n    //       the excluded pathway will be ignored.\n    //       See excludePathway usage in excludePlaylist().\n    // If there are no available pathways, we need to stop content steering.\n\n    if (!this.availablePathways_.size) {\n      this.logger_('There are no available pathways for content steering. Ending content steering.');\n      this.trigger('error');\n      this.dispose();\n    }\n    const chooseNextPathway = pathwaysByPriority => {\n      for (const path of pathwaysByPriority) {\n        if (this.availablePathways_.has(path)) {\n          return path;\n        }\n      } // If no pathway matches, ignore the manifest and choose the first available.\n\n      return [...this.availablePathways_][0];\n    };\n    const nextPathway = chooseNextPathway(this.steeringManifest.priority);\n    if (this.currentPathway !== nextPathway) {\n      this.currentPathway = nextPathway;\n      this.trigger('content-steering');\n    }\n  }\n  /**\n   * Returns the pathway to use for steering decisions\n   *\n   * @return {string} returns the current pathway or the default\n   */\n\n  getPathway() {\n    return this.currentPathway || this.defaultPathway;\n  }\n  /**\n   * Chooses the manifest request URI based on proxy URIs and server URLs.\n   * Also accounts for exclusion on certain manifest URIs.\n   *\n   * @param {string} reloadUri the base uri before parameters\n   *\n   * @return {string} the final URI for the request to the manifest server.\n   */\n\n  getRequestURI(reloadUri) {\n    if (!reloadUri) {\n      return null;\n    }\n    const isExcluded = uri => this.excludedSteeringManifestURLs.has(uri);\n    if (this.proxyServerUrl_) {\n      const proxyURI = this.setProxyServerUrl_(reloadUri);\n      if (!isExcluded(proxyURI)) {\n        return proxyURI;\n      }\n    }\n    const steeringURI = this.setSteeringParams_(reloadUri);\n    if (!isExcluded(steeringURI)) {\n      return steeringURI;\n    } // Return nothing if all valid manifest URIs are excluded.\n\n    return null;\n  }\n  /**\n   * Start the timeout for re-requesting the steering manifest at the TTL interval.\n   *\n   * @param {number} ttl time in seconds of the timeout. Defaults to the\n   *        ttl interval in the steering manifest\n   */\n\n  startTTLTimeout_(ttl = this.steeringManifest.ttl) {\n    // 300 (5 minutes) is the default value.\n    const ttlMS = ttl * 1000;\n    this.ttlTimeout_ = window$1.setTimeout(() => {\n      this.requestSteeringManifest();\n    }, ttlMS);\n  }\n  /**\n   * Clear the TTL timeout if necessary.\n   */\n\n  clearTTLTimeout_() {\n    window$1.clearTimeout(this.ttlTimeout_);\n    this.ttlTimeout_ = null;\n  }\n  /**\n   * aborts any current steering xhr and sets the current request object to null\n   */\n\n  abort() {\n    if (this.request_) {\n      this.request_.abort();\n    }\n    this.request_ = null;\n  }\n  /**\n   * aborts steering requests clears the ttl timeout and resets all properties.\n   */\n\n  dispose() {\n    this.off('content-steering');\n    this.off('error');\n    this.abort();\n    this.clearTTLTimeout_();\n    this.currentPathway = null;\n    this.defaultPathway = null;\n    this.queryBeforeStart = null;\n    this.proxyServerUrl_ = null;\n    this.manifestType_ = null;\n    this.ttlTimeout_ = null;\n    this.request_ = null;\n    this.excludedSteeringManifestURLs = new Set();\n    this.availablePathways_ = new Set();\n    this.steeringManifest = new SteeringManifest();\n  }\n  /**\n   * adds a pathway to the available pathways set\n   *\n   * @param {string} pathway the pathway string to add\n   */\n\n  addAvailablePathway(pathway) {\n    if (pathway) {\n      this.availablePathways_.add(pathway);\n    }\n  }\n  /**\n   * Clears all pathways from the available pathways set\n   */\n\n  clearAvailablePathways() {\n    this.availablePathways_.clear();\n  }\n  /**\n   * Removes a pathway from the available pathways set.\n   */\n\n  excludePathway(pathway) {\n    return this.availablePathways_.delete(pathway);\n  }\n  /**\n   * Checks the refreshed DASH manifest content steering tag for changes.\n   *\n   * @param {string} baseURL new steering tag on DASH manifest refresh\n   * @param {Object} newTag the new tag to check for changes\n   * @return a true or false whether the new tag has different values\n   */\n\n  didDASHTagChange(baseURL, newTag) {\n    return !newTag && this.steeringManifest.reloadUri || newTag && (resolveUrl(baseURL, newTag.serverURL) !== this.steeringManifest.reloadUri || newTag.defaultServiceLocation !== this.defaultPathway || newTag.queryBeforeStart !== this.queryBeforeStart || newTag.proxyServerURL !== this.proxyServerUrl_);\n  }\n  getAvailablePathways() {\n    return this.availablePathways_;\n  }\n}\nconst debounce = (callback, wait) => {\n  let timeoutId = null;\n  return (...args) => {\n    clearTimeout(timeoutId);\n    timeoutId = setTimeout(() => {\n      callback.apply(null, args);\n    }, wait);\n  };\n};\nconst ABORT_EARLY_EXCLUSION_SECONDS = 10;\nlet Vhs$1; // SegmentLoader stats that need to have each loader's\n// values summed to calculate the final value\n\nconst loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];\nconst sumLoaderStat = function (stat) {\n  return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];\n};\nconst shouldSwitchToMedia = function ({\n  currentPlaylist,\n  buffered,\n  currentTime,\n  nextPlaylist,\n  bufferLowWaterLine,\n  bufferHighWaterLine,\n  duration,\n  bufferBasedABR,\n  log\n}) {\n  // we have no other playlist to switch to\n  if (!nextPlaylist) {\n    videojs.log.warn('We received no playlist to switch to. Please check your stream.');\n    return false;\n  }\n  const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;\n  if (!currentPlaylist) {\n    log(`${sharedLogLine} as current playlist is not set`);\n    return true;\n  } // no need to switch if playlist is the same\n\n  if (nextPlaylist.id === currentPlaylist.id) {\n    return false;\n  } // determine if current time is in a buffered range.\n\n  const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.\n  // This is because in LIVE, the player plays 3 segments from the end of the\n  // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble\n  // in those segments, a viewer will never experience a rendition upswitch.\n\n  if (!currentPlaylist.endList) {\n    // For LLHLS live streams, don't switch renditions before playback has started, as it almost\n    // doubles the time to first playback.\n    if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {\n      log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);\n      return false;\n    }\n    log(`${sharedLogLine} as current playlist is live`);\n    return true;\n  }\n  const forwardBuffer = timeAheadOf(buffered, currentTime);\n  const maxBufferLowWaterLine = bufferBasedABR ? 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\n  // duration is below the max potential low water line\n\n  if (duration < maxBufferLowWaterLine) {\n    log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);\n    return true;\n  }\n  const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;\n  const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,\n  // we can switch down\n\n  if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {\n    let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;\n    if (bufferBasedABR) {\n      logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;\n    }\n    log(logLine);\n    return true;\n  } // and if our buffer is higher than the low water line,\n  // we can switch up\n\n  if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {\n    let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;\n    if (bufferBasedABR) {\n      logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;\n    }\n    log(logLine);\n    return true;\n  }\n  log(`not ${sharedLogLine} as no switching criteria met`);\n  return false;\n};\n/**\n * the main playlist controller controller all interactons\n * between playlists and segmentloaders. At this time this mainly\n * involves a main playlist and a series of audio playlists\n * if they are available\n *\n * @class PlaylistController\n * @extends videojs.EventTarget\n */\n\nclass PlaylistController extends videojs.EventTarget {\n  constructor(options) {\n    super(); // Adding a slight debounce to avoid duplicate calls during rapid quality changes, for example:\n    // When selecting quality from the quality list,\n    // where we may have multiple bandwidth profiles for the same vertical resolution.\n\n    this.fastQualityChange_ = debounce(this.fastQualityChange_.bind(this), 100);\n    const {\n      src,\n      withCredentials,\n      tech,\n      bandwidth,\n      externVhs,\n      useCueTags,\n      playlistExclusionDuration,\n      enableLowInitialPlaylist,\n      sourceType,\n      cacheEncryptionKeys,\n      bufferBasedABR,\n      leastPixelDiffSelector,\n      captionServices,\n      experimentalUseMMS\n    } = options;\n    if (!src) {\n      throw new Error('A non-empty playlist URL or JSON manifest string is required');\n    }\n    let {\n      maxPlaylistRetries\n    } = options;\n    if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {\n      maxPlaylistRetries = Infinity;\n    }\n    Vhs$1 = externVhs;\n    this.bufferBasedABR = Boolean(bufferBasedABR);\n    this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);\n    this.withCredentials = withCredentials;\n    this.tech_ = tech;\n    this.vhs_ = tech.vhs;\n    this.player_ = options.player_;\n    this.sourceType_ = sourceType;\n    this.useCueTags_ = useCueTags;\n    this.playlistExclusionDuration = playlistExclusionDuration;\n    this.maxPlaylistRetries = maxPlaylistRetries;\n    this.enableLowInitialPlaylist = enableLowInitialPlaylist;\n    this.usingManagedMediaSource_ = false;\n    if (this.useCueTags_) {\n      this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');\n      this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';\n    }\n    this.requestOptions_ = {\n      withCredentials,\n      maxPlaylistRetries,\n      timeout: null\n    };\n    this.on('error', this.pauseLoading);\n    this.mediaTypes_ = createMediaTypes();\n    if (experimentalUseMMS && window$1.ManagedMediaSource) {\n      // Airplay source not yet implemented. Remote playback must be disabled.\n      this.tech_.el_.disableRemotePlayback = true;\n      this.mediaSource = new window$1.ManagedMediaSource();\n      this.usingManagedMediaSource_ = true;\n      videojs.log('Using ManagedMediaSource');\n    } else if (window$1.MediaSource) {\n      this.mediaSource = new window$1.MediaSource();\n    }\n    this.handleDurationChange_ = this.handleDurationChange_.bind(this);\n    this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);\n    this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);\n    this.load = this.load.bind(this);\n    this.pause = this.pause.bind(this);\n    this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player\n\n    this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);\n    this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_);\n    this.mediaSource.addEventListener('startstreaming', this.load);\n    this.mediaSource.addEventListener('endstreaming', this.pause); // we don't have to handle sourceclose since dispose will handle termination of\n    // everything, and the MediaSource should not be detached without a proper disposal\n\n    this.seekable_ = createTimeRanges();\n    this.hasPlayed_ = false;\n    this.syncController_ = new SyncController(options);\n    this.segmentMetadataTrack_ = tech.addRemoteTextTrack({\n      kind: 'metadata',\n      label: 'segment-metadata'\n    }, false).track;\n    this.segmentMetadataTrack_.mode = 'hidden';\n    this.decrypter_ = new Decrypter();\n    this.sourceUpdater_ = new SourceUpdater(this.mediaSource);\n    this.inbandTextTracks_ = {};\n    this.timelineChangeController_ = new TimelineChangeController();\n    this.keyStatusMap_ = new Map();\n    const segmentLoaderSettings = {\n      vhs: this.vhs_,\n      parse708captions: options.parse708captions,\n      useDtsForTimestampOffset: options.useDtsForTimestampOffset,\n      captionServices,\n      mediaSource: this.mediaSource,\n      currentTime: this.tech_.currentTime.bind(this.tech_),\n      seekable: () => this.seekable(),\n      seeking: () => this.tech_.seeking(),\n      duration: () => this.duration(),\n      hasPlayed: () => this.hasPlayed_,\n      goalBufferLength: () => this.goalBufferLength(),\n      bandwidth,\n      syncController: this.syncController_,\n      decrypter: this.decrypter_,\n      sourceType: this.sourceType_,\n      inbandTextTracks: this.inbandTextTracks_,\n      cacheEncryptionKeys,\n      sourceUpdater: this.sourceUpdater_,\n      timelineChangeController: this.timelineChangeController_,\n      exactManifestTimings: options.exactManifestTimings,\n      addMetadataToTextTrack: this.addMetadataToTextTrack.bind(this)\n    }; // The source type check not only determines whether a special DASH playlist loader\n    // should be used, but also covers the case where the provided src is a vhs-json\n    // manifest object (instead of a URL). In the case of vhs-json, the default\n    // PlaylistLoader should be used.\n\n    this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, merge(this.requestOptions_, {\n      addMetadataToTextTrack: this.addMetadataToTextTrack.bind(this)\n    })) : new PlaylistLoader(src, this.vhs_, merge(this.requestOptions_, {\n      addDateRangesToTextTrack: this.addDateRangesToTextTrack_.bind(this)\n    }));\n    this.setupMainPlaylistLoaderListeners_(); // setup segment loaders\n    // combined audio/video or just video when alternate audio track is selected\n\n    this.mainSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {\n      segmentMetadataTrack: this.segmentMetadataTrack_,\n      loaderType: 'main'\n    }), options); // alternate audio track\n\n    this.audioSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {\n      loaderType: 'audio'\n    }), options);\n    this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge(segmentLoaderSettings, {\n      loaderType: 'vtt',\n      featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,\n      loadVttJs: () => new Promise((resolve, reject) => {\n        function onLoad() {\n          tech.off('vttjserror', onError);\n          resolve();\n        }\n        function onError() {\n          tech.off('vttjsloaded', onLoad);\n          reject();\n        }\n        tech.one('vttjsloaded', onLoad);\n        tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:\n\n        tech.addWebVttScript_();\n      })\n    }), options);\n    const getBandwidth = () => {\n      return this.mainSegmentLoader_.bandwidth;\n    };\n    this.contentSteeringController_ = new ContentSteeringController(this.vhs_.xhr, getBandwidth);\n    this.setupSegmentLoaderListeners_();\n    if (this.bufferBasedABR) {\n      this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());\n      this.tech_.on('pause', () => this.stopABRTimer_());\n      this.tech_.on('play', () => this.startABRTimer_());\n    } // Create SegmentLoader stat-getters\n    // mediaRequests_\n    // mediaRequestsAborted_\n    // mediaRequestsTimedout_\n    // mediaRequestsErrored_\n    // mediaTransferDuration_\n    // mediaBytesTransferred_\n    // mediaAppends_\n\n    loaderStats.forEach(stat => {\n      this[stat + '_'] = sumLoaderStat.bind(this, stat);\n    });\n    this.logger_ = logger('pc');\n    this.triggeredFmp4Usage = false;\n    if (this.tech_.preload() === 'none') {\n      this.loadOnPlay_ = () => {\n        this.loadOnPlay_ = null;\n        this.mainPlaylistLoader_.load();\n      };\n      this.tech_.one('play', this.loadOnPlay_);\n    } else {\n      this.mainPlaylistLoader_.load();\n    }\n    this.timeToLoadedData__ = -1;\n    this.mainAppendsToLoadedData__ = -1;\n    this.audioAppendsToLoadedData__ = -1;\n    const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)\n\n    this.tech_.one(event, () => {\n      const timeToLoadedDataStart = Date.now();\n      this.tech_.one('loadeddata', () => {\n        this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;\n        this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;\n        this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;\n      });\n    });\n  }\n  mainAppendsToLoadedData_() {\n    return this.mainAppendsToLoadedData__;\n  }\n  audioAppendsToLoadedData_() {\n    return this.audioAppendsToLoadedData__;\n  }\n  appendsToLoadedData_() {\n    const main = this.mainAppendsToLoadedData_();\n    const audio = this.audioAppendsToLoadedData_();\n    if (main === -1 || audio === -1) {\n      return -1;\n    }\n    return main + audio;\n  }\n  timeToLoadedData_() {\n    return this.timeToLoadedData__;\n  }\n  /**\n   * Run selectPlaylist and switch to the new playlist if we should\n   *\n   * @param {string} [reason=abr] a reason for why the ABR check is made\n   * @private\n   */\n\n  checkABR_(reason = 'abr') {\n    const nextPlaylist = this.selectPlaylist();\n    if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {\n      this.switchMedia_(nextPlaylist, reason);\n    }\n  }\n  switchMedia_(playlist, cause, delay) {\n    const oldMedia = this.media();\n    const oldId = oldMedia && (oldMedia.id || oldMedia.uri);\n    const newId = playlist && (playlist.id || playlist.uri);\n    if (oldId && oldId !== newId) {\n      this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);\n      const metadata = {\n        renditionInfo: {\n          id: newId,\n          bandwidth: playlist.attributes.BANDWIDTH,\n          resolution: playlist.attributes.RESOLUTION,\n          codecs: playlist.attributes.CODECS\n        },\n        cause\n      };\n      this.trigger({\n        type: 'renditionselected',\n        metadata\n      });\n      this.tech_.trigger({\n        type: 'usage',\n        name: `vhs-rendition-change-${cause}`\n      });\n    }\n    this.mainPlaylistLoader_.media(playlist, delay);\n  }\n  /**\n   * A function that ensures we switch our playlists inside of `mediaTypes`\n   * to match the current `serviceLocation` provided by the contentSteering controller.\n   * We want to check media types of `AUDIO`, `SUBTITLES`, and `CLOSED-CAPTIONS`.\n   *\n   * This should only be called on a DASH playback scenario while using content steering.\n   * This is necessary due to differences in how media in HLS manifests are generally tied to\n   * a video playlist, where in DASH that is not always the case.\n   */\n\n  switchMediaForDASHContentSteering_() {\n    ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {\n      const mediaType = this.mediaTypes_[type];\n      const activeGroup = mediaType ? mediaType.activeGroup() : null;\n      const pathway = this.contentSteeringController_.getPathway();\n      if (activeGroup && pathway) {\n        // activeGroup can be an array or a single group\n        const mediaPlaylists = activeGroup.length ? activeGroup[0].playlists : activeGroup.playlists;\n        const dashMediaPlaylists = mediaPlaylists.filter(p => p.attributes.serviceLocation === pathway); // Switch the current active playlist to the correct CDN\n\n        if (dashMediaPlaylists.length) {\n          this.mediaTypes_[type].activePlaylistLoader.media(dashMediaPlaylists[0]);\n        }\n      }\n    });\n  }\n  /**\n   * Start a timer that periodically calls checkABR_\n   *\n   * @private\n   */\n\n  startABRTimer_() {\n    this.stopABRTimer_();\n    this.abrTimer_ = window$1.setInterval(() => this.checkABR_(), 250);\n  }\n  /**\n   * Stop the timer that periodically calls checkABR_\n   *\n   * @private\n   */\n\n  stopABRTimer_() {\n    // if we're scrubbing, we don't need to pause.\n    // This getter will be added to Video.js in version 7.11.\n    if (this.tech_.scrubbing && this.tech_.scrubbing()) {\n      return;\n    }\n    window$1.clearInterval(this.abrTimer_);\n    this.abrTimer_ = null;\n  }\n  /**\n   * Get a list of playlists for the currently selected audio playlist\n   *\n   * @return {Array} the array of audio playlists\n   */\n\n  getAudioTrackPlaylists_() {\n    const main = this.main();\n    const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only\n    // assume that the audio tracks are contained in main\n    // playlist array, use that or an empty array.\n\n    if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {\n      return defaultPlaylists;\n    }\n    const AUDIO = main.mediaGroups.AUDIO;\n    const groupKeys = Object.keys(AUDIO);\n    let track; // get the current active track\n\n    if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {\n      track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet\n    } else {\n      // default group is `main` or just the first group.\n      const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];\n      for (const label in defaultGroup) {\n        if (defaultGroup[label].default) {\n          track = {\n            label\n          };\n          break;\n        }\n      }\n    } // no active track no playlists.\n\n    if (!track) {\n      return defaultPlaylists;\n    }\n    const playlists = []; // get all of the playlists that are possible for the\n    // active track.\n\n    for (const group in AUDIO) {\n      if (AUDIO[group][track.label]) {\n        const properties = AUDIO[group][track.label];\n        if (properties.playlists && properties.playlists.length) {\n          playlists.push.apply(playlists, properties.playlists);\n        } else if (properties.uri) {\n          playlists.push(properties);\n        } else if (main.playlists.length) {\n          // if an audio group does not have a uri\n          // see if we have main playlists that use it as a group.\n          // if we do then add those to the playlists list.\n          for (let i = 0; i < main.playlists.length; i++) {\n            const playlist = main.playlists[i];\n            if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {\n              playlists.push(playlist);\n            }\n          }\n        }\n      }\n    }\n    if (!playlists.length) {\n      return defaultPlaylists;\n    }\n    return playlists;\n  }\n  /**\n   * Register event handlers on the main playlist loader. A helper\n   * function for construction time.\n   *\n   * @private\n   */\n\n  setupMainPlaylistLoaderListeners_() {\n    this.mainPlaylistLoader_.on('loadedmetadata', () => {\n      const media = this.mainPlaylistLoader_.media();\n      const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to\n      // timeout the request.\n\n      if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {\n        this.requestOptions_.timeout = 0;\n      } else {\n        this.requestOptions_.timeout = requestTimeout;\n      } // if this isn't a live video and preload permits, start\n      // downloading segments\n\n      if (media.endList && this.tech_.preload() !== 'none') {\n        this.mainSegmentLoader_.playlist(media, this.requestOptions_);\n        this.mainSegmentLoader_.load();\n      }\n      setupMediaGroups({\n        sourceType: this.sourceType_,\n        segmentLoaders: {\n          AUDIO: this.audioSegmentLoader_,\n          SUBTITLES: this.subtitleSegmentLoader_,\n          main: this.mainSegmentLoader_\n        },\n        tech: this.tech_,\n        requestOptions: this.requestOptions_,\n        mainPlaylistLoader: this.mainPlaylistLoader_,\n        vhs: this.vhs_,\n        main: this.main(),\n        mediaTypes: this.mediaTypes_,\n        excludePlaylist: this.excludePlaylist.bind(this)\n      });\n      this.triggerPresenceUsage_(this.main(), media);\n      this.setupFirstPlay();\n      if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {\n        this.trigger('selectedinitialmedia');\n      } else {\n        // We must wait for the active audio playlist loader to\n        // finish setting up before triggering this event so the\n        // representations API and EME setup is correct\n        this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {\n          this.trigger('selectedinitialmedia');\n        });\n      }\n    });\n    this.mainPlaylistLoader_.on('loadedplaylist', () => {\n      if (this.loadOnPlay_) {\n        this.tech_.off('play', this.loadOnPlay_);\n      }\n      let updatedPlaylist = this.mainPlaylistLoader_.media();\n      if (!updatedPlaylist) {\n        // Add content steering listeners on first load and init.\n        this.attachContentSteeringListeners_();\n        this.initContentSteeringController_(); // exclude any variants that are not supported by the browser before selecting\n        // an initial media as the playlist selectors do not consider browser support\n\n        this.excludeUnsupportedVariants_();\n        let selectedMedia;\n        if (this.enableLowInitialPlaylist) {\n          selectedMedia = this.selectInitialPlaylist();\n        }\n        if (!selectedMedia) {\n          selectedMedia = this.selectPlaylist();\n        }\n        if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {\n          return;\n        }\n        this.initialMedia_ = selectedMedia;\n        this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will\n        // fire again since the playlist will be requested. In the case of vhs-json\n        // (where the manifest object is provided as the source), when the media\n        // playlist's `segments` list is already available, a media playlist won't be\n        // requested, and loadedplaylist won't fire again, so the playlist handler must be\n        // called on its own here.\n\n        const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;\n        if (!haveJsonSource) {\n          return;\n        }\n        updatedPlaylist = this.initialMedia_;\n      }\n      this.handleUpdatedMediaPlaylist(updatedPlaylist);\n    });\n    this.mainPlaylistLoader_.on('error', () => {\n      const error = this.mainPlaylistLoader_.error;\n      this.excludePlaylist({\n        playlistToExclude: error.playlist,\n        error\n      });\n    });\n    this.mainPlaylistLoader_.on('mediachanging', () => {\n      this.mainSegmentLoader_.abort();\n      this.mainSegmentLoader_.pause();\n    });\n    this.mainPlaylistLoader_.on('mediachange', () => {\n      const media = this.mainPlaylistLoader_.media();\n      const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to\n      // timeout the request.\n\n      if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {\n        this.requestOptions_.timeout = 0;\n      } else {\n        this.requestOptions_.timeout = requestTimeout;\n      }\n      if (this.sourceType_ === 'dash') {\n        // we don't want to re-request the same hls playlist right after it was changed\n        // Initially it was implemented as workaround to restart playlist loader for live\n        // when playlist loader is paused because of playlist exclusions:\n        // see: https://github.com/videojs/http-streaming/pull/1339\n        // but this introduces duplicate \"loadedplaylist\" event.\n        // Ideally we want to re-think playlist loader life-cycle events,\n        // but simply checking \"paused\" state should help a lot\n        if (this.mainPlaylistLoader_.isPaused) {\n          this.mainPlaylistLoader_.load();\n        }\n      } // TODO: Create a new event on the PlaylistLoader that signals\n      // that the segments have changed in some way and use that to\n      // update the SegmentLoader instead of doing it twice here and\n      // on `loadedplaylist`\n\n      this.mainSegmentLoader_.pause();\n      this.mainSegmentLoader_.playlist(media, this.requestOptions_);\n      if (this.waitingForFastQualityPlaylistReceived_) {\n        this.runFastQualitySwitch_();\n      } else {\n        this.mainSegmentLoader_.load();\n      }\n      this.tech_.trigger({\n        type: 'mediachange',\n        bubbles: true\n      });\n    });\n    this.mainPlaylistLoader_.on('playlistunchanged', () => {\n      const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been\n      // excluded for not-changing. We likely just have a really slowly updating\n      // playlist.\n\n      if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {\n        return;\n      }\n      const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);\n      if (playlistOutdated) {\n        // Playlist has stopped updating and we're stuck at its end. Try to\n        // exclude it and switch to another playlist in the hope that that\n        // one is updating (and give the player a chance to re-adjust to the\n        // safe live point).\n        this.excludePlaylist({\n          error: {\n            message: 'Playlist no longer updating.',\n            reason: 'playlist-unchanged'\n          }\n        }); // useful for monitoring QoS\n\n        this.tech_.trigger('playliststuck');\n      }\n    });\n    this.mainPlaylistLoader_.on('renditiondisabled', () => {\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-rendition-disabled'\n      });\n    });\n    this.mainPlaylistLoader_.on('renditionenabled', () => {\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-rendition-enabled'\n      });\n    });\n    const playlistLoaderEvents = ['manifestrequeststart', 'manifestrequestcomplete', 'manifestparsestart', 'manifestparsecomplete', 'playlistrequeststart', 'playlistrequestcomplete', 'playlistparsestart', 'playlistparsecomplete', 'renditiondisabled', 'renditionenabled'];\n    playlistLoaderEvents.forEach(eventName => {\n      this.mainPlaylistLoader_.on(eventName, metadata => {\n        // trigger directly on the player to ensure early events are fired.\n        this.player_.trigger(_extends({}, metadata));\n      });\n    });\n  }\n  /**\n   * Given an updated media playlist (whether it was loaded for the first time, or\n   * refreshed for live playlists), update any relevant properties and state to reflect\n   * changes in the media that should be accounted for (e.g., cues and duration).\n   *\n   * @param {Object} updatedPlaylist the updated media playlist object\n   *\n   * @private\n   */\n\n  handleUpdatedMediaPlaylist(updatedPlaylist) {\n    if (this.useCueTags_) {\n      this.updateAdCues_(updatedPlaylist);\n    } // TODO: Create a new event on the PlaylistLoader that signals\n    // that the segments have changed in some way and use that to\n    // update the SegmentLoader instead of doing it twice here and\n    // on `mediachange`\n\n    this.mainSegmentLoader_.pause();\n    this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);\n    if (this.waitingForFastQualityPlaylistReceived_) {\n      this.runFastQualitySwitch_();\n    }\n    this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,\n    // as it is possible that it was temporarily stopped while waiting for\n    // a playlist (e.g., in case the playlist errored and we re-requested it).\n\n    if (!this.tech_.paused()) {\n      this.mainSegmentLoader_.load();\n      if (this.audioSegmentLoader_) {\n        this.audioSegmentLoader_.load();\n      }\n    }\n  }\n  /**\n   * A helper function for triggerring presence usage events once per source\n   *\n   * @private\n   */\n\n  triggerPresenceUsage_(main, media) {\n    const mediaGroups = main.mediaGroups || {};\n    let defaultDemuxed = true;\n    const audioGroupKeys = Object.keys(mediaGroups.AUDIO);\n    for (const mediaGroup in mediaGroups.AUDIO) {\n      for (const label in mediaGroups.AUDIO[mediaGroup]) {\n        const properties = mediaGroups.AUDIO[mediaGroup][label];\n        if (!properties.uri) {\n          defaultDemuxed = false;\n        }\n      }\n    }\n    if (defaultDemuxed) {\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-demuxed'\n      });\n    }\n    if (Object.keys(mediaGroups.SUBTITLES).length) {\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-webvtt'\n      });\n    }\n    if (Vhs$1.Playlist.isAes(media)) {\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-aes'\n      });\n    }\n    if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-alternate-audio'\n      });\n    }\n    if (this.useCueTags_) {\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-playlist-cue-tags'\n      });\n    }\n  }\n  shouldSwitchToMedia_(nextPlaylist) {\n    const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;\n    const currentTime = this.tech_.currentTime();\n    const bufferLowWaterLine = this.bufferLowWaterLine();\n    const bufferHighWaterLine = this.bufferHighWaterLine();\n    const buffered = this.tech_.buffered();\n    return shouldSwitchToMedia({\n      buffered,\n      currentTime,\n      currentPlaylist,\n      nextPlaylist,\n      bufferLowWaterLine,\n      bufferHighWaterLine,\n      duration: this.duration(),\n      bufferBasedABR: this.bufferBasedABR,\n      log: this.logger_\n    });\n  }\n  /**\n   * Register event handlers on the segment loaders. A helper function\n   * for construction time.\n   *\n   * @private\n   */\n\n  setupSegmentLoaderListeners_() {\n    this.mainSegmentLoader_.on('bandwidthupdate', () => {\n      // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's\n      // useful to check to see if a rendition switch should be made.\n      this.checkABR_('bandwidthupdate');\n      this.tech_.trigger('bandwidthupdate');\n    });\n    this.mainSegmentLoader_.on('timeout', () => {\n      if (this.bufferBasedABR) {\n        // If a rendition change is needed, then it would've be done on `bandwidthupdate`.\n        // Here the only consideration is that for buffer based ABR there's no guarantee\n        // of an immediate switch (since the bandwidth is averaged with a timeout\n        // bandwidth value of 1), so force a load on the segment loader to keep it going.\n        this.mainSegmentLoader_.load();\n      }\n    }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer\n    // based ABR.\n\n    if (!this.bufferBasedABR) {\n      this.mainSegmentLoader_.on('progress', () => {\n        this.trigger('progress');\n      });\n    }\n    this.mainSegmentLoader_.on('error', () => {\n      const error = this.mainSegmentLoader_.error();\n      this.excludePlaylist({\n        playlistToExclude: error.playlist,\n        error\n      });\n    });\n    this.mainSegmentLoader_.on('appenderror', () => {\n      this.error = this.mainSegmentLoader_.error_;\n      this.trigger('error');\n    });\n    this.mainSegmentLoader_.on('syncinfoupdate', () => {\n      this.onSyncInfoUpdate_();\n    });\n    this.mainSegmentLoader_.on('timestampoffset', () => {\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-timestamp-offset'\n      });\n    });\n    this.audioSegmentLoader_.on('syncinfoupdate', () => {\n      this.onSyncInfoUpdate_();\n    });\n    this.audioSegmentLoader_.on('appenderror', () => {\n      this.error = this.audioSegmentLoader_.error_;\n      this.trigger('error');\n    });\n    this.mainSegmentLoader_.on('ended', () => {\n      this.logger_('main segment loader ended');\n      this.onEndOfStream();\n    }); // There is the possibility of the video segment and the audio segment\n    // at a current time to be on different timelines. When this occurs, the player\n    // forwards playback to a point where these two segment types are back on the same\n    // timeline. This time will be just after the end of the audio segment that is on\n    // a previous timeline.\n\n    this.timelineChangeController_.on('audioTimelineBehind', () => {\n      const segmentInfo = this.audioSegmentLoader_.pendingSegment_;\n      if (!segmentInfo || !segmentInfo.segment || !segmentInfo.segment.syncInfo) {\n        return;\n      } // Update the current time to just after the faulty audio segment.\n      // This moves playback to a spot where both audio and video segments\n      // are on the same timeline.\n\n      const newTime = segmentInfo.segment.syncInfo.end + 0.01;\n      this.tech_.setCurrentTime(newTime);\n    });\n    this.timelineChangeController_.on('fixBadTimelineChange', () => {\n      // pause, reset-everything and load for all segment-loaders\n      this.logger_('Fix bad timeline change. Restarting al segment loaders...');\n      this.mainSegmentLoader_.pause();\n      this.mainSegmentLoader_.resetEverything();\n      if (this.mediaTypes_.AUDIO.activePlaylistLoader) {\n        this.audioSegmentLoader_.pause();\n        this.audioSegmentLoader_.resetEverything();\n      }\n      if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {\n        this.subtitleSegmentLoader_.pause();\n        this.subtitleSegmentLoader_.resetEverything();\n      } // start segment loader loading in case they are paused\n\n      this.load();\n    });\n    this.mainSegmentLoader_.on('earlyabort', event => {\n      // never try to early abort with the new ABR algorithm\n      if (this.bufferBasedABR) {\n        return;\n      }\n      this.delegateLoaders_('all', ['abort']);\n      this.excludePlaylist({\n        error: {\n          message: 'Aborted early because there isn\\'t enough bandwidth to complete ' + 'the request without rebuffering.'\n        },\n        playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS\n      });\n    });\n    const updateCodecs = () => {\n      if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {\n        return this.tryToCreateSourceBuffers_();\n      }\n      const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded\n\n      if (!codecs) {\n        return;\n      }\n      this.sourceUpdater_.addOrChangeSourceBuffers(codecs);\n    };\n    this.mainSegmentLoader_.on('trackinfo', updateCodecs);\n    this.audioSegmentLoader_.on('trackinfo', updateCodecs);\n    this.mainSegmentLoader_.on('fmp4', () => {\n      if (!this.triggeredFmp4Usage) {\n        this.tech_.trigger({\n          type: 'usage',\n          name: 'vhs-fmp4'\n        });\n        this.triggeredFmp4Usage = true;\n      }\n    });\n    this.audioSegmentLoader_.on('fmp4', () => {\n      if (!this.triggeredFmp4Usage) {\n        this.tech_.trigger({\n          type: 'usage',\n          name: 'vhs-fmp4'\n        });\n        this.triggeredFmp4Usage = true;\n      }\n    });\n    this.audioSegmentLoader_.on('ended', () => {\n      this.logger_('audioSegmentLoader ended');\n      this.onEndOfStream();\n    });\n    const segmentLoaderEvents = ['segmentselected', 'segmentloadstart', 'segmentloaded', 'segmentkeyloadstart', 'segmentkeyloadcomplete', 'segmentdecryptionstart', 'segmentdecryptioncomplete', 'segmenttransmuxingstart', 'segmenttransmuxingcomplete', 'segmenttransmuxingtrackinfoavailable', 'segmenttransmuxingtiminginfoavailable', 'segmentappendstart', 'appendsdone', 'bandwidthupdated', 'timelinechange', 'codecschange'];\n    segmentLoaderEvents.forEach(eventName => {\n      this.mainSegmentLoader_.on(eventName, metadata => {\n        this.player_.trigger(_extends({}, metadata));\n      });\n      this.audioSegmentLoader_.on(eventName, metadata => {\n        this.player_.trigger(_extends({}, metadata));\n      });\n      this.subtitleSegmentLoader_.on(eventName, metadata => {\n        this.player_.trigger(_extends({}, metadata));\n      });\n    });\n  }\n  mediaSecondsLoaded_() {\n    return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);\n  }\n  /**\n   * Call load on our SegmentLoaders\n   */\n\n  load() {\n    this.mainSegmentLoader_.load();\n    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {\n      this.audioSegmentLoader_.load();\n    }\n    if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {\n      this.subtitleSegmentLoader_.load();\n    }\n  }\n  /**\n   * Call pause on our SegmentLoaders\n   */\n\n  pause() {\n    this.mainSegmentLoader_.pause();\n    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {\n      this.audioSegmentLoader_.pause();\n    }\n    if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {\n      this.subtitleSegmentLoader_.pause();\n    }\n  }\n  /**\n   * Re-tune playback quality level for the current player\n   * conditions. This method will perform destructive actions like removing\n   * already buffered content in order to readjust the currently active\n   * playlist quickly. This is good for manual quality changes\n   *\n   * @private\n   */\n\n  fastQualityChange_(media = this.selectPlaylist()) {\n    if (media && media === this.mainPlaylistLoader_.media()) {\n      this.logger_('skipping fastQualityChange because new media is same as old');\n      return;\n    }\n    this.switchMedia_(media, 'fast-quality'); // we would like to avoid race condition when we call fastQuality,\n    // reset everything and start loading segments from prev segments instead of new because new playlist is not received yet\n\n    this.waitingForFastQualityPlaylistReceived_ = true;\n  }\n  runFastQualitySwitch_() {\n    this.waitingForFastQualityPlaylistReceived_ = false;\n    this.mainSegmentLoader_.pause();\n    this.mainSegmentLoader_.resetEverything();\n    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {\n      this.audioSegmentLoader_.pause();\n      this.audioSegmentLoader_.resetEverything();\n    }\n    if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {\n      this.subtitleSegmentLoader_.pause();\n      this.subtitleSegmentLoader_.resetEverything();\n    } // start segment loader loading in case they are paused\n\n    this.load();\n  }\n  /**\n   * Begin playback.\n   */\n\n  play() {\n    if (this.setupFirstPlay()) {\n      return;\n    }\n    if (this.tech_.ended()) {\n      this.tech_.setCurrentTime(0);\n    }\n    if (this.hasPlayed_) {\n      this.load();\n    }\n    const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,\n    // seek forward to the live point\n\n    if (this.tech_.duration() === Infinity) {\n      if (this.tech_.currentTime() < seekable.start(0)) {\n        return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));\n      }\n    }\n  }\n  /**\n   * Seek to the latest media position if this is a live video and the\n   * player and video are loaded and initialized.\n   */\n\n  setupFirstPlay() {\n    const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play\n    //  If 1) there is no active media\n    //     2) the player is paused\n    //     3) the first play has already been setup\n    // then exit early\n\n    if (!media || this.tech_.paused() || this.hasPlayed_) {\n      return false;\n    } // when the video is a live stream and/or has a start time\n\n    if (!media.endList || media.start) {\n      const seekable = this.seekable();\n      if (!seekable.length) {\n        // without a seekable range, the player cannot seek to begin buffering at the\n        // live or start point\n        return false;\n      }\n      const seekableEnd = seekable.end(0);\n      let startPoint = seekableEnd;\n      if (media.start) {\n        const offset = media.start.timeOffset;\n        if (offset < 0) {\n          startPoint = Math.max(seekableEnd + offset, seekable.start(0));\n        } else {\n          startPoint = Math.min(seekableEnd, offset);\n        }\n      } // trigger firstplay to inform the source handler to ignore the next seek event\n\n      this.trigger('firstplay'); // seek to the live point\n\n      this.tech_.setCurrentTime(startPoint);\n    }\n    this.hasPlayed_ = true; // we can begin loading now that everything is ready\n\n    this.load();\n    return true;\n  }\n  /**\n   * handle the sourceopen event on the MediaSource\n   *\n   * @private\n   */\n\n  handleSourceOpen_() {\n    // Only attempt to create the source buffer if none already exist.\n    // handleSourceOpen is also called when we are \"re-opening\" a source buffer\n    // after `endOfStream` has been called (in response to a seek for instance)\n    this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of\n    // code in video.js but is required because play() must be invoked\n    // *after* the media source has opened.\n\n    if (this.tech_.autoplay()) {\n      const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request\n      // on browsers which return a promise\n\n      if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {\n        playPromise.then(null, e => {});\n      }\n    }\n    this.trigger('sourceopen');\n  }\n  /**\n   * handle the sourceended event on the MediaSource\n   *\n   * @private\n   */\n\n  handleSourceEnded_() {\n    if (!this.inbandTextTracks_.metadataTrack_) {\n      return;\n    }\n    const cues = this.inbandTextTracks_.metadataTrack_.cues;\n    if (!cues || !cues.length) {\n      return;\n    }\n    const duration = this.duration();\n    cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;\n  }\n  /**\n   * handle the durationchange event on the MediaSource\n   *\n   * @private\n   */\n\n  handleDurationChange_() {\n    this.tech_.trigger('durationchange');\n  }\n  /**\n   * Calls endOfStream on the media source when all active stream types have called\n   * endOfStream\n   *\n   * @param {string} streamType\n   *        Stream type of the segment loader that called endOfStream\n   * @private\n   */\n\n  onEndOfStream() {\n    let isEndOfStream = this.mainSegmentLoader_.ended_;\n    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {\n      const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active\n\n      if (!mainMediaInfo || mainMediaInfo.hasVideo) {\n        // if we do not know if the main segment loader contains video yet or if we\n        // definitively know the main segment loader contains video, then we need to wait\n        // for both main and audio segment loaders to call endOfStream\n        isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;\n      } else {\n        // otherwise just rely on the audio loader\n        isEndOfStream = this.audioSegmentLoader_.ended_;\n      }\n    }\n    if (!isEndOfStream) {\n      return;\n    }\n    this.stopABRTimer_();\n    this.sourceUpdater_.endOfStream();\n  }\n  /**\n   * Check if a playlist has stopped being updated\n   *\n   * @param {Object} playlist the media playlist object\n   * @return {boolean} whether the playlist has stopped being updated or not\n   */\n\n  stuckAtPlaylistEnd_(playlist) {\n    const seekable = this.seekable();\n    if (!seekable.length) {\n      // playlist doesn't have enough information to determine whether we are stuck\n      return false;\n    }\n    const expired = this.syncController_.getExpiredTime(playlist, this.duration());\n    if (expired === null) {\n      return false;\n    } // does not use the safe live end to calculate playlist end, since we\n    // don't want to say we are stuck while there is still content\n\n    const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);\n    const currentTime = this.tech_.currentTime();\n    const buffered = this.tech_.buffered();\n    if (!buffered.length) {\n      // return true if the playhead reached the absolute end of the playlist\n      return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;\n    }\n    const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute\n    // end of playlist\n\n    return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;\n  }\n  /**\n   * Exclude a playlist for a set amount of time, making it unavailable for selection by\n   * the rendition selection algorithm, then force a new playlist (rendition) selection.\n   *\n   * @param {Object=} playlistToExclude\n   *                  the playlist to exclude, defaults to the currently selected playlist\n   * @param {Object=} error\n   *                  an optional error\n   * @param {number=} playlistExclusionDuration\n   *                  an optional number of seconds to exclude the playlist\n   */\n\n  excludePlaylist({\n    playlistToExclude = this.mainPlaylistLoader_.media(),\n    error = {},\n    playlistExclusionDuration\n  }) {\n    // If the `error` was generated by the playlist loader, it will contain\n    // the playlist we were trying to load (but failed) and that should be\n    // excluded instead of the currently selected playlist which is likely\n    // out-of-date in this scenario\n    playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();\n    playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were\n    // trying to load the main OR while we were disposing of the tech\n\n    if (!playlistToExclude) {\n      this.error = error;\n      if (this.mediaSource.readyState !== 'open') {\n        this.trigger('error');\n      } else {\n        this.sourceUpdater_.endOfStream('network');\n      }\n      return;\n    }\n    playlistToExclude.playlistErrors_++;\n    const playlists = this.mainPlaylistLoader_.main.playlists;\n    const enabledPlaylists = playlists.filter(isEnabled);\n    const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded\n    // forever\n\n    if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {\n      videojs.log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');\n      this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay\n\n      return this.mainPlaylistLoader_.load(isFinalRendition);\n    }\n    if (isFinalRendition) {\n      // If we're content steering, try other pathways.\n      if (this.main().contentSteering) {\n        const pathway = this.pathwayAttribute_(playlistToExclude); // Ignore at least 1 steering manifest refresh.\n\n        const reIncludeDelay = this.contentSteeringController_.steeringManifest.ttl * 1000;\n        this.contentSteeringController_.excludePathway(pathway);\n        this.excludeThenChangePathway_();\n        setTimeout(() => {\n          this.contentSteeringController_.addAvailablePathway(pathway);\n        }, reIncludeDelay);\n        return;\n      } // Since we're on the final non-excluded playlist, and we're about to exclude\n      // it, instead of erring the player or retrying this playlist, clear out the current\n      // exclusion list. This allows other playlists to be attempted in case any have been\n      // fixed.\n\n      let reincluded = false;\n      playlists.forEach(playlist => {\n        // skip current playlist which is about to be excluded\n        if (playlist === playlistToExclude) {\n          return;\n        }\n        const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.\n\n        if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {\n          reincluded = true;\n          delete playlist.excludeUntil;\n        }\n      });\n      if (reincluded) {\n        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\n        // playlist. This is needed for users relying on the retryplaylist event to catch a\n        // case where the player might be stuck and looping through \"dead\" playlists.\n\n        this.tech_.trigger('retryplaylist');\n      }\n    } // Exclude this playlist\n\n    let excludeUntil;\n    if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {\n      excludeUntil = Infinity;\n    } else {\n      excludeUntil = Date.now() + playlistExclusionDuration * 1000;\n    }\n    playlistToExclude.excludeUntil = excludeUntil;\n    if (error.reason) {\n      playlistToExclude.lastExcludeReason_ = error.reason;\n    }\n    this.tech_.trigger('excludeplaylist');\n    this.tech_.trigger({\n      type: 'usage',\n      name: 'vhs-rendition-excluded'\n    }); // TODO: only load a new playlist if we're excluding the current playlist\n    // If this function was called with a playlist that's not the current active playlist\n    // (e.g., media().id !== playlistToExclude.id),\n    // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.\n\n    const nextPlaylist = this.selectPlaylist();\n    if (!nextPlaylist) {\n      this.error = 'Playback cannot continue. No available working or supported playlists.';\n      this.trigger('error');\n      return;\n    }\n    const logFn = error.internal ? this.logger_ : videojs.log.warn;\n    const errorMessage = error.message ? ' ' + error.message : '';\n    logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders\n\n    if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {\n      this.delegateLoaders_('audio', ['abort', 'pause']);\n    } // if subtitle group changed reset subtitle loaders\n\n    if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {\n      this.delegateLoaders_('subtitle', ['abort', 'pause']);\n    }\n    this.delegateLoaders_('main', ['abort', 'pause']);\n    const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;\n    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\n\n    return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);\n  }\n  /**\n   * Pause all segment/playlist loaders\n   */\n\n  pauseLoading() {\n    this.delegateLoaders_('all', ['abort', 'pause']);\n    this.stopABRTimer_();\n  }\n  /**\n   * Call a set of functions in order on playlist loaders, segment loaders,\n   * or both types of loaders.\n   *\n   * @param {string} filter\n   *        Filter loaders that should call fnNames using a string. Can be:\n   *        * all - run on all loaders\n   *        * audio - run on all audio loaders\n   *        * subtitle - run on all subtitle loaders\n   *        * main - run on the main loaders\n   *\n   * @param {Array|string} fnNames\n   *        A string or array of function names to call.\n   */\n\n  delegateLoaders_(filter, fnNames) {\n    const loaders = [];\n    const dontFilterPlaylist = filter === 'all';\n    if (dontFilterPlaylist || filter === 'main') {\n      loaders.push(this.mainPlaylistLoader_);\n    }\n    const mediaTypes = [];\n    if (dontFilterPlaylist || filter === 'audio') {\n      mediaTypes.push('AUDIO');\n    }\n    if (dontFilterPlaylist || filter === 'subtitle') {\n      mediaTypes.push('CLOSED-CAPTIONS');\n      mediaTypes.push('SUBTITLES');\n    }\n    mediaTypes.forEach(mediaType => {\n      const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;\n      if (loader) {\n        loaders.push(loader);\n      }\n    });\n    ['main', 'audio', 'subtitle'].forEach(name => {\n      const loader = this[`${name}SegmentLoader_`];\n      if (loader && (filter === name || filter === 'all')) {\n        loaders.push(loader);\n      }\n    });\n    loaders.forEach(loader => fnNames.forEach(fnName => {\n      if (typeof loader[fnName] === 'function') {\n        loader[fnName]();\n      }\n    }));\n  }\n  /**\n   * set the current time on all segment loaders\n   *\n   * @param {TimeRange} currentTime the current time to set\n   * @return {TimeRange} the current time\n   */\n\n  setCurrentTime(currentTime) {\n    const buffered = findRange(this.tech_.buffered(), currentTime);\n    if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {\n      // return immediately if the metadata is not ready yet\n      return 0;\n    } // it's clearly an edge-case but don't thrown an error if asked to\n    // seek within an empty playlist\n\n    if (!this.mainPlaylistLoader_.media().segments) {\n      return 0;\n    } // if the seek location is already buffered, continue buffering as usual\n\n    if (buffered && buffered.length) {\n      return currentTime;\n    } // cancel outstanding requests so we begin buffering at the new\n    // location\n\n    this.mainSegmentLoader_.pause();\n    this.mainSegmentLoader_.resetEverything();\n    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {\n      this.audioSegmentLoader_.pause();\n      this.audioSegmentLoader_.resetEverything();\n    }\n    if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {\n      this.subtitleSegmentLoader_.pause();\n      this.subtitleSegmentLoader_.resetEverything();\n    } // start segment loader loading in case they are paused\n\n    this.load();\n  }\n  /**\n   * get the current duration\n   *\n   * @return {TimeRange} the duration\n   */\n\n  duration() {\n    if (!this.mainPlaylistLoader_) {\n      return 0;\n    }\n    const media = this.mainPlaylistLoader_.media();\n    if (!media) {\n      // no playlists loaded yet, so can't determine a duration\n      return 0;\n    } // Don't rely on the media source for duration in the case of a live playlist since\n    // setting the native MediaSource's duration to infinity ends up with consequences to\n    // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.\n    //\n    // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,\n    // however, few browsers have support for setLiveSeekableRange()\n    // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange\n    //\n    // Until a time when the duration of the media source can be set to infinity, and a\n    // seekable range specified across browsers, just return Infinity.\n\n    if (!media.endList) {\n      return Infinity;\n    } // Since this is a VOD video, it is safe to rely on the media source's duration (if\n    // available). If it's not available, fall back to a playlist-calculated estimate.\n\n    if (this.mediaSource) {\n      return this.mediaSource.duration;\n    }\n    return Vhs$1.Playlist.duration(media);\n  }\n  /**\n   * check the seekable range\n   *\n   * @return {TimeRange} the seekable range\n   */\n\n  seekable() {\n    return this.seekable_;\n  }\n  getSeekableRange_(playlistLoader, mediaType) {\n    const media = playlistLoader.media();\n    if (!media) {\n      return null;\n    }\n    const mediaSequenceSync = this.syncController_.getMediaSequenceSync(mediaType);\n    if (mediaSequenceSync && mediaSequenceSync.isReliable) {\n      const start = mediaSequenceSync.start;\n      const end = mediaSequenceSync.end;\n      if (!isFinite(start) || !isFinite(end)) {\n        return null;\n      }\n      const liveEdgeDelay = Vhs$1.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main, media); // Make sure our seekable end is not less than the seekable start\n\n      const calculatedEnd = Math.max(start, end - liveEdgeDelay);\n      return createTimeRanges([[start, calculatedEnd]]);\n    }\n    const expired = this.syncController_.getExpiredTime(media, this.duration());\n    if (expired === null) {\n      return null;\n    }\n    const seekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main, media));\n    return seekable.length ? seekable : null;\n  }\n  computeFinalSeekable_(mainSeekable, audioSeekable) {\n    if (!audioSeekable) {\n      return mainSeekable;\n    }\n    const mainStart = mainSeekable.start(0);\n    const mainEnd = mainSeekable.end(0);\n    const audioStart = audioSeekable.start(0);\n    const audioEnd = audioSeekable.end(0);\n    if (audioStart > mainEnd || mainStart > audioEnd) {\n      // Seekables are far apart, rely on main\n      return mainSeekable;\n    } // Return the overlapping seekable range\n\n    return createTimeRanges([[Math.max(mainStart, audioStart), Math.min(mainEnd, audioEnd)]]);\n  }\n  onSyncInfoUpdate_() {\n    // TODO check for creation of both source buffers before updating seekable\n    //\n    // A fix was made to this function where a check for\n    // this.sourceUpdater_.hasCreatedSourceBuffers\n    // was added to ensure that both source buffers were created before seekable was\n    // updated. However, it originally had a bug where it was checking for a true and\n    // returning early instead of checking for false. Setting it to check for false to\n    // return early though created other issues. A call to play() would check for seekable\n    // end without verifying that a seekable range was present. In addition, even checking\n    // for that didn't solve some issues, as handleFirstPlay is sometimes worked around\n    // due to a media update calling load on the segment loaders, skipping a seek to live,\n    // thereby starting live streams at the beginning of the stream rather than at the end.\n    //\n    // This conditional should be fixed to wait for the creation of two source buffers at\n    // the same time as the other sections of code are fixed to properly seek to live and\n    // not throw an error due to checking for a seekable end when no seekable range exists.\n    //\n    // For now, fall back to the older behavior, with the understanding that the seekable\n    // range may not be completely correct, leading to a suboptimal initial live point.\n    if (!this.mainPlaylistLoader_) {\n      return;\n    }\n    const mainSeekable = this.getSeekableRange_(this.mainPlaylistLoader_, 'main');\n    if (!mainSeekable) {\n      return;\n    }\n    let audioSeekable;\n    if (this.mediaTypes_.AUDIO.activePlaylistLoader) {\n      audioSeekable = this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader, 'audio');\n      if (!audioSeekable) {\n        return;\n      }\n    }\n    const oldSeekable = this.seekable_;\n    this.seekable_ = this.computeFinalSeekable_(mainSeekable, audioSeekable);\n    if (!this.seekable_) {\n      return;\n    }\n    if (oldSeekable && oldSeekable.length && this.seekable_.length) {\n      if (oldSeekable.start(0) === this.seekable_.start(0) && oldSeekable.end(0) === this.seekable_.end(0)) {\n        // Seekable range hasn't changed\n        return;\n      }\n    }\n    this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);\n    const metadata = {\n      seekableRanges: this.seekable_\n    };\n    this.trigger({\n      type: 'seekablerangeschanged',\n      metadata\n    });\n    this.tech_.trigger('seekablechanged');\n  }\n  /**\n   * Update the player duration\n   */\n\n  updateDuration(isLive) {\n    if (this.updateDuration_) {\n      this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);\n      this.updateDuration_ = null;\n    }\n    if (this.mediaSource.readyState !== 'open') {\n      this.updateDuration_ = this.updateDuration.bind(this, isLive);\n      this.mediaSource.addEventListener('sourceopen', this.updateDuration_);\n      return;\n    }\n    if (isLive) {\n      const seekable = this.seekable();\n      if (!seekable.length) {\n        return;\n      } // Even in the case of a live playlist, the native MediaSource's duration should not\n      // be set to Infinity (even though this would be expected for a live playlist), since\n      // setting the native MediaSource's duration to infinity ends up with consequences to\n      // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.\n      //\n      // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,\n      // however, few browsers have support for setLiveSeekableRange()\n      // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange\n      //\n      // Until a time when the duration of the media source can be set to infinity, and a\n      // seekable range specified across browsers, the duration should be greater than or\n      // equal to the last possible seekable value.\n      // MediaSource duration starts as NaN\n      // It is possible (and probable) that this case will never be reached for many\n      // sources, since the MediaSource reports duration as the highest value without\n      // accounting for timestamp offset. For example, if the timestamp offset is -100 and\n      // we buffered times 0 to 100 with real times of 100 to 200, even though current\n      // time will be between 0 and 100, the native media source may report the duration\n      // as 200. However, since we report duration separate from the media source (as\n      // Infinity), and as long as the native media source duration value is greater than\n      // our reported seekable range, seeks will work as expected. The large number as\n      // duration for live is actually a strategy used by some players to work around the\n      // issue of live seekable ranges cited above.\n\n      if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {\n        this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));\n      }\n      return;\n    }\n    const buffered = this.tech_.buffered();\n    let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());\n    if (buffered.length > 0) {\n      duration = Math.max(duration, buffered.end(buffered.length - 1));\n    }\n    if (this.mediaSource.duration !== duration) {\n      this.sourceUpdater_.setDuration(duration);\n    }\n  }\n  /**\n   * dispose of the PlaylistController and everything\n   * that it controls\n   */\n\n  dispose() {\n    this.trigger('dispose');\n    this.decrypter_.terminate();\n    this.mainPlaylistLoader_.dispose();\n    this.mainSegmentLoader_.dispose();\n    this.contentSteeringController_.dispose();\n    this.keyStatusMap_.clear();\n    if (this.loadOnPlay_) {\n      this.tech_.off('play', this.loadOnPlay_);\n    }\n    ['AUDIO', 'SUBTITLES'].forEach(type => {\n      const groups = this.mediaTypes_[type].groups;\n      for (const id in groups) {\n        groups[id].forEach(group => {\n          if (group.playlistLoader) {\n            group.playlistLoader.dispose();\n          }\n        });\n      }\n    });\n    this.audioSegmentLoader_.dispose();\n    this.subtitleSegmentLoader_.dispose();\n    this.sourceUpdater_.dispose();\n    this.timelineChangeController_.dispose();\n    this.stopABRTimer_();\n    if (this.updateDuration_) {\n      this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);\n    }\n    this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player\n\n    this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);\n    this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);\n    this.off();\n  }\n  /**\n   * return the main playlist object if we have one\n   *\n   * @return {Object} the main playlist object that we parsed\n   */\n\n  main() {\n    return this.mainPlaylistLoader_.main;\n  }\n  /**\n   * return the currently selected playlist\n   *\n   * @return {Object} the currently selected playlist object that we parsed\n   */\n\n  media() {\n    // playlist loader will not return media if it has not been fully loaded\n    return this.mainPlaylistLoader_.media() || this.initialMedia_;\n  }\n  areMediaTypesKnown_() {\n    const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;\n    const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info\n    // otherwise check on the segment loader.\n\n    const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs\n\n    if (!hasMainMediaInfo || !hasAudioMediaInfo) {\n      return false;\n    }\n    return true;\n  } // find from and to for codec switch event\n\n  getCodecsOrExclude_() {\n    const media = {\n      main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},\n      audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}\n    };\n    const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set \"main\" media equal to video\n\n    media.video = media.main;\n    const playlistCodecs = codecsForPlaylist(this.main(), playlist);\n    const codecs = {};\n    const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;\n    if (media.main.hasVideo) {\n      codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;\n    }\n    if (media.main.isMuxed) {\n      codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;\n    }\n    if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {\n      codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct \"supports\" function below\n\n      media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;\n    } // no codecs, no playback.\n\n    if (!codecs.audio && !codecs.video) {\n      this.excludePlaylist({\n        playlistToExclude: playlist,\n        error: {\n          message: 'Could not determine codecs for playlist.'\n        },\n        playlistExclusionDuration: Infinity\n      });\n      return;\n    } // fmp4 relies on browser support, while ts relies on muxer support\n\n    const supportFunction = (isFmp4, codec) => isFmp4 ? browserSupportsCodec(codec, this.usingManagedMediaSource_) : muxerSupportsCodec(codec);\n    const unsupportedCodecs = {};\n    let unsupportedAudio;\n    ['video', 'audio'].forEach(function (type) {\n      if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {\n        const supporter = media[type].isFmp4 ? 'browser' : 'muxer';\n        unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];\n        unsupportedCodecs[supporter].push(codecs[type]);\n        if (type === 'audio') {\n          unsupportedAudio = supporter;\n        }\n      }\n    });\n    if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {\n      const audioGroup = playlist.attributes.AUDIO;\n      this.main().playlists.forEach(variant => {\n        const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;\n        if (variantAudioGroup === audioGroup && variant !== playlist) {\n          variant.excludeUntil = Infinity;\n        }\n      });\n      this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): \"${codecs.audio}\"`);\n    } // if we have any unsupported codecs exclude this playlist.\n\n    if (Object.keys(unsupportedCodecs).length) {\n      const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {\n        if (acc) {\n          acc += ', ';\n        }\n        acc += `${supporter} does not support codec(s): \"${unsupportedCodecs[supporter].join(',')}\"`;\n        return acc;\n      }, '') + '.';\n      this.excludePlaylist({\n        playlistToExclude: playlist,\n        error: {\n          internal: true,\n          message\n        },\n        playlistExclusionDuration: Infinity\n      });\n      return;\n    } // check if codec switching is happening\n\n    if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {\n      const switchMessages = [];\n      ['video', 'audio'].forEach(type => {\n        const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;\n        const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;\n        if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {\n          switchMessages.push(`\"${this.sourceUpdater_.codecs[type]}\" -> \"${codecs[type]}\"`);\n        }\n      });\n      if (switchMessages.length) {\n        this.excludePlaylist({\n          playlistToExclude: playlist,\n          error: {\n            message: `Codec switching not supported: ${switchMessages.join(', ')}.`,\n            internal: true\n          },\n          playlistExclusionDuration: Infinity\n        });\n        return;\n      }\n    } // TODO: when using the muxer shouldn't we just return\n    // the codecs that the muxer outputs?\n\n    return codecs;\n  }\n  /**\n   * Create source buffers and exlude any incompatible renditions.\n   *\n   * @private\n   */\n\n  tryToCreateSourceBuffers_() {\n    // media source is not ready yet or sourceBuffers are already\n    // created.\n    if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {\n      return;\n    }\n    if (!this.areMediaTypesKnown_()) {\n      return;\n    }\n    const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded\n\n    if (!codecs) {\n      return;\n    }\n    this.sourceUpdater_.createSourceBuffers(codecs);\n    const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');\n    this.excludeIncompatibleVariants_(codecString);\n  }\n  /**\n   * Excludes playlists with codecs that are unsupported by the muxer and browser.\n   */\n\n  excludeUnsupportedVariants_() {\n    const playlists = this.main().playlists;\n    const ids = []; // TODO: why don't we have a property to loop through all\n    // playlist? Why did we ever mix indexes and keys?\n\n    Object.keys(playlists).forEach(key => {\n      const variant = playlists[key]; // check if we already processed this playlist.\n\n      if (ids.indexOf(variant.id) !== -1) {\n        return;\n      }\n      ids.push(variant.id);\n      const codecs = codecsForPlaylist(this.main, variant);\n      const unsupported = [];\n      if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio, this.usingManagedMediaSource_)) {\n        unsupported.push(`audio codec ${codecs.audio}`);\n      }\n      if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video, this.usingManagedMediaSource_)) {\n        unsupported.push(`video codec ${codecs.video}`);\n      }\n      if (codecs.text && codecs.text === 'stpp.ttml.im1t') {\n        unsupported.push(`text codec ${codecs.text}`);\n      }\n      if (unsupported.length) {\n        variant.excludeUntil = Infinity;\n        this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);\n      }\n    });\n  }\n  /**\n   * Exclude playlists that are known to be codec or\n   * stream-incompatible with the SourceBuffer configuration. For\n   * instance, Media Source Extensions would cause the video element to\n   * stall waiting for video data if you switched from a variant with\n   * video and audio to an audio-only one.\n   *\n   * @param {Object} media a media playlist compatible with the current\n   * set of SourceBuffers. Variants in the current main playlist that\n   * do not appear to have compatible codec or stream configurations\n   * will be excluded from the default playlist selection algorithm\n   * indefinitely.\n   * @private\n   */\n\n  excludeIncompatibleVariants_(codecString) {\n    const ids = [];\n    const playlists = this.main().playlists;\n    const codecs = unwrapCodecList(parseCodecs(codecString));\n    const codecCount_ = codecCount(codecs);\n    const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;\n    const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;\n    Object.keys(playlists).forEach(key => {\n      const variant = playlists[key]; // check if we already processed this playlist.\n      // or it if it is already excluded forever.\n\n      if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {\n        return;\n      }\n      ids.push(variant.id);\n      const exclusionReasons = []; // get codecs from the playlist for this variant\n\n      const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);\n      const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this\n      // variant is incompatible. Wait for mux.js to probe\n\n      if (!variantCodecs.audio && !variantCodecs.video) {\n        return;\n      } // TODO: we can support this by removing the\n      // old media source and creating a new one, but it will take some work.\n      // The number of streams cannot change\n\n      if (variantCodecCount !== codecCount_) {\n        exclusionReasons.push(`codec count \"${variantCodecCount}\" !== \"${codecCount_}\"`);\n      } // only exclude playlists by codec change, if codecs cannot switch\n      // during playback.\n\n      if (!this.sourceUpdater_.canChangeType()) {\n        const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;\n        const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change\n\n        if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {\n          exclusionReasons.push(`video codec \"${variantVideoDetails.type}\" !== \"${videoDetails.type}\"`);\n        } // the audio codec cannot change\n\n        if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {\n          exclusionReasons.push(`audio codec \"${variantAudioDetails.type}\" !== \"${audioDetails.type}\"`);\n        }\n      }\n      if (exclusionReasons.length) {\n        variant.excludeUntil = Infinity;\n        this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);\n      }\n    });\n  }\n  updateAdCues_(media) {\n    let offset = 0;\n    const seekable = this.seekable();\n    if (seekable.length) {\n      offset = seekable.start(0);\n    }\n    updateAdCues(media, this.cueTagsTrack_, offset);\n  }\n  /**\n   * Calculates the desired forward buffer length based on current time\n   *\n   * @return {number} Desired forward buffer length in seconds\n   */\n\n  goalBufferLength() {\n    const currentTime = this.tech_.currentTime();\n    const initial = Config.GOAL_BUFFER_LENGTH;\n    const rate = Config.GOAL_BUFFER_LENGTH_RATE;\n    const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);\n    return Math.min(initial + currentTime * rate, max);\n  }\n  /**\n   * Calculates the desired buffer low water line based on current time\n   *\n   * @return {number} Desired buffer low water line in seconds\n   */\n\n  bufferLowWaterLine() {\n    const currentTime = this.tech_.currentTime();\n    const initial = Config.BUFFER_LOW_WATER_LINE;\n    const rate = Config.BUFFER_LOW_WATER_LINE_RATE;\n    const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);\n    const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);\n    return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);\n  }\n  bufferHighWaterLine() {\n    return Config.BUFFER_HIGH_WATER_LINE;\n  }\n  addDateRangesToTextTrack_(dateRanges) {\n    createMetadataTrackIfNotExists(this.inbandTextTracks_, 'com.apple.streaming', this.tech_);\n    addDateRangeMetadata({\n      inbandTextTracks: this.inbandTextTracks_,\n      dateRanges\n    });\n  }\n  addMetadataToTextTrack(dispatchType, metadataArray, videoDuration) {\n    const timestampOffset = this.sourceUpdater_.videoBuffer ? this.sourceUpdater_.videoTimestampOffset() : this.sourceUpdater_.audioTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed\n    // audio/video source with a metadata track, and an alt audio with a metadata track.\n    // However, this probably won't happen, and if it does it can be handled then.\n\n    createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.tech_);\n    addMetadata({\n      inbandTextTracks: this.inbandTextTracks_,\n      metadataArray,\n      timestampOffset,\n      videoDuration\n    });\n  }\n  /**\n   * Utility for getting the pathway or service location from an HLS or DASH playlist.\n   *\n   * @param {Object} playlist for getting pathway from.\n   * @return the pathway attribute of a playlist\n   */\n\n  pathwayAttribute_(playlist) {\n    return playlist.attributes['PATHWAY-ID'] || playlist.attributes.serviceLocation;\n  }\n  /**\n   * Initialize available pathways and apply the tag properties.\n   */\n\n  initContentSteeringController_() {\n    const main = this.main();\n    if (!main.contentSteering) {\n      return;\n    }\n    for (const playlist of main.playlists) {\n      this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(playlist));\n    }\n    this.contentSteeringController_.assignTagProperties(main.uri, main.contentSteering); // request the steering manifest immediately if queryBeforeStart is set.\n\n    if (this.contentSteeringController_.queryBeforeStart) {\n      // When queryBeforeStart is true, initial request should omit steering parameters.\n      this.contentSteeringController_.requestSteeringManifest(true);\n      return;\n    } // otherwise start content steering after playback starts\n\n    this.tech_.one('canplay', () => {\n      this.contentSteeringController_.requestSteeringManifest();\n    });\n  }\n  /**\n   * Reset the content steering controller and re-init.\n   */\n\n  resetContentSteeringController_() {\n    this.contentSteeringController_.clearAvailablePathways();\n    this.contentSteeringController_.dispose();\n    this.initContentSteeringController_();\n  }\n  /**\n   * Attaches the listeners for content steering.\n   */\n\n  attachContentSteeringListeners_() {\n    this.contentSteeringController_.on('content-steering', this.excludeThenChangePathway_.bind(this));\n    const contentSteeringEvents = ['contentsteeringloadstart', 'contentsteeringloadcomplete', 'contentsteeringparsed'];\n    contentSteeringEvents.forEach(eventName => {\n      this.contentSteeringController_.on(eventName, metadata => {\n        this.trigger(_extends({}, metadata));\n      });\n    });\n    if (this.sourceType_ === 'dash') {\n      this.mainPlaylistLoader_.on('loadedplaylist', () => {\n        const main = this.main(); // check if steering tag or pathways changed.\n\n        const didDashTagChange = this.contentSteeringController_.didDASHTagChange(main.uri, main.contentSteering);\n        const didPathwaysChange = () => {\n          const availablePathways = this.contentSteeringController_.getAvailablePathways();\n          const newPathways = [];\n          for (const playlist of main.playlists) {\n            const serviceLocation = playlist.attributes.serviceLocation;\n            if (serviceLocation) {\n              newPathways.push(serviceLocation);\n              if (!availablePathways.has(serviceLocation)) {\n                return true;\n              }\n            }\n          } // If we have no new serviceLocations and previously had availablePathways\n\n          if (!newPathways.length && availablePathways.size) {\n            return true;\n          }\n          return false;\n        };\n        if (didDashTagChange || didPathwaysChange()) {\n          this.resetContentSteeringController_();\n        }\n      });\n    }\n  }\n  /**\n   * Simple exclude and change playlist logic for content steering.\n   */\n\n  excludeThenChangePathway_() {\n    const currentPathway = this.contentSteeringController_.getPathway();\n    if (!currentPathway) {\n      return;\n    }\n    this.handlePathwayClones_();\n    const main = this.main();\n    const playlists = main.playlists;\n    const ids = new Set();\n    let didEnablePlaylists = false;\n    Object.keys(playlists).forEach(key => {\n      const variant = playlists[key];\n      const pathwayId = this.pathwayAttribute_(variant);\n      const differentPathwayId = pathwayId && currentPathway !== pathwayId;\n      const steeringExclusion = variant.excludeUntil === Infinity && variant.lastExcludeReason_ === 'content-steering';\n      if (steeringExclusion && !differentPathwayId) {\n        delete variant.excludeUntil;\n        delete variant.lastExcludeReason_;\n        didEnablePlaylists = true;\n      }\n      const noExcludeUntil = !variant.excludeUntil && variant.excludeUntil !== Infinity;\n      const shouldExclude = !ids.has(variant.id) && differentPathwayId && noExcludeUntil;\n      if (!shouldExclude) {\n        return;\n      }\n      ids.add(variant.id);\n      variant.excludeUntil = Infinity;\n      variant.lastExcludeReason_ = 'content-steering'; // TODO: kind of spammy, maybe move this.\n\n      this.logger_(`excluding ${variant.id} for ${variant.lastExcludeReason_}`);\n    });\n    if (this.contentSteeringController_.manifestType_ === 'DASH') {\n      Object.keys(this.mediaTypes_).forEach(key => {\n        const type = this.mediaTypes_[key];\n        if (type.activePlaylistLoader) {\n          const currentPlaylist = type.activePlaylistLoader.media_; // Check if the current media playlist matches the current CDN\n\n          if (currentPlaylist && currentPlaylist.attributes.serviceLocation !== currentPathway) {\n            didEnablePlaylists = true;\n          }\n        }\n      });\n    }\n    if (didEnablePlaylists) {\n      this.changeSegmentPathway_();\n    }\n  }\n  /**\n   * Add, update, or delete playlists and media groups for\n   * the pathway clones for HLS Content Steering.\n   *\n   * See https://datatracker.ietf.org/doc/draft-pantos-hls-rfc8216bis/\n   *\n   * NOTE: Pathway cloning does not currently support the `PER_VARIANT_URIS` and\n   * `PER_RENDITION_URIS` as we do not handle `STABLE-VARIANT-ID` or\n   * `STABLE-RENDITION-ID` values.\n   */\n\n  handlePathwayClones_() {\n    const main = this.main();\n    const playlists = main.playlists;\n    const currentPathwayClones = this.contentSteeringController_.currentPathwayClones;\n    const nextPathwayClones = this.contentSteeringController_.nextPathwayClones;\n    const hasClones = currentPathwayClones && currentPathwayClones.size || nextPathwayClones && nextPathwayClones.size;\n    if (!hasClones) {\n      return;\n    }\n    for (const [id, clone] of currentPathwayClones.entries()) {\n      const newClone = nextPathwayClones.get(id); // Delete the old pathway clone.\n\n      if (!newClone) {\n        this.mainPlaylistLoader_.updateOrDeleteClone(clone);\n        this.contentSteeringController_.excludePathway(id);\n      }\n    }\n    for (const [id, clone] of nextPathwayClones.entries()) {\n      const oldClone = currentPathwayClones.get(id); // Create a new pathway if it is a new pathway clone object.\n\n      if (!oldClone) {\n        const playlistsToClone = playlists.filter(p => {\n          return p.attributes['PATHWAY-ID'] === clone['BASE-ID'];\n        });\n        playlistsToClone.forEach(p => {\n          this.mainPlaylistLoader_.addClonePathway(clone, p);\n        });\n        this.contentSteeringController_.addAvailablePathway(id);\n        continue;\n      } // There have not been changes to the pathway clone object, so skip.\n\n      if (this.equalPathwayClones_(oldClone, clone)) {\n        continue;\n      } // Update a preexisting cloned pathway.\n      // True is set for the update flag.\n\n      this.mainPlaylistLoader_.updateOrDeleteClone(clone, true);\n      this.contentSteeringController_.addAvailablePathway(id);\n    } // Deep copy contents of next to current pathways.\n\n    this.contentSteeringController_.currentPathwayClones = new Map(JSON.parse(JSON.stringify([...nextPathwayClones])));\n  }\n  /**\n   * Determines whether two pathway clone objects are equivalent.\n   *\n   * @param {Object} a The first pathway clone object.\n   * @param {Object} b The second pathway clone object.\n   * @return {boolean} True if the pathway clone objects are equal, false otherwise.\n   */\n\n  equalPathwayClones_(a, b) {\n    if (a['BASE-ID'] !== b['BASE-ID'] || a.ID !== b.ID || a['URI-REPLACEMENT'].HOST !== b['URI-REPLACEMENT'].HOST) {\n      return false;\n    }\n    const aParams = a['URI-REPLACEMENT'].PARAMS;\n    const bParams = b['URI-REPLACEMENT'].PARAMS; // We need to iterate through both lists of params because one could be\n    // missing a parameter that the other has.\n\n    for (const p in aParams) {\n      if (aParams[p] !== bParams[p]) {\n        return false;\n      }\n    }\n    for (const p in bParams) {\n      if (aParams[p] !== bParams[p]) {\n        return false;\n      }\n    }\n    return true;\n  }\n  /**\n   * Changes the current playlists for audio, video and subtitles after a new pathway\n   * is chosen from content steering.\n   */\n\n  changeSegmentPathway_() {\n    const nextPlaylist = this.selectPlaylist();\n    this.pauseLoading(); // Switch audio and text track playlists if necessary in DASH\n\n    if (this.contentSteeringController_.manifestType_ === 'DASH') {\n      this.switchMediaForDASHContentSteering_();\n    }\n    this.switchMedia_(nextPlaylist, 'content-steering');\n  }\n  /**\n   * Iterates through playlists and check their keyId set and compare with the\n   * keyStatusMap, only enable playlists that have a usable key. If the playlist\n   * has no keyId leave it enabled by default.\n   */\n\n  excludeNonUsablePlaylistsByKeyId_() {\n    if (!this.mainPlaylistLoader_ || !this.mainPlaylistLoader_.main) {\n      return;\n    }\n    let nonUsableKeyStatusCount = 0;\n    const NON_USABLE = 'non-usable';\n    this.mainPlaylistLoader_.main.playlists.forEach(playlist => {\n      const keyIdSet = this.mainPlaylistLoader_.getKeyIdSet(playlist); // If the playlist doesn't have keyIDs lets not exclude it.\n\n      if (!keyIdSet || !keyIdSet.size) {\n        return;\n      }\n      keyIdSet.forEach(key => {\n        const USABLE = 'usable';\n        const hasUsableKeyStatus = this.keyStatusMap_.has(key) && this.keyStatusMap_.get(key) === USABLE;\n        const nonUsableExclusion = playlist.lastExcludeReason_ === NON_USABLE && playlist.excludeUntil === Infinity;\n        if (!hasUsableKeyStatus) {\n          // Only exclude playlists that haven't already been excluded as non-usable.\n          if (playlist.excludeUntil !== Infinity && playlist.lastExcludeReason_ !== NON_USABLE) {\n            playlist.excludeUntil = Infinity;\n            playlist.lastExcludeReason_ = NON_USABLE;\n            this.logger_(`excluding playlist ${playlist.id} because the key ID ${key} doesn't exist in the keyStatusMap or is not ${USABLE}`);\n          } // count all nonUsableKeyStatus\n\n          nonUsableKeyStatusCount++;\n        } else if (hasUsableKeyStatus && nonUsableExclusion) {\n          delete playlist.excludeUntil;\n          delete playlist.lastExcludeReason_;\n          this.logger_(`enabling playlist ${playlist.id} because key ID ${key} is ${USABLE}`);\n        }\n      });\n    }); // If for whatever reason every playlist has a non usable key status. Lets try re-including the SD renditions as a failsafe.\n\n    if (nonUsableKeyStatusCount >= this.mainPlaylistLoader_.main.playlists.length) {\n      this.mainPlaylistLoader_.main.playlists.forEach(playlist => {\n        const isNonHD = playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height < 720;\n        const excludedForNonUsableKey = playlist.excludeUntil === Infinity && playlist.lastExcludeReason_ === NON_USABLE;\n        if (isNonHD && excludedForNonUsableKey) {\n          // Only delete the excludeUntil so we don't try and re-exclude these playlists.\n          delete playlist.excludeUntil;\n          videojs.log.warn(`enabling non-HD playlist ${playlist.id} because all playlists were excluded due to ${NON_USABLE} key IDs`);\n        }\n      });\n    }\n  }\n  /**\n   * Adds a keystatus to the keystatus map, tries to convert to string if necessary.\n   *\n   * @param {any} keyId the keyId to add a status for\n   * @param {string} status the status of the keyId\n   */\n\n  addKeyStatus_(keyId, status) {\n    const isString = typeof keyId === 'string';\n    const keyIdHexString = isString ? keyId : bufferToHexString(keyId);\n    const formattedKeyIdString = keyIdHexString.slice(0, 32).toLowerCase();\n    this.logger_(`KeyStatus '${status}' with key ID ${formattedKeyIdString} added to the keyStatusMap`);\n    this.keyStatusMap_.set(formattedKeyIdString, status);\n  }\n  /**\n   * Utility function for adding key status to the keyStatusMap and filtering usable encrypted playlists.\n   *\n   * @param {any} keyId the keyId from the keystatuschange event\n   * @param {string} status the key status string\n   */\n\n  updatePlaylistByKeyStatus(keyId, status) {\n    this.addKeyStatus_(keyId, status);\n    if (!this.waitingForFastQualityPlaylistReceived_) {\n      this.excludeNonUsableThenChangePlaylist_();\n    } // Listen to loadedplaylist with a single listener and check for new contentProtection elements when a playlist is updated.\n\n    this.mainPlaylistLoader_.off('loadedplaylist', this.excludeNonUsableThenChangePlaylist_.bind(this));\n    this.mainPlaylistLoader_.on('loadedplaylist', this.excludeNonUsableThenChangePlaylist_.bind(this));\n  }\n  excludeNonUsableThenChangePlaylist_() {\n    this.excludeNonUsablePlaylistsByKeyId_();\n    this.fastQualityChange_();\n  }\n}\n\n/**\n * Returns a function that acts as the Enable/disable playlist function.\n *\n * @param {PlaylistLoader} loader - The main playlist loader\n * @param {string} playlistID - id of the playlist\n * @param {Function} changePlaylistFn - A function to be called after a\n * playlist's enabled-state has been changed. Will NOT be called if a\n * playlist's enabled-state is unchanged\n * @param {boolean=} enable - Value to set the playlist enabled-state to\n * or if undefined returns the current enabled-state for the playlist\n * @return {Function} Function for setting/getting enabled\n */\n\nconst enableFunction = (loader, playlistID, changePlaylistFn) => enable => {\n  const playlist = loader.main.playlists[playlistID];\n  const incompatible = isIncompatible(playlist);\n  const currentlyEnabled = isEnabled(playlist);\n  if (typeof enable === 'undefined') {\n    return currentlyEnabled;\n  }\n  if (enable) {\n    delete playlist.disabled;\n  } else {\n    playlist.disabled = true;\n  }\n  const metadata = {\n    renditionInfo: {\n      id: playlistID,\n      bandwidth: playlist.attributes.BANDWIDTH,\n      resolution: playlist.attributes.RESOLUTION,\n      codecs: playlist.attributes.CODECS\n    },\n    cause: 'fast-quality'\n  };\n  if (enable !== currentlyEnabled && !incompatible) {\n    // Ensure the outside world knows about our changes\n    if (enable) {\n      // call fast quality change only when the playlist is enabled\n      changePlaylistFn(playlist);\n      loader.trigger({\n        type: 'renditionenabled',\n        metadata\n      });\n    } else {\n      loader.trigger({\n        type: 'renditiondisabled',\n        metadata\n      });\n    }\n  }\n  return enable;\n};\n/**\n * The representation object encapsulates the publicly visible information\n * in a media playlist along with a setter/getter-type function (enabled)\n * for changing the enabled-state of a particular playlist entry\n *\n * @class Representation\n */\n\nclass Representation {\n  constructor(vhsHandler, playlist, id) {\n    const {\n      playlistController_: pc\n    } = vhsHandler;\n    const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional\n\n    if (playlist.attributes) {\n      const resolution = playlist.attributes.RESOLUTION;\n      this.width = resolution && resolution.width;\n      this.height = resolution && resolution.height;\n      this.bandwidth = playlist.attributes.BANDWIDTH;\n      this.frameRate = playlist.attributes['FRAME-RATE'];\n    }\n    this.codecs = codecsForPlaylist(pc.main(), playlist);\n    this.playlist = playlist; // The id is simply the ordinality of the media playlist\n    // within the main playlist\n\n    this.id = id; // Partially-apply the enableFunction to create a playlist-\n    // specific variant\n\n    this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);\n  }\n}\n/**\n * A mixin function that adds the `representations` api to an instance\n * of the VhsHandler class\n *\n * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the\n * representation API into\n */\n\nconst renditionSelectionMixin = function (vhsHandler) {\n  // Add a single API-specific function to the VhsHandler instance\n  vhsHandler.representations = () => {\n    const main = vhsHandler.playlistController_.main();\n    const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;\n    if (!playlists) {\n      return [];\n    }\n    return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));\n  };\n};\n\n/**\n * @file playback-watcher.js\n *\n * Playback starts, and now my watch begins. It shall not end until my death. I shall\n * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns\n * and win no glory. I shall live and die at my post. I am the corrector of the underflow.\n * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge\n * my life and honor to the Playback Watch, for this Player and all the Players to come.\n */\n\nconst timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];\n/**\n * @class PlaybackWatcher\n */\n\nclass PlaybackWatcher extends videojs.EventTarget {\n  /**\n   * Represents an PlaybackWatcher object.\n   *\n   * @class\n   * @param {Object} options an object that includes the tech and settings\n   */\n  constructor(options) {\n    super();\n    this.playlistController_ = options.playlistController;\n    this.tech_ = options.tech;\n    this.seekable = options.seekable;\n    this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;\n    this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;\n    this.media = options.media;\n    this.playedRanges_ = [];\n    this.consecutiveUpdates = 0;\n    this.lastRecordedTime = null;\n    this.checkCurrentTimeTimeout_ = null;\n    this.logger_ = logger('PlaybackWatcher');\n    this.logger_('initialize');\n    const playHandler = () => this.monitorCurrentTime_();\n    const canPlayHandler = () => this.monitorCurrentTime_();\n    const waitingHandler = () => this.techWaiting_();\n    const cancelTimerHandler = () => this.resetTimeUpdate_();\n    const pc = this.playlistController_;\n    const loaderTypes = ['main', 'subtitle', 'audio'];\n    const loaderChecks = {};\n    loaderTypes.forEach(type => {\n      loaderChecks[type] = {\n        reset: () => this.resetSegmentDownloads_(type),\n        updateend: () => this.checkSegmentDownloads_(type)\n      };\n      pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer\n      // isn't changing we want to reset. We cannot assume that the new rendition\n      // will also be stalled, until after new appends.\n\n      pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.\n      // This prevents one segment playlists (single vtt or single segment content)\n      // from being detected as stalling. As the buffer will not change in those cases, since\n      // the buffer is the entire video duration.\n\n      this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);\n    });\n    /**\n     * We check if a seek was into a gap through the following steps:\n     * 1. We get a seeking event and we do not get a seeked event. This means that\n     *    a seek was attempted but not completed.\n     * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already\n     *    removed everything from our buffer and appended a segment, and should be ready\n     *    to check for gaps.\n     */\n\n    const setSeekingHandlers = fn => {\n      ['main', 'audio'].forEach(type => {\n        pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);\n      });\n    };\n    this.seekingAppendCheck_ = () => {\n      if (this.fixesBadSeeks_()) {\n        this.consecutiveUpdates = 0;\n        this.lastRecordedTime = this.tech_.currentTime();\n        setSeekingHandlers('off');\n      }\n    };\n    this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');\n    this.watchForBadSeeking_ = () => {\n      this.clearSeekingAppendCheck_();\n      setSeekingHandlers('on');\n    };\n    this.tech_.on('seeked', this.clearSeekingAppendCheck_);\n    this.tech_.on('seeking', this.watchForBadSeeking_);\n    this.tech_.on('waiting', waitingHandler);\n    this.tech_.on(timerCancelEvents, cancelTimerHandler);\n    this.tech_.on('canplay', canPlayHandler);\n    /*\n      An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case\n      is surfaced in one of two ways:\n       1)  The `waiting` event is fired before the player has buffered content, making it impossible\n          to find or skip the gap. The `waiting` event is followed by a `play` event. On first play\n          we can check if playback is stalled due to a gap, and skip the gap if necessary.\n      2)  A source with a gap at the beginning of the stream is loaded programatically while the player\n          is in a playing state. To catch this case, it's important that our one-time play listener is setup\n          even if the player is in a playing state\n    */\n\n    this.tech_.one('play', playHandler); // Define the dispose function to clean up our events\n\n    this.dispose = () => {\n      this.clearSeekingAppendCheck_();\n      this.logger_('dispose');\n      this.tech_.off('waiting', waitingHandler);\n      this.tech_.off(timerCancelEvents, cancelTimerHandler);\n      this.tech_.off('canplay', canPlayHandler);\n      this.tech_.off('play', playHandler);\n      this.tech_.off('seeking', this.watchForBadSeeking_);\n      this.tech_.off('seeked', this.clearSeekingAppendCheck_);\n      loaderTypes.forEach(type => {\n        pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);\n        pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);\n        this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);\n      });\n      if (this.checkCurrentTimeTimeout_) {\n        window$1.clearTimeout(this.checkCurrentTimeTimeout_);\n      }\n      this.resetTimeUpdate_();\n    };\n  }\n  /**\n   * Periodically check current time to see if playback stopped\n   *\n   * @private\n   */\n\n  monitorCurrentTime_() {\n    this.checkCurrentTime_();\n    if (this.checkCurrentTimeTimeout_) {\n      window$1.clearTimeout(this.checkCurrentTimeTimeout_);\n    } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15\n\n    this.checkCurrentTimeTimeout_ = window$1.setTimeout(this.monitorCurrentTime_.bind(this), 250);\n  }\n  /**\n   * Reset stalled download stats for a specific type of loader\n   *\n   * @param {string} type\n   *        The segment loader type to check.\n   *\n   * @listens SegmentLoader#playlistupdate\n   * @listens Tech#seeking\n   * @listens Tech#seeked\n   */\n\n  resetSegmentDownloads_(type) {\n    const loader = this.playlistController_[`${type}SegmentLoader_`];\n    if (this[`${type}StalledDownloads_`] > 0) {\n      this.logger_(`resetting possible stalled download count for ${type} loader`);\n    }\n    this[`${type}StalledDownloads_`] = 0;\n    this[`${type}Buffered_`] = loader.buffered_();\n  }\n  /**\n   * Checks on every segment `appendsdone` to see\n   * if segment appends are making progress. If they are not\n   * and we are still downloading bytes. We exclude the playlist.\n   *\n   * @param {string} type\n   *        The segment loader type to check.\n   *\n   * @listens SegmentLoader#appendsdone\n   */\n\n  checkSegmentDownloads_(type) {\n    const pc = this.playlistController_;\n    const loader = pc[`${type}SegmentLoader_`];\n    const buffered = loader.buffered_();\n    const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);\n    this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or\n    // the buffered value for this loader changed\n    // appends are working\n\n    if (isBufferedDifferent) {\n      const metadata = {\n        bufferedRanges: buffered\n      };\n      pc.trigger({\n        type: 'bufferedrangeschanged',\n        metadata\n      });\n      this.resetSegmentDownloads_(type);\n      return;\n    }\n    this[`${type}StalledDownloads_`]++;\n    this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {\n      playlistId: loader.playlist_ && loader.playlist_.id,\n      buffered: timeRangesToArray(buffered)\n    }); // after 10 possibly stalled appends with no reset, exclude\n\n    if (this[`${type}StalledDownloads_`] < 10) {\n      return;\n    }\n    this.logger_(`${type} loader stalled download exclusion`);\n    this.resetSegmentDownloads_(type);\n    this.tech_.trigger({\n      type: 'usage',\n      name: `vhs-${type}-download-exclusion`\n    });\n    if (type === 'subtitle') {\n      return;\n    } // TODO: should we exclude audio tracks rather than main tracks\n    // when type is audio?\n\n    pc.excludePlaylist({\n      error: {\n        message: `Excessive ${type} segment downloading detected.`\n      },\n      playlistExclusionDuration: Infinity\n    });\n  }\n  /**\n   * The purpose of this function is to emulate the \"waiting\" event on\n   * browsers that do not emit it when they are waiting for more\n   * data to continue playback\n   *\n   * @private\n   */\n\n  checkCurrentTime_() {\n    if (this.tech_.paused() || this.tech_.seeking()) {\n      return;\n    }\n    const currentTime = this.tech_.currentTime();\n    const buffered = this.tech_.buffered();\n    if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {\n      // If current time is at the end of the final buffered region, then any playback\n      // stall is most likely caused by buffering in a low bandwidth environment. The tech\n      // should fire a `waiting` event in this scenario, but due to browser and tech\n      // inconsistencies. Calling `techWaiting_` here allows us to simulate\n      // responding to a native `waiting` event when the tech fails to emit one.\n      return this.techWaiting_();\n    }\n    if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {\n      this.consecutiveUpdates++;\n      this.waiting_();\n    } else if (currentTime === this.lastRecordedTime) {\n      this.consecutiveUpdates++;\n    } else {\n      this.playedRanges_.push(createTimeRanges([this.lastRecordedTime, currentTime]));\n      const metadata = {\n        playedRanges: this.playedRanges_\n      };\n      this.playlistController_.trigger({\n        type: 'playedrangeschanged',\n        metadata\n      });\n      this.consecutiveUpdates = 0;\n      this.lastRecordedTime = currentTime;\n    }\n  }\n  /**\n   * Resets the 'timeupdate' mechanism designed to detect that we are stalled\n   *\n   * @private\n   */\n\n  resetTimeUpdate_() {\n    this.consecutiveUpdates = 0;\n  }\n  /**\n   * Fixes situations where there's a bad seek\n   *\n   * @return {boolean} whether an action was taken to fix the seek\n   * @private\n   */\n\n  fixesBadSeeks_() {\n    const seeking = this.tech_.seeking();\n    if (!seeking) {\n      return false;\n    } // TODO: It's possible that these seekable checks should be moved out of this function\n    // and into a function that runs on seekablechange. It's also possible that we only need\n    // afterSeekableWindow as the buffered check at the bottom is good enough to handle before\n    // seekable range.\n\n    const seekable = this.seekable();\n    const currentTime = this.tech_.currentTime();\n    const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);\n    let seekTo;\n    if (isAfterSeekableRange) {\n      const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)\n\n      seekTo = seekableEnd;\n    }\n    if (this.beforeSeekableWindow_(seekable, currentTime)) {\n      const seekableStart = seekable.start(0); // sync to the beginning of the live window\n      // provide a buffer of .1 seconds to handle rounding/imprecise numbers\n\n      seekTo = seekableStart + (\n      // if the playlist is too short and the seekable range is an exact time (can\n      // happen in live with a 3 segment playlist), then don't use a time delta\n      seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);\n    }\n    if (typeof seekTo !== 'undefined') {\n      this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);\n      this.tech_.setCurrentTime(seekTo);\n      return true;\n    }\n    const sourceUpdater = this.playlistController_.sourceUpdater_;\n    const buffered = this.tech_.buffered();\n    const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;\n    const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;\n    const media = this.media(); // verify that at least two segment durations or one part duration have been\n    // appended before checking for a gap.\n\n    const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been\n    // appended before checking for a gap.\n\n    const bufferedToCheck = [audioBuffered, videoBuffered];\n    for (let i = 0; i < bufferedToCheck.length; i++) {\n      // skip null buffered\n      if (!bufferedToCheck[i]) {\n        continue;\n      }\n      const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part\n      // duration behind we haven't appended enough to call this a bad seek.\n\n      if (timeAhead < minAppendedDuration) {\n        return false;\n      }\n    }\n    const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered\n    // to seek over the gap\n\n    if (nextRange.length === 0) {\n      return false;\n    }\n    seekTo = nextRange.start(0) + SAFE_TIME_DELTA;\n    this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);\n    this.tech_.setCurrentTime(seekTo);\n    return true;\n  }\n  /**\n   * Handler for situations when we determine the player is waiting.\n   *\n   * @private\n   */\n\n  waiting_() {\n    if (this.techWaiting_()) {\n      return;\n    } // All tech waiting checks failed. Use last resort correction\n\n    const currentTime = this.tech_.currentTime();\n    const buffered = this.tech_.buffered();\n    const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered\n    // region with no indication that anything is amiss (seen in Firefox). Seeking to\n    // currentTime is usually enough to kickstart the player. This checks that the player\n    // is currently within a buffered region before attempting a corrective seek.\n    // Chrome does not appear to continue `timeupdate` events after a `waiting` event\n    // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also\n    // make sure there is ~3 seconds of forward buffer before taking any corrective action\n    // to avoid triggering an `unknownwaiting` event when the network is slow.\n\n    if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {\n      this.resetTimeUpdate_();\n      this.tech_.setCurrentTime(currentTime);\n      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\n\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-unknown-waiting'\n      });\n      return;\n    }\n  }\n  /**\n   * Handler for situations when the tech fires a `waiting` event\n   *\n   * @return {boolean}\n   *         True if an action (or none) was needed to correct the waiting. False if no\n   *         checks passed\n   * @private\n   */\n\n  techWaiting_() {\n    const seekable = this.seekable();\n    const currentTime = this.tech_.currentTime();\n    if (this.tech_.seeking()) {\n      // Tech is seeking or already waiting on another action, no action needed\n      return true;\n    }\n    if (this.beforeSeekableWindow_(seekable, currentTime)) {\n      const livePoint = seekable.end(seekable.length - 1);\n      this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);\n      this.resetTimeUpdate_();\n      this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS\n\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-live-resync'\n      });\n      return true;\n    }\n    const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;\n    const buffered = this.tech_.buffered();\n    const videoUnderflow = this.videoUnderflow_({\n      audioBuffered: sourceUpdater.audioBuffered(),\n      videoBuffered: sourceUpdater.videoBuffered(),\n      currentTime\n    });\n    if (videoUnderflow) {\n      // Even though the video underflowed and was stuck in a gap, the audio overplayed\n      // the gap, leading currentTime into a buffered range. Seeking to currentTime\n      // allows the video to catch up to the audio position without losing any audio\n      // (only suffering ~3 seconds of frozen video and a pause in audio playback).\n      this.resetTimeUpdate_();\n      this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS\n\n      this.tech_.trigger({\n        type: 'usage',\n        name: 'vhs-video-underflow'\n      });\n      return true;\n    }\n    const nextRange = findNextRange(buffered, currentTime); // check for gap\n\n    if (nextRange.length > 0) {\n      this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);\n      this.resetTimeUpdate_();\n      this.skipTheGap_(currentTime);\n      return true;\n    } // All checks failed. Returning false to indicate failure to correct waiting\n\n    return false;\n  }\n  afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {\n    if (!seekable.length) {\n      // we can't make a solid case if there's no seekable, default to false\n      return false;\n    }\n    let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;\n    const isLive = !playlist.endList;\n    const isLLHLS = typeof playlist.partTargetDuration === 'number';\n    if (isLive && (isLLHLS || allowSeeksWithinUnsafeLiveWindow)) {\n      allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;\n    }\n    if (currentTime > allowedEnd) {\n      return true;\n    }\n    return false;\n  }\n  beforeSeekableWindow_(seekable, currentTime) {\n    if (seekable.length &&\n    // can't fall before 0 and 0 seekable start identifies VOD stream\n    seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {\n      return true;\n    }\n    return false;\n  }\n  videoUnderflow_({\n    videoBuffered,\n    audioBuffered,\n    currentTime\n  }) {\n    // audio only content will not have video underflow :)\n    if (!videoBuffered) {\n      return;\n    }\n    let gap; // find a gap in demuxed content.\n\n    if (videoBuffered.length && audioBuffered.length) {\n      // in Chrome audio will continue to play for ~3s when we run out of video\n      // so we have to check that the video buffer did have some buffer in the\n      // past.\n      const lastVideoRange = findRange(videoBuffered, currentTime - 3);\n      const videoRange = findRange(videoBuffered, currentTime);\n      const audioRange = findRange(audioBuffered, currentTime);\n      if (audioRange.length && !videoRange.length && lastVideoRange.length) {\n        gap = {\n          start: lastVideoRange.end(0),\n          end: audioRange.end(0)\n        };\n      } // find a gap in muxed content.\n    } else {\n      const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are\n      // stuck in a gap due to video underflow.\n\n      if (!nextRange.length) {\n        gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);\n      }\n    }\n    if (gap) {\n      this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);\n      return true;\n    }\n    return false;\n  }\n  /**\n   * Timer callback. If playback still has not proceeded, then we seek\n   * to the start of the next buffered region.\n   *\n   * @private\n   */\n\n  skipTheGap_(scheduledCurrentTime) {\n    const buffered = this.tech_.buffered();\n    const currentTime = this.tech_.currentTime();\n    const nextRange = findNextRange(buffered, currentTime);\n    this.resetTimeUpdate_();\n    if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {\n      return;\n    }\n    this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played\n\n    this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);\n    const metadata = {\n      gapInfo: {\n        from: currentTime,\n        to: nextRange.start(0)\n      }\n    };\n    this.playlistController_.trigger({\n      type: 'gapjumped',\n      metadata\n    });\n    this.tech_.trigger({\n      type: 'usage',\n      name: 'vhs-gap-skip'\n    });\n  }\n  gapFromVideoUnderflow_(buffered, currentTime) {\n    // At least in Chrome, if there is a gap in the video buffer, the audio will continue\n    // playing for ~3 seconds after the video gap starts. This is done to account for\n    // video buffer underflow/underrun (note that this is not done when there is audio\n    // buffer underflow/underrun -- in that case the video will stop as soon as it\n    // encounters the gap, as audio stalls are more noticeable/jarring to a user than\n    // video stalls). The player's time will reflect the playthrough of audio, so the\n    // time will appear as if we are in a buffered region, even if we are stuck in a\n    // \"gap.\"\n    //\n    // Example:\n    // video buffer:   0 => 10.1, 10.2 => 20\n    // audio buffer:   0 => 20\n    // overall buffer: 0 => 10.1, 10.2 => 20\n    // current time: 13\n    //\n    // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,\n    // however, the audio continued playing until it reached ~3 seconds past the gap\n    // (13 seconds), at which point it stops as well. Since current time is past the\n    // gap, findNextRange will return no ranges.\n    //\n    // To check for this issue, we see if there is a gap that starts somewhere within\n    // a 3 second range (3 seconds +/- 1 second) back from our current time.\n    const gaps = findGaps(buffered);\n    for (let i = 0; i < gaps.length; i++) {\n      const start = gaps.start(i);\n      const end = gaps.end(i); // gap is starts no more than 4 seconds back\n\n      if (currentTime - start < 4 && currentTime - start > 2) {\n        return {\n          start,\n          end\n        };\n      }\n    }\n    return null;\n  }\n}\nconst defaultOptions = {\n  errorInterval: 30,\n  getSource(next) {\n    const tech = this.tech({\n      IWillNotUseThisInPlugins: true\n    });\n    const sourceObj = tech.currentSource_ || this.currentSource();\n    return next(sourceObj);\n  }\n};\n/**\n * Main entry point for the plugin\n *\n * @param {Player} player a reference to a videojs Player instance\n * @param {Object} [options] an object with plugin options\n * @private\n */\n\nconst initPlugin = function (player, options) {\n  let lastCalled = 0;\n  let seekTo = 0;\n  const localOptions = merge(defaultOptions, options);\n  player.ready(() => {\n    player.trigger({\n      type: 'usage',\n      name: 'vhs-error-reload-initialized'\n    });\n  });\n  /**\n   * Player modifications to perform that must wait until `loadedmetadata`\n   * has been triggered\n   *\n   * @private\n   */\n\n  const loadedMetadataHandler = function () {\n    if (seekTo) {\n      player.currentTime(seekTo);\n    }\n  };\n  /**\n   * Set the source on the player element, play, and seek if necessary\n   *\n   * @param {Object} sourceObj An object specifying the source url and mime-type to play\n   * @private\n   */\n\n  const setSource = function (sourceObj) {\n    if (sourceObj === null || sourceObj === undefined) {\n      return;\n    }\n    seekTo = player.duration() !== Infinity && player.currentTime() || 0;\n    player.one('loadedmetadata', loadedMetadataHandler);\n    player.src(sourceObj);\n    player.trigger({\n      type: 'usage',\n      name: 'vhs-error-reload'\n    });\n    player.play();\n  };\n  /**\n   * Attempt to get a source from either the built-in getSource function\n   * or a custom function provided via the options\n   *\n   * @private\n   */\n\n  const errorHandler = function () {\n    // Do not attempt to reload the source if a source-reload occurred before\n    // 'errorInterval' time has elapsed since the last source-reload\n    if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {\n      player.trigger({\n        type: 'usage',\n        name: 'vhs-error-reload-canceled'\n      });\n      return;\n    }\n    if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {\n      videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');\n      return;\n    }\n    lastCalled = Date.now();\n    return localOptions.getSource.call(player, setSource);\n  };\n  /**\n   * Unbind any event handlers that were bound by the plugin\n   *\n   * @private\n   */\n\n  const cleanupEvents = function () {\n    player.off('loadedmetadata', loadedMetadataHandler);\n    player.off('error', errorHandler);\n    player.off('dispose', cleanupEvents);\n  };\n  /**\n   * Cleanup before re-initializing the plugin\n   *\n   * @param {Object} [newOptions] an object with plugin options\n   * @private\n   */\n\n  const reinitPlugin = function (newOptions) {\n    cleanupEvents();\n    initPlugin(player, newOptions);\n  };\n  player.on('error', errorHandler);\n  player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before\n  // initializing the plugin\n\n  player.reloadSourceOnError = reinitPlugin;\n};\n/**\n * Reload the source when an error is detected as long as there\n * wasn't an error previously within the last 30 seconds\n *\n * @param {Object} [options] an object with plugin options\n */\n\nconst reloadSourceOnError = function (options) {\n  initPlugin(this, options);\n};\nvar version$4 = \"3.17.2\";\nvar version$3 = \"7.1.0\";\nvar version$2 = \"1.3.1\";\nvar version$1 = \"7.2.0\";\nvar version = \"4.0.2\";\nconst Vhs = {\n  PlaylistLoader,\n  Playlist,\n  utils,\n  STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,\n  INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,\n  lastBandwidthSelector,\n  movingAverageBandwidthSelector,\n  comparePlaylistBandwidth,\n  comparePlaylistResolution,\n  xhr: xhrFactory()\n}; // Define getter/setters for config properties\n\nObject.keys(Config).forEach(prop => {\n  Object.defineProperty(Vhs, prop, {\n    get() {\n      videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);\n      return Config[prop];\n    },\n    set(value) {\n      videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);\n      if (typeof value !== 'number' || value < 0) {\n        videojs.log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);\n        return;\n      }\n      Config[prop] = value;\n    }\n  });\n});\nconst LOCAL_STORAGE_KEY = 'videojs-vhs';\n/**\n * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.\n *\n * @param {QualityLevelList} qualityLevels The QualityLevelList to update.\n * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.\n * @function handleVhsMediaChange\n */\n\nconst handleVhsMediaChange = function (qualityLevels, playlistLoader) {\n  const newPlaylist = playlistLoader.media();\n  let selectedIndex = -1;\n  for (let i = 0; i < qualityLevels.length; i++) {\n    if (qualityLevels[i].id === newPlaylist.id) {\n      selectedIndex = i;\n      break;\n    }\n  }\n  qualityLevels.selectedIndex_ = selectedIndex;\n  qualityLevels.trigger({\n    selectedIndex,\n    type: 'change'\n  });\n};\n/**\n * Adds quality levels to list once playlist metadata is available\n *\n * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.\n * @param {Object} vhs Vhs object to listen to for media events.\n * @function handleVhsLoadedMetadata\n */\n\nconst handleVhsLoadedMetadata = function (qualityLevels, vhs) {\n  vhs.representations().forEach(rep => {\n    qualityLevels.addQualityLevel(rep);\n  });\n  handleVhsMediaChange(qualityLevels, vhs.playlists);\n}; // VHS is a source handler, not a tech. Make sure attempts to use it\n// as one do not cause exceptions.\n\nVhs.canPlaySource = function () {\n  return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\\'s techOrder.');\n};\nconst emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {\n  if (!keySystemOptions) {\n    return keySystemOptions;\n  }\n  let codecs = {};\n  if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {\n    codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));\n  }\n  if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {\n    codecs.audio = audioPlaylist.attributes.CODECS;\n  }\n  const videoContentType = getMimeForCodec(codecs.video);\n  const audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist\n\n  const keySystemContentTypes = {};\n  for (const keySystem in keySystemOptions) {\n    keySystemContentTypes[keySystem] = {};\n    if (audioContentType) {\n      keySystemContentTypes[keySystem].audioContentType = audioContentType;\n    }\n    if (videoContentType) {\n      keySystemContentTypes[keySystem].videoContentType = videoContentType;\n    } // Default to using the video playlist's PSSH even though they may be different, as\n    // videojs-contrib-eme will only accept one in the options.\n    //\n    // This shouldn't be an issue for most cases as early intialization will handle all\n    // unique PSSH values, and if they aren't, then encrypted events should have the\n    // specific information needed for the unique license.\n\n    if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {\n      keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;\n    } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'\n    // so we need to prevent overwriting the URL entirely\n\n    if (typeof keySystemOptions[keySystem] === 'string') {\n      keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];\n    }\n  }\n  return merge(keySystemOptions, keySystemContentTypes);\n};\n/**\n * @typedef {Object} KeySystems\n *\n * keySystems configuration for https://github.com/videojs/videojs-contrib-eme\n * Note: not all options are listed here.\n *\n * @property {Uint8Array} [pssh]\n *           Protection System Specific Header\n */\n\n/**\n * Goes through all the playlists and collects an array of KeySystems options objects\n * containing each playlist's keySystems and their pssh values, if available.\n *\n * @param {Object[]} playlists\n *        The playlists to look through\n * @param {string[]} keySystems\n *        The keySystems to collect pssh values for\n *\n * @return {KeySystems[]}\n *         An array of KeySystems objects containing available key systems and their\n *         pssh values\n */\n\nconst getAllPsshKeySystemsOptions = (playlists, keySystems) => {\n  return playlists.reduce((keySystemsArr, playlist) => {\n    if (!playlist.contentProtection) {\n      return keySystemsArr;\n    }\n    const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {\n      const keySystemOptions = playlist.contentProtection[keySystem];\n      if (keySystemOptions && keySystemOptions.pssh) {\n        keySystemsObj[keySystem] = {\n          pssh: keySystemOptions.pssh\n        };\n      }\n      return keySystemsObj;\n    }, {});\n    if (Object.keys(keySystemsOptions).length) {\n      keySystemsArr.push(keySystemsOptions);\n    }\n    return keySystemsArr;\n  }, []);\n};\n/**\n * Returns a promise that waits for the\n * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.\n *\n * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11\n * browsers.\n *\n * As per the above ticket, this is particularly important for Chrome, where, if\n * unencrypted content is appended before encrypted content and the key session has not\n * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached\n * during playback.\n *\n * @param {Object} player\n *        The player instance\n * @param {Object[]} sourceKeySystems\n *        The key systems options from the player source\n * @param {Object} [audioMedia]\n *        The active audio media playlist (optional)\n * @param {Object[]} mainPlaylists\n *        The playlists found on the main playlist object\n *\n * @return {Object}\n *         Promise that resolves when the key session has been created\n */\n\nconst waitForKeySessionCreation = ({\n  player,\n  sourceKeySystems,\n  audioMedia,\n  mainPlaylists\n}) => {\n  if (!player.eme.initializeMediaKeys) {\n    return Promise.resolve();\n  } // TODO should all audio PSSH values be initialized for DRM?\n  //\n  // All unique video rendition pssh values are initialized for DRM, but here only\n  // the initial audio playlist license is initialized. In theory, an encrypted\n  // event should be fired if the user switches to an alternative audio playlist\n  // where a license is required, but this case hasn't yet been tested. In addition, there\n  // may be many alternate audio playlists unlikely to be used (e.g., multiple different\n  // languages).\n\n  const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;\n  const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));\n  const initializationFinishedPromises = [];\n  const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The\n  // only place where it should not be deduped is for ms-prefixed APIs, but\n  // the existence of modern EME APIs in addition to\n  // ms-prefixed APIs on Edge should prevent this from being a concern.\n  // initializeMediaKeys also won't use the webkit-prefixed APIs.\n\n  keySystemsOptionsArr.forEach(keySystemsOptions => {\n    keySessionCreatedPromises.push(new Promise((resolve, reject) => {\n      player.tech_.one('keysessioncreated', resolve);\n    }));\n    initializationFinishedPromises.push(new Promise((resolve, reject) => {\n      player.eme.initializeMediaKeys({\n        keySystems: keySystemsOptions\n      }, err => {\n        if (err) {\n          reject(err);\n          return;\n        }\n        resolve();\n      });\n    }));\n  }); // The reasons Promise.race is chosen over Promise.any:\n  //\n  // * Promise.any is only available in Safari 14+.\n  // * None of these promises are expected to reject. If they do reject, it might be\n  //   better here for the race to surface the rejection, rather than mask it by using\n  //   Promise.any.\n\n  return Promise.race([\n  // If a session was previously created, these will all finish resolving without\n  // creating a new session, otherwise it will take until the end of all license\n  // requests, which is why the key session check is used (to make setup much faster).\n  Promise.all(initializationFinishedPromises),\n  // Once a single session is created, the browser knows DRM will be used.\n  Promise.race(keySessionCreatedPromises)]);\n};\n/**\n * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and\n * there are keySystems on the source, sets up source options to prepare the source for\n * eme.\n *\n * @param {Object} player\n *        The player instance\n * @param {Object[]} sourceKeySystems\n *        The key systems options from the player source\n * @param {Object} media\n *        The active media playlist\n * @param {Object} [audioMedia]\n *        The active audio media playlist (optional)\n *\n * @return {boolean}\n *         Whether or not options were configured and EME is available\n */\n\nconst setupEmeOptions = ({\n  player,\n  sourceKeySystems,\n  media,\n  audioMedia\n}) => {\n  const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);\n  if (!sourceOptions) {\n    return false;\n  }\n  player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing\n  // do nothing.\n\n  if (sourceOptions && !player.eme) {\n    videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');\n    return false;\n  }\n  return true;\n};\nconst getVhsLocalStorage = () => {\n  if (!window$1.localStorage) {\n    return null;\n  }\n  const storedObject = window$1.localStorage.getItem(LOCAL_STORAGE_KEY);\n  if (!storedObject) {\n    return null;\n  }\n  try {\n    return JSON.parse(storedObject);\n  } catch (e) {\n    // someone may have tampered with the value\n    return null;\n  }\n};\nconst updateVhsLocalStorage = options => {\n  if (!window$1.localStorage) {\n    return false;\n  }\n  let objectToStore = getVhsLocalStorage();\n  objectToStore = objectToStore ? merge(objectToStore, options) : options;\n  try {\n    window$1.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));\n  } catch (e) {\n    // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where\n    // storage is set to 0).\n    // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions\n    // No need to perform any operation.\n    return false;\n  }\n  return objectToStore;\n};\n/**\n * Parses VHS-supported media types from data URIs. See\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs\n * for information on data URIs.\n *\n * @param {string} dataUri\n *        The data URI\n *\n * @return {string|Object}\n *         The parsed object/string, or the original string if no supported media type\n *         was found\n */\n\nconst expandDataUri = dataUri => {\n  if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {\n    return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));\n  } // no known case for this data URI, return the string as-is\n\n  return dataUri;\n};\n/**\n * Adds a request hook to an xhr object\n *\n * @param {Object} xhr object to add the onRequest hook to\n * @param {function} callback hook function for an xhr request\n */\n\nconst addOnRequestHook = (xhr, callback) => {\n  if (!xhr._requestCallbackSet) {\n    xhr._requestCallbackSet = new Set();\n  }\n  xhr._requestCallbackSet.add(callback);\n};\n/**\n * Adds a response hook to an xhr object\n *\n * @param {Object} xhr object to add the onResponse hook to\n * @param {function} callback hook function for an xhr response\n */\n\nconst addOnResponseHook = (xhr, callback) => {\n  if (!xhr._responseCallbackSet) {\n    xhr._responseCallbackSet = new Set();\n  }\n  xhr._responseCallbackSet.add(callback);\n};\n/**\n * Removes a request hook on an xhr object, deletes the onRequest set if empty.\n *\n * @param {Object} xhr object to remove the onRequest hook from\n * @param {function} callback hook function to remove\n */\n\nconst removeOnRequestHook = (xhr, callback) => {\n  if (!xhr._requestCallbackSet) {\n    return;\n  }\n  xhr._requestCallbackSet.delete(callback);\n  if (!xhr._requestCallbackSet.size) {\n    delete xhr._requestCallbackSet;\n  }\n};\n/**\n * Removes a response hook on an xhr object, deletes the onResponse set if empty.\n *\n * @param {Object} xhr object to remove the onResponse hook from\n * @param {function} callback hook function to remove\n */\n\nconst removeOnResponseHook = (xhr, callback) => {\n  if (!xhr._responseCallbackSet) {\n    return;\n  }\n  xhr._responseCallbackSet.delete(callback);\n  if (!xhr._responseCallbackSet.size) {\n    delete xhr._responseCallbackSet;\n  }\n};\n/**\n * Whether the browser has built-in HLS support.\n */\n\nVhs.supportsNativeHls = function () {\n  if (!document$1 || !document$1.createElement) {\n    return false;\n  }\n  const video = document$1.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't\n\n  if (!videojs.getTech('Html5').isSupported()) {\n    return false;\n  } // HLS manifests can go by many mime-types\n\n  const canPlay = [\n  // Apple santioned\n  'application/vnd.apple.mpegurl',\n  // Apple sanctioned for backwards compatibility\n  'audio/mpegurl',\n  // Very common\n  'audio/x-mpegurl',\n  // Very common\n  'application/x-mpegurl',\n  // Included for completeness\n  'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];\n  return canPlay.some(function (canItPlay) {\n    return /maybe|probably/i.test(video.canPlayType(canItPlay));\n  });\n}();\nVhs.supportsNativeDash = function () {\n  if (!document$1 || !document$1.createElement || !videojs.getTech('Html5').isSupported()) {\n    return false;\n  }\n  return /maybe|probably/i.test(document$1.createElement('video').canPlayType('application/dash+xml'));\n}();\nVhs.supportsTypeNatively = type => {\n  if (type === 'hls') {\n    return Vhs.supportsNativeHls;\n  }\n  if (type === 'dash') {\n    return Vhs.supportsNativeDash;\n  }\n  return false;\n};\n/**\n * VHS is a source handler, not a tech. Make sure attempts to use it\n * as one do not cause exceptions.\n */\n\nVhs.isSupported = function () {\n  return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\\'s techOrder.');\n};\n/**\n * A global function for setting an onRequest hook\n *\n * @param {function} callback for request modifiction\n */\n\nVhs.xhr.onRequest = function (callback) {\n  addOnRequestHook(Vhs.xhr, callback);\n};\n/**\n * A global function for setting an onResponse hook\n *\n * @param {callback} callback for response data retrieval\n */\n\nVhs.xhr.onResponse = function (callback) {\n  addOnResponseHook(Vhs.xhr, callback);\n};\n/**\n * Deletes a global onRequest callback if it exists\n *\n * @param {function} callback to delete from the global set\n */\n\nVhs.xhr.offRequest = function (callback) {\n  removeOnRequestHook(Vhs.xhr, callback);\n};\n/**\n * Deletes a global onResponse callback if it exists\n *\n * @param {function} callback to delete from the global set\n */\n\nVhs.xhr.offResponse = function (callback) {\n  removeOnResponseHook(Vhs.xhr, callback);\n};\nconst Component = videojs.getComponent('Component');\n/**\n * The Vhs Handler object, where we orchestrate all of the parts\n * of VHS to interact with video.js\n *\n * @class VhsHandler\n * @extends videojs.Component\n * @param {Object} source the soruce object\n * @param {Tech} tech the parent tech object\n * @param {Object} options optional and required options\n */\n\nclass VhsHandler extends Component {\n  constructor(source, tech, options) {\n    super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed\n    // use that over the VHS level `bandwidth` option\n\n    if (typeof options.initialBandwidth === 'number') {\n      this.options_.bandwidth = options.initialBandwidth;\n    }\n    this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,\n    // so, get it from Video.js via the `playerId`\n\n    if (tech.options_ && tech.options_.playerId) {\n      const _player = videojs.getPlayer(tech.options_.playerId);\n      this.player_ = _player;\n    }\n    this.tech_ = tech;\n    this.source_ = source;\n    this.stats = {};\n    this.ignoreNextSeekingEvent_ = false;\n    this.setOptions_();\n    if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {\n      tech.overrideNativeAudioTracks(true);\n      tech.overrideNativeVideoTracks(true);\n    } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {\n      // overriding native VHS only works if audio tracks have been emulated\n      // error early if we're misconfigured\n      throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');\n    } // listen for fullscreenchange events for this player so that we\n    // can adjust our quality selection quickly\n\n    this.on(document$1, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {\n      const fullscreenElement = document$1.fullscreenElement || document$1.webkitFullscreenElement || document$1.mozFullScreenElement || document$1.msFullscreenElement;\n      if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {\n        this.playlistController_.fastQualityChange_();\n      } else {\n        // When leaving fullscreen, since the in page pixel dimensions should be smaller\n        // than full screen, see if there should be a rendition switch down to preserve\n        // bandwidth.\n        this.playlistController_.checkABR_();\n      }\n    });\n    this.on(this.tech_, 'seeking', function () {\n      if (this.ignoreNextSeekingEvent_) {\n        this.ignoreNextSeekingEvent_ = false;\n        return;\n      }\n      this.setCurrentTime(this.tech_.currentTime());\n    });\n    this.on(this.tech_, 'error', function () {\n      // verify that the error was real and we are loaded\n      // enough to have pc loaded.\n      if (this.tech_.error() && this.playlistController_) {\n        this.playlistController_.pauseLoading();\n      }\n    });\n    this.on(this.tech_, 'play', this.play);\n  }\n  /**\n   * Set VHS options based on options from configuration, as well as partial\n   * options to be passed at a later time.\n   *\n   * @param {Object} options A partial chunk of config options\n   */\n\n  setOptions_(options = {}) {\n    this.options_ = merge(this.options_, options); // defaults\n\n    this.options_.withCredentials = this.options_.withCredentials || false;\n    this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;\n    this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;\n    this.options_.usePlayerObjectFit = this.options_.usePlayerObjectFit || false;\n    this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;\n    this.options_.useForcedSubtitles = this.options_.useForcedSubtitles || false;\n    this.options_.useNetworkInformationApi = typeof this.options_.useNetworkInformationApi !== 'undefined' ? this.options_.useNetworkInformationApi : true;\n    this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;\n    this.options_.customTagParsers = this.options_.customTagParsers || [];\n    this.options_.customTagMappers = this.options_.customTagMappers || [];\n    this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;\n    this.options_.llhls = this.options_.llhls === false ? false : true;\n    this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;\n    if (typeof this.options_.playlistExclusionDuration !== 'number') {\n      this.options_.playlistExclusionDuration = 60;\n    }\n    if (typeof this.options_.bandwidth !== 'number') {\n      if (this.options_.useBandwidthFromLocalStorage) {\n        const storedObject = getVhsLocalStorage();\n        if (storedObject && storedObject.bandwidth) {\n          this.options_.bandwidth = storedObject.bandwidth;\n          this.tech_.trigger({\n            type: 'usage',\n            name: 'vhs-bandwidth-from-local-storage'\n          });\n        }\n        if (storedObject && storedObject.throughput) {\n          this.options_.throughput = storedObject.throughput;\n          this.tech_.trigger({\n            type: 'usage',\n            name: 'vhs-throughput-from-local-storage'\n          });\n        }\n      }\n    } // if bandwidth was not set by options or pulled from local storage, start playlist\n    // selection at a reasonable bandwidth\n\n    if (typeof this.options_.bandwidth !== 'number') {\n      this.options_.bandwidth = Config.INITIAL_BANDWIDTH;\n    } // If the bandwidth number is unchanged from the initial setting\n    // then this takes precedence over the enableLowInitialPlaylist option\n\n    this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src\n\n    ['withCredentials', 'useDevicePixelRatio', 'usePlayerObjectFit', 'customPixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useForcedSubtitles', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {\n      if (typeof this.source_[option] !== 'undefined') {\n        this.options_[option] = this.source_[option];\n      }\n    });\n    this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;\n    this.useDevicePixelRatio = this.options_.useDevicePixelRatio;\n    this.usePlayerObjectFit = this.options_.usePlayerObjectFit;\n    const customPixelRatio = this.options_.customPixelRatio; // Ensure the custom pixel ratio is a number greater than or equal to 0\n\n    if (typeof customPixelRatio === 'number' && customPixelRatio >= 0) {\n      this.customPixelRatio = customPixelRatio;\n    }\n  } // alias for public method to set options\n\n  setOptions(options = {}) {\n    this.setOptions_(options);\n  }\n  /**\n   * called when player.src gets called, handle a new source\n   *\n   * @param {Object} src the source object to handle\n   */\n\n  src(src, type) {\n    // do nothing if the src is falsey\n    if (!src) {\n      return;\n    }\n    this.setOptions_(); // add main playlist controller options\n\n    this.options_.src = expandDataUri(this.source_.src);\n    this.options_.tech = this.tech_;\n    this.options_.externVhs = Vhs;\n    this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech\n\n    this.options_.seekTo = time => {\n      this.tech_.setCurrentTime(time);\n    }; // pass player to allow for player level eventing on construction.\n\n    this.options_.player_ = this.player_;\n    this.playlistController_ = new PlaylistController(this.options_);\n    const playbackWatcherOptions = merge({\n      liveRangeSafeTimeDelta: SAFE_TIME_DELTA\n    }, this.options_, {\n      seekable: () => this.seekable(),\n      media: () => this.playlistController_.media(),\n      playlistController: this.playlistController_\n    });\n    this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);\n    this.attachStreamingEventListeners_();\n    this.playlistController_.on('error', () => {\n      const player = videojs.players[this.tech_.options_.playerId];\n      let error = this.playlistController_.error;\n      if (typeof error === 'object' && !error.code) {\n        error.code = 3;\n      } else if (typeof error === 'string') {\n        error = {\n          message: error,\n          code: 3\n        };\n      }\n      player.error(error);\n    });\n    const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards\n    // compatibility with < v2\n\n    this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);\n    this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2\n\n    this.playlists = this.playlistController_.mainPlaylistLoader_;\n    this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist\n    // controller. Using a custom property for backwards compatibility\n    // with < v2\n\n    Object.defineProperties(this, {\n      selectPlaylist: {\n        get() {\n          return this.playlistController_.selectPlaylist;\n        },\n        set(selectPlaylist) {\n          this.playlistController_.selectPlaylist = selectPlaylist.bind(this);\n        }\n      },\n      throughput: {\n        get() {\n          return this.playlistController_.mainSegmentLoader_.throughput.rate;\n        },\n        set(throughput) {\n          this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value\n          // for the cumulative average\n\n          this.playlistController_.mainSegmentLoader_.throughput.count = 1;\n        }\n      },\n      bandwidth: {\n        get() {\n          let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;\n          const networkInformation = window$1.navigator.connection || window$1.navigator.mozConnection || window$1.navigator.webkitConnection;\n          const tenMbpsAsBitsPerSecond = 10e6;\n          if (this.options_.useNetworkInformationApi && networkInformation) {\n            // downlink returns Mbps\n            // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink\n            const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player\n            // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that\n            // high quality streams are not filtered out.\n\n            if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {\n              playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);\n            } else {\n              playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;\n            }\n          }\n          return playerBandwidthEst;\n        },\n        set(bandwidth) {\n          this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter\n          // `count` is set to zero that current value of `rate` isn't included\n          // in the cumulative average\n\n          this.playlistController_.mainSegmentLoader_.throughput = {\n            rate: 0,\n            count: 0\n          };\n        }\n      },\n      /**\n       * `systemBandwidth` is a combination of two serial processes bit-rates. The first\n       * is the network bitrate provided by `bandwidth` and the second is the bitrate of\n       * the entire process after that - decryption, transmuxing, and appending - provided\n       * by `throughput`.\n       *\n       * Since the two process are serial, the overall system bandwidth is given by:\n       *   sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)\n       */\n      systemBandwidth: {\n        get() {\n          const invBandwidth = 1 / (this.bandwidth || 1);\n          let invThroughput;\n          if (this.throughput > 0) {\n            invThroughput = 1 / this.throughput;\n          } else {\n            invThroughput = 0;\n          }\n          const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));\n          return systemBitrate;\n        },\n        set() {\n          videojs.log.error('The \"systemBandwidth\" property is read-only');\n        }\n      }\n    });\n    if (this.options_.bandwidth) {\n      this.bandwidth = this.options_.bandwidth;\n    }\n    if (this.options_.throughput) {\n      this.throughput = this.options_.throughput;\n    }\n    Object.defineProperties(this.stats, {\n      bandwidth: {\n        get: () => this.bandwidth || 0,\n        enumerable: true\n      },\n      mediaRequests: {\n        get: () => this.playlistController_.mediaRequests_() || 0,\n        enumerable: true\n      },\n      mediaRequestsAborted: {\n        get: () => this.playlistController_.mediaRequestsAborted_() || 0,\n        enumerable: true\n      },\n      mediaRequestsTimedout: {\n        get: () => this.playlistController_.mediaRequestsTimedout_() || 0,\n        enumerable: true\n      },\n      mediaRequestsErrored: {\n        get: () => this.playlistController_.mediaRequestsErrored_() || 0,\n        enumerable: true\n      },\n      mediaTransferDuration: {\n        get: () => this.playlistController_.mediaTransferDuration_() || 0,\n        enumerable: true\n      },\n      mediaBytesTransferred: {\n        get: () => this.playlistController_.mediaBytesTransferred_() || 0,\n        enumerable: true\n      },\n      mediaSecondsLoaded: {\n        get: () => this.playlistController_.mediaSecondsLoaded_() || 0,\n        enumerable: true\n      },\n      mediaAppends: {\n        get: () => this.playlistController_.mediaAppends_() || 0,\n        enumerable: true\n      },\n      mainAppendsToLoadedData: {\n        get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,\n        enumerable: true\n      },\n      audioAppendsToLoadedData: {\n        get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,\n        enumerable: true\n      },\n      appendsToLoadedData: {\n        get: () => this.playlistController_.appendsToLoadedData_() || 0,\n        enumerable: true\n      },\n      timeToLoadedData: {\n        get: () => this.playlistController_.timeToLoadedData_() || 0,\n        enumerable: true\n      },\n      buffered: {\n        get: () => timeRangesToArray(this.tech_.buffered()),\n        enumerable: true\n      },\n      currentTime: {\n        get: () => this.tech_.currentTime(),\n        enumerable: true\n      },\n      currentSource: {\n        get: () => this.tech_.currentSource_,\n        enumerable: true\n      },\n      currentTech: {\n        get: () => this.tech_.name_,\n        enumerable: true\n      },\n      duration: {\n        get: () => this.tech_.duration(),\n        enumerable: true\n      },\n      main: {\n        get: () => this.playlists.main,\n        enumerable: true\n      },\n      playerDimensions: {\n        get: () => this.tech_.currentDimensions(),\n        enumerable: true\n      },\n      seekable: {\n        get: () => timeRangesToArray(this.tech_.seekable()),\n        enumerable: true\n      },\n      timestamp: {\n        get: () => Date.now(),\n        enumerable: true\n      },\n      videoPlaybackQuality: {\n        get: () => this.tech_.getVideoPlaybackQuality(),\n        enumerable: true\n      }\n    });\n    this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));\n    this.tech_.on('bandwidthupdate', () => {\n      if (this.options_.useBandwidthFromLocalStorage) {\n        updateVhsLocalStorage({\n          bandwidth: this.bandwidth,\n          throughput: Math.round(this.throughput)\n        });\n      }\n    });\n    this.playlistController_.on('selectedinitialmedia', () => {\n      // Add the manual rendition mix-in to VhsHandler\n      renditionSelectionMixin(this);\n    });\n    this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {\n      this.setupEme_();\n    }); // the bandwidth of the primary segment loader is our best\n    // estimate of overall bandwidth\n\n    this.on(this.playlistController_, 'progress', function () {\n      this.tech_.trigger('progress');\n    }); // In the live case, we need to ignore the very first `seeking` event since\n    // that will be the result of the seek-to-live behavior\n\n    this.on(this.playlistController_, 'firstplay', function () {\n      this.ignoreNextSeekingEvent_ = true;\n    });\n    this.setupQualityLevels_(); // do nothing if the tech has been disposed already\n    // this can occur if someone sets the src in player.ready(), for instance\n\n    if (!this.tech_.el()) {\n      return;\n    }\n    this.mediaSourceUrl_ = window$1.URL.createObjectURL(this.playlistController_.mediaSource); // If we are playing HLS with MSE in Safari, add source elements for both the blob and manifest URLs.\n    // The latter will enable Airplay playback on receiver devices.\n\n    if ((videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS) && this.options_.overrideNative && this.options_.sourceType === 'hls' && typeof this.tech_.addSourceElement === 'function') {\n      this.tech_.addSourceElement(this.mediaSourceUrl_);\n      this.tech_.addSourceElement(this.source_.src);\n    } else {\n      this.tech_.src(this.mediaSourceUrl_);\n    }\n  }\n  createKeySessions_() {\n    const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;\n    this.logger_('waiting for EME key session creation');\n    waitForKeySessionCreation({\n      player: this.player_,\n      sourceKeySystems: this.source_.keySystems,\n      audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),\n      mainPlaylists: this.playlists.main.playlists\n    }).then(() => {\n      this.logger_('created EME key session');\n      this.playlistController_.sourceUpdater_.initializedEme();\n    }).catch(err => {\n      this.logger_('error while creating EME key session', err);\n      this.player_.error({\n        message: 'Failed to initialize media keys for EME',\n        code: 3\n      });\n    });\n  }\n  handleWaitingForKey_() {\n    // If waitingforkey is fired, it's possible that the data that's necessary to retrieve\n    // the key is in the manifest. While this should've happened on initial source load, it\n    // may happen again in live streams where the keys change, and the manifest info\n    // reflects the update.\n    //\n    // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's\n    // already requested keys for, we don't have to worry about this generating extraneous\n    // requests.\n    this.logger_('waitingforkey fired, attempting to create any new key sessions');\n    this.createKeySessions_();\n  }\n  /**\n   * If necessary and EME is available, sets up EME options and waits for key session\n   * creation.\n   *\n   * This function also updates the source updater so taht it can be used, as for some\n   * browsers, EME must be configured before content is appended (if appending unencrypted\n   * content before encrypted content).\n   */\n\n  setupEme_() {\n    const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;\n    const didSetupEmeOptions = setupEmeOptions({\n      player: this.player_,\n      sourceKeySystems: this.source_.keySystems,\n      media: this.playlists.media(),\n      audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()\n    });\n    this.player_.tech_.on('keystatuschange', e => {\n      this.playlistController_.updatePlaylistByKeyStatus(e.keyId, e.status);\n    });\n    this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);\n    this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_);\n    if (!didSetupEmeOptions) {\n      // If EME options were not set up, we've done all we could to initialize EME.\n      this.playlistController_.sourceUpdater_.initializedEme();\n      return;\n    }\n    this.createKeySessions_();\n  }\n  /**\n   * Initializes the quality levels and sets listeners to update them.\n   *\n   * @method setupQualityLevels_\n   * @private\n   */\n\n  setupQualityLevels_() {\n    const player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin\n    // or qualityLevels_ listeners have already been setup, do nothing.\n\n    if (!player || !player.qualityLevels || this.qualityLevels_) {\n      return;\n    }\n    this.qualityLevels_ = player.qualityLevels();\n    this.playlistController_.on('selectedinitialmedia', () => {\n      handleVhsLoadedMetadata(this.qualityLevels_, this);\n    });\n    this.playlists.on('mediachange', () => {\n      handleVhsMediaChange(this.qualityLevels_, this.playlists);\n    });\n  }\n  /**\n   * return the version\n   */\n\n  static version() {\n    return {\n      '@videojs/http-streaming': version$4,\n      'mux.js': version$3,\n      'mpd-parser': version$2,\n      'm3u8-parser': version$1,\n      'aes-decrypter': version\n    };\n  }\n  /**\n   * return the version\n   */\n\n  version() {\n    return this.constructor.version();\n  }\n  canChangeType() {\n    return SourceUpdater.canChangeType();\n  }\n  /**\n   * Begin playing the video.\n   */\n\n  play() {\n    this.playlistController_.play();\n  }\n  /**\n   * a wrapper around the function in PlaylistController\n   */\n\n  setCurrentTime(currentTime) {\n    this.playlistController_.setCurrentTime(currentTime);\n  }\n  /**\n   * a wrapper around the function in PlaylistController\n   */\n\n  duration() {\n    return this.playlistController_.duration();\n  }\n  /**\n   * a wrapper around the function in PlaylistController\n   */\n\n  seekable() {\n    return this.playlistController_.seekable();\n  }\n  /**\n   * Abort all outstanding work and cleanup.\n   */\n\n  dispose() {\n    if (this.playbackWatcher_) {\n      this.playbackWatcher_.dispose();\n    }\n    if (this.playlistController_) {\n      this.playlistController_.dispose();\n    }\n    if (this.qualityLevels_) {\n      this.qualityLevels_.dispose();\n    }\n    if (this.tech_ && this.tech_.vhs) {\n      delete this.tech_.vhs;\n    }\n    if (this.mediaSourceUrl_ && window$1.URL.revokeObjectURL) {\n      window$1.URL.revokeObjectURL(this.mediaSourceUrl_);\n      this.mediaSourceUrl_ = null;\n    }\n    if (this.tech_) {\n      this.tech_.off('waitingforkey', this.handleWaitingForKey_);\n    }\n    super.dispose();\n  }\n  convertToProgramTime(time, callback) {\n    return getProgramTime({\n      playlist: this.playlistController_.media(),\n      time,\n      callback\n    });\n  } // the player must be playing before calling this\n\n  seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {\n    return seekToProgramTime({\n      programTime,\n      playlist: this.playlistController_.media(),\n      retryCount,\n      pauseAfterSeek,\n      seekTo: this.options_.seekTo,\n      tech: this.options_.tech,\n      callback\n    });\n  }\n  /**\n   * Adds the onRequest, onResponse, offRequest and offResponse functions\n   * to the VhsHandler xhr Object.\n   */\n\n  setupXhrHooks_() {\n    /**\n     * A player function for setting an onRequest hook\n     *\n     * @param {function} callback for request modifiction\n     */\n    this.xhr.onRequest = callback => {\n      addOnRequestHook(this.xhr, callback);\n    };\n    /**\n     * A player function for setting an onResponse hook\n     *\n     * @param {callback} callback for response data retrieval\n     */\n\n    this.xhr.onResponse = callback => {\n      addOnResponseHook(this.xhr, callback);\n    };\n    /**\n     * Deletes a player onRequest callback if it exists\n     *\n     * @param {function} callback to delete from the player set\n     */\n\n    this.xhr.offRequest = callback => {\n      removeOnRequestHook(this.xhr, callback);\n    };\n    /**\n     * Deletes a player onResponse callback if it exists\n     *\n     * @param {function} callback to delete from the player set\n     */\n\n    this.xhr.offResponse = callback => {\n      removeOnResponseHook(this.xhr, callback);\n    }; // Trigger an event on the player to notify the user that vhs is ready to set xhr hooks.\n    // This allows hooks to be set before the source is set to vhs when handleSource is called.\n\n    this.player_.trigger('xhr-hooks-ready');\n  }\n  attachStreamingEventListeners_() {\n    const playlistControllerEvents = ['seekablerangeschanged', 'bufferedrangeschanged', 'contentsteeringloadstart', 'contentsteeringloadcomplete', 'contentsteeringparsed'];\n    const playbackWatcher = ['gapjumped', 'playedrangeschanged']; // re-emit streaming events and payloads on the player.\n\n    playlistControllerEvents.forEach(eventName => {\n      this.playlistController_.on(eventName, metadata => {\n        this.player_.trigger(_extends({}, metadata));\n      });\n    });\n    playbackWatcher.forEach(eventName => {\n      this.playbackWatcher_.on(eventName, metadata => {\n        this.player_.trigger(_extends({}, metadata));\n      });\n    });\n  }\n}\n/**\n * The Source Handler object, which informs video.js what additional\n * MIME types are supported and sets up playback. It is registered\n * automatically to the appropriate tech based on the capabilities of\n * the browser it is running in. It is not necessary to use or modify\n * this object in normal usage.\n */\n\nconst VhsSourceHandler = {\n  name: 'videojs-http-streaming',\n  VERSION: version$4,\n  canHandleSource(srcObj, options = {}) {\n    const localOptions = merge(videojs.options, options); // If not opting to experimentalUseMMS, and playback is only supported with MediaSource, cannot handle source\n\n    if (!localOptions.vhs.experimentalUseMMS && !browserSupportsCodec('avc1.4d400d,mp4a.40.2', false)) {\n      return false;\n    }\n    return VhsSourceHandler.canPlayType(srcObj.type, localOptions);\n  },\n  handleSource(source, tech, options = {}) {\n    const localOptions = merge(videojs.options, options);\n    tech.vhs = new VhsHandler(source, tech, localOptions);\n    tech.vhs.xhr = xhrFactory();\n    tech.vhs.setupXhrHooks_();\n    tech.vhs.src(source.src, source.type);\n    return tech.vhs;\n  },\n  canPlayType(type, options) {\n    const simpleType = simpleTypeFromSourceType(type);\n    if (!simpleType) {\n      return '';\n    }\n    const overrideNative = VhsSourceHandler.getOverrideNative(options);\n    const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);\n    const canUseMsePlayback = !supportsTypeNatively || overrideNative;\n    return canUseMsePlayback ? 'maybe' : '';\n  },\n  getOverrideNative(options = {}) {\n    const {\n      vhs = {}\n    } = options;\n    const defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);\n    const {\n      overrideNative = defaultOverrideNative\n    } = vhs;\n    return overrideNative;\n  }\n};\n/**\n * Check to see if either the native MediaSource or ManagedMediaSource\n * objectx exist and support an MP4 container with both H.264 video\n * and AAC-LC audio.\n *\n * @return {boolean} if  native media sources are supported\n */\n\nconst supportsNativeMediaSources = () => {\n  return browserSupportsCodec('avc1.4d400d,mp4a.40.2', true);\n}; // register source handlers with the appropriate techs\n\nif (supportsNativeMediaSources()) {\n  videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);\n}\nvideojs.VhsHandler = VhsHandler;\nvideojs.VhsSourceHandler = VhsSourceHandler;\nvideojs.Vhs = Vhs;\nif (!videojs.use) {\n  videojs.registerComponent('Vhs', Vhs);\n}\nvideojs.options.vhs = videojs.options.vhs || {};\nif (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {\n  videojs.registerPlugin('reloadSourceOnError', reloadSourceOnError);\n}\n\nexport { videojs as default };\n"],"names":["_extends","n","r","module","e","t","win","global","window_1","__viteBrowserExternal","topLevel","minDoc","require$$0","doccy","document_1","isFunction_1","isFunction","toString","fn","string","_createForOfIteratorHelperLoose","o","allowArrayLike","it","_unsupportedIterableToArray","minLen","_arrayLikeToArray","arr","len","i","arr2","InterceptorsStorage","_proto","type","interceptor","interceptorsSet","payload","interceptors","_iterator","_step","RetryManager","maxAttempts","delayFactor","fuzzFactor","initialDelay","_temp","_ref","Retry","options","_proto2","delayDelta","lowValue","highValue","retry","window","httpResponseHandler","callback","decodeResponseBody","err","response","responseBody","cause","charset","getCharset","contentTypeHeader","contentType","_contentType$split","value","httpHandler","require$$1","require$$2","require$$3","require$$4","createXHR","require$$5","parseHeaders","headers","result","row","index","key","libModule","noop","forEachArray","method","uri","initParams","_createXHR","array","iterator","isEmpty","obj","params","requestInterceptorPayload","updatedPayload","called","body","readystatechange","xhr","loadFunc","getBody","getXml","isJson","errorFunc","evt","timeoutTimer","aborted","responseInterceptorPayload","failureResponse","_updatedPayload","status","_updatedPayload2","sync","firefoxBugTakenEffect","document","_objCreate","F","ParsingError","errorData","message","parseTimeStamp","input","computeSeconds","h","m","s","f","Settings","k","v","dflt","defaultKey","a","parseOptions","keyValueDelim","groupDelim","groups","kv","parseCue","cue","regionList","oInput","consumeTimeStamp","ts","consumeCueSettings","settings","vals","vals0","skipWhitespace","TEXTAREA_ELEMENT","TAG_NAME","DEFAULT_COLOR_CLASS","TAG_ANNOTATION","NEEDS_PARENT","parseContent","nextToken","consume","unescape","shouldAdd","current","element","createElement","annotation","tagName","name","rootDiv","tagStack","node","classes","cl","bgColor","colorName","propName","propValue","strongRTLRanges","isStrongRTLChar","charCode","currentRange","determineBidi","cueDiv","nodeStack","text","pushNodes","nextTextNode","computeLinePos","track","trackList","count","StyleBox","styles","div","prop","val","unit","CueStyleBox","styleOptions","textPos","box","BoxPosition","lh","height","width","top","rects","axis","toMove","b2","boxes","container","x","y","intersectArea","reference","ret","moveBoxToLinePosition","styleBox","containerBox","boxPositions","findBestPosition","b","bestPosition","specifiedPosition","percentage","p","boxPosition","linePos","size","step","position","maxPosition","initialAxis","calculatedPercentage","WebVTT","data","cuetext","FONT_SIZE_PERCENT","FONT_STYLE","CUE_BACKGROUND_PADDING","cues","overlay","paddedOverlay","shouldCompute","fontSize","vttjs","decoder","self","collectNextLine","buffer","pos","line","parseRegion","xy","anchor","region","parseTimestampMap","parseHeader","alreadyCollectedLine","hasSubstring","vtt","autoKeyword","directionSetting","alignSetting","findDirectionSetting","dir","findAlignSetting","align","VTTCue","startTime","endTime","_id","_pauseOnExit","_startTime","_endTime","_text","_region","_vertical","_snapToLines","_line","_lineAlign","_position","_positionAlign","_size","_align","setting","vttcue","scrollSetting","findScrollSetting","scroll","isValidPercentValue","VTTRegion","_width","_lines","_regionAnchorX","_regionAnchorY","_viewportAnchorX","_viewportAnchorY","_scroll","vttregion","browserIndexModule","cueShim","regionShim","nativeVTTCue","nativeVTTRegion","DEFAULT_LOCATION","resolveUrl","baseUrl","relativeUrl","protocolLess","removeLocation","newUrl","regexs","mediaTypes","upperMediaTypes","translateLegacyCodec","codec","orig","profile","avcLevel","profileHex","avcLevelHex","parseCodecs","codecString","codecs","codecType","match","details","codecsFromDefault","master","audioGroupId","audioGroup","audioType","isAudioCodec","isTextCodec","getMimeForCodec","c","browserSupportsCodec","withMMS","muxerSupportsCodec","DEFAULT_AUDIO_CODEC","DEFAULT_VIDEO_CODEC","MPEGURL_REGEX","DASH_REGEX","simpleTypeFromSourceType","countBits","countBytes","isArrayBufferView","isTypedArray","toUint8","bytes","BigInt","BYTE_TABLE","bytesToNumber","_ref$signed","signed","_ref$le","le","number","total","byte","exponent","max","numberToBytes","_temp2","_ref2","_ref2$le","byteCount","byteIndex","stringToBytes","stringIsBytes","view","concatTypedArrays","_len","buffers","_key","totalLen","buf","tempBuffer","offset","bytesMatch","_temp3","_ref3","_ref3$offset","_ref3$mask","mask","bByte","aByte","MAX_UINT32","getUint64","uint8","dv","numbers","parseSidx","referenceCount","parseSidx_1","ID3","getId3Size","flags","returnSize","footerPresent","getId3Offset","normalizePath","path","normalizePaths","paths","findBox","complete","results","end","EBML_TAGS","LENGTH_TABLE","getLength","getvint","removeLength","length","valueBytes","getInfinityDataSize","id","innerid","dataHeader","findEbml","dataStart","dataEnd","totalLength","NAL_TYPE_ONE","NAL_TYPE_TWO","EMULATION_PREVENTION","discardEmulationPreventionBytes","positions","newLength","newData","sourceIndex","findNal","dataType","types","nalLimit","nalStart","nalsFound","nalOffset","nalType","findH264Nal","findH265Nal","CONSTANTS","_isLikely","docType","isLikelyTypes","isLikelyFn","isLikely","detectContainerForBytes","isLikelyFmp4MediaSegment","clock","version$6","hooks_","hooks","hook","removeHook","hookOnce","original","wrapper","args","FullscreenApi","apiMap","specApi","browserApi","document$1","history","LogByTypeFactory","log","level","lvl","lvlRegExp","resultName","splice","window$1","createLogger$1","delimiter","logByType","subName","subDelimiter","subStyles","resultDelimiter","resultStyles","newName","newDelimiter","newStyles","fname","historyItem","log$1","createLogger","keys","object","isObject","each","reduce","initial","accum","isPlain","merge$1","sources","source","values","defineLazyProperty","getValue","setter","set","Obj","IS_IPOD","IOS_VERSION","IS_ANDROID","ANDROID_VERSION","IS_FIREFOX","IS_EDGE","IS_CHROMIUM","IS_CHROME","CHROMIUM_VERSION","CHROME_VERSION","IS_CHROMECAST_RECEIVER","IE_VERSION","IS_SAFARI","IS_WINDOWS","IS_IPAD","IS_IPHONE","IS_TIZEN","IS_WEBOS","IS_SMART_TV","TOUCH_ENABLED","isReal","UAD","USER_AGENT","major","minor","version","IS_IOS","IS_ANY_SAFARI","browser","isNonBlankString","str","throwIfWhitespace","isEl","isInFrame","createQuerier","selector","context","ctx","createEl","properties","attributes","content","el","textContent","attrName","appendContent","prependTo","child","parent","hasClass","classToCheck","addClass","classesToAdd","prev","removeClass","classesToRemove","toggleClass","classToToggle","predicate","className","setAttributes","attrValue","getAttributes","tag","knownBooleans","attrs","attrVal","getAttribute","attribute","setAttribute","removeAttribute","blockTextSelection","unblockTextSelection","getBoundingClientRect","rect","computedStyle","findPosition","left","getPointerPosition","event","translated","item","transform","transformValue","matrix","boxTarget","boxW","boxH","offsetY","offsetX","isTextNode","emptyEl","normalizeContent","insertContent","isSingleLeftClick","$","$$","computedStyleValue","copyStyleSheetsToWindow","styleSheet","cssRules","rule","style","link","Dom","_windowLoaded","videojs$1","autoSetup","vids","audios","divs","mediaEls","mediaEl","autoSetupTimeout","wait","vjs","setWindowLoaded","createStyleElement","setTextContent","DomData","_initialGuid","_guid","newGUID","_cleanUpEvents","elem","_handleMultipleEvents","fixEvent","returnTrue","returnFalse","old","deprecatedProps","doc","_supportsPassive","supportsPassive","opts","passiveEvents","on","hash","handlers","handlersCopy","off","removeType","trigger","elemData","targetData","one","func","any","Events","UPDATE_REFRESH_INTERVAL","bind_","uid","bound","throttle","last","now","debounce$1","immediate","timeout","cancel","debounced","later","Fn","EVENT_MAP","EventTarget$2","ael","map","oldTimeout","objName","isEvented","addEventedCallback","target","isValidEventType","validateTarget","fnName","validateEventType","validateListener","listener","normalizeListenArgs","isTargetingSelf","listen","EventedMixin","removeListenerOnDispose","removeRemoverOnTargetDispose","largs","targetOrType","typeOrListener","evented","eventBusKey","StatefulMixin","stateUpdates","changes","stateful","defaultState","toLowerCase","w","toTitleCase$1","titleCaseEquals","str1","str2","Str","Component$1","player","ready","tokens","defaultValue","code","languages","language","primaryCode","primaryLang","localizedString","names","acc","currentChild","iconName","xmlnsURL","iconContainer","svgEl","useEl","component","componentName","componentClassName","ComponentClass","refNode","childFound","compEl","children","parentOptions","handleAdd","newChild","workingChildren","Tech","wchild","readyQueue","num","skipListeners","widthOrHeight","pxIndex","computedWidthOrHeight","boundingClientRect","center","touchStart","firstTouch","tapMovementThreshold","touchTimeThreshold","couldBeTap","xdiff","ydiff","noTap","report","touchHolding","touchEnd","timeoutId","interval","intervalId","idName","cancelName","isVisibleStyleProperty","elementStyle","thisVisibility","isBeingRendered","isVisible","elementCenter","pointContainer","ComponentToRegister","isTech","isComp","reason","Player","players","playerNames","rangeCheck","maxIndex","getRange","valueIndex","ranges","rangeIndex","createTimeRangesObj","timeRangesObj","createTimeRanges$1","start","defaultImplementation","seconds","guide","gm","gh","implementation","setFormatTime","customImplementation","resetFormatTime","formatTime","Time","bufferedPercent","buffered","duration","bufferedDuration","MediaError","isPromise","silencePromise","trackToJson","textTracksToJson","tech","trackEls","trackObjs","trackEl","json","jsonToTextTracks","addedTrack","textTrackConverter","MODAL_CLASS_NAME","ModalDialog","desc","closeable","close","temp","contentEl","parentEl","nextSiblingEl","closeButton","activeEl","playerEl","focusableEls","focusIndex","allChildren","TrackList","tracks","rtrack","l","disableOthers$1","list","AudioTrackList","disableOthers","VideoTrackList","TextTrackList","HtmlTrackElementList","trackElements","trackElement","trackElement_","TextTrackCueList","oldLength","defineProp","VideoTrackKind","AudioTrackKind","TextTrackKind","TextTrackMode","Track","trackProps","label","newLabel","parseUrl","url","getAbsoluteURL","getFileExtension","isCrossOrigin","winLoc","Url","parseCues","srcContent","parser","errors","error","loadTrack","src","crossOrigin","withCredentials","XHR","TextTrack","mode","default_","activeCues","changed","disposeHandler","newMode","ct","active","originalCue","removeCue","AudioTrack","enabled","newEnabled","VideoTrack","selected","newSelected","HTMLTrackElement","readyState","NORMAL","REMOTE","ALL","createTrackHelper","kind","props","numBufferedPercent","_isScrubbing","_seconds","trackListChanges","script","remoteTracks","handleAddTrack","handleRemoveTrack","updateDisplay","textTracksChanges","manualCleanup","htmlTrackElement","cb","override","_type","srcObj","_Tech","handler","can","sh","originalFn","middlewares","middlewareInstances","TERMINATOR","use","middleware","setSource","next","setSourceHelper","setTech","mw","get","middlewareIterator","arg","mediate","callMethod","middlewareValue","terminated","returnValue","executeRight","allowedGetters","allowedSetters","allowedMediators","mws","clearCacheForPlayer","getOrCreateFactory","mwFactory","mwf","mwi","lastRun","mwrest","_src","MimetypesKind","getMimetype","ext","findMimetype","matchingSources","filterSource","newsrc","srcobj","fixSource","mimetype","icons","backKeyCode","SpatialNavKeyCodes","keyName","STEP_SECONDS","SpatialNavigation","actualEvent","direction","action","nextFocusedElement","isChildrenOfPlayer","currentComponent","focusableComponents","searchForChildrenCandidates","componentsArray","buttonContainer","searchForSuitableChild","suitableChild","curComp","currentFocusedComponent","currentPositions","candidates","bestCandidate","currentCenter","minDistance","candidate","candidateCenter","distance","srcRect","targetRect","center1","center2","dx","dy","spatialNavigation","MediaLoader","options_","j","techName","ClickableComponent","localizedText","PosterImage","darkGray","lightGray","fontMap","constructColor","color","opacity","hex","tryUpdateStyle","getCSSPositionValue","TextTrackDisplay","updateDisplayTextHandler","updateDisplayHandler","screenOrientation","changeOrientationEvent","modes","userPref","firstDesc","firstCaptions","preferredTrack","allowMultipleShowingTracks","showingTracks","descriptionsTrack","captionsSubtitlesTrack","textTrackDisplay","vjsTextTrackCues","controlBarHeight","playerHeight","vjsTextTrackCue","insetStyles","playerWidth","playerAspectRatio","videoAspectRatio","insetInlineMatch","insetBlockMatch","overrides","cueEl","LoadingSpinner","isAudio","playerType","controlText","Button","BigPlayButton","playPromise","playToggle","playFocus","CloseButton","PlayToggle","TimeDisplay","span","time","oldNode","CurrentTimeDisplay","DurationDisplay","updateContent","TimeDivider","RemainingTimeDisplay","LiveDisplay","SeekToLive","clamp","min","Num","Slider","progress","sizeKey","spatialNavOptions","spatialNavEnabled","horizontalSeek","bool","percentify","LoadProgressBar","loadedText","separator","liveTracker","bufferedEnd","percent","part","TimeTooltip","seekBarRect","seekBarPoint","tooltipRect","playerRect","seekBarPointPx","spaceLeftOfPoint","spaceRightOfPoint","pullTooltipBy","liveWindow","secondsBehind","PlayProgressBar","timeTooltip","MouseTimeDisplay","SeekBar","shouldDisableSeekWhileScrubbing","currentTime","mouseDown","newTime","seekableStart","seekableEnd","mouseTimeDisplay","stepAmount","currentPos","gotoFraction","ProgressControl","seekBar","playProgressBar","seekBarEl","PictureInPictureToggle","FullscreenToggle","checkVolumeSupport","VolumeLevel","VolumeLevelTooltip","rangeBarRect","rangeBarPoint","vertical","volumeBarPointPx","volume","MouseVolumeLevelDisplay","VolumeBar","mouseVolumeLevelDisplay","volumeBarEl","volumeBarRect","volumeBarPoint","ariaValue","volumeBeforeDrag","VolumeControl","orientationClass","checkMuteSupport","MuteToggle","vol","lastVolume","volumeToSet","VolumePanel","SkipForward","playerOptions","currentVideoTime","SkipBackward","Menu","childComponent","contentElType","relatedTarget","btn","childComponents","foundComponent","stepChild","MenuButton","buttonClass","handleClick","menu","titleEl","titleComponent","menuButtonClass","TrackButton","updateHandler","MenuItem","menuItemEl","TextTrackMenuItem","changeHandler","selectedLanguageChangeHandler","referenceTrack","shouldBeSelected","selectedLanguage","OffTextTrackMenuItem","allHidden","TextTrackButton","items","TrackMenuItem","ChaptersTrackMenuItem","ChaptersButton","remoteTextTrackEl","mi","DescriptionsButton","disabled","SubtitlesButton","CaptionSettingsMenuItem","CaptionsButton","SubsCapsMenuItem","parentSpan","SubsCapsButton","AudioTrackMenuItem","AudioTrackButton","PlaybackRateMenuItem","rate","PlaybackRateMenuButton","rates","Spacer","CustomControlSpacer","ControlBar","ErrorDisplay","TextTrackSelect","optionText","optionId","option","TextTrackFieldset","legendElement","selects","selectConfig","selectClassName","guid","textTrackSelect","TextTrackSettingsColors","id_","ElFgColorFieldset","ElBgColorFieldset","ElWinColorFieldset","TextTrackSettingsFont","TrackSettingsControls","resetButton","doneText","doneButton","LOCAL_STORAGE_KEY$1","COLOR_BLACK","COLOR_BLUE","COLOR_CYAN","COLOR_GREEN","COLOR_MAGENTA","COLOR_RED","COLOR_WHITE","COLOR_YELLOW","OPACITY_OPAQUE","OPACITY_SEMI","OPACITY_TRANS","selectConfigs","parseOptionValue","getSelectedOptionValue","setSelectedOption","TextTrackSettings","textTrackSettingsColors","textTrackSettingsFont","trackSettingsControls","config","ttDisplay","ResizeManager","RESIZE_OBSERVER_AVAILABLE","debouncedHandler_","unloadListener_","defaults$1","LiveTracker","seekable","deltaTime","liveCurrentTime","isBehind","timeDiff","seekableEnds","seekableStarts","TitleBar","techEl","techAriaAttrs","techAriaAttr","defaults","TransientButton","sourcesetLoad","srcUrls","innerHTMLDescriptorPolyfill","dummy","docFrag","getDescriptor","priority","descriptor","getInnerHTMLDescriptor","firstSourceWatch","innerDescriptor","appendWrapper","appendFn","retval","srcDescriptorPolyfill","getSrcDescriptor","setupSourceset","srcDescriptor","oldSetAttribute","oldLoad","Html5","crossoriginTracks","nodes","nodesLength","removeNodes","textTracks","metadataTracksPreFullscreenState","takeMetadataTrackSnapshot","restoreTrackMode","storedTrack","lowerCaseType","eventName","elTracks","techTracks","listeners","removeOldTracks","removeTracks","found","clone","tagAttributes","settingsAttrs","attr","loadstartFired","setLoadstartFired","triggerLoadstart","eventsToTrigger","isScrubbing","checkProgress","endFn","beginFn","video","srcUrl","mimeType","sourceAttributes","sourceElement","sourceElements","videoPlaybackQuality","canControl","muted","playbackRate","TECH_EVENTS_RETRIGGER","TECH_EVENTS_QUEUE","BREAKPOINT_ORDER","BREAKPOINT_CLASSES","DEFAULT_BREAKPOINTS","closest","languagesToLower","playerOptionsCopy","parsedSVG","sprite","majorVersion","playerElIngest","divEmbed","deviceClassNames","defaultsStyleEl","head","links","linkEl","dimension","privDimension","parsedVal","ratio","aspectRatio","idClass","ratioParts","ratioMultiplier","titleTechName","camelTechName","autoplay","techOptions","TechClass","eventObj","safety","resolveMuted","previouslyMuted","restoreMuted","mutedPromise","promise","sourceElSources","sourceEls","matchingSourceEls","sourceObj","updateSourceCaches","playerSrc","eventSrc","techSrc","request","queued","timeWhenWaiting","timeUpdateListener","targetPlayer","isFs","resolve","isSrcReady","isSafariOrIOS","queue","q","callbacks","percentAsDecimal","defaultMuted","isFS","oldValue","fullscreenOptions","reject","offHandler","errorHandler","fsOptions","isPiP","pipContainer","pipWindow","pipVideo","userActions","allowedInputTypes","hotkeys","fullscreenKey","keydownEvent","muteKey","playPauseKey","FSToggle","techs","findFirstPassingTechSourcePair","outerArray","innerArray","tester","outerChoice","innerChoice","foundSourceAndTech","flip","finder","isRetry","middlewareSource","stopListeningForErrors","sourceTech","currentTimeDisplay","durationDisplay","progressControl","remainingTimeDisplay","techAutoplay","newPoster","hookFunction","newErr","triggerSuppressedError","mouseInProgress","lastMoveX","lastMoveY","handleActivity","handleMouseMove","handleMouseDown","handleMouseUpAndMouseLeave","controlBar","inactivityTimeout","activityCheck","playerChildren","exitPromises","modal","currentBreakpoint","currentWidth","candidateBreakpoint","maxWidth","breakpoints","media","artist","artwork","description","poster","title","tt","baseOptions","tagOptions","dataSetup","childName","newRates","navigator","BASE_PLUGIN_NAME","PLUGIN_CACHE_KEY","pluginStorage","pluginExists","getPlugin","markPluginAsActive","triggerSetupEvent","before","createBasicPlugin","plugin","basicPluginWrapper","instance","createPluginFactory","PluginSubClass","Plugin","deprecate","warned","deprecateForMajor","oldName","VjsErrors","normalizeId","videojs","rootNode","PlayerComponent","nId","playerId","comp","QualityLevel","representation","enable","QualityLevelList","qualityLevel","removed","version$5","initPlugin$1","originalPluginFn","qualityLevelList","qualityLevels","_resolveUrl","resolveManifestRedirect","req","logger","merge","createTimeRanges","bufferedRangesToString","bufferedRangesStr","TIME_FUDGE_FACTOR","SAFE_TIME_DELTA","filterRanges","timeRanges","findRange","findNextRange","findGaps","bufferIntersection","bufferA","bufferB","arity","extents","printableRange","range","strArr","timeUntilRebuffer","timeRangesToArray","timeRangesList","isRangeDifferent","lastBufferedEnd","timeAheadOf","segmentDurationWithParts","playlist","segment","getPartsAndSegments","si","pi","getLastParts","lastSegment","getKnownPartCount","preloadSegment","parts","preloadHints","partCount","hint","liveEdgeDelay","main","hasParts","backwardDuration","endSequence","forwardDuration","intervalDuration","expired","backward","forward","sumDurations","defaultDuration","durationList","startIndex","endIndex","durations","playlistEnd","useSafeLiveEnd","liveEdgePadding","lastSegmentEndTime","getMediaInfoForTime","startingSegmentIndex","startingPartIndex","exactManifestTimings","partsAndSegments","partAndSegment","canUseFudgeFactor","isExactlyAtTheEnd","isExtremelyCloseToTheEnd","isExcluded","isIncompatible","isEnabled","excluded","isDisabled","isAes","hasAttribute","estimateSegmentRequestTime","segmentDuration","bandwidth","bytesReceived","isLowestEnabledRendition","currentBandwidth","playlistMatch","someAudioVariant","AUDIO","groupName","isAudioOnly","variant","CODECS","Playlist","createPlaylistID","groupID","group","parseManifest","onwarn","oninfo","manifestString","customTagParsers","customTagMappers","llhls","Parser","customParser","mapper","manifest","targetDuration","partTargetDuration","forEachMediaGroup","mediaType","groupKey","labelKey","mediaProperties","setupMediaPlaylist","setupMediaPlaylists","resolveMediaGroupUris","mainForMedia","addPropertiesToMain","createGroupID","phonyUri","audioOnlyMain","groupId","DateRangesStorage","segments","firstSegment","dateRanges","dateRange","pendingDateRange","dateRangeClasses","dateRangesToProcess","classList","QUOTA_EXCEEDED_ERR","getStreamingNetworkErrorMetadata","requestType","parseFailure","isBadStatus","isFailure","errorMetadata","isBadStatusOrParseFailure","errorType","logFn$1","getCodecs","mediaAttributes","isMaat","isMuxed","unwrapCodecList","codecList","codecCount","codecObj","codecsForPlaylist","codecInfo","defaultCodecs","EventTarget$1","addLLHLSQueryDirectives","parameters","nextMSN","nextPart","parsedUri","updateSegment","updateSegments","update","oldSegments","newSegments","currentMap","newIndex","oldSegment","newSegment","resolveSegmentUris","baseUri","getAllSegments","isPlaylistUnchanged","updateMain$1","newMedia","unchangedCheck","oldMedia","mergedPlaylist","refreshDelay","lastPart","lastDuration","playlistMetadataPayload","playlists","isLive","renditions","BANDWIDTH","RESOLUTION","PlaylistLoader","vhs","vhsOptions","mediaPlaylist","availableDateRanges","startingState","parsed","hasVideo","codecsList","playlistString","playlistObject","metadata","oldRequest","shouldDelay","delay","mediaChange","mainPlaylistRef","isUpdate","pathway","oldPlaylistUri","oldPlaylistId","newPlaylistUri","newPlaylistId","updatedPlaylist","oldMediaPlaylist","basePlaylist","playlistId","baseID","newUri","newPlaylistID","newMediaPlaylist","newProps","baseURI","oldAttributes","keyIds","keysystem","keyId","callbackWrapper","reqResponse","callAllRequestHooks","requestSet","newOptions","requestCallback","callAllResponseHooks","responseSet","responseCallback","xhrFactory","XhrFunction","beforeRequest","_requestCallbackSet","_responseCallbackSet","xhrMethod","beforeRequestOptions","originalAbort","byterangeStr","byterange","byterangeEnd","byterangeStart","segmentXhrHeaders","textRange","formatHexString","formatAsciiString","createTransferableMessage","transferable","initSegmentId","initSegment","segmentKeyId","hexDump","ascii","tagDump","textRanges","utils","SEGMENT_END_FUDGE_PERCENT","playerTimeToProgramTime","playerTime","transmuxerPrependedSeconds","startOfSegment","offsetFromSegmentStart","originalSegmentVideoDuration","videoTimingInfo","findSegmentForProgramTime","programTime","dateTimeObject","nextSegmentStart","lastSegmentStart","lastSegmentDuration","lastSegmentEnd","findSegmentForPlayerTime","segmentEnd","getOffsetFromTimestamp","comparisonTimeStamp","segmentDateTime","programDateTime","segmentTimeEpoch","verifyProgramDateTimeTags","getProgramTime","matchedSegment","programTimeObject","seekToProgramTime","retryCount","seekTo","pauseAfterSeek","mediaOffset","seekToTime","seekedCallback","callbackOnCompleted","containerRequest","id3Offset","finished","endRequestAndCallback","_bytes","progressListener","newPart","loaded","EventTarget","dashPlaylistUnchanged","aSegment","bSegment","aByterange","bByterange","dashGroupId","parseMainXml","mainXml","clientOffset","sidxMapping","previousManifest","parse","removeOldMediaGroupLabels","newMain","updateMain","oldMain","noChanges","sidxKey","generateSidxKey","addSidxSegmentsToPlaylist","playlistUpdate","equivalentSidx","compareSidxEntry","oldSidxMapping","newSidxMapping","currentSidxInfo","savedSidxInfo","filterChangedSidxMappings","mediaGroupSidx","DashPlaylistLoader","srcUrlOrPlaylist","mainPlaylistLoader","fin","sidx","REQUEST_TYPE","sidxContainer","sidxChanged","isFinalRendition","mainChanged","done","utcTiming","parseUTCTiming","serverTime","location","endList","parsedManifest","mpl","mup","mediaID","mediaChanged","createMediaUpdateTimeout","metadataArray","eventStreamNode","defaultKID","Config","stringToArrayBuffer","browserWorkerPolyFill","workerObj","createObjectURL","blob","factory","objectUrl","worker","terminate","getWorkerString","workerCode$1","commonjsGlobal","Stream$8","destination","flushSource","stream","MAX_UINT32$1","getUint64$5","dinf","esds","ftyp","mdat","mfhd","minf","moof","moov","mvex","mvhd","trak","tkhd","mdia","mdhd","hdlr","sdtp","stbl","stsd","traf","trex","trun$1","MAJOR_BRAND","MINOR_VERSION","AVC1_BRAND","VIDEO_HDLR","AUDIO_HDLR","HDLR_TYPES","VMHD","SMHD","DREF","STCO","STSC","STSZ","STTS","sequenceNumber","trackFragments","samples","videoSample","audioSample","sps","pps","sequenceParameterSets","pictureParameterSets","avc1Box","hSpacing","vSpacing","trackFragmentHeader","trackFragmentDecodeTime","trackFragmentRun","sampleDependencyTable","dataOffset","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","audioTrun","videoTrun","trunHeader","durationPresent","sizePresent","flagsPresent","compositionTimeOffset","bytesOffest","header","sample","mp4Generator","fileType","movie","groupNalsIntoFrames","nalUnits","currentNal","currentFrame","frames","groupFramesIntoGops","currentGop","gops","extendFirstKeyFrame","createDefaultSample","sampleForFrame","frame","generateSampleTable$1","baseDataOffset","concatenateNalData","nalsByteLength","numberOfNals","totalByteLength","generateSampleTableForFrame","concatenateNalDataForFrame","frameUtils$1","highPrefix","lowPrefix","zeroFill","makeTable","metaTable","silence","silence_1","coneOfSilence","ONE_SECOND_IN_TS$4","secondsToVideoTs","secondsToAudioTs","videoTsToSeconds","audioTsToSeconds","audioTsToVideoTs","videoTsToAudioTs","metadataTsToSeconds","sampleRate","timestamp","timelineStartPts","keepOriginalTimestamps","clock$2","clock$1","sumFrameByteLengths","currentObj","sum","prefixWithSilence","audioAppendStartTs","videoBaseMediaDecodeTime","baseMediaDecodeTimeTs","frameDuration","audioGapDuration","audioFillFrameCount","audioFillDuration","silentFrame","firstFrame","trimAdtsFramesByEarliestDts","adtsFrames","earliestAllowedDts","generateSampleTable","concatenateFrameData","audioFrameUtils$1","ONE_SECOND_IN_TS$3","collectDtsInfo","clearDtsInfo","calculateTrackBaseMediaDecodeTime","baseMediaDecodeTime","scale","minSegmentDts","trackDecodeInfo$1","USER_DATA_REGISTERED_ITU_T_T35","RBSP_TRAILING_BITS","parseSei","payloadType","payloadSize","userIdentifier","parseUserData","sei","parseCaptionPackets","pts","userData","discardEmulationPreventionBytes$1","emulationPreventionBytesPositions","captionPacketParser","Stream$7","cea708Parser","CaptionStream$2","Cea608Stream","Cea708Stream","cc","newCaptionPackets","flushType","idx","packet","ccStream","CHARACTER_TRANSLATION_708","get708CharFromCode","newCode","within708TextBlock","Cea708Window","windowNum","Cea708Service","serviceNum","encoding","beforeRowOverflow","captionServices","captionServiceEncodings","serviceProps","serviceName","byte0","byte1","packet708","packetData","blockSize","service","isExtended","isMultiByte","extended","currentByte","nextByte","char","charCodeArray","toHexString","byteArray","unicode","firstByte","secondByte","winAttr","displayedText","winId","penAttr","penColor","penLoc","CHARACTER_TRANSLATION","getCharFromCode","BOTTOM_ROW","ROWS","createDisplayBuffer","field","dataChannel","swap","char0","char1","indentations","logWarning","newBaseRow","format","baseRow","captionStream","streamTypes","Stream$6","MAX_TS","RO_THRESH","TYPE_SHARED","handleRollover$1","TimestampRolloverStream$1","lastDTS","referenceDTS","timestampRolloverStream","typedArrayIndexOf$1","typedArray","fromIndex","currentIndex","typedArrayIndexOf","textEncodingDescriptionByte","percentEncode$1","parseUtf8","parseIso88591$1","parseSyncSafeInteger$1","frameParsers","mimeTypeEndIndex","descriptionEndIndex","LINK_MIME_TYPE","parseId3Frames$1","frameSize","frameHeader","frameStart","tagSize","hasExtendedHeader","parseId3","Stream$5","StreamTypes$3","id3","MetadataStream","bufferSize","chunk","d","metadataStream","Stream$4","CaptionStream$1","StreamTypes$2","TimestampRolloverStream","TransportPacketStream","TransportParseStream","ElementaryStream","MP2T_PACKET_LENGTH$1","SYNC_BYTE$1","bytesInBuffer","everything","parsePsi","parsePat","parsePmt","psi","pat","pmt","sectionLength","tableEnd","programInfoLength","streamType","pid","segmentHadPmt","audio","timedMetadata","programMapTable","parsePes","pes","ptsDtsFlags","startPrefix","flushStream","forceFlush","packetFlushable","fragment","m2ts$1","m2ts_1","Stream$3","ONE_SECOND_IN_TS$2","AdtsStream$1","ADTS_SAMPLING_FREQUENCIES$1","handlePartialSegments","frameNum","frameLength","protectionSkipBytes","oldBuffer","sampleCount","adtsFrameDuration","skip","adts","ExpGolomb$1","workingData","workingBytesAvailable","workingWord","workingBitsAvailable","workingBytes","availableBytes","skipBytes","bits","valu","leadingZeroCount","clz","expGolomb","Stream$2","ExpGolomb","H264Stream$1","NalByteStream","PROFILES_WITH_OPTIONAL_SPS_DATA","syncPoint","swapBuffer","nalByteStream","trackId","currentPts","currentDts","readSequenceParameterSet","skipScalingList","expGolombDecoder","lastScale","nextScale","deltaScale","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","profileIdc","levelIdc","profileCompatibility","chromaFormatIdc","picOrderCntType","numRefFramesInPicOrderCntCycle","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","scalingListCount","sarRatio","aspectRatioIdc","h264","ADTS_SAMPLING_FREQUENCIES","parseId3TagSize","isLikelyAacData$1","parseSyncSafeInteger","percentEncode","parseIso88591","parseAdtsSize","lowThree","middle","highTwo","parseType$5","parseSampleRate","parseAacTimestamp","owner","Stream$1","aacUtils","AacStream$1","timeStamp","bytesLeft","tempLength","aac","AUDIO_PROPERTIES$1","audioProperties","VIDEO_PROPERTIES$1","videoProperties","Stream","mp4","frameUtils","audioFrameUtils","trackDecodeInfo","m2ts","AdtsStream","H264Stream","AacStream","isLikelyAacData","ONE_SECOND_IN_TS$1","AUDIO_PROPERTIES","VIDEO_PROPERTIES","VideoSegmentStream","AudioSegmentStream","Transmuxer","CoalesceStream","retriggerForStream","addPipelineLogRetriggers","transmuxer","pipeline","arrayEquals","generateSegmentTimingInfo","startDts","startPts","endDts","endPts","prependedContentDuration","ptsOffsetFromDts","decodeDuration","presentationDuration","earliestDts","videoClockCyclesOfSilencePrefixed","gopsToAlignWith","nalUnit","gopForFusion","firstGop","lastGop","alignedGops","gop","halfSecond","nearestDistance","dtsDistance","nearestGopObj","currentGopObj","alignIndex","gopIndex","byteLength","nalCount","alignEndIndex","matchFound","trimIndex","newGopsToAlignWith","output","caption","hasFlushed","videoTrack","audioTrack","timelineStartInfo","id3Frame","isAac","toUnsigned$3","toHexString$1","bin","parseType$4","parseType_1","toUnsigned$2","parseType$3","findBox$5","subresults","findBox_1","toUnsigned$1","getUint64$4","tfdt","parseTfdt$3","tfhd","baseDataOffsetPresent","sampleDescriptionIndexPresent","defaultSampleDurationPresent","defaultSampleSizePresent","defaultSampleFlagsPresent","durationIsEmpty","defaultBaseIsMoof","parseTfhd$2","parseSampleFlags$1","parseSampleFlags_1","parseSampleFlags","trun","dataOffsetPresent","firstSampleFlagsPresent","sampleDurationPresent","sampleSizePresent","sampleFlagsPresent","sampleCompositionTimeOffsetPresent","parseTrun$2","mp4Inspector","uint8ToCString$1","curChar","retString","uint8ToCString","getUint64$1","parseEmsgBox","boxData","scheme_id_uri","timescale","presentation_time","presentation_time_delta","event_duration","message_data","emsgBox","isValidEmsgBox","scaleTime","presentationTime","timeDelta","emsg","hasScheme","isValidV0Box","isDefined","isValidV1Box","emsg$1","toUnsigned","findBox$3","parseType$1","parseTfhd$1","parseTrun$1","parseTfdt$2","compositionStartTime","getVideoTrackIds","getTracks","getTimescaleFromMediaHeader$1","getEmsgID3","window$2","parseId3Frames","init","traks","trafs","lowestTime","baseTime","timescales","trafBoxes","parsedTfhd","parsedTfdt","parsedTrun","videoTrackIds","hdlrs","tkhds","handlerType","tkhdVersion","sampleDescriptions","codecBox","codecConfig","codecConfigType","segmentData","emsgBoxes","parsedBox","parsedId3Frames","probe$2","parseTrun","findBox$2","getMdatTrafPairs$2","mdats","mdatTrafPairs","matchingTraf","parseSamples$2","truns","defaultSampleDuration","defaultSampleSize","allSamples","trackRun","CaptionStream","findBox$1","parseTfdt$1","parseTfhd","getMdatTrafPairs$1","parseSamples$1","mapToSample","approximateOffset","findSeiNals","avcStream","avcView","seiNal","lastMatchedSample","matchingSample","parseCaptionNals","videoTrackId","captionNals","pair","headerInfo","parseEmbeddedCaptions","trackNals","CaptionParser","isInitialized","segmentCache","parsedCaptions","parsingPartial","parsedData","cachedSegment","nals","nal","captionParser","parseTfdt","getTimescaleFromMediaHeader","parseSamples","getMdatTrafPairs","webvttParser","vttCues","mdatBox","trafBox","tfdtBox","tfhdBox","trunBoxes","mdatOffset","UTF_8","textDecoder","sampleData","vttcBox","paylBox","sttgBox","cueText","StreamTypes$1","parsePid","parsePayloadUnitStartIndicator","parseAdaptionField","parseType","pmtPid","pusi","payloadOffset","parsePesType","parsePesTime","parseNalUnitType","videoPacketContainsKeyFrame","frameBuffer","frameI","frameSyncPoint","foundKeyFrame","probe$1","StreamTypes","handleRollover","probe","ONE_SECOND_IN_TS","MP2T_PACKET_LENGTH","SYNC_BYTE","parsePsi_","table","parseAudioPes_","pesType","endLoop","parseVideoPes_","firstKeyFrame","adjustTimestamp_","segmentInfo","baseTimestamp","audioBaseTimestamp","info","videoBaseTimestamp","inspectAac_","audioCount","audioTimescale","inspectTs_","inspect","isAacData","tsInspector","wireTransmuxerEvents","initArray","gopInfo","timingInfo","videoSegmentTimingInfo","audioSegmentTimingInfo","trackInfo","audioTimingInfo","MessageHandlers","id3Frames","baseStartTime","tsStartTime","timeInfo","timestampOffset","TransmuxWorker","handleData_","transmuxedData","captions","captionStreams","videoFrameDtsTime","videoFramePtsTime","handleDone_","handleGopInfo_","processTransmux","audioAppendStart","remux","onData","onTrackInfo","onAudioTimingInfo","onVideoTimingInfo","onVideoSegmentTimingInfo","onAudioSegmentTimingInfo","onId3","onCaptions","onDone","onEndedTimeline","onTransmuxerLog","isEndOfTimeline","triggerSegmentEventFn","waitForEndedTimelineEvent","handleMessage","dequeue","handleError","segmentInfoPayload","byteOffset","processAction","enqueueAction","reset","endTimeline","transmux","createTransmuxer","term","segmentTransmuxer","workerCallback","endAction","listenForEndEvent","isArrayBuffer","transfers","REQUEST_ERRORS","WEB_VTT_CODEC","abortAll","activeXhrs","getRequestStats","getProgressStats","progressEvent","stats","handleErrors","handleKeyResponse","objects","finishProcessingFn","errorObj","keyInfo","initMp4Text","parseMp4TextSegment","doneFn","mp4VttCues","parseInitSegment","handleInitSegmentResponse","parseError","handleSegmentResponse","responseType","newBytes","transmuxAndNotify","trackInfoFn","timingInfoFn","videoSegmentTimingInfoFn","audioSegmentTimingInfoFn","id3Fn","captionsFn","endedTimelineFn","dataFn","fmp4Tracks","audioStartFn","audioEndFn","videoStartFn","videoEndFn","finish","dispatchType","probeResult","handleSegmentBytes","bytesAsUint8Array","finishLoading","emsgData","decrypt","encryptedBytes","decryptionWorker","decryptionHandler","decrypted","decryptError","keyBytes","decryptSegment","decryptedBytes","waitForCompletion","didError","segmentFinish","handleLoadEnd","loadendState","abortFn","handleProgress","progressFn","mediaSegmentRequest","xhrOptions","keyRequestOptions","keyRequestCallback","keyXhr","mapKeyRequestOptions","mapKeyRequestCallback","mapKeyXhr","initSegmentOptions","initSegmentRequestCallback","initSegmentXhr","segmentRequestOptions","segmentRequestCallback","segmentXhr","activeXhr","logFn","representationToString","safeGetComputedStyle","property","stableSort","sortFn","newArray","right","cmp","comparePlaylistBandwidth","leftBandwidth","rightBandwidth","comparePlaylistResolution","leftWidth","rightWidth","simpleSelector","playerBandwidth","playerObjectFit","limitRenditionByPlayerDimensions","playlistController","sortedPlaylistReps","rep","enabledPlaylistReps","bandwidthPlaylistReps","highestRemainingBandwidthRep","bandwidthBestRep","chosenRep","haveResolution","resolutionBestRepList","resolutionBestRep","resolutionPlusOneList","resolutionPlusOneSmallest","resolutionPlusOneRep","leastPixelDiffRep","leastPixelDiffList","lastBandwidthSelector","pixelRatio","movingAverageBandwidthSelector","decay","average","lastSystemBandwidth","minRebufferMaxBandwidthSelector","currentTimeline","syncController","compatiblePlaylists","enabledPlaylists","rebufferingEstimates","numRequests","rebufferingImpact","noRebufferingPlaylists","estimate","lowestBitrateCompatibleVariantSelector","concatSegments","segmentObj","compactSegmentUrlDescription","resolvedUri","createCaptionsTrackIfNotExists","inbandTextTracks","instreamId","def","captionService","addCaptionData","captionArray","Cue","deprecateOldCue","addMetadata","videoDuration","metadataTrack","cuesArray","cuesGroupedByStartTime","timeSlot","sortedStartTimes","cueGroup","finiteDuration","nextTime","dateRangeAttr","dateRangeKeysToOmit","addDateRangeMetadata","createMetadataTrackIfNotExists","removeCuesFromTrack","removeDuplicateCuesFromTrack","uniqueCues","cueKey","gopsSafeToAlignWith","mapping","currentTimePts","updateGopBuffer","replace","removeGopBuffer","updatedBuffer","shallowEqual","akeys","bkeys","getSyncSegmentCandidate","targetTime","timelineSegments","MIN_BACK_BUFFER","CHECK_BUFFER_DELAY","finite","MIN_SEGMENT_DURATION_TO_SAVE_STATS","illegalMediaSwitch","loaderType","startingMedia","safeBackBufferTrimTime","trimTime","maxTrimTime","segmentInfoString","seq","partIndex","timeline","segmentLen","selection","hasPartIndex","zeroBasedPartCount","timingInfoPropertyForMedia","timestampOffsetForSegment","segmentTimeline","overrideCheck","shouldWaitForTimelineChange","timelineChangeController","audioDisabled","lastMainTimelineChange","pendingAudioTimelineChange","shouldFixBadTimelineChanges","pendingMainTimelineChange","hasPendingTimelineChanges","differentPendingChanges","isAudioTimelineBehind","segmentLoader","checkAndFixTimelines","mediaDuration","timingInfos","maxDuration","typeTimingInfo","segmentTooLong","getTroublesomeSegmentDurationMessage","sourceType","isSegmentWayTooLong","isSegmentSlightlyTooLong","segmentTooLongMessage","isEncrypted","isMediaInitialization","SegmentLoader","newState","requestId","hasAudio","storedMap","storedKey","newPlaylist","oldPlaylist","oldId","mediaSequenceDiff","mediaIndex","isFmp4","force","removesRemaining","removeFinished","appendedLastSegment","appendedLastPart","bufferedTime","preloaded","haveEnoughBuffer","segmentIndex","syncInfo","mediaInfoForTime","nextSegment","hasIndependentSegments","lastSegmentLastPart","ended","finalTargetTime","mediaSequenceSyncInfo","nextMediaSequenceSyncInfo","independent","isSyncRequest","forceTimestampOffset","audioBufferedEnd","measuredBandwidth","requestTimeRemaining","timeUntilRebuffer$1","switchCandidate","timeSavedBySwitching","minimumTimeSaving","simpleSegment","timeType","timingInfoProperty","captionData","captionTracks","captionTrack","trackName","callQueue","fun","loadQueue","useVideoTimingInfo","firstVideoFrameTimeForData","audioBuffered","videoBuffered","audioBufferStart","audioBufferEnd","videoBufferStart","videoBufferEnd","timeToRemoveUntil","segmentTimingInfo","isEndOfStream","isWalkingForward","isDiscontinuity","removeToTime","previousSegment","iv","timelineMapping","currentStart","currentVideoTimestampOffset","waitForVideo","waitForAudio","illegalMediaSwitchError","didChange","prioritizedTimingInfo","segmentDurationMessage","badSegmentGuess","badPartGuess","segmentProcessingTime","segmentProcessingThroughput","toTitleCase","bufferTypes","updating","sourceUpdater","sourceBuffer","nextQueueIndexOfType","queueEntry","shiftQueue","queueIndex","cleanupBuffer","titleType","inSourceBuffers","mediaSource","actions","onError","mime","newCodecBase","oldCodec","pushQueue","onUpdateend","bufferedRangesForType","descriptiveString","SourceUpdater","que","uint8ToUtf8","uintArray","bufferToHexString","uInt8Buffer","VTT_LINE_TERMINATORS","NoVttJsError","VTTSegmentLoader","combinedByteLength","combinedSegment","checkTimestampOffset","isMp4WebVttSegmentWithCues","isVttType","isTextResult","vttCue","cueSetting","keyValString","decodeBytesToString","mapData","mappingObj","MPEGTS","LOCAL","diff","firstStart","lastStart","valueIn90khz","referenceIn90khz","findAdCue","mediaTime","updateAdCues","adOffset","adTotal","SyncInfo","appended","SyncInfoData","segmentSyncInfo","partsSyncInfo","partSyncInfo","MediaSequenceSync","syncInfoData","mediaSequence","startingMediaSequence","startingTime","newStorage","newDiagnostics","currentMediaSequence","prevSyncInfoData","segmentStart","segmentIsAppended","currentPartStart","partStart","partEnd","partIsAppended","fallback","minMediaSequenceFromStorage","DependantMediaSequenceSync","MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC","syncPointStrategies","mediaSequenceSync","lastDistance","datetimeMapping","z","discontinuity","discontinuitySync","SyncController","syncPoints","syncPointInfo","strategy","selectedSegment","bestSyncPoint","bestDistance","bestStrategy","newDistance","lastRemovedSegment","playlistTimestamp","shouldSaveTimelineMapping","didCalculateSegmentTimeMapping","dateTime","mediaIndexDiff","accuracy","TimelineChangeController","from","to","workerCode","_length","_i","unpad","padded","precompute","tables","encTable","decTable","sbox","sboxInv","xInv","th","x2","x4","x8","tEnc","tDec","aesTables","AES","tmp","keyLen","rcon","encKey","decKey","encrypted0","encrypted1","encrypted2","encrypted3","out","a2","c2","nInnerRounds","kIndex","table0","table1","table2","table3","AsyncStream","job","ntoh","word","encrypted","initVector","encrypted32","decipher","decrypted32","init0","init1","init2","init3","wordIx","Decrypter","audioTrackKind_","stopLoaders","startLoaders","playlistLoader","onGroupChanged","mainSegmentLoader","activeTrack","activeGroup","previousActiveLoader","lastGroup","onGroupChanging","onTrackChanged","lastTrack","pc","excludePlaylist","defaultTrack","setupListeners","requestOptions","initialize","mediaGroups","logger_","variantLabel","groupMatch","variants","groupKeys","groupPropertyList","getActiveGroup","activeTrack_","setupMediaGroups","audioSegmentLoader","onAudioTrackChanged","createMediaTypes","SteeringManifest","ContentSteeringController","steeringTag","steeringUri","reloadUri","errorInfo","retrySeconds","steeringManifestJson","parsedMetadata","steeringUrl","steeringUrlObject","proxyServerUrlObject","dataUri","urlObject","networkThroughput","pathwayKey","throughputKey","steeringJson","nextPathway","pathwaysByPriority","proxyURI","steeringURI","ttl","ttlMS","baseURL","newTag","debounce","ABORT_EARLY_EXCLUSION_SECONDS","Vhs$1","loaderStats","sumLoaderStat","stat","shouldSwitchToMedia","currentPlaylist","nextPlaylist","bufferLowWaterLine","bufferHighWaterLine","bufferBasedABR","sharedLogLine","isBuffered","forwardBuffer","maxBufferLowWaterLine","nextBandwidth","currBandwidth","logLine","PlaylistController","externVhs","useCueTags","playlistExclusionDuration","enableLowInitialPlaylist","cacheEncryptionKeys","leastPixelDiffSelector","experimentalUseMMS","maxPlaylistRetries","segmentLoaderSettings","onLoad","getBandwidth","timeToLoadedDataStart","newId","dashMediaPlaylists","defaultPlaylists","defaultGroup","requestTimeout","selectedMedia","defaultDemuxed","audioGroupKeys","mediaGroup","updateCodecs","startPoint","mainMediaInfo","absolutePlaylistEnd","playlistToExclude","reIncludeDelay","reincluded","excludeUntil","errorMessage","delayDuration","filter","fnNames","loaders","dontFilterPlaylist","loader","calculatedEnd","mainSeekable","audioSeekable","mainStart","mainEnd","audioStart","audioEnd","oldSeekable","usingAudioLoader","hasMainMediaInfo","hasAudioMediaInfo","playlistCodecs","supportFunction","unsupportedCodecs","unsupportedAudio","supporter","switchMessages","newCodec","ids","unsupported","codecCount_","videoDetails","audioDetails","exclusionReasons","variantCodecs","variantCodecCount","variantVideoDetails","variantAudioDetails","newMax","availablePathways","newPathways","serviceLocation","currentPathway","didEnablePlaylists","pathwayId","differentPathwayId","noExcludeUntil","currentPathwayClones","nextPathwayClones","oldClone","aParams","bParams","nonUsableKeyStatusCount","NON_USABLE","keyIdSet","USABLE","hasUsableKeyStatus","nonUsableExclusion","isNonHD","excludedForNonUsableKey","formattedKeyIdString","enableFunction","playlistID","changePlaylistFn","incompatible","currentlyEnabled","Representation","vhsHandler","qualityChangeFunction","resolution","renditionSelectionMixin","timerCancelEvents","PlaybackWatcher","playHandler","canPlayHandler","waitingHandler","cancelTimerHandler","loaderTypes","loaderChecks","setSeekingHandlers","isBufferedDifferent","isAfterSeekableRange","minAppendedDuration","bufferedToCheck","nextRange","livePoint","allowSeeksWithinUnsafeLiveWindow","allowedEnd","isLLHLS","gap","lastVideoRange","videoRange","audioRange","scheduledCurrentTime","gaps","defaultOptions","initPlugin","lastCalled","localOptions","loadedMetadataHandler","cleanupEvents","reinitPlugin","reloadSourceOnError","version$4","version$3","version$2","version$1","Vhs","LOCAL_STORAGE_KEY","handleVhsMediaChange","selectedIndex","handleVhsLoadedMetadata","emeKeySystems","keySystemOptions","mainPlaylist","audioPlaylist","videoContentType","audioContentType","keySystemContentTypes","keySystem","getAllPsshKeySystemsOptions","keySystems","keySystemsArr","keySystemsOptions","keySystemsObj","waitForKeySessionCreation","sourceKeySystems","audioMedia","mainPlaylists","keySystemsOptionsArr","initializationFinishedPromises","keySessionCreatedPromises","setupEmeOptions","sourceOptions","getVhsLocalStorage","storedObject","updateVhsLocalStorage","objectToStore","expandDataUri","addOnRequestHook","addOnResponseHook","removeOnRequestHook","removeOnResponseHook","canItPlay","Component","VhsHandler","_player","fullscreenElement","customPixelRatio","playbackWatcherOptions","defaultSelector","selectPlaylist","throughput","playerBandwidthEst","networkInformation","tenMbpsAsBitsPerSecond","networkInfoBandwidthEstBitsPerSec","invBandwidth","invThroughput","audioPlaylistLoader","didSetupEmeOptions","playlistControllerEvents","playbackWatcher","VhsSourceHandler","simpleType","overrideNative","defaultOverrideNative","supportsNativeMediaSources"],"mappings":";AAAA,SAASA,KAAW;AAClB,SAAOA,KAAW,OAAO,SAAS,OAAO,OAAO,KAAI,IAAK,SAAUC,GAAG;AACpE,aAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;AACzC,UAAI,IAAI,UAAU,CAAC;AACnB,eAASC,KAAK,EAAG,EAAC,CAAA,GAAI,eAAe,KAAK,GAAGA,CAA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